Move to_dict to JSONEncoder.
[chrisu/seepark.git] / web / seepark_web.py
index c96632191781caae2a5df734a36197f68b804076..fc28fdead7f895951f9fd03ccf72ddbf573d83b4 100644 (file)
@@ -16,10 +16,18 @@ 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,10 +60,6 @@ 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)
@@ -101,7 +105,7 @@ def select_sensordata(initial_where):
             c3result[row.sensor_id + '_x'].append(dt)
         return c3result
     else:
-        return [row.to_dict() for row in result]
+        return result
 
 
 def currentairtemperature(apikey, cityid):