python - 了解如何通过 Python 使用 Google API 客户端库

标签 python methods google-api google-drive-api google-api-python-client

为了提高我的 Python 技能,我尝试阅读和理解 Google API Python client 的源代码.
但是我被卡住了,尽管四处搜索,我还是无法理解代码特定部分的工作原理。

我做了一个小程序来演示那部分:

upload.py

from __future__ import print_function
import os
import httplib2

import apiclient
import oauth2client

try:
    import argparse
    flags = argparse.ArgumentParser(
        parents=[oauth2client.tools.argparser]).parse_args()
except ImportError:
    flags = None

SCOPES = 'https://www.googleapis.com/auth/drive'
CLIENT_SECRET_FILE = 'client_secret.json'

# Enter your project name here!!
APPLICATION_NAME = 'API Project'


def get_credentials():
    """Gets valid user credentials from storage.

    If nothing has been stored, or if the stored credentials are invalid,
    the OAuth2 flow is completed to obtain the new credentials.

    Returns:
        Credentials, the obtained credential.
    """
    home_dir = os.path.expanduser('~')
    credential_dir = os.path.join(home_dir, '.credentials')
    if not os.path.exists(credential_dir):
        os.makedirs(credential_dir)
    credential_path = os.path.join(credential_dir,
                                   'drive-credentials.json')

    store = oauth2client.file.Storage(credential_path)
    credentials = store.get()
    if not credentials or credentials.invalid:
        flow = oauth2client.client.flow_from_clientsecrets(
            CLIENT_SECRET_FILE, SCOPES)
        flow.user_agent = APPLICATION_NAME
        if flags:
            credentials = oauth2client.tools.run_flow(flow, store, flags)
        else:  # Needed only for compatibility with Python 2.6
            credentials = oauth2client.tools.run(flow, store)
        print('Storing credentials to ' + credential_path)
    return credentials


def main():
    credentials = get_credentials()
    http = credentials.authorize(httplib2.Http())

    file_service = apiclient.discovery.build('drive', 'v3', http=http).files()

    results = file_service.get(
        fileId="0Bw239KLrN7zoWl95Nml2ZUpsNnc").execute()
    print(results)

    results = file_service.list(
        pageSize=10, fields="files(id, name)").execute()
    print(results)

if __name__ == '__main__':
    main()

file_service = apiclient.discovery.build('drive', 'v3', http=http).files() 行中,我找不到 的定义库源代码中任何位置的 files() 方法。我也找不到任何称为 get()list() 的方法。

我已经在 Github repository 上阅读了库的源代码以及它的 code documentation ,但没能找到任何有用的东西。

这是我到目前为止尝试过的:

通过查看文件 discovery.py ,函数 build() 返回函数 build_from_document() 的结果,后者又返回类 Resource() 的实例。

但现在有一个死胡同,因为 Resource() 类没有任何名为 files() 的方法。

那么,如何找到这些方法的内部工作原理 files()get()list() 等?

最佳答案

(2017 年 2 月)好问题!当我第一次开始使用 Google API 时,我想我在理解方面遇到了同样的问题。让我稍微简化一下您的代码。那么它应该更有意义,我也可以将您转发到正确的文档。

您使用的授权代码现在可以通过 Google API 客户端库中的最新更新得到显着简化。 (确保使用 pip install -U google-api-python-client [或 pip3 for Python 3] 更新您的 Python 库。)这是一个使用 list() -- 您应该能够以此示例为灵感并(重新)实现您的 main() 以使其正常工作。

# authorization boilerplate code
SCOPES = 'https://www.googleapis.com/auth/drive.readonly.metadata'
store = file.Storage('storage.json')
creds = store.get()
if not creds or creds.invalid:
    flow = client.flow_from_clientsecrets('client_id.json', SCOPES)
    creds = tools.run_flow(flow, store)

# call files().list() to display 1st 100 files in My Drive folder
DRIVE = discovery.build('drive', 'v3', http=creds.authorize(Http()))
files = DRIVE.files().list().execute().get('files', [])
for f in files:
    print(f['name'], f['mimeType'])

下面是一些额外的资源(视频、博客文章等),我为使用 Python 中的 Drive API 而创建...上面的代码在第一对中:

(*) - TL;DR:将纯文本文件上传到云端硬盘,导入/转换为 Google 文档格式,然后将该文档导出为 PDF。上面的帖子像您的代码示例一样使用 Drive API v2; this follow-up post描述了将其迁移到 Drive API v3,这里是一个 developer video合并两个“穷人的皈依者”帖子。

要回答问题的第二部分,答案是:您使用的方法(及其文档)不是客户端库的一部分(apiclientoauth2client 等)。这就是为什么您可以找到有关它们的任何文档的原因。请注意,在我上面的代码中,我从 apiclient.discovery.build() 创建了一个 DRIVE 服务端点,当您在末尾添加 .files() 时停在那里。

Drive 服务端点是您想要离开的地方,而不是像您那样潜入** API(在调用 build 结束时使用 .files() () 函数)。如果将其保留在更高级别,则可以对 API 进行多次调用(而不是被锁定为仅使用 files()),即 about().get() , files().list(), files().export(), 等一些建议:

  1. 创建一个通用服务端点,如 DRIVE,然后从那里使用 API 调用(而不是你所做的,这相当于 DRIVE.files()) .
  2. 您正在使用的 API 的文档可以在 Drive API 中找到文档。即 files() , files().get() , files().list()等。它们不是您所知道的“Python 函数”,而是 API 调用自身的 Python 包装器,这就是您需要服务端点的原因。
  3. 这是 general overview to the Drive API进一步阅读。

最后的提示:尽可能使用最严格的范围 -- https://www.googleapis.com/auth/drive 是完整的驱动器读写访问权限,通常不是 必要的。由于上面我只显示文件名和 MIME 类型,所以我只需要只读范围。你知道当你安装一个应用程序时,它会要求所有这些疯狂的权限吗?这是相似的。您请求的范围越少,限制越多,您的用户就越不会担心选择您。研究 all the Drive scopes并找到最适合您和您的用户的。

请注意,我使用 storage.json 而不是 .credentials/drive-credentials.json

来存储我的 key

关于python - 了解如何通过 Python 使用 Google API 客户端库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34743774/

相关文章:

django - Google API 范围已更改

java - 无法使用 Eclipse 编译简单的 Google api Android 应用程序

python - 计算每个用户每月的平均收入

python - 将一个模块调用到另一个模块

python:(lambda)函数的字典

java - new ActionListener(){} 类型的方法 xy(double, ...) 未定义

python - 使用 CSV 写入文件会添加无关的引号

Java 差异方法

java - 无法对非静态方法进行静态引用 (Java)

javascript - Google fit aggregate rest api调用问题解析错误javascript