5

我想将 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()

这是回溯:

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 服务器似乎以浏览器在请求标头中指定的任何字符集进行编码。但是,我希望自己拥有这种控制权,因为我怀疑我是否可以期望所有 WSGI 服务器都这样做。我应该怎么做才能返回一个 UTF-8 编码的 HTML 页面?

谢谢!

4

3 回答 3

5

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

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(完整或部分)。

于 2010-01-31T22:32:25.883 回答
0

编辑

vim /usr/lib/python2.7/site.py

encoding = "ascii" # Default value set by _PyUnicode_Init()

encoding = "utf-8"

重启系统

para forcar o python 2.7 a trabalhar com utf-8 como padrão pois o mod_wsgi busca a codificacao padrao do python que antes era ascii com no maximo 128 caracteres!

于 2013-12-19T16:39:10.383 回答
0

AndiDog 的答案是正确的,但在某些环境中,您必须将应用程序更改为应用程序

def application(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]
于 2018-01-11T00:20:23.070 回答