Python CGI(Common Gateway Interface) 用于在 Web 服务器 上运行 Python 脚本,处理 HTTP 请求,并动态生成 HTML 响应。
1. CGI 基础概念
1.1 CGI 运行流程
- 客户端(浏览器) 发送请求(如表单提交)。
- Web 服务器 解析请求,并调用 CGI 脚本(如 Python)。
- CGI 脚本 处理请求,生成 HTML 响应,并返回给服务器。
- Web 服务器 发送 HTML 响应给客户端。
2. 配置 Web 服务器支持 CGI
2.1 Apache 配置 CGI(常见 Web 服务器)
如果使用 Apache,需要启用 CGI 支持。
修改 Apache 配置文件(httpd.conf
):
# 启用 CGI
Options +ExecCGI
# 指定 CGI 目录
ScriptAlias /cgi-bin/ "/var/www/cgi-bin/"
# 允许执行 Python 脚本
AddHandler cgi-script .cgi .py
然后,重启 Apache 服务器:
sudo systemctl restart apache2
CGI 脚本存放路径:/var/www/cgi-bin/
或 htdocs/cgi-bin/
3. 编写 CGI 脚本
3.1 编写一个简单的 CGI 脚本
在 /var/www/cgi-bin/
目录下,创建 hello.py
:
#!/usr/bin/python3
# -*- coding: utf-8 -*-
print("Content-Type: text/html\n") # HTTP 头部,必须有
print("<html><body>")
print("<h1>Hello, CGI!</h1>")
print("</body></html>")
执行权限:
chmod +x /var/www/cgi-bin/hello.py
然后在浏览器访问:
http://localhost/cgi-bin/hello.py
4. 处理 HTML 表单数据
4.1 创建 HTML 表单(form.html
)
<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="UTF-8">
<title>CGI 表单</title>
</head>
<body>
<form action="/cgi-bin/process.py" method="post">
姓名: <input type="text" name="name"><br>
年龄: <input type="text" name="age"><br>
<input type="submit" value="提交">
</form>
</body>
</html>
4.2 处理表单数据(process.py
)
#!/usr/bin/python3
# -*- coding: utf-8 -*-
import cgi
print("Content-Type: text/html\n") # 必须有 HTTP 头部
print("<html><body>")
# 获取表单数据
form = cgi.FieldStorage()
name = form.getvalue("name", "未知")
age = form.getvalue("age", "未知")
print(f"<h1>欢迎, {name}!</h1>")
print(f"<p>你的年龄是 {age} 岁。</p>")
print("</body></html>")
5. 读取 HTTP 请求数据
5.1 读取 GET 请求参数
http://localhost/cgi-bin/get_example.py?user=Tom&age=30
#!/usr/bin/python3
# -*- coding: utf-8 -*-
import os
import urllib.parse
print("Content-Type: text/html\n")
# 解析 URL 参数
query = os.environ.get("QUERY_STRING", "")
params = urllib.parse.parse_qs(query)
user = params.get("user", ["未知"])[0]
age = params.get("age", ["未知"])[0]
print(f"<h1>用户: {user}</h1>")
print(f"<p>年龄: {age}</p>")
5.2 读取 POST 请求参数
#!/usr/bin/python3
# -*- coding: utf-8 -*-
import sys
import cgi
print("Content-Type: text/html\n")
# 解析表单数据
form = cgi.FieldStorage()
name = form.getvalue("name", "未知")
print(f"<h1>欢迎 {name}!</h1>")
6. 处理 Cookies
6.1 设置 Cookie
#!/usr/bin/python3
# -*- coding: utf-8 -*-
print("Content-Type: text/html")
print("Set-Cookie: user=Alice; path=/\n")
print("<html><body>")
print("<h1>Cookie 已设置</h1>")
print("</body></html>")
6.2 读取 Cookie
#!/usr/bin/python3
# -*- coding: utf-8 -*-
import os
print("Content-Type: text/html\n")
cookies = os.environ.get("HTTP_COOKIE", "")
print(f"<h1>Cookies: {cookies}</h1>")
7. CGI 调试技巧
- 检查权限:确保
cgi-bin
目录下的 Python 脚本具有 可执行权限。chmod +x /var/www/cgi-bin/*.py
- 查看 Apache 日志:
tail -f /var/log/apache2/error.log
- 使用命令行测试:
python3 /var/www/cgi-bin/test.py
8. 参考资料
出站链接
站内链接
CGI 适用于 小型 Web 应用,但对于高并发场景,建议使用 WSGI(如 Flask、Django) 替代!🚀
发表回复