How to send compressed string and unpack string in Django?
I am using django server and I want to post a compressed string and then unpack the string in django. My OS is Ubuntu14.04 and my python version is 2.7.6. My django answer function like this:
# 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
Then I write a test case to test the function, the url of the function is "music_main_page", my test code is:
# 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()
The program throws an exception: Error -2 while preparing to decompress data: inconsistent stream state
how to fix the error?
source to share
I'm pretty sure it has to do with the encoding. Try converting the unicode string you are getting from request.POST["content"]
to byte string before decompression (instead of .encode('latin-1')
instead .encode('utf-8')
).
This fixed it for me. I was too lazy to reproduce your error in a full Django project, although I used this to put your line through the example parsing steps:
>>> 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')
... )
(Where is bytes_to_text
this one .
What do you get if you use a browser form instead of a script?
In any case, perhaps you shouldn't be sending compressed data to the content of the POSTed form. Its intended for clear Unicode text, which is something like what I see.
Instead, you can just send the compressed bytes as-is and use request.body
to read the data and then decompress. Or better yet, configure so that server side gzip compression works.
source to share