2016-10-22 7 views
1

例を読むだけでコードを実行しようとしていますが、APIを使用して正しい書込み方法を見つけることができません。GoogleシートAPI v4でPythonを使用して書く

はここで機能していない私のコードの一部です:

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の一つであり、コンソールは言う:「リクエストが不十分認証のスコープを持っていました」。私はそれが何を意味するのか理解できません。

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 

そして、ここで私は、すべてのモジュールがインポートされている:ここでの方法は、関数のget_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シートに書き込むための作業コードを作成すると、本当に役に立ちます。また、コードに関する情報が必要な場合は、教えてください。 (私はただのnoobの学生です。)

編集:

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

ありがとう!

+0

SCOPESを変更した後にOAuth2フローを再開しましたか? – davejagoda

+0

どうすればいいですか? –

+0

最善の方法はわかりませんが、 '〜/ .credentials'ディレクトリ、またはおそらくそのディレクトリ内の最も最近変更されたファイルの名前を変更してみてください。 – davejagoda

答えて

2

さて、あなたはあなたのデベロッパーコンソールで、特にここシートのAPIを使用するすべてのAPIを有効ていることを確認してください。

エラー"Request had insufficient authentication scopes"は、使用しているscopesが要求されたデータにアクセスするには不十分であることを指定する要求に含まれているOAuth 2.0トークンにエラーがあります。

OAuthでリクエストを承認する方法については、documentationのこちらの手順を必ず実行してください。

この詳細については、SO questionを参照してください。

+0

これを変更しました –

+0

申し訳ありませんが、これを変更しました:SCOPES = 'https://www.googleapis.com/auth/drive' –

関連する問題