web-dev-qa-db-ja.com

google api(sheets)リクエストの認証範囲が不十分でした

シートから書き込みデータを読み取りたいのですが、読み取りは正常に機能しますが、書き込みは機能しません。ドキュメントに記載されているすべてのスコープを使用します: https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets.values/append

data_writer(1,1,1)

コード:

from __future__ import print_function
from apiclient.discovery import build
from httplib2 import Http
from oauth2client import file, client, tools
# Setup the Sheets API
SCOPES = 'https://www.googleapis.com/auth/spreadsheets'+"https://www.googleapis.com/auth/drive.file"+"https://www.googleapis.com/auth/drive"
store = file.Storage('credentials.json')
creds = store.get()
if not creds or creds.invalid:
    flow = client.flow_from_clientsecrets('client_secret.json', SCOPES)
    creds = tools.run_flow(flow, store)
service = apiclient.discovery.build('sheets', 'v4', http=creds.authorize(Http()))

# Call the Sheets API
SPREADSHEET_ID = '1JwVOqtUCWBMm_O6esIb-9J4TgqAmMIdYm9sf5y-A7EM'
RANGE_NAME = 'Jokes!A:C'
# How the input data should be interpreted.
value_input_option = 'USER_ENTERED'  
# How the input data should be inserted.
insert_data_option = 'INSERT_ROWS' 

def data_reader():
    #reading data
    read = service.spreadsheets().values().get(spreadsheetId=SPREADSHEET_ID,range=RANGE_NAME).execute()
    #reading values
    values = read.get('values', [])
    if not values:
        print('No data found.')
    else:

        for row in values:
            print(row[2])
            continue
def data_writer(score,num_comments,mystring):
    value_range_body = {
        "score":score,
        "num_comments":num_comments,
        "joke":mystring
    }
    request = service.spreadsheets().values().append(spreadsheetId=SPREADSHEET_ID, range=RANGE_NAME, valueInputOption=value_input_option, insertDataOption=insert_data_option, body=value_range_body)
    response = request.execute()
2
extreme4all

SCOPESはタイプリストでなければなりません

SCOPES = [' https://www.googleapis.com/auth/spreadsheets '、 " https://www.googleapis.com/auth/drive.file " 、 " https://www.googleapis.com/auth/drive "]

補足:あなたは

.../auth/drive

そして

.../auth/drive.file

/drive.fileは、APIがdrive.file APIのみで動作するように制限しますが、/ driveはすべてのドライブAPIを開きます。したがって、ニーズに合ったものを選択する必要があります。

補足2:提供したリンクに基づいて、スプレッドシートを操作するには少なくとも1つのAPIが必要であると記載されているため、すべてのAPIが必要なわけではありません。

7
skarchmit

まず最初に必要なのはhttps://www.googleapis.com/auth/driveシートの読み取りと書き込みを含む、ユーザーのドライブアカウントへのフルアクセスを提供します。

すでにコードを一度実行してユーザーを認証した場合は、コードのスコープを変更してください。新しいスコープによって付与されたアクセスを取得するには、コードを再度実行し、ユーザーを再認証する必要があることに注意してください。

サイドノート:

SCOPES = 'https://www.googleapis.com/auth/spreadsheets'+"https://www.googleapis.com/auth/drive.file"+"https://www.googleapis.com/auth/drive"

スペースで区切るか、他の回答状態が配列を使用するため、1つの長い文字列になります。

SCOPES = 'https://www.googleapis.com/auth/spreadsheets ' + "https://www.googleapis.com/auth/drive.file " + "https://www.googleapis.com/auth/drive"
0
DaImTo