首页 > python3使用wsgiref时环境变量出现乱码

python3使用wsgiref时环境变量出现乱码

使用python3完成一个简单的wsgi示例,代码如下:

from wsgiref.simple_server import make_server

def application(environ, start_response) :
    print(environ['PATH_INFO'])
    start_response('200 OK', [('Content-Type', 'text/html;charset=utf-8')])
    body = '<h1>Hello, %s!</h1>'%(environ['PATH_INFO'][1:] or 'web')
    return [body.encode('utf-8')]

if __name__ == '__main__':
    httpd = make_server('', 8000, application)
    print('Serving HTTP on port 8000...')
    httpd.serve_forever()

程序正常运行

但是输入中文时就出现了乱码:

后台显示通过environ获取参数时就已经出现乱码了:

请问我应该怎么修复这个问题,让中文正常显示?


病急乱投医,找到了wsgiref.simple_server的源码,在WSGIRequestHandlerget_environ中看到了这么一句话:

env['PATH_INFO'] = urllib.parse.unquote_to_bytes(path).decode('iso-8859-1')

然后抱着试试看的心态修改了一下代码:

def application(environ, start_response) :
    print(environ['PATH_INFO'].encode('iso-8859-1').decode('utf8'))
    start_response('200 OK', [('Content-Type', 'text/html;charset=utf-8')])
    body = '<h1>Hello, %s!</h1>'%(environ['PATH_INFO'].encode('iso-8859-1').decode('utf8')[1:] or 'web')
    return [body.encode('utf-8')]

然后奇迹般地,中文正常显示了。

不过还是不太明白,为什么wsgiref中硬编码iso-8859-1进行编码。

【热门文章】
【热门文章】