Python 如何在Django中发布压缩字符串并解压缩该字符串?

Python 如何在Django中发布压缩字符串并解压缩该字符串?,python,django,Python,Django,我让服务器使用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" } tr

我让服务器使用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
# 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()
然后我编写了一个测试用例来测试函数,函数的url是“music_main_page”,我的测试代码如下:

# 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
# 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()

程序抛出异常:
准备解压缩数据时出错-2:流状态不一致
,如何修复错误?

我打赌这与编码有关。尝试将您从
请求中获得的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')
... )
(其中
字节到文本
为。)

如果使用浏览器表单而不是脚本,会得到什么


无论如何,也许您不应该以已发布的表单内容发送压缩数据。它是为清晰的unicode文本而设计的,从我所看到的情况来看,这是把事情搞砸的原因


相反,您可以按原样发送压缩字节,然后使用读取数据,然后解压缩。或者,更好的是,设置好服务器端gzip压缩工作。

我只使用这个函数bytes\u to\u text(),然后我就可以解压缩字符串。我不需要调用bytes\u to\u text(),因为它是由Django在访问请求时完成的。POST[“content”]…我把它放在这里只是为了说明提交时表单参数的处理过程。