【问题标题】:How to read a spreadsheet using python API and Applications Default Credentials?如何使用 python API 和应用程序默认凭证读取电子表格?
【发布时间】:2023-02-16 23:32:17
【问题描述】:

我有以下代码:

    scope = ['https://www.googleapis.com/auth/cloud-platform',
             'https://www.googleapis.com/auth/drive',
             'https://www.googleapis.com/auth/spreadsheets',
             'https://www.googleapis.com/auth/spreadsheets.readonly']

    credentials, project = google.auth.default(scopes=scope)

    service = discovery.build('sheets', 'v4', credentials=credentials, cache_discovery=False)
    sheet = service.spreadsheets()
    result_input = sheet.values().get(spreadsheetId=id,range=range).execute()

但是我得到了 403,即使工作表是公开的: googleapiclient.errors.HttpError: <HttpError 403 请求时

https://sheets.googleapis.com/v4/spreadsheets/<SHEET_ID_HERE>/values/<RANGE_HERE>?alt=json returned "Request had insufficient authentication scopes.". Details: "[{'@type': 'type.googleapis.com/google.rpc.ErrorInfo', 'reason': 'ACCESS_TOKEN_SCOPE_INSUFFICIENT', 'domain': 'googleapis.com', 'metadata': {'service': 'sheets.googleapis.com', 'method': 'google.apps.sheets.v4.SpreadsheetsService.GetValues'}}]">

我有

  • Google SDK 配置良好
  • 我是 GCP 项目的所有者
  • 我是 google 工作表的所有者,使用相同的电子邮件(知道是公开的)

我不想下载任何 .json api 密钥。我还有其他选择吗?我究竟做错了什么?

【问题讨论】:

  • 您需要以某种方式提供密钥。为什么不下载 JSON?
  • 我正在尝试直接从我的应用程序环境生成凭据。当我实例化一个大查询或存储客户端时也是如此。应用程序应该回退到从环境推断的默认值

标签: python google-cloud-platform scope google-oauth google-sheets-api


【解决方案1】:

读取 Google 电子表格中特定单元格和行的简单示例

from oauth2client.service_account import ServiceAccountCredentials
import gspread
scopes = [
  'https://www.googleapis.com/auth/spreadsheets',
  'https://www.googleapis.com/auth/drive']
    
credentials = ServiceAccountCredentials.from_json_keyfile_name("token.json", scopes) #access the json key you downloaded earlier 
file = gspread.authorize(credentials) # authenticate the JSON key with gspread
sheet = file.open_by_key("SPREADSHEET_ID") #open sheet
print(sheet.get_worksheet(0).cell(i,1).value)

要下载 token.json 文件,您需要执行以下步骤:

  1. 在 Google Cloud 控制台中,转到“菜单”>“IAM 和管理”>“服务帐户”。转到服务帐户。
  2. 选择您的服务帐户。
  3. 单击“密钥”>“添加密钥”>“创建新密钥”。
  4. 选择 JSON,然后单击创建。 ...
  5. 单击“关闭”。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-08-08
    • 1970-01-01
    • 1970-01-01
    • 2016-03-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多