Каждый раз, когда я запускаю эту программу, она запускается в первый раз, но во второй раз выдает эту ошибку в терминале:
Traceback (most recent call last):
File "main.py", line 30, in <module>
timenow = datetime.now()
File "main.py", line 27, in temperature
moApparent = regexApparentTemp.search(str(json_object))
File "/usr/local/lib/python3.7/dist-packages/gspread/models.py", line 888, in append_row
return self.spreadsheet.values_append(self.title, params, body)
File "/usr/local/lib/python3.7/dist-packages/gspread/models.py", line 119, in values_append
r = self.client.request('post', url, params=params, json=body)
File "/usr/local/lib/python3.7/dist-packages/gspread/client.py", line 79, in request
raise APIError(response)
gspread.exceptions.APIError: {
"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"
}
}
Код:
import requests, pprint, re, gspread, time
from oauth2client.service_account import ServiceAccountCredentials
from datetime import datetime
def temperature():
from oauth2client.service_account import ServiceAccountCredentials
from datetime import datetime
scope = ['https://spreadsheets.google.com/feeds', 'https://www.googleapis.com/auth/drive']
credentials = ServiceAccountCredentials.from_json_keyfile_name('Singapore-Weather-84def2be176a.json', scope)
gc = gspread.authorize(credentials)
wks = gc.open('Singapore Weather').sheet1
r = requests.get('https://api.darksky.net/forecast/b02b5107a2c9c27deaa3bc1876bcee81/1.312914,%20103.780257')
json_object = r.text
regexCurrentTemp = re.compile(r'"temperature":(\d\d.\d\d)')
moTemp = regexCurrentTemp.search(str(json_object))
temperature = moTemp.group(1)
regexApparentTemp = re.compile(r'"apparentTemperature":(\d\d.\d\d)')
moApparent = regexApparentTemp.search(str(json_object))
apparent = moApparent.group(1)
timenow = datetime.now()
wks.append_row([str(timenow), temperature, apparent])
while True:
temperature()
time.sleep(3597)
I поместите аутентификацию внутри функции в l oop, чтобы она работала, но это не так. В чем проблема?