Discuss / Python / 按照示例的编码,英文输入没问题,但是中文就出现乱码。如下解决

按照示例的编码,英文输入没问题,但是中文就出现乱码。如下解决

Topic source

根据同学的回复,找到编码如下:

#hello.py

def application(environ, start_response):

    print(environ['PATH_INFO'].encode('iso-8859-1').decode('utf-8'))

    start_response('200 OK',[('Content-Type','text/html; charset=utf-8')])

    body = '<h1>Hello,%s!</h1>' % ((environ['PATH_INFO'].encode('iso-8859-1').decode('utf-8'))[1:] or 'web')

    return [body.encode('utf-8')]

上述代码,就可以输入中英文混杂,如:http://localhost:8000/你好daxiu,运行正常。

原因就是

WSGIRequestHandlerget_environ中有如下代码

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

说明原来用到iso-8859-1来编码的。

廖雪峰

#2 Created at ... [Delete] [Delete and Lock User]

path你必须用urlencode编码,直接utf8或者gbk都是违反http规范的


  • 1

Reply