ralokt
ralokt

Reputation: 1925

How to get binary post data in Django !nicely?

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.

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.

Upvotes: 4

Views: 7809

Answers (1)

Henrik P. Hessel
Henrik P. Hessel

Reputation: 36627

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.

Upvotes: 4

Related Questions