-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathapp.py
346 lines (243 loc) · 9.61 KB
/
app.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
import logging
import os
from logging.handlers import TimedRotatingFileHandler
from flask import Flask, flash, g, redirect, render_template, request, session, url_for
from flask_mail import Mail, Message
from flask_sqlalchemy import SQLAlchemy
from sqlalchemy import exc
from wb.forms import BuilderForm, HubForm, RimForm, SearchForm
from wb.models import Hubs, Mru, Rims, Wheel, metadata, spoke_lengths, nipple_size_for_display
app = Flask(__name__)
FORMAT = "%(asctime)-15s [%(filename)s:%(lineno)s : %(funcName)s()] %(message)s"
formatter = logging.Formatter(FORMAT)
# initialize the log handler
logHandler = TimedRotatingFileHandler('logs/app.log', when='D', backupCount=7)
logHandler.setFormatter(formatter)
# set the app logger level
app.logger.setLevel(logging.DEBUG)
app.logger.addHandler(logHandler)
app.logger.info("Starting up...")
config = os.environ.get('WB_CONFIG', 'config.DevelopmentConfig')
app.config.from_object(config)
if app.config['SENTRY_DSN']:
import sentry_sdk
from sentry_sdk.integrations.flask import FlaskIntegration
sentry_sdk.init(
dsn=app.config['SENTRY_DSN'],
integrations=[FlaskIntegration()],
# Set traces_sample_rate to 1.0 to capture 100%
# of transactions for performance monitoring.
# We recommend adjusting this value in production,
traces_sample_rate=1.0
)
db = SQLAlchemy(metadata=metadata)
db.init_app(app)
ITEMS_PER_PAGE = 15
def bform(data=None):
# app.logger.info(session)
b = BuilderForm(data,
hub_field=session['wheel']['hub_id'],
rim_field=session['wheel']['rim_id'],
spoke_field=session['wheel']['spokes'],
pattern_field=session['wheel']['pattern'],
nipple_length_field=session['wheel']['nipple_length'],
)
b.hub_field.choices = session['hub_mru']
b.rim_field.choices = session['rim_mru']
return b
@app.before_request
def before_request():
try:
db.engine.execute('SELECT 1 from rims')
except exc.SQLAlchemyError as e:
return f"{e}<br>Wheelbuilder is unavailable at the moment", 503
if 'wheel' not in session:
session['wheel'] = Wheel().__dict__
if 'rim_mru' not in session:
session['rim_mru'] = []
if 'hub_mru' not in session:
session['hub_mru'] = []
if 'lengths' not in session:
session['lengths'] = (0, 0)
@app.route('/')
def index():
g.bform = bform()
return render_template('index.html.j2', show_builder=True)
@app.route('/wheel', methods=["POST"])
def wheel():
# app.logger.info(session)
b_form = bform(request.form)
if b_form.validate():
if b_form.hub_field.data != session['wheel']['hub_id']:
try:
hub = db.session.query(Hubs).filter_by(id=b_form.hub_field.data).first()
session['wheel']['hub_id'] = hub.id
session['hub'] = hub.as_dict()
mru = Mru(session['hub_mru'])
mru.add(hub.mru_props)
session['hub_mru'] = mru.queue
except Exception as e:
app.logger.exception(e)
if b_form.rim_field.data != session['wheel']['rim_id']:
try:
rim = db.session.query(Rims).filter_by(id=b_form.rim_field.data).first()
session['wheel']['rim_id'] = rim.id
session['rim'] = rim.as_dict()
mru = Mru(session['rim_mru'])
mru.add(rim.mru_props)
session['rim_mru'] = mru.queue
except Exception as e:
app.logger.error(e)
session['wheel']['spokes'] = b_form.spoke_field.data
session['wheel']['pattern'] = b_form.pattern_field.data
session['wheel']['nipple_length'] = b_form.nipple_length_field.data
session['wheel']['nipple_length_for_display'] = nipple_size_for_display(b_form.nipple_length_field.data)
session.modified = True
else:
for e in b_form.errors.items():
app.logger.error(e)
if 'hub' in session and 'rim' in session:
session['lengths'] = spoke_lengths(session['wheel'], session['hub'], session['rim'])
# app.logger.info(session)
return redirect(url_for('index'))
@app.route('/wheel/add_rim/<int:rim_id>')
def wheel_add_rim(rim_id=None):
try:
rim = db.session.query(Rims).filter_by(id=rim_id).first()
session['wheel']['rim_id'] = rim.id
session['rim'] = rim.as_dict()
mru = Mru(session['rim_mru'])
mru.add(rim.mru_props)
session['rim_mru'] = mru.queue
except Exception as e:
app.logger.error(e)
if 'hub' in session and 'rim' in session:
session['lengths'] = spoke_lengths(session['wheel'], session['hub'], session['rim'])
# app.logger.info(session)
return redirect(url_for('index'))
@app.route('/wheel/add_hub/<int:hub_id>')
def wheel_add_hub(hub_id=None):
try:
hub = db.session.query(Hubs).filter_by(id=hub_id).first()
session['wheel']['hub_id'] = hub.id
session['hub'] = hub.as_dict()
mru = Mru(session['hub_mru'])
mru.add(hub.mru_props)
session['hub_mru'] = mru.queue
session.modified = True
except Exception as e:
app.logger.error(e)
if 'hub' in session and 'rim' in session:
session['lengths'] = spoke_lengths(session['wheel'], session['hub'], session['rim'])
# app.logger.info(session)
return redirect(url_for('index'))
@app.route('/wheel_print')
def wheel_print():
rim = db.session.query(Rims).filter_by(id=session['wheel']['rim_id']).first()
hub = db.session.query(Hubs).filter_by(id=session['wheel']['hub_id']).first()
return render_template('print.html.j2',
show_builder=False,
hub=hub,
rim=rim,
wheel=session['wheel'])
@app.route('/rims/add', methods=["GET", "POST"])
def rims_add():
form = RimForm(request.form)
if request.method == "POST" and form.validate_on_submit():
rim = Rims()
form.populate_obj(rim)
db.session.add(rim)
db.session.commit()
flash("Rim Created")
if app.config.get('MAIL_SERVER', None):
mail = Mail(app)
body = render_template('rims_email.txt.j2', form=form, rim=rim)
msg = Message(subject="New Rim submitted",
body=body,
recipients=[app.config.get('MAIL_TO', None)])
try:
mail.send(msg)
except Exception as e:
app.logger.error(e)
return redirect(url_for("wheel_add_rim", rim_id=rim.id))
else:
for e in form.errors.items():
flash(f"{e[0]} - {e[1][0]}")
return render_template('rims_add.html.j2',
form=form)
@app.route('/rims/list')
@app.route('/rims/list/<int:page>')
def rims_list(page=1):
g.bform = bform()
g.sform = SearchForm(request.args)
rims = db.session.query(Rims)
form = SearchForm(request.args)
if form.validate():
size = form.size.data
search = form.search.data
if size:
rims = rims.filter(Rims.size == size)
if search:
rims = rims.filter(Rims.description.like(f"%{search}%"))
else:
for e in form.errors.items():
app.logger.error(e)
rims = rims.order_by(Rims.description.asc()).paginate(page=page, per_page=ITEMS_PER_PAGE)
return render_template('rims.html.j2',
rims_paginated=rims,
form=form,
show_builder=True)
@app.route('/hubs/add', methods=["GET", "POST"])
def hubs_add():
form = HubForm(request.form)
if request.method == "POST" and form.validate_on_submit():
hub = Hubs()
form.populate_obj(hub)
db.session.add(hub)
db.session.commit()
flash("Hub Created")
if app.config.get('MAIL_SERVER', None):
mail = Mail(app)
body = render_template('hubs_email.txt.j2', form=form, hub=hub)
msg = Message(subject="New Hub submitted",
body=body,
sender="[email protected]",
recipients=[app.config.get('MAIL_TO', None)])
try:
mail.send(msg)
except Exception as e:
app.logger.error(e)
return redirect(url_for("wheel_add_hub", hub_id=hub.id))
else:
for e in form.errors.items():
flash(f"{e[0]} - {e[1][0]}")
return render_template('hubs_add.html.j2',
form=form)
@app.route('/hubs/list')
@app.route('/hubs/list/<int:page>')
def hubs_list(page=1):
# app.logger.info(session)
g.bform = bform()
g.sform = SearchForm(request.args)
hubs = db.session.query(Hubs)
form = SearchForm(request.args)
if form.validate():
forr = form.forr.data
search = form.search.data
if forr and forr in ['F', 'R']:
hubs = hubs.filter(Hubs.forr == forr)
if search:
hubs = hubs.filter(Hubs.description.like(f"%{search}%"))
else:
for e in form.errors.items():
app.logger.error(e)
hubs = hubs.order_by(Hubs.description.asc()).paginate(page=page, per_page=ITEMS_PER_PAGE)
return render_template('hubs.html.j2',
hubs_paginated=hubs,
form=form,
show_builder=True)
@app.errorhandler(404)
def page_not_found(e):
return render_template('404.html.j2'), 404
if __name__ == '__main__':
app.run()