具有应用程序默认凭据的Google Sheet API访问权限

问题描述 投票:0回答:1

我正在尝试从Python(在GKE中运行)访问Google表格(只读模式)。

我能够获得应用程序默认凭据,但出现范围问题(因为我缺少https://www.googleapis.com/auth/spreadsheets.readonly范围)。参见下面的代码:

from googleapiclient.discovery import build
from oauth2client import client

creds=client.GoogleCredentials.get_application_default()
service = build('sheets', 'v4', credentials=creds)
sheet = service.spreadsheets()
sheet.values().get(spreadsheetId='XXXXXXXXXX', range='Sheet1!A:C').execute()

输出为:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/local/lib/python3.5/dist-packages/oauth2client/_helpers.py", line 133, in positional_wrapper
    return wrapped(*args, **kwargs)
  File "/usr/local/lib/python3.5/dist-packages/googleapiclient/http.py", line 840, in execute
    raise HttpError(resp, content, uri=self.uri)
googleapiclient.errors.HttpError: <HttpError 403 when requesting https://sheets.googleapis.com/v4/spreadsheets/XXXXXX/values/Sheet1%21A%3AC?alt=json returned "Request had insufficient authentication scopes.">

我试图阅读任何可用的文档,但是相关的所有相关范围都在使用外部服务帐户JSON文件。

是否有使用“应用程序默认值”并添加所需范围的方法?

google-sheets-api google-oauth2 scopes
1个回答
0
投票

答案:

您需要在create_scoped()GoogleCredentials.get_application_default()方法中定义范围。

代码段:

creds = GoogleCredentials.get_application_default().create_scoped(
          ['https://www.googleapis.com/auth/spreadsheets.readonly'])

希望对您有帮助!

参考:

© www.soinside.com 2019 - 2024. All rights reserved.