了解如何将Google API客户端库与Python一起使用

了解如何将Google API客户端库与Python一起使用,python,methods,google-api,google-drive-api,google-api-python-client,Python,Methods,Google Api,Google Drive Api,Google Api Python Client,为了提高我的Python技能,我尝试阅读并理解的源代码。 但是我被卡住了,尽管在谷歌上搜索,我还是无法理解代码中某个特定部分的工作原理 我制作了一个小程序来演示该部分: upload.py from __future__ import print_function import os import httplib2 import apiclient import oauth2client try: import argparse flags = argparse.Argume

为了提高我的Python技能,我尝试阅读并理解的源代码。
但是我被卡住了,尽管在谷歌上搜索,我还是无法理解代码中某个特定部分的工作原理

我制作了一个小程序来演示该部分:

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\u service=apiclient.discovery.build('drive','v3',http=http.files()
)行中,我无法在库源代码的任何地方找到
files()
方法的定义。我也找不到任何名为
get()
list()
的方法

我已经在its和its上阅读了该库的源代码,但没有找到任何有用的东西

以下是我迄今为止所尝试的:

通过查看文件,函数
build()
返回函数
build\u from\u document()
,该函数返回类
Resource()
的实例

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

那么,我如何找到这些方法的内部工作机制呢?

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

通过Google API客户端库中的最新更新,您使用的身份验证代码现在可以大大简化。(请确保使用
pip安装-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中的驱动API创建的一些附加资源(视频、博客帖子等)。。。上述代码在第一对中具有特色:

  • 深潜
  • 视频加上“穷人的纯文本到PDF转换器”代码深入(*)
  • 仅将Google工作表导出为CSV
(*)-TL;DR:将纯文本文件上传到硬盘,导入/转换为Google文档格式,然后将该文档导出为PDF。上面的文章使用了驱动API v2,就像您的代码示例一样;描述了如何将其迁移到驱动API v3,下面是一篇结合了“穷人的转换器”两篇文章的文章

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

驱动器服务端点是您想要离开它的地方,而不是像您那样**深入*一个API(在调用
build()
函数的末尾使用
.files()
)。如果将其保留在更高的级别,则可以对API进行多次调用(而不是仅使用
文件()
),即
关于().get()
文件().list()
文件().export(),
等。一些建议:

  • 创建一个通用的服务端点,如
    DRIVE
    ,然后从那里使用API调用(而不是您所做的,这相当于
    DRIVE.files()
  • 您正在使用的API的文档可以在文档中找到。i、 它们不是您所知道的“Python函数”,而是API调用本身的Python包装器,这就是您需要服务端点的原因
  • 这是供进一步阅读的答案
  • 最后一个提示:尽可能使用最严格的范围--
    https://www.googleapis.com/auth/drive
    是全驱动器读写访问,通常不需要。因为我只显示上面的文件名和mimetype,所以我只需要只读范围。你知道当你安装一个应用程序时,它要求所有这些疯狂的权限吗?这是相似的。您请求的作用域越少,限制性越强,您的用户就越不担心选择您。研究并找到最适合您和您的用户的方案


    请注意,我使用
    storage.json
    来存储我的密钥,而不是
    .credentials/drive credentials.json

    ,这是基于wescpy令人敬畏的答案:

    在使用各种作用域时,每次都需要删除在完成google登录时自动创建的
    storage.json

    在我的例子中,我在玩
    drive.readonly
    ,然后想开始上传文件
    drive
    ,但是我已经好几个月没有玩过readonly了,我忘记了
    storage.json
    是如何创建的


    因此,我花了一段时间才意识到,与其删除storage.json,不如让我的脚本指向一个新的(不存在的)
    storage2.json
    来捕获
    驱动器
    凭据。

    但是
    资源
    类似乎有方法可以动态地向自身添加方法。我将从那里开始。@Jasper我绝对不知道这是如何工作的(我是Python的初学者)。你能详细解释一下从哪里开始吗?我想这就是相关的函数。添加类似“
    print attr\u name,value
    ”和code来打印堆栈跟踪()(或使用您喜爱的调试器),以查看是谁调用此函数来添加
    文件()
    get()
    等。