backend_iot/views.py (view raw)
1from backend_iot import app
2from backend_iot.db import getLatestRecord, addRecord, get_aqi
3from flask import request, redirect, render_template, abort
4from datetime import datetime
5
6current_latitude, current_longitude = 45.46437891252755, 7.872049153560152
7
8def update_record(record):
9 record["latitude"] = current_latitude
10 record["longitude"] = current_longitude
11 record["timestamp"] = datetime.now()
12 record["aqi"] = get_aqi(current_latitude, current_longitude)
13
14def latest_or_abort():
15 latest = getLatestRecord()
16 if latest is None:
17 return abort(400)
18 return latest
19
20@app.route("/")
21def index_route():
22 if request.method == 'GET':
23 return render_template("index.html")
24
25editable_fields = ["t_target", "power", "fan_speed", "auto", "airflow"]
26
27@app.route("/data", methods = ['GET', 'POST'])
28def data_route():
29
30 if request.method == "GET":
31 return latest_or_abort()
32
33 latest = getLatestRecord()
34 form = request.form
35
36 for key in form.keys():
37 if key not in latest.keys():
38 continue
39 if key == "fan_speed" and latest["auto"]:
40 continue
41 latest[key] = form[key]
42
43 update_record(latest)
44 addRecord(**latest)