如何使用Python从Google Drive API初始化drive_service对象?

问题描述 投票:0回答:1

[Google Drive API website上的所有教程都有一个对象drive_service,该对象先前已初始化到获取所提供代码段的位置,但没有说明它的用途,用途或构建方式。我正在使用Python。

This is the example I am trying to do

我能够通过quickstart.py进行身份验证,没有问题。

这是我的代码:

file_id = '0BwwA4oUTeiV1UVNwOHItT0xfa2M'
request = drive_service.files().get_media(fileId=file_id)
fh = io.BytesIO()
downloader = MediaIoBaseDownload(fh, request)
done = False
while done is False:
    status, done = downloader.next_chunk()
    print "Download %d%%." % int(status.progress() * 100)

这里有更多示例:

this one

another one

and another

python google-drive-api
1个回答
0
投票

我相信您的目标如下。

  • 您想知道这些URL的serviceservice = build('drive', 'v3', credentials=creds)与这些URL的drive_service之间的区别。
  • 您要创建This is the example I am trying to doHere is my code:的2个脚本。
  • 您确认适用于python的快速入门。

为此,这个答案如何?

1。关于servicedrive_service

service的[service = build('drive', 'v3', credentials=creds)与这些URL的drive_service相同。因此service包含使用API​​的授权(在本例中为Drive API v3。)。因此可以修改“ Python快速入门”的示例脚本,也可以用作授权脚本。

2。 This is the example I am trying to do的脚本:

这是This is the example I am trying to do的示例脚本。此示例脚本将本地文件上传到Google云端硬盘。在这种情况下,https://www.googleapis.com/auth/drive用作范围。在这里,有一个重点。您可以从快速入门中看到复制和粘贴的授权脚本。

在本地文件夹中,当您运行快速入门脚本时,已经用token.pickle的作用域创建了https://www.googleapis.com/auth/drive.metadata.readonly,请删除它,然后重新授权该作用域。这样,新作用域将反映到访问令牌中。请注意这一点。

示例脚本:

from __future__ import print_function import pickle import os.path from googleapiclient.discovery import build from google_auth_oauthlib.flow import InstalledAppFlow from google.auth.transport.requests import Request # If modifying these scopes, delete the file token.pickle. SCOPES = ['https://www.googleapis.com/auth/drive'] def main(): """Shows basic usage of the Drive v3 API. Prints the names and ids of the first 10 files the user has access to. """ creds = None # The file token.pickle stores the user's access and refresh tokens, and is # created automatically when the authorization flow completes for the first # time. if os.path.exists('token.pickle'): with open('token.pickle', 'rb') as token: creds = pickle.load(token) # If there are no (valid) credentials available, let the user log in. if not creds or not creds.valid: if creds and creds.expired and creds.refresh_token: creds.refresh(Request()) else: flow = InstalledAppFlow.from_client_secrets_file( 'credentials.json', SCOPES) creds = flow.run_local_server(port=0) # Save the credentials for the next run with open('token.pickle', 'wb') as token: pickle.dump(creds, token) drive_service = build('drive', 'v3', credentials=creds) file_metadata = {'name': '###'} # Please set filename. media = MediaFileUpload('###', mimetype='###', resumable=True) # Please set filename and mimeType of the file you want to upload. file = drive_service.files().create(body=file_metadata, media_body=media, fields='id').execute() print('File ID: %s' % file.get('id')) if __name__ == '__main__': main()
    [在resumable=True使用MediaFileUpload时,可以通过断点续传上传大文件。

  • 3。 Here is my code:的脚本:

    这是Here is my code的示例脚本。此示例脚本将文件从Google云端硬盘下载到本地PC。在这种情况下,https://www.googleapis.com/auth/drive和/或https://www.googleapis.com/auth/drive.readonly可用作范围。在这里,作为测试用例,为了使用在以上第2节中创建的token.pickle文件,范围未从https://www.googleapis.com/auth/drive更改。因此,您可以使用脚本而无需重新授权范围。

    示例脚本:

    from __future__ import print_function import pickle import os.path from googleapiclient.discovery import build from google_auth_oauthlib.flow import InstalledAppFlow from google.auth.transport.requests import Request # If modifying these scopes, delete the file token.pickle. SCOPES = ['https://www.googleapis.com/auth/drive'] def main(): """Shows basic usage of the Drive v3 API. Prints the names and ids of the first 10 files the user has access to. """ creds = None # The file token.pickle stores the user's access and refresh tokens, and is # created automatically when the authorization flow completes for the first # time. if os.path.exists('token.pickle'): with open('token.pickle', 'rb') as token: creds = pickle.load(token) # If there are no (valid) credentials available, let the user log in. if not creds or not creds.valid: if creds and creds.expired and creds.refresh_token: creds.refresh(Request()) else: flow = InstalledAppFlow.from_client_secrets_file( 'credentials.json', SCOPES) creds = flow.run_local_server(port=0) # Save the credentials for the next run with open('token.pickle', 'wb') as token: pickle.dump(creds, token) drive_service = build('drive', 'v3', credentials=creds) file_id = '0BwwA4oUTeiV1UVNwOHItT0xfa2M' request = drive_service.files().get_media(fileId=file_id) fh = io.BytesIO() downloader = MediaIoBaseDownload(fh, request) done = False while done is False: status, done = downloader.next_chunk() print("Download %d%%." % int(status.progress() * 100)) if __name__ == '__main__': main()
      在此脚本中,无法导出Google Docs文件(电子表格,文档,幻灯片等)。可以下载除Google Docs文件以外的文件。因此,请注意这一点。

  • 在这种情况下,下载的文件未创建为文件。所以请注意这一点。如果要将文件下载为文件,请将fh = io.BytesIO()修改为fh = io.FileIO("### filename ###", mode='wb')
  • 注意:

      在这种情况下,作为重点,修改范围时,需要删除token.pickle并重新授权范围。请注意这一点。

  • 参考:

  • Download files
  • © www.soinside.com 2019 - 2024. All rights reserved.