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

时间:2019-07-02 16:51:59

标签: python google-sheets anaconda google-sheets-api

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

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())

我收到的错误消息是

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."
 }
}

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

4 个答案:

答案 0 :(得分:2)

我在github上使用Google lib找到了一种新方法。这样做

import gspread
from google.oauth2.service_account import Credentials

scope = ['https://spreadsheets.google.com/feeds',
         'https://www.googleapis.com/auth/drive']

creds = Credentials.from_service_account_file('client_secret.json', scopes=scope)

client = gspread.authorize(creds) 

我使用了以下链接:https://github.com/burnash/gspread

答案 1 :(得分:0)

别忘了允许您访问从API仪表板下载的凭据.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",
  .......
}

我的意思是,您应该转到Google表格文件并在其中手动允许访问此电子邮件。就我而言,效果很好。

答案 2 :(得分:0)

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

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

enter image description here

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

答案 3 :(得分:0)

这就是我的工作方式,例如从谷歌表中读取文档

import gspread
from oauth2client.service_account import ServiceAccountCredentials
# use creds to create a client to interact with the Google Drive API
scope = ['https://spreadsheets.google.com/feeds',
         'https://www.googleapis.com/auth/drive']
creds = ServiceAccountCredentials.from_json_keyfile_name('my-drive.json', scope)
client = gspread.authorize(creds)

# Find a workbook by name and open the first sheet
# Make sure you use the right name here.
sheet = client.open("contactos-xxx").sheet1

# Extract and print all of the values
list_of_hashes = sheet.get_all_records()
print(list_of_hashes)