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