Sunday, May 8, 2011

How to write a dynamically generated file to a django FileField in App Engine

I was struggling for days with finding a way to associated a dynamically created csv file with an entity in my django-nonrel project on App Engine.  Then answer finally came as I was looking through the code of the storage module of djangoappenine.  Low and behold, there lies the BlobstoreUploadedFile class, which solved my problem.


from __future__ import with_statement
from djangoappengine.storage import BlobstoreUploadedFile
from google.appengine.ext.blobstore import BlobInfo
from google.appengine.api import files

file_name = files.blobstore.create(mime_type='text/csv')
with files.open(file_name, 'a') as f:
    #do stuff to write your file

files.finalize(file_name)
blobFile = BlobstoreUploadedFile(BlobInfo(files.blobstore.get_blob_key(file_name)), charset="utf-8")
device = Device.objects.get(pk=1)
device.cacheFile.save("filename.csv", blobFile)


Updated to include missing import.  Thanks Ezu.