gpt4 book ai didi

python - 如何以 UTF-8 编码 WSGI 输出?

转载 作者:太空狗 更新时间:2023-10-30 02:50:32 24 4
gpt4 key购买 nike

我想向网络浏览器发送一个编码为 UTF-8 的 HTML 页面。但是以下示例失败了:

from wsgiref.simple_server import make_server

def app(environ, start_response):
output = "<html><body><p>Räksmörgås</p></body></html>".encode('utf-8')
start_response('200 OK', [
('Content-Type', 'text/html'),
('Content-Length', str(len(output))),
])
return output

port = 8000
httpd = make_server('', port, app)
print("Serving on", port)
httpd.serve_forever()

这是回溯:

Serving on 8000
Traceback (most recent call last):
File "/Library/Frameworks/Python.framework/Versions/3.1/lib/python3.1/wsgiref/handlers.py", line 75, in run
self.finish_response()
File "/Library/Frameworks/Python.framework/Versions/3.1/lib/python3.1/wsgiref/handlers.py", line 116, in finish_response
self.write(data)
File "/Library/Frameworks/Python.framework/Versions/3.1/lib/python3.1/wsgiref/handlers.py", line 202, in write
"write() argument must be a string or bytes"

如果我删除编码并简单地返回 python 3 unicode 字符串,wsgiref 服务器似乎使用浏览器在请求 header 中指定的任何字符集进行编码。但是我想自己控制这个,因为我怀疑我能否期望所有 WSGI 服务器都做同样的事情。我应该怎么做才能返回 UTF-8 编码的 HTML 页面?

谢谢!

最佳答案

您需要将页面作为列表返回:

def app(environ, start_response):
output = "<html><body><p>Räksmörgås</p></body></html>".encode('utf-8')
start_response('200 OK', [
('Content-Type', 'text/html; charset=utf-8'),
('Content-Length', str(len(output)))
])

return [output]

WSGI 就是这样设计的,因此您可以yield HTML(完整的或部分的)。

关于python - 如何以 UTF-8 编码 WSGI 输出?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2173592/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com