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 playhouse.shortcuts import model_to_dict
5from datetime import datetime
6
7current_latitude, current_longitude = 45.46437891252755, 7.872049153560152
8
9def update_record(record):
10 record.update()
11 record.latitude = current_latitude
12 record.longitude = current_longitude
13 record.timestamp = datetime.now()
14 record.aqi = get_aqi(current_latitude, current_longitude)
15 return record
16
17def record_to_dict(record):
18 temp = model_to_dict(record)
19 del temp["id"]
20 return temp
21
22def latest_or_abort():
23 latest = getLatestRecord()
24 if latest is None:
25 return abort(400)
26 return record_to_dict(latest)
27
28@app.route("/")
29def index_route():
30 if request.method == 'GET':
31 return render_template("index.html")
32
33editable_fields = ["t_target", "power", "fan_speed", "auto", "airflow"]
34
35@app.route("/data", methods = ['GET', 'POST'])
36def data_route():
37
38 if request.method == "GET":
39 return latest_or_abort()
40
41 latest = getLatestRecord()
42 form = request.form
43
44 for key in form.keys():
45 if key not in latest.keys():
46 continue
47 if key == "fan_speed" and latest["auto"]:
48 continue
49 latest[key] = form[key]
50
51 new_record = update_record(latest)
52 temp = record_to_dict(new_record)
53 addRecord(**temp)
54 return temp