如何使用Python从Google drive API初始化drive_服务对象?

2024-04-24 20:33:28 发布

您现在位置:Python中文网/ 问答频道 /正文

GoogleDriveAPI上的所有教程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


Tags: 对象idfalseisrequeststatusserviceanother
1条回答
网友
1楼 · 发布于 2024-04-24 20:33:28

我相信你的目标如下

  • 您想知道service = build('drive', 'v3', credentials=creds)中的service和这些URL中的drive_service之间的区别
  • 您想创建两个脚本This is the example I am trying to doHere is my code:
  • 您确认了python的快速入门功能已经发挥了作用

对于这个问题,这个答案如何

一,。关于servicedrive_service

“Python快速入门”的service中的service = build('drive', 'v3', credentials=creds)与这些URL中的drive_service相同。因此service包括使用API的授权(在本例中,它是驱动器API v3)。因此,可以修改“Python快速启动”的示例脚本,也可以将其用作授权脚本

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

这是This is the example I am trying to do的示例脚本。此示例脚本将本地文件上载到Google Drive。在本例中,https://www.googleapis.com/auth/drive用作作用域。这里有一点很重要。您可以看到从Quickstart复制和粘贴的授权脚本

在本地文件夹中,已创建了作用域为token.picklehttps://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()
  • 当在MediaFileUpload使用resumable=True时,可以通过可恢复上载来上载大文件

三,。{}的脚本:

这是Here is my code的示例脚本。此示例脚本将文件从Google Drive下载到本地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文档文件(电子表格、文档、幻灯片等)。可以下载除Google Docs文件以外的文件。所以请小心这个
  • 在这种情况下,下载的文件不会创建为文件。所以请小心这个。如果要将文件作为文件下载,请将fh = io.BytesIO()修改为fh = io.FileIO("### filename ###", mode='wb')

注:

  • 在这种情况下,重要的一点是,当修改作用域时,需要删除token.pickle并重新授权作用域。请小心这个

参考资料:

相关问题 更多 >