如何在WSGI的application方法中获取并返回environ字典内容
WSGI返回environ内容的正确实现
核心错误原因
你之前的尝试失败主要是两个问题:
- Python3中字符串转字节流必须指定编码,直接调用
bytes(字符串)不传编码参数会触发报错 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
相关产品推荐
相关产品推荐

