I’ve written a couple of bits of code I’ve reused
pickleHelper.py
This simplifies using pickle objects in code
import pickle def writeToPickle(_pickleName, _object): with open(_pickleName, 'wb') as file: pickle.dump(_object, file) def checkPickle(_pickleName): try: with open(_pickleName,"rb") as file: return pickle.load(file) except IOError: return False def updatePickleInPlace(_pickleName, _object): existing = checkPickle(_pickleName) if existing!=False: existing = checkPickle(_pickleName) for key, val in _object.items(): existing[key]=val writeToPickle(_pickleName, existing) else: writeToPickle(_pickleName, _object)
tadoAuth.py
I’ve replaced a chunk of my home heating system with Tado, this is a simple function to return and store the bearer token for API requests to view and change the settings. It assumes you have TADOUSER/TADOPASS in an environment file.
import requests, json, datetime from pickleHelper import checkPickle, updatePickleInPlace from requests.utils import quote import os from dotenv import load_dotenv load_dotenv() accessToken = "" refreshToken = "" expiresTime = datetime.datetime.now() pickleFile = "auth.pickle" def getTadoToken(): username=os.getenv('TADOUSER') password=quote(os.getenv('TADOPASS'), safe='') url="https://auth.tado.com/oauth/token?client_id=tado-web-app&grant_type=password&scope=home.user&username="+str(username)+"&password="+password+"&client_secret=wZaRN7rpjn3FoNyF5IFuxg9uMzYJcvOoQ8QWiIqS3hfk6gLhVlG57j5YNoZL2Rtc" #Don't worry, this isn't my secret! response = requests.post(url) accessToken=response.json()["access_token"] refreshToken=response.json()["refresh_token"] expiresTime=datetime.datetime.now() + datetime.timedelta(seconds=response.json()["expires_in"]) updatePickleInPlace(pickleFile, {"accessToken":accessToken, "refreshToken":refreshToken, "expiresTime":expiresTime}) return accessToken def returnTadoToken(): depickle = checkPickle(pickleFile) if (depickle==False): return getTadoToken() if (datetime.datetime.now() > depickle["expiresTime"]): return getTadoToken() else: return depickle["accessToken"]
Pingback: Charting my Smart Heating system | Alex's Blog