From aa1bea0db818edb422ca5db0d5636a9ec9f71388 Mon Sep 17 00:00:00 2001 From: Gabriel Augendre Date: Tue, 30 Jun 2020 08:10:48 +0200 Subject: [PATCH] Catch errors during server communication --- main.py | 37 +++++++++++++++++++++++-------------- 1 file changed, 23 insertions(+), 14 deletions(-) diff --git a/main.py b/main.py index 4cd6db9..fd877fb 100644 --- a/main.py +++ b/main.py @@ -1,4 +1,5 @@ import os +import sys from dotenv import load_dotenv import pendulum @@ -13,21 +14,29 @@ def main(): assert BASE_URL, "Must supply HASS_BASE_URL env variable" assert TOKEN, "Must supply HASS_TOKEN env variable" - client = requests.Session() - client.headers.update({ - "Authorization": f"Bearer {TOKEN}", - "Content-Type": "application/json", - }) - - url = f"{BASE_URL}/states/sensor.chambre_temperature" - bedroom = client.get(url) - bedroom.raise_for_status() - bedroom = bedroom.json() + try: + client.headers.update({ + "Authorization": f"Bearer {TOKEN}", + "Content-Type": "application/json", + }) - url = f"{BASE_URL}/states/sensor.exterieur_temperature" - outside = client.get(url) - outside.raise_for_status() - outside = outside.json() + url = f"{BASE_URL}/states/sensor.chambre_temperature" + bedroom = client.get(url, timeout=5) + bedroom.raise_for_status() + bedroom = bedroom.json() + + url = f"{BASE_URL}/states/sensor.exterieur_temperature" + outside = client.get(url, timeout=5) + outside.raise_for_status() + outside = outside.json() + except requests.exceptions.ConnectionError: + client.close() + print("Erreur lors de la connexion au serveur.") + sys.exit(1) + except Exception as e: + client.close() + print(f"Erreur inconnue: {e}") + sys.exit(1) print(format_temp(bedroom)) print(format_temp(outside))