You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何读取WSGI start_response设置的响应头

如何读取WSGI start_response设置的响应头

WSGI标准里的start_response本身并不提供直接访问已设置响应头的接口——它的核心作用是将状态码和头信息传递给WSGI服务器,由服务器负责存储并在后续时机发送。要获取这些信息,有两种可行的方式:

方法1:包装start_response函数捕获头信息

这是跨WSGI服务器通用的方案,通过自定义包装函数拦截start_response的调用,记录状态码和响应头:

from wsgiref.simple_server import make_server

def hello_world_app(environ, start_response):
    # 初始化变量用于存储捕获到的响应数据
    captured_status = None
    captured_headers = None

    def wrapped_start_response(status, headers, exc_info=None):
        nonlocal captured_status, captured_headers
        # 记录状态码和响应头(转成字典更易访问)
        captured_status = status
        captured_headers = dict(headers)
        # 调用原始的start_response函数
        return start_response(status, headers, exc_info)

    status = "200 OK"
    headers = [("Content-type", "text/plain; charset=utf-8"), ("X-Custom-Header", "demo-value")]
    wrapped_start_response(status, headers)
    
    # 此处可直接访问已捕获的响应头
    print(f"捕获的状态码: {captured_status}")
    print(f"捕获的响应头: {captured_headers}")
    return [b"Hello world"]

with make_server("", 8000, hello_world_app) as httpd:
    print("Serving on port 8000...")
    httpd.serve_forever()

方法2:访问wsgiref服务器的内部存储(仅调试用)

如果你使用的是wsgiref.simple_server这类参考实现,可以通过自定义请求处理器查看服务器内部存储的响应头,但这属于特定实现细节,生产环境不建议依赖:

from wsgiref.simple_server import make_server, WSGIRequestHandler

class DebugRequestHandler(WSGIRequestHandler):
    def finish_response(self):
        # 在响应发送前打印服务器存储的响应头
        print(f"服务器存储的响应头: {dict(self.headers.items())}")
        super().finish_response()

def hello_world_app(environ, start_response):
    status = "200 OK"
    headers = [("Content-type", "text/plain; charset=utf-8")]
    start_response(status, headers)
    return [b"Hello world"]

with make_server("", 8000, hello_world_app, handler_class=DebugRequestHandler) as httpd:
    print("Serving on port 8000...")
    httpd.serve_forever()

注意事项

  • 优先使用包装start_response的方案,这符合WSGI规范,适配所有WSGI服务器。
  • 不要依赖特定服务器的内部属性,不同服务器(如uWSGI、Gunicorn)的存储实现差异极大,这类代码不具备通用性。

内容的提问来源于stack exchange,提问作者NickC

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.18 21:19:58