python 中 google 驱动器 API 的身份验证问题

Authentication problem with google drive API in python

我有一个从 Google 复制的小脚本,它应该将文件上传到我位于 google 驱动器的 appDataFolder, 当 运行 第一次要求身份验证时,我授予它权限

import os.path
from googleapiclient.http import MediaFileUpload
from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request
from google.oauth2.credentials import Credentials

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

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.json 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.json'):
        creds = Credentials.from_authorized_user_file('token.json', SCOPES)
    # 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.json', 'w') as token:
            token.write(creds.to_json())

    # Create the service
    service = build('drive', 'v3', credentials=creds)

    file_metadata = {
        'title': 'token_lol.json',
        'parents': [{
            'id': 'appDataFolder'
        }]
    }
    media = MediaFileUpload('token_lol.json',
                            mimetype='application/json',
                            resumable=True)
    service.files().create(body=file_metadata,
                                        media_body=media,
                                        fields='id').execute()
    #print 'File ID: %s' % file.get('id')

if __name__ == '__main__':
    main()

然后当我尝试上传文件时出现此错误:

HttpError(resp, content, uri=self.uri)
googleapiclient.errors.HttpError: 
<HttpError 403 when requesting https://www.googleapis.com/upload/drive/v3/files?fields=id&alt=json&uploadType=resumable returned "The user does not have sufficient permissions for this file.". Details: "[{'domain': 'global', 'reason': 'insufficientFilePermissions', 'message': 'The user does not have sufficient permissions for this file.'}]">

它只在我使用这个 SCOPE 时有效:https://www.googleapis.com/auth/drive 但是根据 Google 文档 here it should work with this SCOPE : https://www.googleapis.com/auth/drive.appdata 那么问题是什么?

我找到了答案 您需要将这 2 个 SCOPES 加在一起:

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