Start to use sqlalchemy (not all API calls work).
authorPhilipp Spitzer <philipp@spitzer.priv.at>
Wed, 4 Jul 2018 22:04:06 +0000 (00:04 +0200)
committerPhilipp Spitzer <philipp@spitzer.priv.at>
Wed, 4 Jul 2018 22:04:06 +0000 (00:04 +0200)
web/seepark_web.py

index 95c3f9dea734df366631f66bc8d3f1b12eb2aa01..065e3f2a6365535dfae30cff3146d3e43c7cc9a0 100644 (file)
@@ -7,8 +7,8 @@ import sys
 from collections import defaultdict
 from flask import Flask, render_template, jsonify, request
 import flask.json
-from sqlalchemy import create_engine
-import requests
+from flask_sqlalchemy import SQLAlchemy
+
 
 sys.path.append('..')
 from seeparklib.openweathermap import openweathermap_json, OpenWeatherMapError
@@ -25,41 +25,40 @@ def parse_datetime(date_str):
     return datetime.datetime.strptime(date_str, '%Y-%m-%dT%H:%M:%S')
 
 
-app = Flask(__name__)
-app.json_encoder = JSONEncoder
+def get_sqlalchemy_database_uri(config):
+    user = config.get('database', 'user')
+    pwd = config.get('database', 'password')
+    host = config.get('database', 'hostname')
+    db = config.get('database', 'database')
+    return 'mysql+mysqldb://{}:{}@{}/{}'.format(user, pwd, host, db)
+
+
 config = configparser.ConfigParser()
 config.read(os.environ['SEEPARKINI'])
 apikey = config.get('openweathermap', 'apikey')
 cityid = config.get('openweathermap', 'cityid')
 
+app = Flask(__name__)
+app.json_encoder = JSONEncoder
+app.config['SQLALCHEMY_DATABASE_URI'] = get_sqlalchemy_database_uri(config)
+app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
+db = SQLAlchemy(app)
+db.reflect(app=app)
+
 
-def open_engine(config):
-    user = config.get('database', 'user')
-    pwd = config.get('database', 'password')
-    host = config.get('database', 'hostname')
-    db = config.get('database', 'database')
-    engine = create_engine('mysql+mysqldb://{}:{}@{}/{}'.format(user, pwd, host, db), echo=False)
-    return engine
-
-
-def select_sensordata(initial_where, initial_sql_args):
-    engine = open_engine(config)
-    with engine.connect() as conn:
-        where = [initial_where]
-        sql_args = [initial_sql_args]
-        begin = None
-        end = None
-        if 'begin' in request.args:
-            where.append('timestamp>=%s')
-            begin = request.args.get('begin', None, parse_datetime)
-            sql_args.append(begin)
-        if 'end' in request.args:
-            where.append('timestamp<=%s')
-            end = request.args.get('end', None, parse_datetime)
-            sql_args.append(end)
-        sql = 'select * from sensors where {} order by id'.format(' and '.join(where))
-        cursor = conn.execute(sql, *sql_args)
-        result = [dict(row) for row in cursor]
+class Sensors(db.Model):
+    __tablename__ = 'sensors'
+
+
+def select_sensordata(initial_where):
+    query = Sensors.query.filter(initial_where)
+    begin = request.args.get('begin', None, parse_datetime)
+    end = request.args.get('end', None, parse_datetime)
+    if begin is not None:
+        query = query.filter(Sensors.timestamp >= begin)
+    if end is not None:
+        query = query.filter(Sensors.timestamp <= end)
+    result = query.all()
 
     mode = request.args.get('mode', 'full')
     if mode == 'consolidated':
@@ -90,9 +89,9 @@ def select_sensordata(initial_where, initial_sql_args):
     if format == 'c3':
         c3result = defaultdict(list)
         for row in result:
-            c3result[row['sensor_id']].append(row['value'])
-            dt = row['timestamp'].strftime('%Y-%m-%d %H:%M:%S')
-            c3result[row['sensor_id'] + '_x'].append(dt)
+            c3result[row.sensor_id].append(row.value)
+            dt = row.timestamp.strftime('%Y-%m-%d %H:%M:%S')
+            c3result[row.sensor_id + '_x'].append(dt)
         result = c3result
     return result
 
@@ -107,21 +106,15 @@ def currentairtemperature(apikey, cityid):
 
 
 def currentwatertemperature(sensorid):
-    engine = open_engine(config)
-    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']
+    result = Sensors.query.filter_by(sensor_id=sensorid).order_by(Sensors.timestamp.desc()).first()
+    return result.value, result.timestamp
 
 
 @app.route('/api/<version>/sensors/')
 def sensors(version):
     """List all sensors found in the database"""
-    engine = open_engine(config)
-    with engine.connect() as conn:
-        cursor = conn.execute('select distinct sensor_id, sensor_name, value_type from sensors')
-        result = [dict(row) for row in cursor]
-        return jsonify(result)
+    result = db.session.query(Sensors.sensor_id, Sensors.sensor_name, Sensors.value_type).distinct().all()
+    return jsonify(result)
 
 
 @app.route('/api/<version>/sensor/id/<sensor_id>')
@@ -134,8 +127,8 @@ def sensorid(version, sensor_id):
     mode=<full|consolidated>, optional. return all rows (default) or with lower resolution (for charts)
     format=<default|c3>, optional. return result as returned by sqlalchemy (default) or formatted for c3.js
     """
-    result = select_sensordata('sensor_id=%s', sensor_id)
-    return jsonify(result)
+    result = select_sensordata(Sensors.sensor_id == sensor_id)
+    return jsonify([row._asdict() for row in result])
 
 
 @app.route('/api/<version>/sensor/type/<sensor_type>')
@@ -148,7 +141,7 @@ def sensortype(version, sensor_type):
     mode=<full|consolidated>, optional. return all rows (default) or with lower resolution (for charts)
     format=<default|c3>, optional. return result as returned by sqlalchemy (default) or formatted for c3.js
     """
-    result = select_sensordata('value_type=%s', sensor_type)
+    result = select_sensordata(Sensors.value_type == sensor_type)
     return jsonify(result)