【问题标题】:use the same credentials.json to access google drive/google sheet api in python使用相同的 credentials.json 在 python 中访问 google drive/google sheet api
【发布时间】:2020-03-04 04:43:16
【问题描述】:

我正在编写接口来使用谷歌驱动器和谷歌表格访问谷歌 api。对于每个 api,我像 google drive 一样按照google api 创建一个 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.x google-api google-drive-api google-sheets-api google-api-python-client


    【解决方案1】:

    只要谷歌开发者控制台上的项目启用了不同的 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()
    

    【讨论】:

    • 它不起作用。在谷歌驱动器上没问题,但来自谷歌表的错误{HttpError}<HttpError 403 when requesting https://sheets.googleapis.com/v4/spreadsheets?alt=json returned "Google Sheets API has not been used in project xxxxxxx before or it is disabled. Enable it by visiting https://console.developers.google.com/apis/api/sheets.googleapis.com/overview?project=xxxxxxx then retry.
    • 添加访问链接,我仍然无法在我的 gmail 帐户中启用 google sheet。因为它说我没有权限
    • 您需要在 Google 开发者控制台(不是您的 Google 帐户)中为您的项目启用它。找出谁创建了您的凭据文件并让他们修复它。这与您的问题无关,它只是一个设置问题。
    • 您可能会发现 this 对于如何为您的 Google Cloud 项目启用 API 很有用
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-21
    • 1970-01-01
    • 1970-01-01
    • 2015-12-05
    • 2018-07-16
    相关资源
    最近更新 更多