我需要在 GAE 应用程序上将文件/文档上传到 Google 文档。这应该很简单,但我在使用 API 时遇到了很多麻烦。

上下文:

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')

上传我正在使用 client.Upload(), ,它采用 MediaSource(包装器)对象作为参数。然而, MediaSource() 似乎只接受文档的文件路径: 'C:/Docs/ex.doc'.

由于我使用的是没有文件系统的 GAE,因此我只能通过 Blobstore 或文件的直接 URL 访问该文件。但我如何将其输入 MediaSource()?

似乎有一个 Java 中的方式 通过使用来完成此操作 MediaByteArraySource(), ,但对 Python 来说没有任何作用。

有帮助吗?

解决方案

如果有人好奇,以下是我如何使用文档列表 API 解决此问题的方法。

我不想使用 驱动SDK 因为它确实使很多事情变得复杂。使用 List API 进行身份验证/登录要简单得多,而不需要一些 OAuth 技巧。这是使用 2.0.14 版本 gdata Python 库, ,这不是当前版本(2.0.17),但它似乎有一个更简单的上传机制。

2.0.14 的在线文档也稍微多一些(仍然稀疏),尽管我必须从各种来源和反复试验中将其拼凑在一起。缺点是您无法使用此版本上传 pdf 文件。这段代码 将不会 使用 2.0.17。

这是代码:

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

其他提示

Google Drive SDK 文档包含一个用 Python 编写、在 App Engine 上运行的完整示例应用程序:

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

您可以将其用作实施的参考,并了解如何从 App Engine 保存文件。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top