【问题标题】:stop django from automatically unicodifing POST stuff阻止 django 自动对 POST 内容进行统一编码
【发布时间】:2026-01-05 01:35:01
【问题描述】:

我将一些数据上传到 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'

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

如何让 django 不统一 POST 变量?或者,如果是,我该如何撤消?

【问题讨论】:

  • 您需要将字节作为字符串还是数字列表?什么是不可接受的 - 或两者兼而有之?
  • @sergzach:它以某种方式将字节字符串解码为 un​​icode 字符串是不可接受的。我传递的是原始字节,而不是字符串。我想要原始字节,而不是原始字节解码成 unicode 字符串。
  • 你能指定完整的视图函数与声明和必要的进口吗?
  • @sergzach:我更新了它以使其成为一个工作功能,但除此之外没什么可看的

标签: django unicode


【解决方案1】:

您可以撤消此操作。

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

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

请在此处查看文档:https://docs.djangoproject.com/en/dev/ref/unicode/#useful-utility-functions

【讨论】:

  • 不,我不希望我的数据采用可读格式 - 我希望数据上传时 - 原始字节。我从一端上传原始字节并在另一端获取 unicode。那张照片有问题。