Google Drive API: 用户尚未授权应用错误

Google Drive API: The user has not granted the app error

我在 https://developers.google.com/drive/api/v3/quickstart/python 上关注 Quickstart。我已经通过页面启用了驱动器 API,加载了 credentials.json,并且可以成功列出我的 google 驱动器中的文件。但是,当我想下载文件时,我收到消息

`The user has not granted the app ####### read access to the file`

我是否需要做的不仅仅是将该范围放入我的代码中,还是我需要激活其他东西?

SCOPES = 'https://www.googleapis.com/auth/drive.file'
client.flow_from_clientsecrets('credentials.json', SCOPES)

完成 Quick-Start Tutorial 后,最初给出的范围为:

SCOPES = 'https://www.googleapis.com/auth/drive.metadata.readonly'

因此,在列出文件并决定下载后,它不会起作用,因为您需要再次生成令牌,因此更改范围不会重新创建或提示您输入 'google authoriziation'首先运行。

要强制生成令牌,只需删除您当前的令牌或使用新文件从存储器中存储您的密钥:

store = file.Storage('tokenWrite.json')

我运行进入同样的错误。我授权了整个范围,然后检索文件,并使用 io.Base class 将数据流式传输到文件中。请注意,您需要先创建文件。

from __future__ import print_function
from googleapiclient.discovery import build
import io
from apiclient import http
from google.oauth2 import service_account

SCOPES = ['https://www.googleapis.com/auth/drive']

SERVICE_ACCOUNT_FILE = 'credentials.json'
FILE_ID = <file-id>

credentials = service_account.Credentials.from_service_account_file(SERVICE_ACCOUNT_FILE, scopes=SCOPES)

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

def download_file(service, file_id, local_fd):

  request = service.files().get_media(fileId=file_id)
  media_request = http.MediaIoBaseDownload(local_fd, request)

  while True:    
    _, done = media_request.next_chunk()

    if done:
      print ('Download Complete')
      return

file_io_base = open('file.csv','wb')

download_file(service=service,file_id=FILE_ID,local_fd=file_io_base)

希望对您有所帮助。

删除token.pickle并重新运行程序。

详细说明:- 一旦您 运行 快速入门示例,它会存储一个 token.pickle。

此后,即使您在 google api 控制台中更改范围并在代码中添加以下范围:-

SCOPES = ['https://www.googleapis.com/auth/drive']

在您删除更早的作用域 token.pickle 之前,它不会起作用。 一旦删除re运行程序。将出现一个选项卡,授权应用程序并完成。