質問をすることでしか得られない、回答やアドバイスがある。

15分調べてもわからないことは、質問しよう!

新規登録して質問してみよう
ただいま回答率
85.50%
Python 3.x

Python 3はPythonプログラミング言語の最新バージョンであり、2008年12月3日にリリースされました。

Q&A

解決済

2回答

3889閲覧

Google spreadsheets APIアクセストークン3600秒制約解消できないでしょうか

kamenogotoku

総合スコア16

Python 3.x

Python 3はPythonプログラミング言語の最新バージョンであり、2008年12月3日にリリースされました。

0グッド

0クリップ

投稿2019/08/15 16:59

Google spreadsheets APIを使って、書き込んでいます。
下記サンプルプログラムでの環境はJupyterですが、ラズパイから環境データを取得し書き込んでいこうとしています。
必ず3600秒で止まってしまうようですが、https://teratail.com/questions/190677
この制限を解消する「おまじないコード」もしくはプログラミング上の工夫などご教示いただけないでしょうか・・・?
よろしくお願い致します。

python3

1import time 2import gspread 3import json 4from oauth2client.service_account import ServiceAccountCredentials 5 6scope = ['https://spreadsheets.google.com/feeds','https://www.googleapis.com/auth/drive'] 7 8json_file = 'secret name.json' 9sheet_id = 'private id' #from google sheet 10sheet_name = 'trial' 11 12credentials = ServiceAccountCredentials.from_json_keyfile_name(json_file, scope) 13gc = gspread.authorize(credentials) 14sp = gc.open_by_key(sheet_id) 15wks = sp.worksheet(sheet_name) 16 17n = 0 18 19while True: 20 dt_now = datetime.datetime.now() 21 print (dt_now) 22 t = str(dt_now) 23 n = n + 1 24 wks.update_cell(n+1, 1, t) 25 wks.update_cell(n+1, 2, 'X') 26 wks.update_cell(n+1, 3, 'Y') 27 time.sleep(10)

気になる質問をクリップする

クリップした質問は、後からいつでもMYページで確認できます。

またクリップした質問に回答があった際、通知やメールを受け取ることができます。

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

guest

回答2

0

ベストアンサー

ちょっとゴテゴテしてしまいましたけど、こんな感じで例外が発生したら再接続したら良いと思います。
record_to() に本来の処理したいことを書けばいいです。

python

1import time 2import gspread 3from oauth2client.service_account import ServiceAccountCredentials 4import datetime 5 6 7JSON_FILE = 'json_path' 8SHEET_ID = 'spread sheet id' # from google sheet 9SHEET_NAME = 'trial' 10 11 12def create_spreadsheet_client(json_file, sheet_id): 13 scope = ['https://spreadsheets.google.com/feeds', 'https://www.googleapis.com/auth/drive'] 14 credentials = ServiceAccountCredentials.from_json_keyfile_name(json_file, scope) 15 gc = gspread.authorize(credentials) 16 sp = gc.open_by_key(sheet_id) 17 return sp 18 19 20class RecordingData: 21 def __init__(self, json_file, sheet_id, sheet_name): 22 self.json_file = json_file 23 self.sheet_id = sheet_id 24 self.sheet_name = sheet_name 25 self.n = 1 # 0 startから、 1 startに 26 27 def start(self): 28 while True: # 例外が出たら、単に再度 spreadsheet client を作成する、ためのLoop 29 sp = create_spreadsheet_client(self.json_file, self.sheet_id) 30 wks = sp.worksheet(self.sheet_name) 31 try: 32 self.record_to(wks) 33 except gspread.client.APIError as e: 34 # APIErrorの場合は例外の内容を表示だけして無視する 35 print(e) 36 print(repr(e)) 37 38 def record_to(self, wks): # 本当にやりたいこと 39 while True: 40 dt_now = datetime.datetime.now() 41 print(dt_now) 42 t = str(dt_now) 43 ### update_cells でまとめて更新する方が rate limits に抵触しにくい 44 # wks.update_cell(self.n+1, 1, t) 45 # wks.update_cell(self.n+1, 2, 'X') 46 # wks.update_cell(self.n+1, 3, 'Y') 47 48 ### 例えばこんな感じ 49 values = [t, 'X', 'Y'] 50 cell_list = [gspread.models.Cell(self.n+1, col+1, value) for col, value in enumerate(values)] 51 wks.update_cells(cell_list) 52 53 # 54 self.n += 1 # 更新が完了してから n+=1 をする(例外で行があかないように) 55 time.sleep(10) 56 57 58if __name__ == '__main__': 59 RecordingData(JSON_FILE, SHEET_ID, SHEET_NAME).start()

↓ エラー後、復帰しました

2019-08-16 11:33:34.704473 2019-08-16 11:33:45.105864 2019-08-16 11:33:56.156234 { "error": { "code": 401, "message": "Request had invalid authentication credentials. Expected OAuth 2 access token, login cookie or other valid authentication credential. See https://developers.google.com/identity/sign-in/web/devconsole-project.", "status": "UNAUTHENTICATED" } } APIError('{\n "error": {\n "code": 401,\n "message": "Request had invalid authentication credentials. Expected OAuth 2 access token, login cookie or other valid authentication credential. See https://developers.google.com/identity/sign-in/web/devconsole-project.",\n "status": "UNAUTHENTICATED"\n }\n}\n') 2019-08-16 11:33:57.831368 2019-08-16 11:34:08.644737

投稿2019/08/16 02:40

mokemokechicken

総合スコア948

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

kamenogotoku

2019/08/16 14:30

mokemokechickenさん 早速のアドバイスありがとうございます。 さきほど試してみましたが、まだうまくいってません。途中で止まってしまいます。APIエラーではなく、OSErrorと出てAnacondaうんぬんと続きます。じっくり検証してみます。取り急ぎ御礼まで。
kamenogotoku

2019/08/17 02:03

mokemokechickenさん うまくいったようです。前回はscopeを間違えて別の行にも入っていたせいでしょうか・・・ 修正して深夜に長時間連続で書き込めました。10秒に一回でしたのでGooglesheetが1000行でエラーになりましたがもう1000行追加で再開しました。環境データをあす10分に一回でとってみます。 深遠なプログラミング力に触れられ非常に勉強になりました!
mokemokechicken

2019/08/17 02:06

良かったです! 楽しそうなものを作ってて良いなぁ、と思いました(^^
guest

0

試したわけではないのですが、下記で同じような質問がでているので回答として記載します。

https://stackoverflow.com/questions/33596661/

簡単に言うとタイムアウトになる前に再度取得しなおせばよいみたいです。

投稿2019/08/16 02:11

yamap55

総合スコア1376

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

kamenogotoku

2019/08/16 14:31

yamap_55さん アドバイスありがとうございます。 まだ解釈中ですが、まずは中身勉強してみます。 取り急ぎ御礼まで。
guest

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

15分調べてもわからないことは
teratailで質問しよう!

ただいまの回答率
85.50%

質問をまとめることで
思考を整理して素早く解決

テンプレート機能で
簡単に質問をまとめる

質問する

関連した質問