【问题标题】:Writing in Google Sheets API v4 using Python使用 Python 在 Google Sheets API v4 中编写
【发布时间】:2016-10-22 00:45:03
【问题描述】:

我一直在努力通过阅读示例来使我的代码正常工作,但我找不到有关使用 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")

不工作的功能是比较的,控制台说:“请求的身份验证范围不足”。我什至无法理解这意味着什么。 顺便说一下,这里有函数 get_credentials():

def get_credentials():
"""Gets valid user credentials from storage.

If nothing has been stored, or if the stored credentials are invalid,
the OAuth2 flow is completed to obtain the new credentials.

Returns:
    Credentials, the obtained credential.
"""
home_dir = os.path.expanduser('~')
credential_dir = os.path.join(home_dir, '.credentials')
if not os.path.exists(credential_dir):
    os.makedirs(credential_dir)
credential_path = os.path.join(credential_dir,
                               'sheets.googleapis.com-python-quickstart.json')

store = Storage(credential_path)
credentials = store.get()
if not credentials or credentials.invalid:
    flow = client.flow_from_clientsecrets(CLIENT_SECRET_FILE, SCOPES)
    flow.user_agent = APPLICATION_NAME
    if flags:
        credentials = tools.run_flow(flow, store, flags)
    else: # Needed only for compatibility with Python 2.6
        credentials = tools.run(flow, store)
    print('Storing credentials to ' + credential_path)
return credentials

这里我已经导入了所有模块:

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 sheet 中编写的工作代码示例,那将非常有帮助。另外,如果您需要有关代码的更多信息,请告诉我。 (我只是一个菜鸟学生。)

编辑: 我已经改变了这个:

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

谢谢!

【问题讨论】:

  • 您在修改 SCOPES 后是否再次通过 OAuth2 流程?
  • 我该怎么做?
  • 不确定最好的方法,但您可以尝试重命名~/.credentials 目录,或者可能是该目录中最近修改的文件。
  • 现在可以使用了!谢谢!

标签: python google-sheets-api


【解决方案1】:

好吧,请确保您启用您在此处使用的所有 API,尤其是开发者控制台中的 Sheets API

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

因此,请务必按照此documentation 上的步骤操作,了解如何使用 OAuth 授权您的请求。

更多信息可以查看这个相关的SO question

【讨论】:

猜你喜欢
  • 1970-01-01
  • 2016-10-13
  • 2018-11-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-06-27
  • 1970-01-01
  • 2018-03-10
相关资源
最近更新 更多