如何将WSGI输出编码为UTF-8?

5 投票
3 回答
5744 浏览
提问于 2025-04-15 18:42

我想把一个HTML页面以UTF-8编码发送到网页浏览器。但是下面这个例子出错了:

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页面呢?

谢谢!

3 个回答

0

编辑

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

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

encoding = "utf-8"

重启系统

这段话是说要强制让 Python 2.7 使用 UTF-8 作为默认编码,因为之前 Python 的默认编码是 ASCII,只能处理最多 128 个字符!

1

AndiDog的回答是对的,但在某些环境下,你需要把“app”改成“application”。

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]
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(Web Server Gateway Interface)就是这样设计的,这样你就可以直接用 yield 来输出HTML内容(可以是完整的,也可以是分部分输出)。

撰写回答