首页 > 解决方案 > 使用相同的 credentials.json 在 python 中访问 google drive/google sheet api

问题描述

我正在编写接口来使用谷歌驱动器和谷歌表格访问谷歌 api。对于每个 api,我按照google api(如 google drive)创建一个credentials.json并使用以下代码没有问题。但是作为接口,如何只使用一个 credentials.json 文件来访问多个 api?

from googleapiclient.discovery import build
from oauth2client import client, tools
flow = client.flow_from_clientsecrets('~/credentials.json', ['https://spreadsheets.google.com/feeds', 'https://www.googleapis.com/auth/drive'])
creds = tools.run_flow(flow, store)
service = build('drive', 'v3', http=creds.authorize(Http()))

标签: python-3.xgoogle-apigoogle-drive-apigoogle-sheets-apigoogle-api-python-client

解决方案


只要谷歌开发者控制台上的项目启用了不同的 api,您就可以使用相同的文件来访问您想要访问的任何 api,您只需为每个 api 请求访问权限。

from googleapiclient.discovery import build
from oauth2client import client, tools
flow = client.flow_from_clientsecrets('~/credentials.json', 
              ['https://spreadsheets.google.com/feeds',
              'https://www.googleapis.com/auth/drive'])
creds = tools.run_flow(flow, store)
serviceDrive = build('drive', 'v3', credentials=creds)
serviceSheets = build('sheets', 'v4', credentials=creds)

然后,您可以通过它们自己的服务访问每个 api。当用户登录时,系统将提示用户对驱动器和工作表进行身份验证。

sheet = serviceSheets.spreadsheets()
results = serviceDrive.files().list(pageSize=10, fields="nextPageToken, files(id, name)").execute()

推荐阅读