Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

File handling in Django when posting image from service call

I am using PyAMF to transfer a dynamically generated large image from Flex to Django. On the Django side i receive the encodedb64 data as a parameter:

My Item model as an imagefield. What i have trouble to do is saving the data as the File Django Field.

def save_item(request, uname, data):
    """ Save a new item """    
    item = Item()

    img = cStringIO.StringIO()
    img.write(base64.b64decode(data))
    myFile = File(img)

   item.preview.save('fakename.jpg', myFile, save=False)

That would not work because my File object from StringIO misses some properties such as mode, name etc.

I also think that using StringIO will load the image data completely in memory which is bad so i may just give up on the AMF for this particular case and use POST.

What do you think ?

like image 548
coulix Avatar asked Mar 15 '09 14:03

coulix


1 Answers

In django.core.files.base you can find the class ContentFile. That class extends the basic Django File class, so you do not need StringIO (which ContentFile though uses internally). The modified save method looks like this:

from django.core.files.base import ContentFile
def save_item(request, uname, data):
    item = Item()
    myFile = ContentFile(base64.b64decode(data))
    item.preview.save('fakename.jpg', myFile, save=False)
like image 51
Guðmundur H Avatar answered Oct 17 '22 16:10

Guðmundur H