从Google App Engine Python应用访问Google Drive

6 投票
1 回答
5542 浏览
提问于 2025-04-17 19:21

我有一个已经存在的Google App Engine Python应用,功能挺多的。现在我想把Google Drive整合进这个应用里。具体来说,我希望我的应用能够:

  1. 在用户的Google Drive里创建一个空文件,用户可以在这个文件里创建一个Google文档。
  2. 从Google Drive中获取这个文件,以便在我的应用中进一步处理。
  3. 定期将这个文件发送回Google Drive,这样用户就可以继续在Google文档中编辑它。

如果有谁知道怎么实现我想做的事情,能告诉我具体的Google网页链接,我将非常感激(不要给我那种笼统的回答,比如“看看DrEdit的例子”)。提前谢谢你!

更新:

根据在回答1中提到的drive-v2-python-appengine生成的示例代码,这是我用来创建空文件的程序的RequestHandler:

import os
import webapp2

import io

from google.appengine.api import memcache

import httplib2
from apiclient.discovery import build
from apiclient.http import MediaIoBaseUpload
from oauth2client.appengine import oauth2decorator_from_clientsecrets


decorator = oauth2decorator_from_clientsecrets(
    os.path.join(os.path.dirname(__file__), 'client_secrets.json'),
    scope=[
        'https://www.googleapis.com/auth/drive',
    ])

http = httplib2.Http(memcache)
drive_service = build("drive", "v2", http=http)


class CreateEmptyFile(webapp2.RequestHandler):
    @decorator.oauth_required
    def get(self):
        body = {
            'title': 'Sample Document',
            'description': 'A sample document',
            'mimeType': 'text/plain'
        }
        media_body = MediaIoBaseUpload(io.BytesIO(""), mimetype='text/plain', resumable=True)
        file = drive_service.files().insert(body=body, media_body=media_body).execute()
        self.redirect("/synopsis")

测试起来有点让人困惑,因为有时候我运行这个程序时,包括第一次,它会弹出访问请求页面,但大多数时候不会。我使用了https://accounts.google.com/b/0/IssuedAuthSubTokens?hl=en来撤销对Drive的访问,Drive在列表中不再显示,但我想撤销访问可能需要一个小时或更长时间的延迟。对此我不太确定,也没看到相关的文档。

无论如何,如果我把对drive_service.files().insert()的调用注释掉,程序不会中止,而是重定向到我的摘要页面。我认为这意味着授权是正常工作的,因为这和生成的示例代码一样。

但是,如果我取消注释insert并且对媒体主体使用resumable=True,我得到:

ResumableUploadError: Failed to retrieve starting URI.

如果我使用resumable=False,我得到:

HttpError: <HttpError 401 when requesting https://www.googleapis.com/upload/drive/v2/files?uploadType=multipart&alt=json returned "Login Required">

所以我似乎能够通过OAuth 2.0授权,但无法插入文件。

1 个回答

1

请尝试我们的快速入门应用程序,链接在这里:https://developers.google.com/api-client-library/python/start/installation

你可以创建一个快速入门的应用引擎应用,这对你进行初始设置非常有帮助。如果你有特定的使用场景,可以查看这个Drive API 参考

撰写回答