Python CGI 编程:从表单请求到子进程响应
在本机运行 CGI 实验,观察查询参数、表单控件、Cookie、上传和下载如何经过 HTTP 与子进程边界。
学完这一章,你能够
- 在本机运行 CGI 实验,观察查询参数、表单控件、Cookie、上传和下载如何经过 HTTP 与子进程边界。
浏览器、服务器与 CGI 进程
浏览器请求 URL。服务器按路由返回静态文件、启动已配置的 CGI 处理程序,或给出错误响应。CGI 1.1 定义服务器和内容生成程序之间的交接方式。脚本可以用 Python、Perl、Shell 或编译型语言实现。
服务器把请求方法、路径和部分请求头写入环境,把请求体交给子进程的标准输入。子进程在标准输出写入响应字段、一个空行和内容字节。服务器据此构造 HTTP 响应。文件系统和数据库可由脚本按需访问。
读懂历史配置与 Python 版本
Apache 可以用 ScriptAlias 把 URL 前缀映射到允许执行的目录。普通目录则可明确启用 Options +ExecCGI 并用 AddHandler cgi-script 指定后缀。实际目录由站点配置决定。.cgi、.pl、.py 能否执行取决于处理器和部署配置。Apache 2.4 通常使用 Require 指令控制访问。旧版 Order 与 Allow 指令依赖兼容模块。
在类 Unix 主机上,可执行脚本需要正确的解释器路径、执行权限和目录访问权限。chmod 755 是历史示例的权限设置之一,静态 HTML 通常只需服务器可读。本站用 Python 显式启动固定脚本来演示协议,Windows 回环实验没有复现 Apache 或 Unix 权限。
Python 3.11 弃用 cgi 和 cgitb,3.13 从标准库移除。历史 FieldStorage 根据环境和标准输入解析表单。现有代码可迁移到 urllib.parse 解析查询串和 URL 编码表单,受限的 multipart 实验使用 email 解析 MIME 结构。常规 Web 应用使用框架提供的表单、上传和响应接口。调试回溯留在服务器日志,避免把内部路径和环境交给访问者。
验证问候页和请求信息
下载本章自编 Python 源码并在终端运行 python python3-cgi-programming.py,打开终端打印的 127.0.0.1 地址。服务只绑定回环地址,端口由系统分配。按 Ctrl+C 结束服务。程序只执行固定的本站脚本,未知路径返回 404。
打开问候页,浏览器会按 UTF-8 HTML 渲染。CGI 输出中的空行分开字段和正文。访问请求信息页会显示白名单中的请求变量,Cookie 和实际脚本文件路径不回显。REMOTE_HOST 可能未提供,REMOTE_ADDR 表示当前连接的对端,代理、共享网络和地址变更会影响观察值。
所需环境:本地 Python 3 与浏览器
当前源码 SHA256:89cc360b8d7d1b7e5dc53d833bf119fad5f014f915196433139d2c087c74f20f
比较 GET、POST 和四类控件
GET 表单把编码后的字段放进 URL 查询串,适合取回数据。查询串可能出现在历史、书签、日志和某些引用信息里,长度受部署和客户端约束。GET 响应是否缓存由 HTTP 缓存规则和响应字段决定。POST 表单把字段放进请求体,保密要依靠 HTTPS 和服务端妥善处理数据。
在两种表单中输入同一标题和路径,观察 GET URL 带字段、POST URL 不带表单字段。勾选两个同名复选框会送出同一字段的两个值,未勾选则缺键。单选组只发送选中的值,未选时缺键。
文本域提交多行内容,服务端可看到提交时编码的换行。下拉框提交 option 的 value。初始选项和改选后的值不同。空字符串、缺键和重复值分别处理。本站用列表保存同名字段,显示时转义输入。

