我正在尝试使用 gunicorn 发送一个 utf-8 编码的字符串,这是 bz2 压缩的结果,作为对 get 请求的响应。
这是我在 gunicorn 服务器端的代码:
def app(environ, start_response):
data = "Hello, World!" * 10
compressed_data = bz2.compress(data)
start_response("200 OK", [("Content-Type", "text/plain"),
('charset', 'utf-8'),
("Content-Length", str(len(compressed_data))),
('Access-Control-Allow-Headers', '*'),
('Access-Control-Allow-Origin', '*'),
# ('Content-Transfer-Encoding', 'BASE64'),
])
return iter([compressed_data])
当我尝试使用这样的 Python 请求包从客户端获取请求时
import bz2
import requests
res = requests.get('http://127.0.0.1:8000')
bz2.decompress(res.text)
它引发了一个异常
UnicodeEncodeError: 'ascii' codec can't encode character u'\xab' in position 11: ordinal not in range(128)
说响应不能被解码 尝试打印响应文本时
print(res.text)
>>u'BZh91AY&SYy\xabm\x99\x00\x00\x13\x97\x80`\x04\x00@\x00\x80\x06\x04\x90\x00 \x00\xa5P\xd0\xda\x10\x03\x0e\xd3\xd4\xdai4\x9bO\x93\x13\x13\xc2b~\x9c\x17rE8P\x90y\xabm\x99'
打印编码文本时
import bz2
print(bz2.compress("Hello, World!" * 10))
>> 'BZh91AY&SYy\xabm\x99\x00\x00\x13\x97\x80`\x04\x00@\x00\x80\x06\x04\x90\x00 \x00\xa5P\xd0\xda\x10\x03\x0e\xd3\xd4\xdai4\x9bO\x93\x13\x13\xc2b~\x9c\x17rE8P\x90y\xabm\x99'
唯一的区别是 unicode 符号,我通过调整客户端的数据使响应字符串可解码来解决这个问题,但我想知道如何在服务器端解决这个问题?
请您参考如下方法:
问题是字符串以 unicode 形式出现。您不应尝试将 bz2 压缩数据解释为文本。
参见 request docs关于如何将数据解释为原始数据而不是文本:
res.content # not res.text
此外,数据不应首先作为 text/plain 发送。 BZ2 压缩数据不是文本,应作为 application/octet-stream(即字节流)发送。
将文本重新解释为字节流的快速破解(由于默认的 ascii 编解码器无法处理 0-127 范围之外的字节,我们使用 ISO-8859-1 对数据进行编码。
>>> text = u'BZh91AY&SYy\xabm\x99\x00\x00\x13\x97\x80`\x04\x00@\x00\x80\x06\x04\x90\x00 \x00 \xa5P\xd0\xda\x10\x03\x0e\xd3\xd4\xdai4\x9bO\x93\x13\x13\xc2b~\x9c\x17rE8P\x90y\xabm\x99'
>>> byte_string = text.encode('ISO-8859-1')
>>> byte_string
'BZh91AY&SYy\xabm\x99\x00\x00\x13\x97\x80`\x04\x00@\x00\x80\x06\x04\x90\x00 \x00 \xa5P\xd0\xda\x10\x03\x0e\xd3\xd4\xdai4\x9bO\x93\x13\x13\xc2b~\x9c\x17rE8P\x90y\xabm\x99'
>>> bz2.decompress(byte_string)
'Hello, World!Hello, World!Hello, World!Hello, World!Hello, World!Hello, World!Hello, World!Hello, World!Hello, World!Hello, World!'
但理想情况下,您应该修复数据类型。
