开发者

How to get binary post data in Django !nicely?

开发者 https://www.devze.com 2023-01-31 09:37 出处:网络
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.

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 appearantly request.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 o开发者_Python百科r 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 an AssertionError.

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.


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)

def handleFile(self, request):
    file = request.FILES["file"]
    destination = open('filename.ext', 'wb')
        for chunk in file.chunks():
            destination.write(chunk)
    destination.close()

Works for me.

0

精彩评论

暂无评论...
验证码 换一张
取 消