-
Notifications
You must be signed in to change notification settings - Fork 1
/
api.py
68 lines (56 loc) · 2.55 KB
/
api.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
from flask import Flask, jsonify, abort, request, json
from sqlalchemy import desc, func
from sqlalchemy.orm.exc import NoResultFound
from db.models import db, Meta, Sensordata, meta_schema, metas_schema, sensordata_schema, sensordatas_schema
app = Flask(__name__)
app.config.from_pyfile('conf/psql-config.py')
db.init_app(app)
@app.before_first_request
def create_database():
db.create_all()
@app.route('/api/v1/sensors/', methods = ['GET'])
def get_all_sensors():
s = Meta.query.all()
# serialize the queryset
result = metas_schema.dump(s)
return jsonify({'sensors': result.data})
@app.route('/api/v1/sensors/<int:id>', methods = ['GET'])
def get_sensor(id):
try:
# m = Meta.query.get(id)
# in order to fetch NoResultFound exception it is neccessary to query the primary key as follows:
m = Meta.query.filter_by(sid=id).one()
meta_result = meta_schema.dump(m)
return jsonify({'sensors': meta_result.data})
except NoResultFound:
return jsonify({"message": "Sensor could not be found."}), 400
@app.route('/api/v1/sensors/<int:id>/data/', methods = ['GET'])
def get_all_data_sensor(id):
try:
m = Meta.query.filter_by(sid=id).one()
meta_result = meta_schema.dump(m)
sensor_result = sensordatas_schema.dump(m.sensordata.all())
return jsonify({'sensors': meta_result.data, 'data': sensor_result.data})
except NoResultFound:
return jsonify({"message": "Sensor could not be found."}), 400
# to be implemented
# @app.route("/api/v1/sensors/data/latest")
# def get_latest_data_all_sensors():
@app.route("/api/v1/sensors/<int:id>/data/latest", methods = ['GET'])
def get_latest_data_sensor(id):
try:
m = Meta.query.filter_by(sid=id).one()
meta_result = meta_schema.dump(m)
# query the latest unix_epoch for this <id>
# order_by: unix_epoch descending
# with_entities: only return column unix_epoch
# first(): only get first entry
qry = Sensordata.query.filter_by(sid=id).order_by(desc('unix_epoch')).with_entities('unix_epoch').first()
# convert this entry into a scalar representation that can be used for filtering
max = db.session.query(db.func.max(qry)).scalar()
sensor_result = sensordatas_schema.dump(m.sensordata.filter_by(unix_epoch=max))
return jsonify({'sensors': meta_result.data, 'data': sensor_result.data})
except NoResultFound:
return jsonify({"message": "Sensor could not be found."}), 400
if __name__ == '__main__':
app.run(debug=True, host='0.0.0.0', port=8080)