]> rtime.felk.cvut.cz Git - coffee/coffee-flask.git/blob - app.py
Add graphs with total coffee consumption on login screen
[coffee/coffee-flask.git] / app.py
1 from flask import Flask, render_template, send_file, request, session, redirect, url_for, make_response
2 from flask_cors import CORS
3
4 import numpy as np
5 import matplotlib
6 matplotlib.use('Agg')
7 import matplotlib.pyplot as plt
8 from matplotlib.ticker import MaxNLocator
9 from io import BytesIO
10
11 import coffee_db as db
12 import time
13 from datetime import date, timedelta
14
15 db.init_db()
16 app = Flask(__name__)
17 CORS(app, supports_credentials=True)
18 app.secret_key = b'_5#y2L"F4Q8z\n\xec]/'
19
20
21 @app.route('/')
22 def hello():
23     if "uid" in session:
24         uid = session["uid"]
25         return render_template('hello.html', name=db.get_name(uid))
26     return render_template('hello.html')
27
28
29 @app.route('/login', methods=["POST"])
30 @app.route('/login/<uid>')
31 def login(uid=None):
32     if request.method == "POST":
33         uid = request.data.decode("utf-8")
34     if uid is not None:
35         db.add_user(uid)
36         session["uid"] = uid
37     return redirect(url_for('user'))
38
39
40 @app.route('/logout')
41 def logout():
42     session.pop('uid', None)
43     return redirect(url_for('user'))
44
45
46 @app.route('/user')
47 def user():
48     if "uid" in session:
49         uid = session["uid"]
50         return render_template('user.html',
51                                name=db.get_name(uid),
52                                flavors=db.flavors(),
53                                count=db.coffee_count(uid, 0),
54                                stamp=time.time()
55                                )
56     return render_template('user.html', stamp=time.time())
57
58
59 @app.route('/user/rename')
60 def user_rename():
61     name = request.args.get("name")
62     if name and "uid" in session:
63         uid = session["uid"]
64         db.name_user(uid, name)
65     return redirect(url_for('user'))
66
67
68 @app.route("/coffee/graph_flavors")
69 def coffee_graph_flavors():
70     days = request.args.get('days', default = 0, type = int)
71     start = request.args.get('start', default = 0, type = int)
72
73     b = BytesIO()
74     if "uid" in session:
75         uid = session["uid"]
76         flavors, counts = zip(*db.coffee_flavors(uid, days, start))
77     else:
78         flavors, counts = zip(*db.coffee_flavors(None, days, start))
79     fig = plt.figure(figsize=(3, 3))
80     ax = fig.add_subplot(111)
81     ax.set_aspect(1)
82     ax.pie(counts, autopct=lambda p: '{:.0f}'.format(p * sum(counts)/100) if p != 0 else '')
83     ax.legend(flavors, bbox_to_anchor=(1.0, 1.0))
84
85     if "uid" in session:
86         ax.set_title("Your taste")
87     else:
88         ax.set_title("This week taste")
89
90     fig.savefig(b, format="svg", bbox_inches="tight")
91     b.seek(0)
92     return send_file(b, mimetype="image/svg+xml")
93
94
95 @app.route("/coffee/graph_history")
96 def coffee_graph_history():
97     b = BytesIO()
98     if "uid" in session:
99         uid = session["uid"]
100         hist = db.coffee_history(uid)
101     else:
102         hist = db.coffee_history()
103     if hist == []:
104         unix_days = tuple()
105         counts = tuple()
106         flavors = tuple()
107     else:
108         unix_days, counts, flavors = zip(*hist)
109     fig = plt.figure(figsize=(4, 3))
110     ax = fig.add_subplot(111)
111
112     list_flavor = sorted(db.flavors())
113     l = [{} for i in range(len(list_flavor))]
114     for ll in l:
115         for d in unix_days:
116             ll[d] = 0
117
118     for(d, c, f) in zip(unix_days, counts, flavors):
119         if f is None:
120             continue
121         what_f = 0
122         for i in range(len(list_flavor)):
123             if f == list_flavor[i]:
124                 what_f = i
125                 break
126         l[what_f][d] += c
127
128     z = list(0 for i in range(len(l[0])))
129     for flavor in range(len(list_flavor)):
130         sortedlist = [(k, l[flavor][k]) for k in sorted(l[flavor])]
131         x = [i[0] for i in sortedlist]
132         y = [i[1] for i in sortedlist]
133         ax.bar(range(len(x)), y, bottom=z)
134         z = [sum(i) for i in zip(y, z)]
135
136     unix_days = set(unix_days)
137     xdays = [i.strftime("%a") for i in [
138         date.today() - timedelta(j - 1) for j in
139         range(len(unix_days), 0, -1)]]
140     xdays[-1] = "TDY"
141     xdays[-2] = "YDA"
142     ax.set_xticks(range(len(unix_days)))
143     ax.set_xticklabels(xdays)
144
145     if "uid" in session:
146         ax.set_title("Your week")
147     else:
148         ax.set_title("This week total")
149
150     ax.yaxis.set_major_locator(MaxNLocator(integer=True))
151     fig.savefig(b, format="svg", bbox_inches="tight")
152     b.seek(0)
153     plt.close(fig)
154     return send_file(b, mimetype="image/svg+xml")
155
156
157 @app.route("/coffee/add", methods=["POST"])
158 def coffee_add():
159     if request.method == "POST":
160         json = request.json
161         print("User '%(uid)s' had '%(flavor)s' at %(time)s" % json)
162         db.add_coffee(json["uid"], json["flavor"], json["time"])
163     return redirect(url_for('user'))
164
165
166 @app.route("/coffee/count")
167 def coffee_count():
168     start = request.args.get("start")
169     stop = request.args.get("stop")
170     return str(db.coffee_count(session.get("uid"), start, stop))
171
172
173 @app.route('/js')
174 def js():
175     response = make_response(render_template('main.js'))
176     response.headers['Content-Type'] = "text/javascript"
177     return response
178
179
180 @app.route("/log", methods=["POST"])
181 def log():
182     if request.method == "POST":
183         data = request.data.decode("utf-8")
184         print("Log:", data)
185         return data
186     return "nope"