1 from flask import Flask, render_template, send_file, request, session, redirect, url_for, make_response
2 from flask_cors import CORS
7 import matplotlib.pyplot as plt
8 from matplotlib.ticker import MaxNLocator
11 import coffee_db as db
13 from datetime import date, timedelta
17 CORS(app, supports_credentials=True)
18 app.secret_key = b'_5#y2L"F4Q8z\n\xec]/'
25 return render_template('hello.html', name=db.get_name(uid))
26 return render_template('hello.html')
29 @app.route('/login', methods=["POST"])
30 @app.route('/login/<uid>')
32 if request.method == "POST":
33 uid = request.data.decode("utf-8")
37 return redirect(url_for('user'))
42 session.pop('uid', None)
43 return redirect(url_for('user'))
50 return render_template('user.html',
51 name=db.get_name(uid),
53 count=db.coffee_count(uid, 0),
56 return render_template('user.html', stamp=time.time())
59 @app.route('/user/rename')
61 name = request.args.get("name")
62 if name and "uid" in session:
64 db.name_user(uid, name)
65 return redirect(url_for('user'))
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)
76 flavors, counts = zip(*db.coffee_flavors(uid, days, start))
78 flavors, counts = zip(*db.coffee_flavors(None, days, start))
79 fig = plt.figure(figsize=(3, 3))
80 ax = fig.add_subplot(111)
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))
86 ax.set_title("Your taste")
88 ax.set_title("This week taste")
90 fig.savefig(b, format="svg", bbox_inches="tight")
92 return send_file(b, mimetype="image/svg+xml")
95 @app.route("/coffee/graph_history")
96 def coffee_graph_history():
100 hist = db.coffee_history(uid)
102 hist = db.coffee_history()
108 unix_days, counts, flavors = zip(*hist)
109 fig = plt.figure(figsize=(4, 3))
110 ax = fig.add_subplot(111)
112 list_flavor = sorted(db.flavors())
113 l = [{} for i in range(len(list_flavor))]
118 for(d, c, f) in zip(unix_days, counts, flavors):
122 for i in range(len(list_flavor)):
123 if f == list_flavor[i]:
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)]
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)]]
142 ax.set_xticks(range(len(unix_days)))
143 ax.set_xticklabels(xdays)
146 ax.set_title("Your week")
148 ax.set_title("This week total")
150 ax.yaxis.set_major_locator(MaxNLocator(integer=True))
151 fig.savefig(b, format="svg", bbox_inches="tight")
154 return send_file(b, mimetype="image/svg+xml")
157 @app.route("/coffee/add", methods=["POST"])
159 if request.method == "POST":
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'))
166 @app.route("/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))
175 response = make_response(render_template('main.js'))
176 response.headers['Content-Type'] = "text/javascript"
180 @app.route("/log", methods=["POST"])
182 if request.method == "POST":
183 data = request.data.decode("utf-8")