Google Drive API:用户未授予应用错误

use*_*754 7 python google-drive-api google-oauth google-api-python-client

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

`The user has not granted the app ####### read access to the file`
Run Code Online (Sandbox Code Playgroud)

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

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

use*_*754 10

一旦你通过Quick-Start Tutorial最初的范围被给出:

SCOPES = 'https://www.googleapis.com/auth/drive.metadata.readonly'
Run Code Online (Sandbox Code Playgroud)

因此,在列出文件并决定下载后,它将无法工作,因为您需要再次生成令牌,因此更改范围不会重新创建或提示您进行首次运行时发生的“谷歌授权”。

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

store = file.Storage('tokenWrite.json')
Run Code Online (Sandbox Code Playgroud)


eth*_*ish 5

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

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)
Run Code Online (Sandbox Code Playgroud)

希望有帮助。