ちょっとゴテゴテしてしまいましたけど、こんな感じで例外が発生したら再接続したら良いと思います。
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 14:30
2019/08/17 02:03
2019/08/17 02:06