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