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获取参数时就已经出现乱码了:

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

阅读 4.8k
1 个回答

病急乱投医,找到了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进行编码。

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进