python3.x - python3使用wsgiref时环境变量出现乱码
本文介绍了python3.x - 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
的源码,在WSGIRequestHandler
的get_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
进行编码。
这篇关于python3.x - python3使用wsgiref时环境变量出现乱码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文