美文网首页
python3 wsgi服务和响应数据中文乱码问题

python3 wsgi服务和响应数据中文乱码问题

作者: 牛奶大泡芙 | 来源:发表于2020-08-05 17:47 被阅读0次

背景:WSGI是一个协议,或者标准,用来描述Server与Framework之间的通信接口。Flask、Django、web.py等等符合WSGI标准。
项目中,需要两个服务间互相调用,为了方便就在本地启动了wsgi服务,想要从服务端返回纯文本数据,发现会导致中文乱码,如下图所示,分别是response,type(response),response.text


响应数据.png

应该在response_headers的Content-Type中增加charset:utf-8的字符集规定,请求和服务代码如下:

# http请求代码
import requests
url = 'http://127.0.0.1:8080/'
target_value = "这是要发送的数据,target的value"
data = '{"target":"%s"}' % target_value
res = requests.post(url=url, data=data)
print(res, type(res), res.text)


# wsgi服务端代码
from wsgiref.simple_server import make_server
def application(environ, start_response):
    request_body_size = int(environ.get('CONTENT_LENGTH', 0))
    request_body = environ['wsgi.input'].read(request_body_size)
    a = json.loads(request_body)
    target = str(a['target'])
    response_data = someFunc(target)
    response_body = "%s" % response_data
    status = '200 OK'
    response_headers = [('Content-Type','text/plain;charset:utf-8'),('Content-Length',str(len(response_body)))]
    start_response(status, response_headers)
    return [response_headers.encode('utf-8')]

相关文章

网友评论

      本文标题:python3 wsgi服务和响应数据中文乱码问题

      本文链接:https://www.haomeiwen.com/subject/rlyorktx.html