Browse Source

Only delete old data if new data was received.

Stan Jansen 4 years ago
parent
commit
72899ffbcf
1 changed files with 7 additions and 2 deletions
  1. 7 2
      voedingscentrum.py

+ 7 - 2
voedingscentrum.py

@@ -63,6 +63,9 @@ def download_data():
 
     # Download de XML
     r = s.post("https://mijn.voedingscentrum.nl/nl/dashboard/eetmeter/overzicht/", data=data)
+    if r.status_code != 200:
+        print(f"No data was available between {DATE_FROM} and {DATE_TO} (error code {r.status_code}).")
+        return None
     r.encoding = 'utf-8'
     return ElementTree.fromstring(r.text)
 
@@ -115,9 +118,11 @@ DATE_TO = parse_date(args.to_date) if args.to_date else date.today()
 
 conn = psycopg2.connect(**DATABASE)
 cursor = conn.cursor()
-cursor.execute(f"DELETE FROM consumpties_{args.dbuser} WHERE datum BETWEEN %s AND %s", (DATE_FROM, DATE_TO))
-
 data = download_data()
+
+if data:
+    cursor.execute(f"DELETE FROM consumpties_{args.dbuser} WHERE datum BETWEEN %s AND %s", (DATE_FROM, DATE_TO))
+
 for product, consumptie in extract_consumpties(data):
     insert_product(cursor, **product)
     insert_consumptie(cursor, **consumptie)