Google API (Sheets) API 错误代码 403。权限不足:请求的身份验证范围不足

hot*_*ion 3 python google-sheets anaconda google-sheets-api

我正在尝试一个项目,我可以使用 python(我在 Anaconda 上使用 jupyter notebooks)从谷歌表中读取数据。我看了一些视频和指南并复制了代码。但是,我无法使代码正常工作

import pandas as pd
import gspread
from oauth2client.service_account import ServiceAccountCredentials
scope = ['https://spreadsheets.google.com/feeds','https://www.googleapis.com/auth/drive']
creds = ServiceAccountCredentials.from_json_keyfile_name('test.json',scope)
client = gspread.authorize(creds)
data = gc.open('TEST').sheet1
print(data.get_all_records())
Run Code Online (Sandbox Code Playgroud)

我得到的错误信息是

APIError: {
 "error": {
  "errors": [
   {
    "domain": "global",
    "reason": "insufficientPermissions",
    "message": "Insufficient Permission: Request had insufficient authentication scopes."
   }
  ],
  "code": 403,
  "message": "Insufficient Permission: Request had insufficient authentication scopes."
 }
}
Run Code Online (Sandbox Code Playgroud)

关于我应该做什么的任何建议?

Kee*_*asa 6

身份验证范围允许您的应用程序使用 OAuth2 身份验证对服务执行某些操作。使用 google API 时,请参阅Google API 范围表

请参阅下图中的 Google Sheets API V4 相关范围。请确保不要提供可能影响您应用程序安全性的额外权限。

在此处输入图片说明

请注意:由于您计划更改范围,请先删除token.json在本地项目文件夹中创建的文件,然后再次允许访问您的应用程序。这将创建一个新token.json文件。


Con*_*tov 1

不要忘记允许访问您从 API 仪表板下载的 credential.json 中指定的电子邮件 (client_email) 工作表:

{
  "type": "service_account",
  "project_id": "XXXXXXXXXXX",
  "private_key_id": ".........",
  "private_key": .........
  "client_email": "getgooglesheets@xxxxxxxxxx.iam.gserviceaccount.com",
  "client_id": "..............",
  "auth_uri": "https://accounts.google.com/o/oauth2/auth",
  .......
}
Run Code Online (Sandbox Code Playgroud)

我的意思是,您应该转到 Google 表格文件并手动允许访问该电子邮件。这对我来说效果很好。