如何使用Google App Engine中的Google Drive API?

cbo*_*tle 6 google-app-engine python-2.7 google-drive-api

我在GAE(Python 2.7)中有一个应用程序,现在需要访问Google Drive才能显示(共享)文件夹和文档列表.

搜索通常会导致指向DrEdit的指针,包括App Engine和Google Drive API,它会提出相同的问题,但会接受我不同意的答案,因为DrEdit是Google云端硬盘的示例应用,而不是GAE.

我希望能够在GAE中使用Drive API中的文件列表:https://developers.google.com/drive/v2/reference/files/list

小智 4

尽管Google App Engine和Google Drive都是Google产品,但不幸的是它们并没有直接链接。您必须安装该库才能访问 Google Drive API google-api-python-client

该过程可以在Python Google Drive API快速入门指南中找到,总结形式如下:

  1. Google 方面:允许您的 GAE 程序访问 Drive API

    • 激活云端硬盘 API。单击“转到凭据”按钮继续...
    • 创建您的同意屏幕:设置您的OAuth 同意屏幕,因为如果尚未设置,Google 会抛出奇怪的错误:
      • 单击OAuth 同意屏幕选项卡
      • 选择电子邮件地址并输入产品名称
    • 获取凭证:
      • 单击“凭据”选项卡
      • 选择“添加凭据”,然后选择“OAuth 2.0 客户端 ID”。选择您的申请类型,然后输入相关详细信息。您可以稍后更改它们!
      • 返回“凭据”选项卡,下载 JSON 凭据(一直到表中的右侧,仅当您将鼠标悬停在它附近时才会出现下载按钮)。重命名它client_secret.json并将其放在根代码目录中。您将需要它来向用户请求凭据。
  2. 在您这边:下载google-api-python-client,将其解压缩到您的代码目录中并运行python setup.py install。这将安装包含许多 Google 产品 API 的库。

  3. 现在您已准备好使用 Drive API。您可以使用示例代码测试您的访问。阅读它,因为它是编写您自己的代码的良好指南!如果您要访问用户数据,则需要在用户登录时请求用户凭据,并且很可能会存储这些凭据。然后,要使用 API,最简单的方法是获取对象service

    import httplib2
    from apiclient import discovery
    
    credentials = get_credentials() #Your function to request / access stored credentials
    #Authorise access to Drive using the user's credentials
    http = credentials.authorise(httplib2.Http())
    #The service object is the gateway to your API functions
    service = discovery.build('drive', 'v2', http=http)
    
    #Run your requests using the service object. e.g. list first 10 files:
    results = service.files().list(maxResults=10).execute()
    # ... etc ... Do something with results
    
    Run Code Online (Sandbox Code Playgroud)

上面的代码片段是根据示例代码修改的。

可以在此处找到Google Drive 的参考 API 。

将 GAE 链接到其他 Google 产品的 API(例如日历)也需要相同的一般过程。祝您编写程序一切顺利!