蓝色天空.知识 · 实践 · 创造
我的收藏
在线代码实验室

运行回环 CGI 表单、Cookie、上传与下载

PYTHON本地 Python 3.12 与浏览器,监听 127.0.0.1gateway.py
gateway.py265 行
"""蓝色天空网 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 与浏览器,监听 127.0.0.1 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程

运行环境:本地 Python 3.12 与浏览器,监听 127.0.0.1

入口文件:projects/python-legacy-lab/legacy-cgi-lab/gateway.py

本地运行步骤快速上手
  1. 点击上方“保存源码”保存为 gateway.py,或下载右侧课程工程包。
  2. 确认本地已准备 本地 Python 3.12 与浏览器,监听 127.0.0.1。
  3. 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载

下载课程关联工程包:Python2.x

课程关联工程包(登记关联44章) · 含当前章节或实例 · mbskycom202611a446.zip

下载课程关联工程包:Python2.x

课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202611a447.zip
SITE SEARCH

搜索教程、工具与资讯

热门搜索

JavaScriptJSON格式化正则表达式AI 编程AI 翻译AI导航专题标签
Esc 关闭

欢迎登录蓝色天空网

使用会员账号,继续你的学习