Cookie 是独立的请求状态
服务器用 Set-Cookie 保存单个名称和值。要设置多个 Cookie,分别发送多个字段。浏览器在匹配域、路径及其它条件的请求中用 Cookie 字段回送一组名称和值,CGI 通过 HTTP_COOKIE 读取。Cookie 可作会话标识的载体,身份和权限仍由服务器验证。
Expires 用 HTTP 日期表达过期时间,Max-Age 用相对秒数。省略 Domain 通常得到仅限当前主机的 Cookie。Path 决定浏览器在哪些路径发送它,不能用来隔离同站脚本。Secure 用于安全连接,HttpOnly 限制脚本读取,SameSite 约束跨站发送。本站回环 HTTP 只演示本机 Cookie,生产部署另需 HTTPS 与会话保护。
先点「读取 Cookie」观察空值,再点「设置 Cookie」,返回后再次读取。实验 Cookie 只适用于 /cgi-bin/,十分钟过期。浏览器存储的不是认证凭据。
上传文件与下载原始字节
上传表单使用 POST 和 multipart/form-data。浏览器生成 boundary,把字段名、文件名、内容类型和字节放入相应部件。本站只接受一个受限大小的文件,把客户端文件名当作显示标签,写入临时文件并读回计算字节数与 SHA-256。空选、错误媒体类型或超限请求会被拒绝。
历史上传代码用客户端文件名拼接路径并一次性读入整个文件。basename 只按当前平台识别分隔符,混用斜杠时要区分显示与落盘策略。新项目应限制尺寸、由服务端选择存储位置和名称,并按实际用途校验类型。
下载通过 Content-Disposition: attachment 提供文件名,Content-Type 标注内容类型,Content-Length 计的是字节数。把 bytes 交给 print 会输出字面表示,二进制响应应写入字节流。点击「下载文本」后,可将下载内容与代码中的 UTF-8 测试数据比较。
CGI 响应字段
| 字段 | 含义与使用条件 |
|---|---|
| Content-Type | 正文的媒体类型及可选字符集。与请求输入的 CONTENT_TYPE 分开。 |
| Expires | HTTP 日期,向缓存提供响应变陈旧的时间。 |
| Location | 配合重定向状态提供目标,也可在对应状态中标识新资源。 |
| Last-Modified | 服务器所知选中表示的最后修改时间,可用于条件请求。 |
| Content-Length | 消息内容的字节数。UTF-8 多字节文字不能按字符个数计算。 |
| Set-Cookie | 每个字段携带一条 Cookie 和可选属性,由用户代理按策略处理。 |
传给 CGI 脚本的请求变量
| 变量 | 读取时的含义 |
|---|---|
| CONTENT_TYPE | 请求体的媒体类型。URL 编码表单和带 boundary 的 multipart 是两种不同格式。 |
| CONTENT_LENGTH | 通过标准输入提供的请求体字节数。空值表示无请求体长度。读取前仍应限制上限。 |
| HTTP_COOKIE | 浏览器本次请求发送的 Cookie。值来自客户端,可能没有该字段。 |
| HTTP_USER_AGENT | 用户代理声明的标识字符串,可省略或伪造。 |
| PATH_INFO | 脚本 URL 之后的附加路径。与查询串和磁盘文件路径分别处理。 |
| QUERY_STRING | 问号后未经表单解码的查询内容。POST 的 URL 同样可以有查询串。 |
| REMOTE_ADDR | 服务器看到的请求对端网络地址,不能当作身份凭据。 |
| REMOTE_HOST | 服务器有时提供的对端主机名。缺省时按没有处理。 |
| REQUEST_METHOD | 请求方法。应用按支持的语义分别处理或拒绝。 |
| SCRIPT_FILENAME | 部分服务器提供的磁盘路径扩展变量。CGI 1.1 不保证存在。 |
| SCRIPT_NAME | 标识脚本的 URL 路径,不含附加 PATH_INFO。 |
| SERVER_NAME | 服务器给 CGI 提供的主机名或地址。 |
| SERVER_SOFTWARE | 服务器软件标识,由网关环境提供。 |
本章自编源码与运行范围
"""蓝色天空网 mbsky.com | Local CGI and form laboratory."""
from contextlib import contextmanager
from email import policy
from email.parser import BytesParser
from hashlib import sha256
from html import escape
from http.cookies import SimpleCookie
from http.server import BaseHTTPRequestHandler, HTTPServer
from pathlib import Path, PurePosixPath
from tempfile import TemporaryFile
from threading import Thread
from urllib.parse import parse_qs, urlsplit
import json
import os
import subprocess
import sys
LIMIT = 64 * 1024
FILE_BYTES = '蓝色天空网\nCGI bytes\n'.encode('utf-8')
ROUTES = {'hello', 'env', 'fields', 'set-cookie', 'cookie', 'upload', 'download', 'redirect'}
ENV_FIELDS = (
'CONTENT_TYPE', 'CONTENT_LENGTH', 'HTTP_COOKIE', 'HTTP_USER_AGENT', 'PATH_INFO',
'QUERY_STRING', 'REMOTE_ADDR', 'REMOTE_HOST', 'REQUEST_METHOD', 'SCRIPT_FILENAME',
'SCRIPT_NAME', 'SERVER_NAME', 'SERVER_SOFTWARE',
)
INDEX = """<!doctype html>
<html lang="zh-CN"><meta charset="utf-8"><title>蓝色天空网 CGI 实验</title>
<main><h1>CGI 表单实验</h1>
<nav><a id="hello" href="/cgi-bin/hello">问候</a> ·
<a id="env" href="/cgi-bin/env/sample">请求信息</a> ·
<a id="set-cookie" href="/cgi-bin/set-cookie">设置 Cookie</a> ·
<a id="cookie" href="/cgi-bin/cookie">读取 Cookie</a> ·
<a id="download" href="/cgi-bin/download">下载文本</a></nav>
<h2>GET 查询</h2>
<form id="get" method="get" action="/cgi-bin/fields">
<label>标题 <input name="label"></label>
<label>路径 <input name="path"></label>
<button>查询</button>
</form>
<h2>POST 表单</h2>
<form id="post" method="post" action="/cgi-bin/fields">
<label>标题 <input name="label"></label>
<label>路径 <input name="path"></label>
<fieldset><legend>提醒方式</legend>
<label><input type="checkbox" name="channels" value="desk">桌面</label>
<label><input type="checkbox" name="channels" value="log">日志</label>
</fieldset>
<fieldset><legend>优先级</legend>
<label><input type="radio" name="priority" value="normal">常规</label>
<label><input type="radio" name="priority" value="urgent">紧急</label>
</fieldset>
<label>备注 <textarea name="notes" rows="3"></textarea></label>
<label>区域 <select name="zone"><option value="north">北区</option>
<option value="south">南区</option></select></label>
<button>发送</button>
</form>
<h2>上传测试文件</h2>
<form id="upload" method="post" enctype="multipart/form-data" action="/cgi-bin/upload">
<label>文件 <input type="file" name="document"></label><button>上传</button>
</form></main></html>"""
def response(title, data):
content = escape(json.dumps(data, ensure_ascii=False, indent=2))
return (f'<!doctype html><html lang="zh-CN"><meta charset="utf-8"><title>{title}</title>'
f'<h1>{title}</h1><pre id="result">{content}</pre><a href="/">返回表单</a></html>').encode('utf-8')
def uploaded_file(content_type, body):
message = BytesParser(policy=policy.default).parsebytes(
b'Content-Type: ' + content_type.encode('ascii') + b'\r\nMIME-Version: 1.0\r\n\r\n' + body
)
if not message.is_multipart() or message.defects:
raise ValueError('Malformed multipart body')
parts = [part for part in message.iter_parts()
if part.get_content_disposition() == 'form-data'
and part.get_param('name', header='content-disposition') == 'document']
if len(parts) != 1 or not parts[0].get_filename():
raise ValueError('Select one file')
part = parts[0]
# Display a label only. Never use a client filename to choose a storage path.
label = PurePosixPath(part.get_filename().replace('\\', '/')).name
payload = part.get_payload(decode=True)
if part.defects or payload is None or label in {'', '.', '..'}:
raise ValueError('Invalid file part')
with TemporaryFile() as scratch:
scratch.write(payload)
scratch.seek(0)
stored = scratch.read()
return {'filename': label, 'bytes': len(stored), 'sha256': sha256(stored).hexdigest()}
def run_cgi(route):
env = os.environ
length = int(env.get('CONTENT_LENGTH') or 0)
if not 0 <= length <= LIMIT:
raise ValueError('Invalid content length')
body = sys.stdin.buffer.read(length)
if len(body) != length:
raise ValueError('Incomplete request body')
headers = [('Content-Type', 'text/html; charset=utf-8')]
status = '200 OK'
method = env['REQUEST_METHOD']
content_type = env.get('CONTENT_TYPE', '')
if route == 'download':
headers = [
('Content-Type', 'text/plain; charset=utf-8'),
('Content-Disposition', 'attachment; filename="cgi-sample.txt"'),
('Last-Modified', 'Mon, 02 Nov 2026 00:00:00 GMT'),
('Expires', 'Tue, 03 Nov 2026 00:00:00 GMT'),
]
content = FILE_BYTES
elif route == 'redirect':
status = '302 Found'
headers.append(('Location', '/cgi-bin/hello'))
content = b''
elif route == 'hello':
content = response('蓝色天空网 CGI', {'message': '问候来自 CGI 子进程'})
elif route == 'env':
visible = {name: env.get(name) for name in ENV_FIELDS if name not in {'HTTP_COOKIE', 'SCRIPT_FILENAME'}}
content = response('当前请求', visible)
elif route == 'set-cookie':
headers.append(('Set-Cookie', 'mbsky_lab=orange; Path=/cgi-bin/; Max-Age=600; HttpOnly; SameSite=Lax'))
headers.append(('Cache-Control', 'no-store'))
content = response('设置实验 Cookie', {'set': True})
elif route == 'cookie':
jar = SimpleCookie()
jar.load(env.get('HTTP_COOKIE', ''))
headers.append(('Cache-Control', 'no-store'))
content = response('读取实验 Cookie', {'cookie': jar['mbsky_lab'].value if 'mbsky_lab' in jar else None})
else:
try:
if route == 'upload':
if method != 'POST' or content_type.split(';', 1)[0].lower() != 'multipart/form-data':
raise ValueError('Upload requires multipart POST')
data = uploaded_file(content_type, body)
elif method == 'POST':
if content_type.split(';', 1)[0].lower() != 'application/x-www-form-urlencoded':
raise ValueError('Expected URL-encoded form')
data = parse_qs(body.decode('ascii'), keep_blank_values=True, max_num_fields=24, errors='strict')
else:
data = parse_qs(env['QUERY_STRING'], keep_blank_values=True, max_num_fields=24, errors='strict')
content = response('表单结果', {'method': method, 'fields': data})
except (ValueError, UnicodeError):
status = '400 Bad Request'
content = response('请求无效', {'error': '检查编码、表单类型与文件选择'})
if status != '200 OK':
headers.insert(0, ('Status', status))
headers.append(('Content-Length', str(len(content))))
lines = [f'{name}: {value}' for name, value in headers]
sys.stdout.buffer.write(('\r\n'.join(lines) + '\r\n\r\n').encode('ascii') + content)
class LocalHandler(BaseHTTPRequestHandler):
def log_message(self, *_):
pass
def send_content(self, status, headers, content):
self.send_response(status)
self.send_header('X-Content-Type-Options', 'nosniff')
self.send_header('Content-Security-Policy', "default-src 'none'; form-action 'self'; base-uri 'none'")
for name, value in headers:
if name.lower() != 'content-length':
self.send_header(name, value)
self.send_header('Content-Length', str(len(content)))
self.end_headers()
self.wfile.write(content)
def do_GET(self):
self.handle_local()
def do_POST(self):
self.handle_local()
def handle_local(self):
self.connection.settimeout(5)
if self.headers.get('Host') != f'127.0.0.1:{self.server.server_port}':
self.send_error(400)
return
target = urlsplit(self.path)
if target.path == '/' and self.command == 'GET':
self.send_content(200, [('Content-Type', 'text/html; charset=utf-8')], INDEX.encode('utf-8'))
return
if not target.path.startswith('/cgi-bin/'):
self.send_error(404)
return
route, divider, suffix = target.path.removeprefix('/cgi-bin/').partition('/')
if route not in ROUTES or (suffix and route != 'env'):
self.send_error(404)
return
if self.command == 'POST' and route not in {'fields', 'upload'}:
self.send_error(405)
return
lengths = self.headers.get_all('Content-Length', [])
if self.headers.get('Transfer-Encoding') or len(lengths) > 1 or (
lengths and (not lengths[0].isascii() or not lengths[0].isdigit() or len(lengths[0]) > 9)
):
self.send_error(400)
return
length = int(lengths[0]) if lengths else 0
if length > LIMIT:
self.send_error(413)
return
body = self.rfile.read(length)
if len(body) != length:
self.send_error(400)
return
script = str(Path(__file__).resolve())
env = {name: os.environ[name] for name in ('SystemRoot', 'TMP', 'TEMP', 'TMPDIR') if name in os.environ}
env.update(
GATEWAY_INTERFACE='CGI/1.1', REQUEST_METHOD=self.command, QUERY_STRING=target.query,
PATH_INFO=divider+suffix, SCRIPT_NAME='/cgi-bin/'+route, SCRIPT_FILENAME=script,
REMOTE_ADDR=self.client_address[0], SERVER_NAME='127.0.0.1', SERVER_SOFTWARE='mbsky-lab',
SERVER_PROTOCOL=self.request_version, SERVER_PORT=str(self.server.server_port),
)
for header, name in (
('Content-Length', 'CONTENT_LENGTH'), ('Content-Type', 'CONTENT_TYPE'),
('Cookie', 'HTTP_COOKIE'), ('User-Agent', 'HTTP_USER_AGENT'),
):
if header in self.headers:
env[name] = self.headers[header]
try:
child = subprocess.run([sys.executable, '-I', '-B', str(script), '--cgi', route],
env=env, input=body, capture_output=True, check=True, timeout=5)
except (subprocess.SubprocessError, OSError):
self.send_error(502)
return
raw_headers, separator, content = child.stdout.partition(b'\r\n\r\n')
if not separator:
self.send_error(502)
return
headers = []
status = 200
for line in raw_headers.decode('ascii').split('\r\n'):
name, value = line.split(': ', 1)
if name == 'Status':
status = int(value.split()[0])
else:
headers.append((name, value))
self.send_content(status, headers, content)
@contextmanager
def local_server():
with HTTPServer(('127.0.0.1', 0), LocalHandler) as server:
worker = Thread(target=server.serve_forever, daemon=True)
worker.start()
try:
yield f'http://127.0.0.1:{server.server_port}'
finally:
server.shutdown()
worker.join()
if __name__ == '__main__':
if len(sys.argv) == 3 and sys.argv[1] == '--cgi' and sys.argv[2] in ROUTES:
run_cgi(sys.argv[2])
else:
with HTTPServer(('127.0.0.1', 0), LocalHandler) as server:
print(f'http://127.0.0.1:{server.server_port}', flush=True)
try:
server.serve_forever()
except KeyboardInterrupt:
pass
所需环境:本地 Python 环境
当前源码 SHA256:89cc360b8d7d1b7e5dc53d833bf119fad5f014f915196433139d2c087c74f20f
当前源码有命名范围的实际运行记录;原文全部事实、其它平台和IDE界面仍待逐项验收。
常见错误与边界
- 命令、源码、当前解释器和具体平台分别核对,不能以单项运行推断整章验收。
练习与解答
使用本站实例修改一个条件,先写下预期,再实际运行。
展开参考解答
比较原始输出、修改后的输出及错误类型;未执行的平台和界面继续单列。