简体   繁体   English

如何使用 python 解决 google 表格 API 错误

[英]how to resolve google sheets API error with python

I am trying to read / write to google sheets using python.我正在尝试使用 python 读取/写入谷歌表格。

I run this boilerplate code, but get the following error:我运行此样板代码,但出现以下错误:

APIError: {'code': 403, 'message': 'Request had insufficient authentication scopes.', 'errors': [{'message': 'Insufficient Permission', 'domain': 'global', 'reason': 'insufficientPermissions'}], 'status': 'PERMISSION_DENIED', 'details': [{'@type': 'type.googleapis.com/google.rpc.ErrorInfo', 'reason': 'ACCESS_TOKEN_SCOPE_INSUFFICIENT', 'domain': 'googleapis.com', 'metadata': {'method': 'google.apps.drive.v3.DriveFiles.List', 'service': 'drive.googleapis.com'}}]}

what i have done:我做了什么:

  • I have followed the instructions and setup the google-API key.我已按照说明设置了 google-API 密钥。
  • i have downloaded the json key (named it google_keys.json ).我已经下载了 json 密钥(将其命名为google_keys.json )。
  • i created a new google sheet called test sheet for testing.我创建了一个名为test sheet的新谷歌表进行测试。
import gspread
from google.oauth2.service_account import Credentials


# Use the credentials to create a client to interact with the Google Drive API
scopes = ['https://www.googleapis.com/auth/spreadsheets']
creds = Credentials.from_service_account_file('google_keys.json', scopes=scopes)

client = gspread.authorize(creds)

# Open a sheet from a spreadsheet in Google Sheets
sheet = client.open("test sheet").worksheet("Sheet1")

# Read a range of cells
cell_list = sheet.range('A1:C7')

# Print the values in the range of cells
for cell in cell_list:
    print(cell.value)

# Write values to the sheet
sheet.update_acell('B2', "I am writing to B2")

It appears to be an authentication problem.这似乎是一个身份验证问题。 So my question is, what else to i need to do to get this test code working?所以我的问题是,我还需要做什么才能让这个测试代码正常工作?

The message says that the request has insufficient scopes, and points out that the method google.apps.drive.v3.DriveFiles.List is the one that triggered the error.该消息指出请求的范围不足,并指出google.apps.drive.v3.DriveFiles.List方法是触发错误的方法。 This means that you need to add a Drive scope so the script can read your files, probably to search for a spreadsheet with the specified filename.这意味着您需要添加一个驱动器 scope 以便脚本可以读取您的文件,可能是为了搜索具有指定文件名的电子表格。

From the gspread documentation , these are the scopes that you need to authenticate with a service account:从 gspread文档中,这些是您需要使用服务帐户进行身份验证的范围:

scopes = [
    'https://www.googleapis.com/auth/spreadsheets',
    'https://www.googleapis.com/auth/drive'
]

Note that you also need to share your spreadsheet with the service account that you got the google_keys.json file from.请注意,您还需要与从中获取google_keys.json文件的服务帐户共享您的电子表格。 It ends in ...gserviceaccount.com .它以...gserviceaccount.com Make sure that you generated the right keys .确保您生成了正确的密钥

Reference:参考:

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM