Google云端硬盘API:用户未授予应用错误

时间:2018-09-02 08:36:38

标签: python google-drive-api google-oauth google-api-python-client

我正在关注https://developers.google.com/drive/api/v3/quickstart/python上的`The user has not granted the app ####### read access to the file` 。我已经通过页面启用了驱动器API,并加载了 credentials.json 并可以成功列出我的Google驱动器中的文件。但是,当我要下载文件时,收到消息

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

除了将作用域放入代码中还是要做其他事情?

.py

3 个答案:

答案 0 :(得分:2)

一旦您完成Quick-Start Tutorial的操作,范围将如下所示:

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

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

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

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

答案 1 :(得分:0)

我遇到了同样的错误。我对整个范围进行了授权,然后检索了文件,并使用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)

希望有帮助。

答案 2 :(得分:0)

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

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

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

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

只有删除并删除了较早的作用域的token.pickle,该功能才起作用。 删除后,重新运行程序。将显示一个标签,授权该应用并完成。

相关问题