python-3.x - 使用相同的 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()))
解决方案
只要谷歌开发者控制台上的项目启用了不同的 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()
推荐阅读
- reactjs - 从项目中删除 Babel?(反应,Parceljs)
- google-apps-script - 甚至不打开谷歌表格就自动保存数据?
- php - 搜索给定值的php数组
- r - 将 tbl_df 转换为数据框会产生错误
- logging - 我看不到 Payara 4.1 上已部署应用程序的日志,仅在 Netbeans 控制台选项卡上显示 |#]
- macos - 从詹金斯触发硒脚本时,chrome浏览器没有启动
- c - 删除包含用户输入字母的链表元素
- biztalk - BizTalk WCF-CUSTOM Sqlbinding 生成从字符串到字节的类型转换错误 []
- android - MotionLayout:点击和触摸在运动场景中的转换中不起作用(Youtube 播放器,如 UI)
- ipad - 当多个连接的场景在前台处于活动状态时获取当前聚焦的 UIScene