使用服务帐户密钥的Google Drive Python API授权

时间:2018-08-29 01:01:20

标签: python oauth google-cloud-platform google-drive-api

对于Google Cloud Platform项目,我具有以下服务帐户json凭据文件:

enter image description here

如何使用该服务帐户向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命令时出现错误,抱怨密钥文件的格式不是以webinstalled开头:

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服务帐户列出我的云端硬盘文件?如果是这样,该怎么办?

2 个答案:

答案 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)