我让服务器使用django,我想发布一个压缩字符串然后解压缩django中的字符串。我的操作系统是Ubuntu14.04,我的python版本是2.7.6。我的django响应函数如下:
# coding=utf-8
import json
from django.http import HttpResponse
import zlib
def first_page(request):
result = {
"title": u"bye"
}
try:
param = request.POST["content"]
a = param.encode("utf-8")
param = zlib.decompress(a)
result["result"] = param
except Exception, e:
print "error in line 21"
print e
result = json.dumps(result)
response = HttpResponse(result, content_type="application/json")
return response
然后我写了一个测试用例来测试函数,函数的url是“music_main_page”,我的测试代码如下:
# coding=utf-8
__author__ = 'lizhihao'
import zlib
import httplib
import urllib
httpClient = None
try:
a = "hello world! what are you doing!"
a = zlib.compress(a)
params = urllib.urlencode(
{
"content": a
}
)
headers = {
"Content-type": "application/x-www-form-urlencoded",
"Accept": "text/plain"
}
httpClient = httplib.HTTPConnection("localhost", 8000, timeout=30)
httpClient.request("POST", "/music_main_page", params, headers)
response = httpClient.getresponse()
print response.read()
except Exception, e:
print e
finally:
if httpClient:
httpClient.close()
该程序抛出异常:Error -2 while preparing to decompress data: inconsistent stream state
,如何修复错误?
答案 0 :(得分:1)
我打赌它与编码有关。尝试在解压缩之前将从request.POST["content"]
获得的unicode字符串转换为字节字符串(换句话说,执行.encode('latin-1')
而不是.encode('utf-8')
)。
这为我修好了。我太懒了,无法在完整的Django项目中重现你的bug,我用这个来通过近似的请求解析阶段来填充你的字符串:
>>> zlib.decompress(
... bytes_to_text(
... urlparse.parse_qsl(
... urllib.urlencode({"content":
... zlib.compress("hello world! what are you doing!")
... })
... )[0][1].decode('iso-8859-1'), 'utf-8'
... ).encode('utf-8')
... )
(bytes_to_text
为this one。)
如果使用浏览器表单而不是脚本,会得到什么?
但在任何情况下,也许您不应该在POSTed表单内容中发送压缩数据。它用于清晰的unicode文本,这就是我所能看到的东西。
相反,您可以按原样发送压缩字节,然后使用request.body
读取数据然后解压缩。或者,更好的是,进行设置,以便服务器端gzip压缩工作。