first rather simple implementation of to_dict() for our Sensors object
authorgregor herrmann <gregor@toastfreeware.priv.at>
Thu, 5 Jul 2018 18:19:20 +0000 (20:19 +0200)
committergregor herrmann <gregor@toastfreeware.priv.at>
Thu, 5 Jul 2018 18:28:10 +0000 (20:28 +0200)
web/seepark_web.py

index de719ba0022292d79d7c296ee6660321e19a47ae..3ee9d9408ba6e08e4b52c04da6e133ab86deb3cd 100644 (file)
@@ -7,7 +7,7 @@ import sys
 from collections import defaultdict
 from flask import Flask, render_template, jsonify, request
 import flask.json
-from flask_sqlalchemy import SQLAlchemy
+from flask_sqlalchemy import SQLAlchemy, inspect
 
 
 app_path = os.path.dirname(os.path.realpath(__file__))
@@ -52,6 +52,10 @@ 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)
@@ -95,8 +99,9 @@ def select_sensordata(initial_where):
             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
+        return c3result
+    else:
+        return [row.to_dict() for row in result]
 
 
 def currentairtemperature(apikey, cityid):
@@ -131,7 +136,7 @@ def sensorid(version, sensor_id):
     format=<default|c3>, optional. return result as returned by sqlalchemy (default) or formatted for c3.js
     """
     result = select_sensordata(Sensors.sensor_id == sensor_id)
-    return jsonify([row._asdict() for row in result])
+    return jsonify(result)
 
 
 @app.route('/api/<version>/sensor/type/<sensor_type>')