我试图使用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请求包从客户端获取请求时
^{pr2}$这是一个例外
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符号,我通过调整客户端的数据以使响应字符串可解码来解决这个问题,但是我想知道如何在服务器端解决这个问题?在
不能将bzip2压缩数据作为utf-8发送。它是二进制数据,不是文本。在
如果您的http客户端接受bzip2内容编码(^{} is not standard ),那么您可以发送使用bzip2压缩的utf-8编码文本:
示例
未压缩响应:
^{pr2}$如果客户端指定接受bzip2,则bzip2压缩响应:
下面是使用
requests
库的相应http客户端:输出
否则(没有非标准的接受编码),您应该以
application/octet-stream
作为@icedtrees suggested发送数据:示例
bzcat
接受bzip2内容:由于终端使用utf-8编码,所以数据显示正确。在
问题是字符串以unicode的形式出现。您不应该尝试将bz2压缩数据解释为文本。在
有关如何将数据解释为原始数据而不是文本,请参见request docs:
此外,首先不应将数据作为
text/plain
发送。BZ2压缩数据不是文本,应该作为application/octet-stream
(即字节流)发送。在快速破解将文本重新解释为字节流(因为默认的ascii编解码器无法处理0-127范围之外的字节,所以我们使用
^{pr2}$ISO-8859-1
对数据进行编码。在但理想情况下,您应该修复您的数据类型。在
相关问题 更多 >
编程相关推荐