X-Git-Url: https://git.toastfreeware.priv.at/chrisu/seepark.git/blobdiff_plain/ca2ff71b9a5b9d5efcdec8ec56c43c74f0818f4f..babe905207138d35d94b476a1f0b81d9514da7d8:/web/seepark_web.py?ds=inline diff --git a/web/seepark_web.py b/web/seepark_web.py index 3ee9d94..b132960 100644 --- a/web/seepark_web.py +++ b/web/seepark_web.py @@ -5,21 +5,29 @@ import configparser import os import sys from collections import defaultdict -from flask import Flask, render_template, jsonify, request +from flask import Flask, render_template, jsonify, request, abort, Response import flask.json from flask_sqlalchemy import SQLAlchemy, inspect app_path = os.path.dirname(os.path.realpath(__file__)) -lib_path = os.path.join(cur_path, '..') +lib_path = os.path.join(app_path, '..') sys.path.append(lib_path) from seeparklib.openweathermap import openweathermap_json, OpenWeatherMapError +# https://stackoverflow.com/a/37350445 +def sqlalchemy_model_to_dict(model): + return {c.key: getattr(model, c.key) + for c in inspect(model).mapper.column_attrs} + + class JSONEncoder(flask.json.JSONEncoder): def default(self, object): if isinstance(object, datetime.datetime): return object.isoformat() + elif isinstance(object, db.Model): + return sqlalchemy_model_to_dict(object) return super().default(object) @@ -52,65 +60,129 @@ db.reflect(app=app) class Sensors(db.Model): __tablename__ = 'sensors' - # https://stackoverflow.com/a/37350445 - def to_dict(self): - return {c.key: getattr(self, c.key) - for c in inspect(self).mapper.column_attrs} -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) +class OpenWeatherMap(db.Model): + __tablename__ = 'openweathermap' + + +def select_sensordata(sensor_id, sensor_type, begin, end, mode): + query = Sensors.query + if sensor_id is not None: + query = query.filter(Sensors.sensor_id == sensor_id) + if sensor_type is not None: + query = query.filter(Sensors.value_type == sensor_type) 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() + if mode == 'consolidated' and begin is not None and end is not None: + # copied from munin/master/_bin/munin-cgi-graph.in + # interval in seconds for data points + resolutions = dict( + day = 300, + week = 1800, + month = 7200, + year = 86400, + ) + duration = (end - begin).total_seconds() + day = 60 * 60 * 24 + if duration < day: + resolution = resolutions['day'] + elif duration < 7 * day: + resolution = resolutions['week'] + elif duration < 31 * day: + resolution = resolutions['month'] + else: + resolution = resolutions['year'] + # TODO: filter out samples from 'result' + # something like + # select to_seconds(datetime) DIV (60*60*24) as interval_id, min(datetime), max(datetime), min(temp), avg(temp), max(temp), count(temp) from openweathermap group by interval_id order by interval_id; + return query.all() - mode = request.args.get('mode', 'full') - if mode == 'consolidated': - if begin is None or end is None: - pass + +def select_openweatherdata(cityid, begin, end, mode): + query = OpenWeatherMap.query.filter(OpenWeatherMap.cityid == cityid) + if begin is not None: + query = query.filter(OpenWeatherMap.datetime >= begin) + if end is not None: + query = query.filter(OpenWeatherMap.datetime <= end) + if mode == 'consolidated' and begin is not None and end is not None: + # copied from munin/master/_bin/munin-cgi-graph.in + # interval in seconds for data points + resolutions = dict( + day = 300, + week = 1800, + month = 7200, + year = 86400, + ) + duration = (end - begin).total_seconds() + day = 60 * 60 * 24 + if duration < day: + resolution = resolutions['day'] + elif duration < 7 * day: + resolution = resolutions['week'] + elif duration < 31 * day: + resolution = resolutions['month'] else: - # copied from munin/master/_bin/munin-cgi-graph.in - resolutions = dict( - day = 300, - week = 1800, - month = 7200, - year = 86400, - ) - duration = (end - begin).total_seconds() - day = 60 * 60 * 24 - if duration < day: - resolution = resolutions['day'] - elif duration < 7 * day: - resolution = resolutions['week'] - elif duration < 31 * day: - resolution = resolutions['month'] - else: - resolution = resolutions['year'] - # TODO: filter out samples from 'result' - # like loop over results and skip if timestamp(n+1)-timestamp(n), optional. return all rows (default) or with lower resolution (for charts) format=, optional. return result as returned by sqlalchemy (default) or formatted for c3.js """ - result = select_sensordata(Sensors.sensor_id == sensor_id) + result = sensordata(sensor_id=sensor_id) return jsonify(result) @@ -149,7 +221,21 @@ def sensortype(version, sensor_type): mode=, optional. return all rows (default) or with lower resolution (for charts) format=, optional. return result as returned by sqlalchemy (default) or formatted for c3.js """ - result = select_sensordata(Sensors.value_type == sensor_type) + result = sensordata(sensor_type=sensor_type) + return jsonify(result) + + +@app.route('/api//openweathermap/cities') +def openweathermap_cities(version): + """List all city IDs found in the database""" + result = db.session.query(OpenWeatherMap.cityid).distinct().all() + return jsonify(result) + + +@app.route('/api//openweathermap/city/') +def openweathermap_city(version, cityid): + """List all data found for a city""" + result = openweathermapdata(cityid=cityid) return jsonify(result) @@ -185,7 +271,7 @@ def data(timespan): @app.route("/") def index(): - airvalue, airtime = currentairtemperature(apikey, cityid) + airvalue, airtime = currentairtemperature(cityid) watervalue, watertime = currentwatertemperature(mainsensor) return render_template(