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

如何使用Python从Google drive API初始化drive_服务对象?,python,google-drive-api,Python,Google Drive Api,GoogleDriveAPI上的所有教程都有一个对象,即Drive_服务,该服务之前已初始化到提供的代码片段拾取的位置,但没有解释它是什么、它的作用以及它应该如何构建。我正在使用Python 我能够通过quickstart.py进行身份验证,没有任何问题 这是我的密码: file_id = '0BwwA4oUTeiV1UVNwOHItT0xfa2M' request = drive_service.files().get_media(fileId=file_id) fh = io.BytesIO

GoogleDriveAPI上的所有教程都有一个对象,即Drive_服务,该服务之前已初始化到提供的代码片段拾取的位置,但没有解释它是什么、它的作用以及它应该如何构建。我正在使用Python

我能够通过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)
以下是更多的例子:


我相信你的目标如下

您想知道service=build'drive',v3',credentials=creds的服务和这些URL的drive\u服务之间的区别。 您想创建两个脚本,这是我尝试执行的示例,下面是我的代码:。 您确认了python的快速入门功能已经发挥了作用。 对于这个问题,这个答案如何

1.关于服务和驾驶室服务: Python Quickstart的service=build'drive',v3',credentials=creds与这些URL的drive\u服务相同。因此,服务包括使用API的授权。在本例中,它是驱动器API v3。。因此,Python Quickstart的示例脚本可以修改,也可以用作授权脚本

2.下面的脚本就是我正在尝试的示例: 这是一个示例脚本,这是我正在尝试做的示例。此示例脚本将本地文件上载到Google Drive。在这种情况下,,https://www.googleapis.com/auth/drive 用作范围。这里有一点很重要。您可以看到从Quickstart复制和粘贴的授权脚本

在本地文件夹中时,已创建范围为的token.picklehttps://www.googleapis.com/auth/drive.metadata.readonly 运行快速启动脚本时,请将其删除,然后再次对作用域进行授权。这样,新的作用域将反映到访问令牌。请小心这个

示例脚本: 当在MediaFileUpload中使用resumable=True时,可以通过resumable upload上载大文件。 3.这里的脚本是我的代码:: 这是一个示例脚本,下面是我的代码。此示例脚本将文件从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. 因此,您可以在不重新授权作用域的情况下使用脚本

示例脚本: 在此脚本中,无法导出Google文档文件、电子表格、文档、幻灯片等。可以下载除Google Docs文件以外的文件。所以请小心这个。 在这种情况下,下载的文件不会创建为文件。所以请小心这个。如果要将文件作为文件下载,请将fh=io.BytesIO修改为fh=io.FileIO文件名,mode='wb'。 注: 在这种情况下,重要的一点是,当修改作用域时,需要删除token.pickle并重新授权作用域。请小心这个。 参考资料:
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()
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()