停止django自动unicodifing POST的东西

时间:2011-12-23 23:27:12

标签: django unicode

我将一些数据上传到django视图。客户端:

from poster.encode import multipart_encode

def upload_data(upload_url, data, filename):
    print "Uploading %d bytes to server, file=%s..." % (len(data), filename)

    datagen, headers = multipart_encode({filename: data})

    request = urllib2.Request(upload_url, datagen, headers)
    # Actually do the request, and get the response
    try:
        resp_f = urllib2.urlopen(request, timeout=120)
    except urllib2.URLError:
        return None

    res = resp_f.read()
    resp_f.close()
    return res

#...

def foo(self, event_dicts_td):
    event_dicts_td_json = json.dumps(event_dicts_td)
    res = upload_data(self.upload_url, event_dicts_td_json.encode('utf8').encode('zlib'), "event_dicts_td.json.gz")

观点:

def my_view(request):
    event_dicts_td_json_gz = request.POST.get('event_dicts_td.json.gz')
    if not event_dicts_td_json_gz:
        return HttpResponse("fail")

    print type(event_dicts_td_json_gz), repr(event_dicts_td_json_gz[:10])
    event_dicts_td_json_gz = event_dicts_td_json_gz.encode("utf8")
    print type(event_dicts_td_json_gz), repr(event_dicts_td_json_gz[:10])

    event_dicts_td_json = event_dicts_td_json_gz.decode("zlib").decode("utf8")

    return HttpResponse("it still failed")

输出:

<type 'unicode'> u'x\ufffd\ufffd]s\ufffd\u0192\ufffd\ufffd\n'
<type 'str'> 'x\xef\xbf\xbd\xef\xbf\xbd]s\xef'

这是不可接受的。我只需要原始字节。我没有上传unicode - 我正在上传原始字节 - 我想要那些原始字节。我不知道它是如何尝试将其解码为unicode - 显然不使用utf8导致zlib无法解压缩数据。 (即使我在zlibbing-it之前没有尝试.encode("utf8"),也无法解压缩它,这只是一个测试。)

如何让django不对POST变量进行unicodify?或者,如果是,我该如何撤消它?

1 个答案:

答案 0 :(得分:0)

您可以撤消此操作。

尝试使用 django.utils.encoding 中的* smart_str *:

from django.utils.encoding import smart_str    
event_dicts_td_json_gz = smart_str( event_dicts_td_json_gz )

请在此处查看文档:{​​{3}}