How to upload files to Google Drive from GAE Python app

I’m working on a Python application running on Google App Engine and I need to upload documents to Google Drive. I’m struggling with the gdata library and how to handle file uploads properly.

Here’s what I have so far:

import gdata.docs.client

docs_client = gdata.docs.client.DocsClient()
docs_client.ClientLogin('username', 'password')

file_source = gdata.MediaSource(# how to handle this part?)
docs_client.Upload(media_source=file_source, title='my_document')

The main issue is that gdata.MediaSource() expects a file path like '/path/to/file.pdf', but in GAE I don’t have access to a traditional file system. My files are stored in the Blobstore or I can access them via direct URLs.

Is there a way to create a MediaSource object from blob data or a URL instead of a file path? I’ve seen some solutions for Java using byte arrays but I can’t find anything similar for Python.

Skip the file_path and use file_contents instead when creating MediaSource. For Blobstore files, grab the data with blobstore.BlobReader(blob_key).read() and pass it straight to MediaSource. URL files? Use urlfetch to pull the content and do the same thing. Hit this same problem last year - GAE’s urlfetch works great for this, just set decent timeout values since docs can be huge. Content type usually gets detected automatically, but I’d specify it anyway to avoid upload headaches.

try using BytesIO with your blob data. like this: MediaSource(file_contents=BytesIO(your_blob_data), content_type='application/pdf'). should work well on GAE if you get the content type right.

Had the same problem migrating from local filesystem to GAE. The trick is that MediaSource takes multiple parameters, not just file_path. You can pass blob content directly: MediaSource(file_contents=blob_data, content_length=len(blob_data), content_type='your/mime-type'). With Blobstore, grab your blob using the key and read it into memory first. For URL files, use urlfetch.fetch() - response.content gives you the raw bytes. Watch out for large files though since GAE has memory limits. Anything over a few MB should use chunked uploads with the resumable upload methods.