使用 Python 从 Google 驱动器下载文件

Downloading files from Google Drive with Python

我正在用 Python 编码,制作一个使用 Googl Drive API 下载文件的程序。 这是代码:

import os
import io
from googleapiclient.discovery import build
from googleapiclient.http import MediaIOBaseDownload

CLIENT_SECRET_FILE = 'client_secret.json'
API_NAME = 'drive'
API_VERSION = 'v3'
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)

    service = build('drive', 'v3', credentials=creds)



    file_ids = ['1aKiVaINA2-_o8zttzYiH60jShzFQRUny', '1Xyy9-LWwTtnWZ1HLVJ74XT0PVsoixHOi']
    file_names = ['PicsArt_08-02-06.15.34.jpg', 'PicsArt_07-22-04.49.32.jpg']
    for file_id, file_name in zip(file_ids, file_names):
        request = service.files().get_media(fileId=file_id)

        fh = io.BytesIO()
        downloader = MediaIOBaseDownload(fd=fh, request=request)

        done = False

        while not done:
            status, done = downloader.next_chunk()
            print('Download progress {0}'.format(status.progress( * 100)))
    
        fh.seek(0)
        with open(os.path.join('./Random Files', file_name), 'wb') as f:
            f.write(fh.read())
            f.close()

if __name__ == '__main__':
    main()

当我 运行 程序出现此错误时:

回溯(最近调用最后): 文件“download.py”,第 4 行,位于 来自 googleapiclient.http 导入 MediaIOBaseDownload 导入错误:无法从 'googleapiclient.http' 导入名称 'MediaIOBaseDownload' (C:\Users\Usuario\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\LocalCache\local-packages\Python38\site-packages\googleapiclient\http.py)

有什么解决办法吗?

我知道您的目标是导入 class http.MediaIoBaseDownload from the Python googleapiclient package。如果我做对了,那么你就非常接近实现你的目标了。您应该用这一行更改有问题的行:

from googleapiclient.http import MediaIoBaseDownload

请注意 MediaIoBaseDownload 的拼写方式有何不同。有疑问可以再问我