CGI 编程、HTTP 表单与历史迁移
观察浏览器请求、服务器与 CGI 子进程的交接,以及表单、Cookie 和文件的字节行为。
学完这一章,你能够
- 观察浏览器请求、服务器与 CGI 子进程的交接,以及表单、Cookie 和文件的字节行为。
从 URL 到子进程
浏览器把方法、路径和头字段发给服务器。服务器可以返回静态内容、调用配置好的 CGI 程序,或生成错误响应。CGI 规定这层交接,脚本可用 Python、Perl、Shell 或其他可执行程序实现。
网关通过环境提供请求元数据,通过 stdin 传送请求体。子进程向 stdout 写响应字段,以空行分隔正文。网关再把状态、字段和正文作为 HTTP 响应交给浏览器。CGI 程序可按需访问数据库和文件系统。
历史服务器配置和运行边界
在 Apache 2.4 中可用 ScriptAlias 指定 CGI URL 前缀和目录。普通目录可以按配置启用 ExecCGI 和 cgi-script 处理器,脚本后缀与目录由站点决定。Order 和 Allow 是旧的兼容配置,现代访问控制通常用 Require。
Unix 的 shebang、文件执行位和目录访问权限各有作用。chmod 755 只是历史示例的一种模式。静态 HTML 不需要以 CGI 脚本执行。本站下载包的网关只监听 127.0.0.1,由解释器启动固定源码。
cgi 和 cgitb 在 Python 3.11 被弃用,3.13 已移除。Python 2.7 代码中的 Cookie 模块在现代可改用 http.cookies。本站提供 3.12 的独立历史解析探针,以及可在现代解释器运行的本地回环网关。
问候页、环境和表单编码
解压工程,运行 python gateway.py,打开终端给出的回环地址。问候页可看到脚本返回的 UTF-8 文本,请求信息页只显示指定字段。退出终端服务可用 Ctrl+C。
GET 表单把数据放进查询串,适合读取数据。查询串可能出现在浏览历史、日志和书签中。缓存按 HTTP 的请求、响应和部署规则决定。POST 把表单字段放到请求体,HTTPS 和服务端的保密措施仍然必要。
在两种表单提交同一标题和路径,比较地址栏和结果。空值与缺键分开,重复名称要保留为列表。旧 FieldStorage 的 getvalue 可能是单个值也可能是列表,getfirst、getlist 可明确选择。生产环境避免回显内部路径或整个进程环境。
四种控件的有效值
选中多个同名复选框时可提交多个值,不勾选时没有该键。单选控件通过同名分组提交选中的一个值,整组未选时也缺键。
文本域用于多行内容,浏览器提交表单时可将换行规范化为 CRLF。下拉框提交所选 option 的 value。测试默认选项,再切换后提交一次。本站表单把用户值转义后显示。
Cookie 的发送、作用域与读取
每个 Set-Cookie 字段设置一条 Cookie。浏览器按域、路径等规则保存并在后续匹配请求中发送 Cookie。CGI 从 HTTP_COOKIE 读取它。会话身份仍由服务端验证,实验值不用于认证。
Expires 是 HTTP 日期,Max-Age 是相对秒数。省略 Domain 时通常仅当前主机可用,Path 决定发送范围。Secure、HttpOnly、SameSite 控制不同边界。实验用回环 HTTP 核对路径和回传,生产配置另按 HTTPS 与会话要求设置。
先读 Cookie,再点设置并返回,重新读取即可对照是否收到练习值。两个 Cookie 的设置需要两条响应字段,不能用分号拼成一个设置字段。
上传与下载的字节
上传需要 multipart/form-data。客户端生成 boundary,文件名与文件内容是不同字段。本站只接收受限大小的单文件,在临时文件读回核对字节数和 SHA-256。缺文件或类型错误返回错误。
历史代码把客户端文件名拼到路径里。basename 对不同操作系统的分隔符规则不同。本站把名字只作显示标签,保存位置由服务端选择,处理内容后清理临时文件。
下载响应使用 Content-Disposition 指定附件名,并用 Content-Type 标明媒体类型。Content-Length 按正文实际字节数计算。通过二进制流原样写出,可以保留中文 UTF-8 和换行。
响应头字段
| 名称 | 用途 | 版本或核对条件 |
| Content-Type | 标明响应正文的媒体类型,可带字符集。 | 用真实回环响应核对 UTF-8 HTML 和文本下载,和请求的 CONTENT_TYPE 分开。 |
| Expires | 向缓存提供过期的 HTTP 日期。 | 实验下载响应有固定值,只核对字段和时间顺序。 |
| Location | 给出资源位置,例如重定向的目标 URI。 | 观察 302 响应的相对目标,再对该地址取回问候页。 |
| Last-Modified | 描述所选表示的最后修改时间。 | 固定实验值可解析为 HTTP 日期,条件缓存命中另验。 |
| Content-Length | 消息正文的字节数。 | 按实际 UTF-8 字节数核对,不能按字符数。 |
| Set-Cookie | 一个响应字段设置一个 Cookie 及属性。 | 检查字段里的值、路径、有效期和标志,并用浏览器回传同一项。 |
CGI 请求环境变量
| 名称 | 用途 | 版本或核对条件 |
| CONTENT_TYPE | 请求体的媒体类型。 | 对比 URL 编码请求与 multipart 请求,后者还带 boundary。 |
| CONTENT_LENGTH | 交给标准输入的请求体字节数,未提供时可为空。 | 按请求体实际大小读取,先校验格式和上限。 |
| HTTP_COOKIE | 用户代理在本请求中发送的 Cookie 头。 | 可能没有该字段。实验仅解析固定的练习 Cookie。 |
| HTTP_USER_AGENT | 客户端提供的 User-Agent。 | 值可省略或自定义,不能当成身份凭据。 |
| PATH_INFO | 脚本名之后的附加 URL 路径。 | 检查样例后缀与脚本路径分开。 |
| QUERY_STRING | 问号之后的原始查询串。 | GET 表单写入此处,POST 的 URL 也可以带查询串。 |
| REMOTE_ADDR | 网关看到的请求对端网络地址。 | 回环演示为 127.0.0.1。代理、共享网络和变化地址会影响其含义。 |
| REMOTE_HOST | 若服务器提供,则是对端主机名。 | 缺值按缺失处理,不能假定每个部署都解析。 |
| REQUEST_METHOD | 当前请求使用的方法。 | GET 和 POST 的表单取值来源不同,服务可拒绝不支持的方法。 |
| SCRIPT_FILENAME | 部分网关的实现扩展,表示脚本磁盘路径。 | CGI/1.1 不要求此变量,演示不向客户端回显它。 |
| SCRIPT_NAME | 脚本在 URL 中的路径部分。 | 不包含 PATH_INFO 和查询串。 |
| SERVER_NAME | 网关提供的服务器主机名或地址。 | 本实验只允许固定回环地址。 |
| SERVER_SOFTWARE | 网关提供的服务器软件标识。 | 实验标识与真实 Apache 部署分开。 |
运行回环 CGI 表单、Cookie、上传与下载
展开查看收起
"""蓝色天空网 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 3.12 历史 FieldStorage 输入探针
展开查看收起
"""Bounded CGI input probe for the CPython 3.12 legacy FieldStorage implementation."""
import cgi
import hashlib
import json
import os
import sys
settings = json.loads(sys.argv[1])
form = cgi.FieldStorage(environ=settings, fp=sys.stdin.buffer,
keep_blank_values=settings.get("MBSKY_KEEP") == "1", encoding="utf-8")
value = form.getvalue("tag")
fields = {
"names": sorted(form.keys()),
"tag_value": value,
"tag_first": form.getfirst("tag"),
"tag_all": form.getlist("tag"),
"blank": form.getfirst("blank", "absent"),
"missing": form.getlist("absent"),
}
if "upload" in form:
upload = form["upload"]
received = upload.file.read()
fields["upload"] = [upload.filename, len(received), hashlib.sha256(received).hexdigest()]
body = json.dumps(fields, ensure_ascii=False).encode("utf-8")
headers = [b"Status: 200 OK", b"Content-Type: application/json; charset=utf-8",
b"Content-Length: " + str(len(body)).encode("ascii")]
sys.stdout.buffer.write(b"\r\n".join(headers) + b"\r\n\r\n" + body)
查看独立实例 ↗ 在独立页面查看源码、运行环境与工程包
CGI 实验工程下载
本章附件与实例包
常见错误与边界检查
- 核对目标解释器版本、环境条件和输入后,再比较实际输出。
技术规范与官方资料
练习与参考解答
查看参考解答
单选字段缺键,复选字段保留两值。先分清缺键、空串和列表,再按字段的协议决定读取方式。