Skip to content
Swizec Teller - a geek with a

Programatically uploading to blobstore in python

Officially this is something that cannot be done. Or rather that shouldn't be done. When you look at the google appengine docs on "uploading to blobstore" this is what they have to say:

Blobs are useful for serving large files, such as video or image files, and for allowing users to upload large data files.

To prompt a user to upload a Blobstore value, your app presents a web form with a file upload field.

So ok, obviously the official documentation isn't of much use here since it only talks about letting users upload files. But I needed something different. I needed to fetch an image from an url (gotten by intricate means, different story) and store it in the blobstore so it could later be served to many users. Obviously since file access isn't permitted on appengine the only choice left was storing the file in the blobstore.

Naturally someone else has had this problem before right?

No. There are no solutions I could find online. None. Nada. Zilch. Niente.

After a few hours of hacking a week or so ago, however, I got it working.

Essentially the solution is to fake a form post to the blobstore url the API creates. An interesting gotcha is that a redirect happens. Initially I thought I was making the form post right back to my application, but apparently you're first posting to the blobstore, then the blobstore posts back to you. For some reason I couldn't keep the associated meta-data to go through with the request so there's an ugly-ish workaround that happens.

Another thing that's important to note for this tutorial/howto is that I am using django-nonrel and that the initial event that starts the process is triggered by appengine's task queue.

The howto

First, these are all the imports I'm using, there's quite a few, so heh :)

from django.http import HttpResponse, HttpResponseBadRequest, HttpRequest
from django.views.decorators.csrf import csrf_exempt
from django.conf import settings
from django.core.urlresolvers import reverse
import simplejson as json
import urllib2, urllib
from cStringIO import StringIO
from google.appengine.api.urlfetch import ResponseTooLargeError, DownloadError
from google.appengine.ext import blobstore
from google.appengine.api import urlfetch
from forms import ArticleProcForm
from models import Article
from lib import ImageExtractor
from lib import urllib2_file
from lib.urllib2_file import UploadFile
from lib.decorators import form_valid

First thing that you're going to need is the function that starts the whole process (in my case this is a django view)

class ArticleProcForm(forms.Form):
article = forms.IntegerField(required=True)
@form_valid(ArticleProcForm, 'POST')
def article(request):
article = Article.objects.get(id=request.form.cleaned_data['article'])
except Article.DoesNotExist:
return HttpResponse(json.dumps({'status': 'Bad Article'}))
image_url = ImageExtractor.getImages(article.url)[0]['url']
except IndexError:
# important bit
image = StringIO(urllib2.urlopen(image_url).read())
except (urllib2.HTTPError, DownloadError):
image = UploadFile(image, '.'.join([str(, image_url.rsplit('.', 1)[1][:4]]))
upload_url = blobstore.create_upload_url(reverse('Articles.views.upload'))
urllib2.urlopen(upload_url, {'file': image})
except (DownloadError, RequestTooLargeError):
# end of important bit
return HttpResponse(json.dumps({'status': 'OK'}))

Here is basically what happens in the important bit:

  1. Download image from url and change it to a StringIO
  2. Make an UploadFile (basically a bundle of byte-string-data and desired filename)
  3. Create an upload_url with the blobstore API
  4. Fake a file-upload form post

The next thing we need is a view that will handle the request the blobstore will send back to our app.

def upload(request):
if request.method == 'POST':
blobs = get_uploads(request, field_name='file', populate_post=True)
article = Article.objects.get(id=int(blobs[0].filename.split('.')[0])) = blobs[0].filename
article.parsed = True
return HttpResponseRedirect(reverse('Articles.views.upload'))
return HttpResponse('meow')

Basically it extracts the article's id from the filename (the only way I could make work to pass that information) and stores some changes into the datastore. You'll notice that I'm basically just storing the article's id again in another field, this is to preserve knowledge of the file extension. It's also important to note that the blobstore requires a redirect response upon success, otherwise it will throw an error.

Here is the get_uploads function I found online somewhere.

def get_uploads(request, field_name=None, populate_post=False):
"""Get uploads sent to this handler.
field_name: Only select uploads that were sent as a specific field.
populate_post: Add the non blob fields to request.POST
A list of BlobInfo records corresponding to each upload.
Empty list if there are no blob-info records for field_name.
if hasattr(request,'__uploads') == False:
fields = cgi.FieldStorage(request.META['wsgi.input'], environ=request.META)
request.__uploads = {}
if populate_post:
request.POST = {}
for key in fields.keys():
field = fields[key]
if isinstance(field, cgi.FieldStorage) and 'blob-key' in field.type_options:
request.__uploads.setdefault(key, []).append(blobstore.parse_blob_info(field))
elif populate_post:
request.POST[key] = field.value
if field_name:
return list(request.__uploads[field_name])
except KeyError:
return []
results = []
for uploads in request.__uploads.itervalues():
results += uploads
return results

Now the process of serving this blob to the browser is very simple and goes something like this:

class ImageForm(forms.Form):
id = forms.CharField(required=True)
@form_valid(ImageForm, 'GET')
def image(request):
blob = BlobInfo.gql("WHERE filename='%s' LIMIT 1" % request.form.cleaned_data['id'])[0]
return HttpResponse(BlobReader(blob.key()).read(),

One final note

And one VERY important final note. The vanilla urllib2 library can't handle file uploads, so I found one online that can. It's called urllib2_file.

However it doesn't quite work on google appengine. For example it can't handle being told what you want the filename to be and some other details because it relies on raw file access. So I changed it a little bit, unfortunately I don't quite know how to upstream my changes so I'm hosting it on github.

You can get it at github, feel free to contribute.

Enhanced by Zemanta

Did you enjoy this article?

Published on August 10th, 2010 in Application programming interface, django, Form (web), Google AppEngine, python, Uncategorized, Uploading and downloading

Learned something new?
Want to become a high value JavaScript expert?

Here's how it works 👇

Leave your email and I'll send you an Interactive Modern JavaScript Cheatsheet 📖right away. After that you'll get thoughtfully written emails every week about React, JavaScript, and your career. Lessons learned over my 20 years in the industry working with companies ranging from tiny startups to Fortune5 behemoths.

Start with an interactive cheatsheet 📖

Then get thoughtful letters 💌 on mindsets, tactics, and technical skills for your career.

"Man, love your simple writing! Yours is the only email I open from marketers and only blog that I give a fuck to read & scroll till the end. And wow always take away lessons with me. Inspiring! And very relatable. 👌"

~ Ashish Kumar

Join over 10,000 engineers just like you already improving their JS careers with my letters, workshops, courses, and talks. ✌️

Have a burning question that you think I can answer? I don't have all of the answers, but I have some! Hit me up on twitter or book a 30min ama for in-depth help.

Ready to Stop copy pasting D3 examples and create data visualizations of your own?  Learn how to build scalable dataviz components your whole team can understand with React for Data Visualization

Curious about Serverless and the modern backend? Check out Serverless Handbook, modern backend for the frontend engineer.

Ready to learn how it all fits together and build a modern webapp from scratch? Learn how to launch a webapp and make your first 💰 on the side with ServerlessReact.Dev

Want to brush up on your modern JavaScript syntax? Check out my interactive cheatsheet:

By the way, just in case no one has told you it yet today: I love and appreciate you for who you are ❤️