]> rtime.felk.cvut.cz Git - coffee/coffee-flask.git/blob - app.py
f4fdc7f78eee249188b731f673a58fb2ad04a077
[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')
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     b = BytesIO()
71     if "uid" in session:
72         uid = session["uid"]
73         flavors, counts = zip(*db.coffee_flavors(uid))
74     else:
75         flavors, counts = zip(*db.coffee_flavors())
76     fig = plt.figure(figsize=(3, 3))
77     ax = fig.add_subplot(111)
78     ax.set_aspect(1)
79     ax.pie(counts, autopct=lambda p: '{:.0f}'.format(p * sum(counts)/100))
80     ax.legend(flavors, bbox_to_anchor=(1.0, 1.0))
81     ax.set_title("Your taste")
82     fig.savefig(b, format="svg", bbox_inches="tight")
83     b.seek(0)
84     return send_file(b, mimetype="image/svg+xml")
85
86
87 @app.route("/coffee/graph_history")
88 def coffee_graph_history():
89     b = BytesIO()
90     if "uid" in session:
91         uid = session["uid"]
92         hist = db.coffee_history(uid)
93     else:
94         hist = db.coffee_history()
95     if hist == []:
96         days = tuple()
97         counts = tuple()
98         flavors = tuple()
99     else:
100         days, counts, flavors = zip(*hist)
101     fig = plt.figure(figsize=(4, 3))
102     ax = fig.add_subplot(111)
103
104     list_flavor = sorted(db.flavors())
105     l = [{} for i in range(len(list_flavor))]
106     for ll in l:
107         for d in days:
108             ll[d] = 0
109
110     for(d, c, f) in zip(days, counts, flavors):
111         if f is None:
112             continue
113         what_f = 0
114         for i in range(len(list_flavor)):
115             if f == list_flavor[i]:
116                 what_f = i
117                 break
118         l[what_f][d] += c
119
120     z = list(0 for i in range(len(l[0])))
121     for flavor in range(len(list_flavor)):
122         sortedlist = [(k, l[flavor][k]) for k in sorted(l[flavor])]
123         x = [i[0] for i in sortedlist]
124         y = [i[1] for i in sortedlist]
125         ax.bar(range(len(x)), y, bottom=z)
126         z = [sum(i) for i in zip(y, z)]
127
128     days = set(days)
129     xdays = [i.strftime("%a") for i in [
130         date.today() - timedelta(j - 1) for j in
131         range(len(days), 0, -1)]]
132     xdays[-1] = "TDY"
133     xdays[-2] = "YDA"
134     ax.set_xticks(range(len(days)))
135     ax.set_xticklabels(xdays)
136     ax.set_title("Your week")
137     ax.yaxis.set_major_locator(MaxNLocator(integer=True))
138     fig.savefig(b, format="svg", bbox_inches="tight")
139     b.seek(0)
140     plt.close(fig)
141     return send_file(b, mimetype="image/svg+xml")
142
143
144 @app.route("/coffee/add", methods=["POST"])
145 def coffee_add():
146     if request.method == "POST":
147         json = request.json
148         if json and "uid" in session:
149             db.add_coffee(session["uid"], json["flavor"], json["time"])
150     return redirect(url_for('user'))
151
152
153 @app.route("/coffee/count")
154 def coffee_count():
155     start = request.args.get("start")
156     stop = request.args.get("stop")
157     return str(db.coffee_count(session.get("uid"), start, stop))
158
159
160 @app.route('/js')
161 def js():
162     response = make_response(render_template('main.js'))
163     response.headers['Content-Type'] = "text/javascript"
164     return response
165
166
167 @app.route("/log", methods=["POST"])
168 def log():
169     if request.method == "POST":
170         data = request.data.decode("utf-8")
171         print(data)
172         return data
173     return "nope"