Python 从 Google 驱动器 403 权限下载文件

Python download file from Google Drive 403 permission

为了从我的云端硬盘下载 .mp4 文件,开始使用 Google Drive API 和需要创建新凭据的目标 CLI 工具。

然后,当下载属于仅使用 Google Drive API、

向我发送 link 的用户的文件时
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
import io
from googleapiclient.http import MediaIoBaseDownload

# If modifying these scopes, delete the file token.pickle.
SCOPES = ['https://www.googleapis.com/auth/drive.file']

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)

    # Call the Drive v3 API to download the file
    file_id = '1ZVFrwYaLClNrIk6TkshJZamHSS-59LLR'
    request = service.files().get_media(fileId=file_id)
    filename = "test.mp4"
    #fh = io.BytesIO()
    fh = io.FileIO(filename, 'wb') # From - 
    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()

我收到以下错误

  File "C:\Users\tiago\Anaconda3\lib\site-packages\googleapiclient\http.py", line 749, in next_chunk
    raise HttpError(resp, content, uri=self._uri)

HttpError: <HttpError 403 when requesting https://www.googleapis.com/drive/v3/files/1ZVFrwYaLClNrIk6TkshJZamHSS-59LLR?alt=media returned "The user has not granted the app 682654872192 read access to the file 1ZVFrwYaLClNrIk6TkshJZamHSS-59LLR.">

这不是什么新鲜事(尽管它 ) and is described in their documentation

Resolve a 403 error: The user has not granted the app {appId} {verb} access to the file {fileId}

其中指出

An appNotAuthorizedToFile error occurs when your app is not on the ACL for the file.

...

To fix this error, perform one of the following operations:

You can also check the isAppAuthorized field on a file to see if the file was created by or opened with your app.

如何检查并下载文件?

为了解决这个问题,我刚刚完成了以下两个步骤。

  1. 将范围更改为 drive - 按照建议 and here

    SCOPES = ['https://www.googleapis.com/auth/drive']
    
  2. 再次删除 token.pickle 和 运行 脚本 - 按照建议 .

然后,设法下载文件,它工作正常。