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

和自甴很熟 提交于 2020-06-27 08:13:31

问题


I'm following the Quickstart on https://developers.google.com/drive/api/v3/quickstart/python. I've enabled the drive API through the page, loaded the credentials.json and can successfully list files in my google drive. However when I wanted to download a file, I got the message

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

Do I need to do more than putting that scope in my code or do I need to activate something else?

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

回答1:


Once you go through the Quick-Start Tutorial initially the Scope is given as:

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

So after listing files and you decide to download, it won't work as you need to generate the the token again, so changing scope won't recreate or prompt you for the 'google authoriziation' which happens on first run.

To force generate the token, just delete your curent token or use a new file to store your key from the storage:

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



回答2:


I ran into the same error. I authorized the entire scope, then retrieved the file, and use the io.Base class to stream the data into a file. Note, you'll need to create the file first.

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)

Hope that helps.



来源:https://stackoverflow.com/questions/52135293/google-drive-api-the-user-has-not-granted-the-app-error

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!