Use defaultdict to simplify code.
[chrisu/seepark.git] / web / seepark_web.py
index ce4347fb315e793e791f84151c17d1d1e6281ff7..95c3f9dea734df366631f66bc8d3f1b12eb2aa01 100644 (file)
@@ -3,11 +3,16 @@ import datetime
 import time
 import configparser
 import os
+import sys
+from collections import defaultdict
 from flask import Flask, render_template, jsonify, request
 import flask.json
 from sqlalchemy import create_engine
 import requests
 
+sys.path.append('..')
+from seeparklib.openweathermap import openweathermap_json, OpenWeatherMapError
+
 
 class JSONEncoder(flask.json.JSONEncoder):
     def default(self, object):
@@ -83,13 +88,9 @@ def select_sensordata(initial_where, initial_sql_args):
 
     format = request.args.get('format', 'default')
     if format == 'c3':
-        c3result = dict()
+        c3result = defaultdict(list)
         for row in result:
-            if not row['sensor_id'] in c3result:
-                c3result[row['sensor_id']] = list()
             c3result[row['sensor_id']].append(row['value'])
-            if not row['sensor_id'] + '_x' in c3result:
-                c3result[row['sensor_id'] + '_x'] = list()
             dt = row['timestamp'].strftime('%Y-%m-%d %H:%M:%S')
             c3result[row['sensor_id'] + '_x'].append(dt)
         result = c3result
@@ -97,18 +98,12 @@ def select_sensordata(initial_where, initial_sql_args):
 
 
 def currentairtemperature(apikey, cityid):
-    baseurl = 'http://api.openweathermap.org/data/2.5/weather'
-    query = baseurl + '?units=metric&APPID={}&id={}&lang=de'.format(apikey, cityid)
+    """Retruns the tuple temperature, datetime (as float, datetime) in case of success, otherwise None, None."""
     try:
-        response = requests.get(query)
-        if response.status_code != 200:
-            response = 'N/A'
-            return response, datetime.datetime.now().strftime('%Y-%m-%d %H:%M')
-        else:
-            weatherdata = response.json()
-            return weatherdata['main']['temp'], datetime.datetime.fromtimestamp(weatherdata['dt']).strftime('%Y-%m-%d %H:%M')
-    except requests.exceptions.RequestException as error:
-        print (error)
+        weatherdata = openweathermap_json(apikey, cityid)
+        return weatherdata['main']['temp'], datetime.datetime.fromtimestamp(weatherdata['dt'])
+    except OpenWeatherMapError:
+        return None, None
 
 
 def currentwatertemperature(sensorid):
@@ -116,7 +111,7 @@ def currentwatertemperature(sensorid):
     with engine.connect() as conn:
         cursor = conn.execute('select value, timestamp from sensors where sensor_id=%s order by timestamp desc limit 1', sensorid)
         result = [dict(row) for row in cursor]
-        return result[0]['value'], result[0]['timestamp'].strftime('%Y-%m-%d %H:%M')
+        return result[0]['value'], result[0]['timestamp']
 
 
 @app.route('/api/<version>/sensors/')
@@ -190,9 +185,7 @@ def data(timespan):
 @app.route("/")
 def index():
     airvalue, airtime     = currentairtemperature(apikey, cityid)
-    airvalue              = "{:.1f}".format(airvalue) if isinstance(airvalue, float) else airvalue
     watervalue, watertime = currentwatertemperature('0316a21383ff') # config? mainwatertemp?
-    watervalue            = "{:.1f}".format(watervalue) if isinstance(watervalue, float) else watervalue
 
     return render_template(
         'seepark_web.html',