文章目錄
- CGI中使用Cookie
- cookie的語法
- 設置Cookie
- 獲取Cookie
- 檢索Cookie信息
- 文件上傳實例
- 1. 創建HTML表單
- 2. 編寫Python腳本處理上傳
- 文件下載對話框
CGI中使用Cookie
在CGI(Common Gateway Interface)中使用Cookie涉及設置和獲取由Web服務器發送到瀏覽器,并由瀏覽器隨每個請求發送回服務器的數據。Cookies通常用于存儲用戶偏好、會話狀態和身份驗證信息等。
cookie的語法
Cookie的語法通常包括以下幾個部分:
- Cookie名稱:一個由字母、數字、下劃線、點號、加號、冒號、斜杠、問號、百分號和等號組成的字符串,用于標識Cookie。
- 等號:將Cookie名稱與值分開,確保值不會被視為Cookie名稱。
- 值:與Cookie名稱等長的任意字符串,表示存儲的數據。
- 分號加空格:分隔Cookie的各個部分。
- 路徑:指定Cookie的作用路徑,默認是當前頁面。
- 域名:指定Cookie適用的域名,默認是當前域名。
- 有效期:指定Cookie的生存時間,可以是絕對時間或相對時間。
- 其他可選字段:如Secure、HttpOnly、SameSite等,用于指定Cookie的安全性和作用范圍。
設置Cookie
在CGI程序中設置Cookie,你需要使用http模塊中的Cookie類。以下是一個設置Cookie的示例:
#!/usr/bin/env python3
import http.cookies# 創建一個Cookie對象
cookie = http.cookies.SimpleCookie()# 設置Cookie的名稱、值、過期時間等
cookie['user_preference'] = 'dark_theme'
cookie['user_preference']['expires'] = 'Fri, 31 Dec 2023 23:59:59 GMT'# 打印Set-Cookie頭
print("Content-Type: text/html")
print() # Blank line required, end of headers
print("Set-Cookie: user_preference=dark_theme; expires=Fri, 31 Dec 2023 23:59:59 GMT; path=/")
print("<html>")
print("<head>")
print("<title>Set Cookie</title>")
print("</head>")
print("<body>")
print("<p>Cookie has been set.</p>")
print("</body>")
print("</html>")
獲取Cookie
要從CGI請求中獲取Cookie,你可以使用cgi.FieldStorage()類,但更常見的是使用http.cookies模塊。以下是一個獲取Cookie的示例:
#!/usr/bin/env python3
import http.cookies# 創建一個CookieJar對象來存儲Cookie
cookie_jar = http.cookies.CookieJar()# 從請求頭中加載Cookie
cookie_jar.extract_cookies(http.client.HTTPResponse(None), None)# 獲取名為'user_preference'的Cookie
user_preference = cookie_jar._cookies.get('example.com', {}).get('user_preference', None)print("Content-Type: text/html")
print() # Blank line required, end of headersif user_preference:print("<html>")print("<head>")print("<title>Get Cookie</title>")print("</head>")print("<body>")print("<p>User preference: {}</p>".format(user_preference.value))print("</body>")print("</html>")
else:print("<html>")print("<head>")print("<title>No Cookie</title>")print("</head>")print("<body>")print("<p>No user preference cookie found.</p>")print("</body>")print("</html>")
檢索Cookie信息
這個模塊提供了一個CookieJar類,用于處理和存儲Cookie。以下是如何使用這個模塊來檢索Cookie的示例:
#!/usr/bin/env python3
import http.cookies# 創建一個CookieJar對象來存儲Cookie
cookie_jar = http.cookies.CookieJar()# 從請求頭中加載Cookie
cookie_jar.extract_cookies(http.client.HTTPResponse(None), None)# 檢索所有Cookie
for cookie in cookie_jar:print(f"Name: {cookie.name}")print(f"Value: {cookie.value}")print(f"Domain: {cookie.domain}")print(f"Path: {cookie.path}")print(f"Expires: {cookie.expires}")print(f"Secure: {cookie.is_secure}")print(f"HttpOnly: {cookie.is_http_only}")print(f"SameSite: {cookie.samesite}")print()
我們首先創建了一個CookieJar對象,然后使用extract_cookies方法從請求頭中加載Cookie。之后,我們遍歷CookieJar對象中的所有Cookie,并打印出它們的名稱、值、域名、路徑、過期時間、是否安全(Secure)、是否僅通過HTTP頭(HttpOnly)以及SameSite屬性。
文件上傳實例
文件上傳是Web應用程序中的一個常見功能,允許用戶將文件(如圖片、文檔等)從客戶端上傳到服務器。以下是使用HTML和Python實現文件上傳功能的基本步驟。
1. 創建HTML表單
首先,你需要創建一個包含元素的HTML表單,該元素類型設置為"file",允許用戶選擇要上傳的文件。
<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><title>File Upload Example</title>
</head>
<body><form action="upload_script.py" method="POST" enctype="multipart/form-data"><input type="file" name="file_to_upload"><input type="submit" value="Upload File"></form>
</body>
</html>
2. 編寫Python腳本處理上傳
接下來,你需要一個Python腳本來處理上傳的文件。這個腳本將接收文件數據,并可以選擇將其保存到服務器的文件系統中。
#!/usr/bin/env python3
import cgi
import os# 創建一個FieldStorage對象來處理表單數據
form = cgi.FieldStorage()# 檢查是否有文件被上傳
if 'file_to_upload' in form:file_item = form['file_to_upload']# 獲取文件名filename = file_item.filename# 確保文件名不是非法的if not filename.endswith('.txt'):print("Content-Type: text/html")print()print("<html><body>Invalid file type. Only .txt files are allowed.</body></html>")exit()# 保存文件到服務器with open(os.path.join('/uploads', filename), 'wb') as file:file.write(file_item.file.read())print("Content-Type: text/html")print()print("<html><body>File successfully uploaded.</body></html>")
else:print("Content-Type: text/html")print()print("<html><body>No file was uploaded.</body></html>")
我們首先創建了一個FieldStorage對象來處理表單數據。然后,我們檢查是否有名為file_to_upload的文件項。如果有,我們獲取文件名并確保它是一個合法的.txt文件。之后,我們將文件保存到服務器的/uploads目錄下。
文件下載對話框
在Web瀏覽器中,文件下載通常是由服務器響應的Content-Disposition頭部觸發的,該頭部指示響應應該被解釋為下載。當服務器返回一個帶有Content-Disposition: attachment頭的響應時,瀏覽器會自動提示用戶保存文件。
以下是一個簡單的Python腳本示例,它將創建一個HTTP響應,并設置Content-Disposition頭部以觸發文件下載對話框。
#!/usr/bin/env python3
import http.server
import socketserver
import os# 定義本地服務器地址和端口
address = ('127.0.0.1', 8000)# 定義文件下載路徑
download_path = '/path/to/your/file.txt'# 創建HTTP服務器
class DownloadHandler(http.server.SimpleHTTPRequestHandler):def do_GET(self):# 檢查請求的路徑是否與要下載的文件匹配if self.path == download_path:# 設置Content-Disposition頭部以觸發下載self.send_response(200)self.send_header('Content-Disposition', 'attachment; filename="file.txt"')self.end_headers()# 打開文件并發送內容with open(download_path, 'rb') as file:self.copyfile(file, self.wfile)returnelse:# 如果請求的路徑不是下載路徑,則返回404錯誤self.send_response(404)self.end_headers()# 啟動服務器
httpd = socketserver.TCPServer(address, DownloadHandler)
httpd.serve_forever()
們定義了一個簡單的HTTP服務器,它監聽本地主機的8000端口。當服務器接收到對特定路徑(在本例中為/path/to/your/file.txt)的GET請求時,它會發送一個帶有Content-Disposition: attachment頭的響應,從而觸發瀏覽器下載該文件。
要測試這個腳本,你需要將其保存為download_server.py,然后使用Python運行它。同時,確保download_path變量指向一個實際存在的文件。
在瀏覽器中,訪問http://127.0.0.1:8000/path/to/your/file.txt,你應該會看到一個下載對話框,提示你保存文件。