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

如何在WSGI的application方法中获取并返回environ字典内容

WSGI返回environ内容的正确实现

核心错误原因

你之前的尝试失败主要是两个问题:

  1. Python3中字符串转字节流必须指定编码,直接调用bytes(字符串)不传编码参数会触发报错
  2. environ字典中包含TextIOWrapper这类不可直接JSON序列化的非基础类型对象,直接调用json.dumps会失败

方案1:返回纯文本格式的environ

def application(environ, start_response):
    status = '200 OK'
    # 先把environ转为字符串,再编码为utf-8字节流
    output = str(environ).encode('utf-8')

    response_headers = [
        ('Content-type', 'text/plain; charset=utf-8'),
        ('Content-Length', str(len(output))),
        ('X-Clacks-Overhead', 'GNU Terry Pratchett')
    ]

    start_response(status, response_headers)
    return [output]

方案2:返回格式化的JSON格式environ

import json

def application(environ, start_response):
    status = '200 OK'
    # default参数指定:遇到不可序列化的对象时自动转为字符串
    json_content = json.dumps(environ, default=lambda val: str(val), indent=2, ensure_ascii=False)
    output = json_content.encode('utf-8')

    response_headers = [
        ('Content-type', 'application/json; charset=utf-8'),
        ('Content-Length', str(len(output))),
        ('X-Clacks-Overhead', 'GNU Terry Pratchett')
    ]

    start_response(status, response_headers)
    return [output]

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 18:54:03