Question

I need to upload a file/document to Google Docs on a GAE application. This should be simple enough, but I'm having a lot of trouble with the API.

The context:

import gdata.docs.service

client = gdata.docs.service.DocsService()
client.ClientLogin('gmail', 'pass')

ms = gdata.MediaSource(#what goes in here?)
client.Upload(media_source=ms, title='title')

To upload I'm using client.Upload(), which takes a MediaSource (wrapper) object as a parameter. However, MediaSource() seems to only accept a filepath for a document: 'C:/Docs/ex.doc'.

Since I'm on GAE with no filesystem, I can only access the file through the Blobstore or a direct URL to the file. But how do I input that into MediaSource()?

There seems to be a way in Java to accomplish this by using MediaByteArraySource(), but nothing for Python.

Was it helpful?

Solution

If anyone is curious, here's how I solved this problem using the Document List API.

I didn't want to use the Drive SDK since it does complicate a lot of things. It's much simpler with the List API to just authenticate/login without the need for some OAuth trickery. This is using version 2.0.14 of the gdata Python library, which is not the current version (2.0.17), but it seems to have a simpler upload mechanism.

There's also slightly more (still sparse) documentation online for 2.0.14, though I had to piece this together from various sources and trial & error. The downside is that you cannot upload pdf's with this version. This code will not work with 2.0.17.

Here's the code:

import gdata.docs.service
import gdata.docs.data
from google.appengine.api import urlfetch

# get file from url
result = urlfetch.fetch('http://example.com/test.docx')
headers = result.headers
data = result.content

# authenticate client object
client = gdata.docs.service.DocsService()
client.ClientLogin('gmail', 'password')

# create MediaSource file wrapper
ms = gdata.MediaSource(file_handle=result.content, 
content_type=headers['content-type'], 
content_length=int(headers['content-length']))

# upload specific folder, return URL of doc
google_doc_name = 'title'
folder_uri = '/feeds/folders/private/full/folder:j7XO8SJj...'
entry = client.Upload(ms, google_doc_name, folder_or_uri=secret.G_FOLDER_URI)
edit_url = entry.GetAlternateLink().href

OTHER TIPS

The Google Drive SDK docs include a complete sample application written in Python that runs on App Engine:

https://developers.google.com/drive/examples/python

You can use it as reference for your implementation and to see how to save a file from App Engine.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top