使用Python在googlesheets API v4中编写

2024-04-25 05:06:19 发布

您现在位置:Python中文网/ 问答频道 /正文

我一直在努力通过阅读示例来实现我的代码工作,但是我找不到一个关于使用API在工作表中编写的正确方法的示例。在

我的代码中有一部分不起作用:

def comprar(producto,cantidad):
credentials = get_credentials()
http = credentials.authorize(httplib2.Http())
discoveryUrl = ('https://sheets.googleapis.com/$discovery/rest?'
                'version=v4')
service = discovery.build('sheets', 'v4', http=http,
                          discoveryServiceUrl=discoveryUrl)

spreadsheetId = '1oN1WkdXSYIlsgjFKZX1YolwajNflqAgE20w8vcRaY8Y'
row = searchInCol("A",producto)
target = "Inventario!"+"J"+str(row)
values = [
    [
        # Cell values to be inputed...
        int(cantidad)
    ],
# Additional rows ...
]
body = {"values":values}
print("Entra")

#THIS ISN'T WOKRING
result = service.spreadsheets().values().update(
spreadsheetId=spreadsheetId, range=target,
valueInputOption="USER_ENTERED", body=body).execute()
print("entra")

不工作的函数是compar函数,控制台显示:“请求的身份验证范围不足”。我甚至不明白这是什么意思。 顺便说一下,这里有函数get_credentials():

^{pr2}$

在这里,我导入了所有模块:

from __future__ import print_function
import httplib2
import os
from apiclient import discovery
from oauth2client import client
from oauth2client import tools
from oauth2client.file import Storage
import time

如果有人能给我解释一点错误,并给出一个使用python和API在google工作表中编写工作代码的例子,那将非常有帮助。另外,如果你需要更多关于代码的信息,请告诉我。(我只是个普通学生。)

编辑: 我改了这个:

SCOPES = 'https://www.googleapis.com/auth/spreadsheets.readonly'

为此:

SCOPES = 'https://www.googleapis.com/auth/spreadsheets'

但它总是抛出以下错误:

Traceback (most recent call last):
  File "quickstart.py", line 210, in <module>
  comprar(pro,cnt)
  File "quickstart.py", line 196, in comprar
valueInputOption="USER_ENTERED", body=body).execute()
  File "/usr/local/lib/python2.7/dist-packages/oauth2client/_helpers.py", line 133, in positional_wrapper
return wrapped(*args, **kwargs)
  File "/usr/local/lib/python2.7/dist-packages/googleapiclient/http.py", line 838, in execute
raise HttpError(resp, content, uri=self.uri)
googleapiclient.errors.HttpError: <HttpError 403 when requesting https://sheets.googleapis.com/v4/spreadsheets/1oN1WkdXSYIlsgjFKZX1YolwajNflqAgE20w8vcRaY8Y/values/Inventario%21J1?alt=json&valueInputOption=USER_ENTERED returned "Request had insufficient authentication scopes.">

谢谢!在


Tags: 代码frompyhttpsimportcomhttpline
1条回答
网友
1楼 · 发布于 2024-04-25 05:06:19

好吧,确保启用这里使用的所有API,尤其是开发人员控制台中的Sheets API。在

您收到的错误"Request had insufficient authentication scopes"是请求中提供的OAuth 2.0令牌中的一个错误,该令牌指定您正在使用的scopes不足以访问请求的数据。在

因此,请确保按照documentation上的步骤操作,说明如何向OAuth授权您的请求。在

有关详细信息,请查看相关的SO question。在

相关问题 更多 >