对于Google Cloud Platform项目,我具有以下服务帐户json凭据文件:
如何使用该服务帐户向Google Drive API进行身份验证?例如,当我尝试执行以下操作时:
from googleapiclient.discovery import build
from httplib2 import Http
from oauth2client import file, client, tools
SCOPES = 'https://www.googleapis.com/auth/drive.metadata.readonly'
flow = client.flow_from_clientsecrets('mykey.json', SCOPES)
creds = tools.run_flow(flow, store)
service = build('drive', 'v3', http=creds.authorize(Http()))
results = service.files().list(pageSize=10, fields="nextPageToken, files(id, name)").execute()
items = results.get('files', [])
运行flow
命令时出现错误,抱怨密钥文件的格式不是以web
或installed
开头:
Invalid file format. See https://developers.google.com/api-client-library/python/guide/aaa_client_secrets
Expected a JSON object with a single property for a "web" or "installed" application
是否可以使用以上密钥为我的Google服务帐户列出我的云端硬盘文件?如果是这样,该怎么办?
答案 0 :(得分:1)
要使用服务帐户凭据,应从 ServiceAccountCredentials
导入 oauth2client.service_account
库并按如下方式使用:
# The needed import for service account credentials:
from oauth2client.service_account import ServiceAccountCredentials
from apiclient.discovery import build
scope = ['https://www.googleapis.com/auth/drive']
# Parsing JSON credentials for a service account:
credentials = ServiceAccountCredentials.from_json_keyfile_name('creds.json', scope)
service = build('drive', 'v3', credentials=credentials)
然后,使用 service
作为常规,例如service.files()
等
答案 1 :(得分:0)
您可以转到以下Python Quickstart for Drive页,然后单击“启用Drive API”按钮。这将允许您下载以下行格式的凭据,除了:
flow = client.flow_from_clientsecrets('mykey.json', SCOPES)