【问题标题】:Google Sheet API access with Application Default credentials使用应用程序默认凭据访问 Google Sheet API
【发布时间】:2020-08-08 06:27:41
【问题描述】:

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

我能够获得应用程序默认凭据,但遇到范围问题(因为我缺少 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 文件。

有没有办法使用 Application Default 并添加所需的范围?

【问题讨论】:

    标签: google-sheets-api google-oauth scopes


    【解决方案1】:

    答案:

    您需要在GoogleCredentials.get_application_default()create_scoped() 方法中定义您的作用域。

    代码sn-p:

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

    参考资料:

    【讨论】:

      【解决方案2】:

      oauth2client 现已弃用。请改用此库 google-auth
      用户指南在这里:
      https://google-auth.readthedocs.io/en/master/user-guide.html

      所以这段代码:

      from oauth2client.client import GoogleCredentials
      from googleapiclient.discovery import build
      
      scopes = [
          'https://www.googleapis.com/auth/cloud-platform'
          'https://www.googleapis.com/auth/spreadsheets.readonly',
      ]
      credentials = GoogleCredentials.get_application_default().create_scoped(scopes)
      service = build('sheets', 'v4', credentials=credentials)
      

      应替换为以下代码:

      from google import auth
      from googleapiclient.discovery import build
      
      scopes = [
          'https://www.googleapis.com/auth/cloud-platform'
          'https://www.googleapis.com/auth/spreadsheets.readonly',
      ]
      credentials, project_id = auth.default(scopes=scopes)  # Returns a tuple.
      service = build('sheets', 'v4', credentials=credentials)
      

      此外,根据此回复,库 google-auth 可能需要另一个库 google-auth-httplib2 才能正常工作:
      https://github.com/googleapis/google-auth-library-python/issues/190#issuecomment-322837328

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-01-23
        • 1970-01-01
        • 2022-01-19
        • 2017-04-04
        • 2018-09-08
        • 2022-07-15
        • 1970-01-01
        • 2016-03-25
        相关资源
        最近更新 更多