Managing the Blobstore with Python

GAE Blobstore is a great way to manage big files. This post is about using the Blogstore with Python and the Django GAE Helper (appengine_django).

Views.py:

  1.  
  2.  
  3. from google.appengine.ext import blobstore
  4. # import other django stuff
  5.  
  6. def show_upload_form(request):
  7. template = "admin_upload_blob.html"
  8. dict = {}
  9. dict['action'] = blobstore.create_upload_url('/admin/upload_blob/')
  10. return render_to_response(template,
  11. context_instance= context.get_context(
  12. dict, request))
  13.  
  14. def upload_blob(request):
  15. try:
  16. uploads = get_uploads(request, 'file')
  17. for upload in uploads:
  18. file = BlobFile(blob=upload)
  19. file.save()
  20. except Exception, e:
  21. return HttpResponseRedirect("/admin")
  22. return HttpResponse("Ok!")
  23.  
  24.  
  25. def get_uploads(request, field_name=None, populate_post=False):
  26. """
  27. http://appengine-cookbook.appspot.com/recipe/blobstore-get_uploads-helper-function-for-django-request/
  28.  
  29. Get uploads sent to this handler.
  30.  
  31. Args:
  32. field_name: Only select uploads that were sent as a specific field.
  33. populate_post: Add the non blob fields to request.POST
  34.  
  35. Returns:
  36. A list of BlobInfo records corresponding to each upload.
  37. Empty list if there are no blob-info records for field_name.
  38. """
  39.  
  40. logging.info(request)
  41. if hasattr(request,'__uploads') == False:
  42. request.META['wsgi.input'].seek(0)
  43. fields = cgi.FieldStorage(request.META['wsgi.input'], environ=request.META)
  44.  
  45. request.__uploads = {}
  46. if populate_post:
  47. request.POST = {}
  48. for key in fields.keys():
  49. field = fields[key]
  50. if isinstance(field, cgi.FieldStorage) and 'blob-key' in field.type_options:
  51. request.__uploads.setdefault(key, []).append(blobstore.parse_blob_info(field))
  52. elif populate_post:
  53. request.POST[key] = field.value
  54.  
  55. if field_name:
  56. try:
  57. return list(request.__uploads[field_name])
  58. except KeyError:
  59. return []
  60. else:
  61. results = []
  62. for uploads in request.__uploads.itervalues():
  63. results += uploads
  64. return results
  65.  

admin_upload_blob.html:

  1.  
  2. {% extends "base.html" %}
  3. {% load i18n %}
  4.  
  5. {% block content %}
  6.  
  7. Upload a big file:
  8.  
  9. <form action="{{ action }}" method="post" enctype="multipart/form-data">
  10. Upload File: <input type="file" name="my_file"><br>
  11. <input type="submit" name="submit" value="Submit"> </form>
  12. {% endblock content %}
  13.  

Make sure urls.py contains the methods in views.py as usual.
Just access show_upload_form with your browser and upload a file. It works!

Enjoyed reading this post?
Subscribe to the RSS feed and have all new posts delivered straight to you.
  • http://www.fitnessmodels.info top fitness models

    I actually need to demonstrate this specific to the trainees and check out what exactly they think concerning this.

  • http://www.wuselrob.de Robert

    First sample I found, that actually works!
    Is there a sample of how to get the uploaded files and show them to the user? uploaded images for example.

    Thank you.

  • http://ghostrecon.za.pl/profile.php?mode=viewprofile&u=17343 alexander wang donna hobo bag

    Pretty section of content. I just stumbled upon your web site and in accession capital to assert that I acquire actually enjoyed account your blog posts. Anyway I’ll be subscribing to your augment and even I achievement you access consistently rapidly.

  • ChrisH

    I’m finding “BlobFile” undefined…..

    def upload_blob(request):
    try:
    uploads = get_uploads(request, ‘file’)
    for upload in uploads:
    file = BlobFile(blob=upload)

  • http://www.carlosble.com Carlos Ble

    Hi,
    Please notice that this post is quite old. I haven’t used this snippet in almost 2 years. Things might have changed since then.

  • Pranjal Mittal

    I tried that it works pretty well for uploading single files.
    However the get_uploads() handler does not work for multiple files.

    It gives the error -> list’ object has no attribute ‘value’
    at the following line -> request.POST[key] = field.value

  • Pingback: GAE - Reading a big CSV blobstore in python • The Developer World Is Yours()

  • Shirlene Spillane

    Simply amazing article! Has anyone ever wondered how to fill out forms online? I have, and found a simple service. Try PDFfiller to fill a form here http://goo.gl/JqR0sd. It allows you to to fill out PDF files.