使用Python在Google表格API v4中书写

时间:2016-10-22 00:45:03

标签: python google-sheets-api

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

无效的功能是comprar one,控制台说:" Request的认证范围不足"。我甚至无法理解它的含义。 顺便说一句,你有函数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工作表中编写工作代码的示例,那将非常有用。此外,如果您需要有关代码的更多信息,请告诉我。 (我只是一个菜鸟学生。)

编辑: 我改变了这个:

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

谢谢!

1 个答案:

答案 0 :(得分:2)

确保您启用此处使用的所有API ,尤其是开发人员控制台中的表格API

您收到的错误"Request had insufficient authentication scopes"是请求中提供的OAuth 2.0令牌中的错误,该错误指定您使用的https://developers.google.com/chart/interactive/docs/animation不足以访问请求的数据。

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

有关详细信息,请查看相关的documentation