all repos — iot-project @ d03d40d836de47ef3e661a2b2052bb97ffc452e7

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 latest_or_abort():
18    latest = getLatestRecord()
19    if latest is None:
20        return abort(400)
21    return latest
22
23@app.route("/")
24def index_route():
25    if request.method == 'GET':
26        return render_template("index.html")
27
28editable_fields = ["t_target", "power", "fan_speed", "auto", "airflow"]
29
30@app.route("/data", methods = ['GET', 'POST'])
31def data_route():
32
33    if request.method == "GET":
34        return latest_or_abort()
35    
36    latest = getLatestRecord()
37    form = request.form
38
39    for key in form.keys():
40        if key not in latest.keys():
41            continue
42        if key == "fan_speed" and latest["auto"]:
43            continue
44        latest[key] = form[key]
45
46    new_record = update_record(latest)
47    temp = model_to_dict(new_record)
48    del temp["id"]
49    addRecord(**temp)
50    return temp