文章目录
- 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,你应该会看到一个下载对话框,提示你保存文件。