pth*_*lin 4 python wsgi wsgiref python-3.x
我想将HTML页面发送到编码为UTF-8的Web浏览器.但是,以下示例失败:
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()
Run Code Online (Sandbox Code Playgroud)
这是追溯:
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"
Run Code Online (Sandbox Code Playgroud)
如果我删除编码并简单地返回python 3 unicode字符串,wsgiref服务器似乎编码在浏览器在请求标头中指定的任何字符集中.但是我想自己拥有这个控件,因为我怀疑我可以期待所有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]
Run Code Online (Sandbox Code Playgroud)
WSGI的设计方式使您可以只yield使用HTML(完整或部分).
| 归档时间: |
|
| 查看次数: |
4512 次 |
| 最近记录: |