]> ToastFreeware Gitweb - chrisu/seepark.git/blobdiff - owm.py
Update insert statement to work with sqlalchemy 2.
[chrisu/seepark.git] / owm.py
diff --git a/owm.py b/owm.py
index c41c3198039ba9526f8b158a79d87c06c32ccff4..307e91061454da269fd558ae1e52216e2e41dcdf 100755 (executable)
--- a/owm.py
+++ b/owm.py
@@ -6,15 +6,20 @@
 # cityid=..
 # 3319578 for Obsteig, AT
 
-from pprint import pprint
+# needed packaes: python3-mysqldb python3-sqlalchemy
+
 import argparse
 import configparser
-import os
 import csv
 import datetime
-import math
 import json
-from sqlalchemy import create_engine
+import math
+import os
+from pprint import pprint
+
+import sqlalchemy
+from sqlalchemy import create_engine, Table
+
 from seeparklib.openweathermap import openweathermap_json
 
 
@@ -47,7 +52,7 @@ def extractweatherdata(w):
 
     data['winddegrees'] = w['wind']['deg'] if 'deg' in w['wind'] else math.nan
     data['winddirection'] = degToCompass(data['winddegrees'])
-    data['precipitation'] = w['rain']['3h'] if 'rain' in w else math.nan
+    data['precipitation'] = w['rain']['3h'] if 'rain' in w and w['rain'].get('3h') else math.nan
     data['visibility'] = w.get('visibility', math.nan)
 
     return data
@@ -83,11 +88,11 @@ def write_db(config, url, weather_json, weather_data):
     for key, value in row.items():
         if isinstance(value, float) and math.isnan(value):
             row[key] = None
-    sql_columns = list(row.keys())
-    sql_values = list(row.values())
-    sql = 'insert into openweathermap ({}) values ({})'.format(', '.join(sql_columns), ','.join(['%s'] * len(sql_columns)))
-    print(sql)
-    conn.execute(sql, *sql_values)
+    metadata = sqlalchemy.MetaData()
+    openweathermap_table = Table('openweathermap', metadata, autoload_with=engine)
+    ins = openweathermap_table.insert().prefix_with('IGNORE').values(**row)
+    conn.execute(ins)
+    conn.commit()
     conn.close()