如何在 Django 中很好地获取二进制发布数据?
如果这是一个新手问题,请原谅我,我昨天开始学习 Django,并且我试图不养成坏习惯,即我试图从一开始就以“django 方式”做事。
我有一个将二进制数据作为 http post 字段接收的视图。现在 Django 当然会自动将我的二进制数据转换为 unicode 字符串。
我的问题是,如何获取原始二进制数据?
我发生了一些事情。让 request
为我正在处理的请求。
- 使用
request.raw_post_data
需要再次解析数据 - 当表面上request.POST
实际上存储原始数据时,我实际上只是想绕过即时转换(此外,这是开发版本中的新功能)。 - 使用 base64 左右来传输数据是可行的,但当数据传输本身不是问题时,似乎开销太大。
- 在获取该字段之前(然后重新分配)执行
request.encoding="foo"
也不起作用,因为我仍然得到一个 unicode 字符串,而且感觉有点肮脏。在这里使用"base64"
(不像传输编码那么糟糕)给了我一个断言错误
。
预先感谢您的想法!
编辑: 澄清一下 - 我在这里谈论的不是经典文件上传,而是存储在 POST 字段中的二进制数据。我想这样做,因为我想要与该视图交互的唯一方法是通过上传脚本。在这种情况下,使用普通的 POST 字段会使客户端和服务器变得更加简单。
forgive me if this is a bit of a newbie question, I started to learn Django yesterday, and I'm trying not to get into bad habits, i.e. I am trying to do things "the django way" from the start.
I have a view that recieves binary data as a http post field. Now Django of course autoconverts my binary data to a unicode string.
My question is, how do I just get the raw binary data?
A couple of things occurred to me. Let request
be the request I'm processing.
- Using
request.raw_post_data
would involve parsing the data again - when appearantlyrequest.POST
actually stores raw data and I am actually just trying to get around the on-the-fly conversion (and besides, that is new in the development version). - Using base64 or so to transfer the data would work, but seems like too much overhead when the data transfer itself is not the problem.
- doing
request.encoding="foo"
before getting that field (and reassigning afterwards) doesn't work either because I still get a unicode string, besides feeling like a bit of a dirty hack. Using"base64"
here (not as bad as for the transfer encoding) gives me anAssertionError
.
Thanks in advance for your ideas!
EDIT:
To clarify - I am not talking about a classic file upload here, but as binary data stored in a POST field. I'd like to do it that way because the only way I want to interface with that view is via an upload script. Using a normal POST field makes both the client and the server much simpler in that case.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
有些人可能会说,在某种程度上,将二进制数据存储在标准表单字段中是一个坏习惯:)
您可以使用 Python 的标准库方法将字符串转换回二进制表示形式。
看看 binascii — 在二进制和 ASCI 之间转换
编辑前发布:
这篇文章怎么样代码(从 POST 接收数据)
对我有用。
Some might say that storing binary data in a standard form field is a bad habit in some way :)
You could use standard library methods of Python to convert your string back to a binary representation.
Take a look at binascii — Convert between binary and ASCI
Posting before edit:
What about this piece of code (receiving data from a POST)
Works for me.