]> ToastFreeware Gitweb - chrisu/seepark.git/blobdiff - owm.py
Use with statement for connection resource handling.
[chrisu/seepark.git] / owm.py
diff --git a/owm.py b/owm.py
index 74fe6c48e2e0fdb30eaa8e3c4aa3a478d0543281..1a55892a1cd0ba7bda3beb25b3dc7e186c107ca9 100755 (executable)
--- a/owm.py
+++ b/owm.py
@@ -8,18 +8,18 @@
 
 # needed packaes: python3-mysqldb python3-sqlalchemy
 
-from pprint import pprint
 import argparse
 import configparser
-import os
 import csv
 import datetime
-import math
 import json
-import warnings
+import math
+import os
+from pprint import pprint
+
 import sqlalchemy
-from sqlalchemy import create_engine
-import MySQLdb.cursors
+from sqlalchemy import create_engine, Table
+
 from seeparklib.openweathermap import openweathermap_json
 
 
@@ -52,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
@@ -82,20 +82,17 @@ def write_db(config, url, weather_json, weather_data):
     db = config.get('database','database')
 
     engine = create_engine('mysql+mysqldb://{}:{}@{}/{}'.format(user, pwd, host, db), echo=False)
-    conn = engine.connect()
-    row = dict(cityid=config.get('openweathermap', 'cityid'), url=url, result=json.dumps(weather_json))
-    row.update(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 ignore into openweathermap ({}) values ({})'.format(', '.join(sql_columns), ','.join(['%s'] * len(sql_columns)))
-    with warnings.catch_warnings():
-        # ignore _mysql_exceptions.Warning: Duplicate entry '3319578-2018-08-01 20:50:00' for key 'cityid_datetime'
-        warnings.simplefilter("ignore", category=MySQLdb.cursors.Warning)
-        conn.execute(sql, *sql_values)
-    conn.close()
+    with engine.connect() as conn:
+        row = dict(cityid=config.get('openweathermap', 'cityid'), url=url, result=json.dumps(weather_json))
+        row.update(weather_data)
+        for key, value in row.items():
+            if isinstance(value, float) and math.isnan(value):
+                row[key] = None
+        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()
 
 
 def main(configfile, debug):