forked from Mariki816/GlazeHub
/
glazehub_2.1PG_deploy.py
700 lines (548 loc) · 23 KB
/
glazehub_2.1PG_deploy.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
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
#This is my controller script
import modelPG
import converter
import pricecompute
from flask import Flask, session, render_template, request
from flask import redirect, flash
import jinja2
import json
import smtplib
import datetime
import os
from passlib.hash import pbkdf2_sha256
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
app = Flask(__name__)
app.secret_key = os.environ.get("FLASK_SECRET_KEY",
"HeLium_M4kes_Ur_v01c3_sQ34KY!")
app.jinja_env.undefined = jinja2.StrictUndefined
# This is the index page. Later it will show the Calculator itself
@app.route("/")
def index():
session["user_id"] = None
return render_template("index.html")
@app.route("/logout", methods=['GET'])
def Logout():
session.clear()
return redirect("/")
# This is the log in page.
@app.route("/login", methods=['GET'])
def showLoginPage():
session["user_id"] = None
return render_template("login.html")
def do_login(userID, userEmail, userName):
session["user"] = userEmail
session["user_id"] = userID
session["user_name"] = userName
return
# This processes a returning user
@app.route("/login", methods=['POST'])
def processLogin():
session["user_id"] = None
session["user_name"] = None
email = request.form.get("userEmail").lower()
password = request.form.get("password")
user = modelPG.User.getUserByEmail(email)
pwordcheck = modelPG.User.getUserPasswordByEmail(email)
if user:
if pbkdf2_sha256.verify(password, pwordcheck):
flash("Welcome, %s" % (user.user_name))
# if the user is already logged in do the first part
if "user" in session:
session["user_id"] = user.id
session["user_name"] = user.user_name
else:
do_login(user.id, email, user.user_name)
else:
flash("Invalid Email or Password. Please try again")
flash('<a href = "/resetpword">Reset Password</a>')
return render_template("login.html")
else:
flash("New User? Please create an account.")
session["user_id"] = None
session["user_name"] = None
return render_template("login.html")
return redirect("/userRecipes/%d" % user.id)
@app.route("/resetpword", methods=['GET'])
def startresetPword():
userEmail = None
password = None
passwordCheck = None
return render_template("resetpword.html", userEmail=userEmail,
password=password, passwordCheck=passwordCheck)
@app.route("/resetpword", methods=['POST'])
def resetPword():
tempPassword = request.form.get("newPassword")
print "this is tempPassword", tempPassword
tempPassword2 = request.form.get("passwordCheck")
if tempPassword == tempPassword2:
tempUserEmail = request.form.get("userEmail").lower()
user = modelPG.User.getUserByEmail(tempUserEmail)
hash = pbkdf2_sha256.encrypt(tempPassword,
rounds=200000, salt_size=16)
user.password = hash
modelPG.session.commit()
return render_template("login.html")
else:
flash("Passwords do not match. Please try again.")
return render_template("resetpword.html")
# This creates a New user
@app.route("/register", methods=['POST'])
def getNewUser():
session["user_id"] = None
session["user_name"] = None
newUser = modelPG.User()
newUser.user_name = request.form.get("NewUserName")
newUser.email = request.form.get("NewUserEmail").lower()
tempPassword = request.form.get("NewUserPassword")
hash = pbkdf2_sha256.encrypt(tempPassword, rounds=200000, salt_size=16)
newUser.password = hash
if modelPG.User.getUserByEmail(newUser.email):
flash("Email address already exists. Please log on or enter new email")
return render_template("login.html")
else:
modelPG.session.add(newUser)
modelPG.session.commit()
flash("Welcome, %s" % (newUser.user_name))
do_login(newUser.id, newUser.email, newUser.user_name)
return redirect("/userRecipes/%d" % newUser.id)
#This is the list of recipes of the logged in user
@app.route("/userRecipes/<int:userViewID>")
def listofUserRecipes(userViewID):
userLoginID = session["user_id"]
if checkUserLoginID(userLoginID, userViewID) is False:
flash("Invalid UserID. Here are your recipes")
userViewID = userLoginID
recipes = showUserRecipeList(userViewID)
return render_template("user_recipes.html", displayRecipes=recipes,
user_id=userViewID)
# This is the function to render the Enter Recipe page if not logged in
@app.route("/enterRecipe", methods=['GET'])
def renderEnterRecipeForm():
chems = modelPG.session.query(modelPG.Chem).all()
chemNames = [chem.chem_name for chem in chems]
batchComp = []
components = modelPG.Component()
if "user_id" in session:
user_id = session["user_id"]
else:
user_id = None
lbschecked = ""
kgchecked = 'checked = "checked"'
wholeNumList = []
frctnList = []
messageToUser = ""
batchsize = 0.0
recipename = ""
percentage = 0.0
session["chem"] = ""
session["percentage"] = 0.0
return render_template("enter_recipe.html", chem_names=chemNames,
batchComp=batchComp, user_id=user_id,
lbschecked=lbschecked, kgchecked=kgchecked,
wholeNumList=wholeNumList,
frctnList=frctnList,
chem_list=chems, messageToUser=messageToUser,
components=components, batchsize=batchsize,
recipename=recipename, percentage=percentage)
# This is the function to calculate on the Enter Recipe page if not logged in
@app.route("/enterRecipe", methods=["POST"])
def enterRecipe():
recipeName = request.form.get('recipename')
batchsize = request.form.get('batchsize')
newRecipe = modelPG.Recipe()
newRecipe.recipe_name = recipeName
batchComp = []
sizeflt = float(batchsize)
kgchecked = 'checked = "checked"'
lbschecked = ""
unitSys = "kg"
percent_list = []
wholeNumList = []
frctnList = []
messageToUser = None
chem_list = request.values.getlist('chem')
percentages = request.values.getlist('percentage')
if percentages == []:
flash("no entry")
return redirect("/enterRecipe")
i = 0
for chem in chem_list:
comp = modelPG.Component()
comp.chem_name = chem
comp.chem_id = modelPG.Chem.getChemIDByName(comp.chem_name)
comp.percentage = float(percentages[i])
percent_list.append(comp.percentage)
i += 1
comp.recipe_id = newRecipe.id
batchComp.append(float(comp.percentage))
onehundred = converter.checkPercent(percent_list)
newPercent = converter.getPercentMult(percent_list)
if onehundred is False:
messageToUser = "Recipe does not add up to 100. Amounts adjusted."
else:
messageToUser = None
for i in range(len(batchComp)):
batchComp[i] = (sizeflt * batchComp[i])*newPercent
wholeNumList.append(int(batchComp[i]))
if unitSys == "kg":
frctnList.append(int(converter.frctnKilosToGrams(batchComp[i])))
kgchecked = 'checked = "checked"'
else:
frctnList.append(int(converter.frctnPoundsToOunces(batchComp[i])))
lbschecked = 'checked = "checked"'
return render_template("calc_recipe.html",
recipe_name=newRecipe.recipe_name,
chem_list=chem_list, percentages=percentages,
batchComp=batchComp, batchsize=batchsize,
kgchecked=kgchecked, lbschecked=lbschecked,
unitSys=unitSys, wholeNumList=wholeNumList,
frctnList=frctnList, messageToUser=messageToUser)
# This is the function to render the Add Recipe page if logged in
@app.route("/addRecipe/<int:userViewID>", methods=['GET'])
def showRecipeAddForm(userViewID):
recipe_name = ""
price_quote = float(0.00)
displayRecipes = showUserRecipeList(userViewID)
chems = modelPG.session.query(modelPG.Chem).all()
chemNames = [chem.chem_name for chem in chems]
components = []
return render_template("add_recipe.html", chem_names=chemNames,
user_id=userViewID,
displayRecipes=displayRecipes,
recipe_name=recipe_name, components=components,
price_quote=price_quote)
# This function gets the recipe name from the form and
# adds it to the Recipes table
@app.route("/addRecipe/<int:userViewID>", methods=["POST"])
def addRecipe(userViewID):
displayRecipes = showUserRecipeList(userViewID)
recipe_name = request.form.get('recipename')
notes = request.form.get('usercomments')
dupe = modelPG.session.query(modelPG.Recipe)\
.filter_by(recipe_name=recipe_name)\
.filter_by(user_id=session["user_id"]).all()
if dupe != []:
flash("Duplicate Recipe Name")
return redirect("/addRecipe/" + str(userViewID))
newRecipe = modelPG.Recipe()
newRecipe.user_id = session["user_id"]
newRecipe.recipe_name = recipe_name
newRecipe.user_notes = notes
displayRecipes.append(newRecipe)
modelPG.session.add(newRecipe)
modelPG.session.commit()
batchComp = []
batchsize = None
chem_list = request.values.getlist("chem")
percentages = request.values.getlist("percentage")
i = 0
for chem in chem_list:
comp = modelPG.Component()
comp.chem_name = chem
comp.chem_id = modelPG.Chem.getChemIDByName(comp.chem_name)
comp.percentage = float(percentages[i])
i += 1
comp.recipe_id = newRecipe.id
batchComp.append(float(comp.percentage))
modelPG.session.add(comp)
modelPG.session.commit()
kgchecked = 'checked = "checked"'
lbschecked = ""
unitSys = "kg"
wholeNumList = []
frctnList = []
messageToUser = None
components = modelPG.Component.getComponentsByRecipeID(newRecipe.id)
return render_template("recipecomps.html", user_id=userViewID,
recipe_name=newRecipe.recipe_name,
components=components, batchComp=batchComp,
batchsize=batchsize,
displayRecipes=displayRecipes,
user_notes=newRecipe.user_notes,
kgchecked=kgchecked, lbschecked=lbschecked,
unitSys=unitSys, wholeNumList=wholeNumList,
frctnList=frctnList, messageToUser=messageToUser)
#this is the recipe page, checks user too
@app.route("/recipecomps/<int:userViewID>/<recipeName>")
def recipe(userViewID, recipeName):
displayRecipes = showUserRecipeList(userViewID)
userLoginID = session["user_id"]
if checkUserLoginID(userLoginID, userViewID) is False:
userViewID = userLoginID
recipes = modelPG.Recipe.getRecipeNamesByUserID(userLoginID)
return render_template("user_recipes.html", displayRecipes=recipes,
user_id=userLoginID)
else:
recipe = modelPG.Recipe.getRecipeIDByName(recipeName, userViewID)
components = modelPG.Component.getComponentsByRecipeID(recipe.id)
messageToUser = None
price_quote = 0.00
batchComp = []
wholeNumList = []
frctnList = []
batchsize = None
unit_sys = "unitSys"
lbschecked = ""
kgchecked = 'checked = "checked"'
return render_template("/recipecomps.html/", user_id=userViewID,
recipe_name=recipeName, components=components,
batchComp=batchComp,
displayRecipes=displayRecipes,
user_notes=recipe.user_notes,
messageToUser=messageToUser,
unitSys=unit_sys, batchsize=batchsize,
wholeNumList=wholeNumList, frctnList=frctnList,
lbschecked=lbschecked, kgchecked=kgchecked,
price_quote=price_quote)
# This section allows the user to change batchsizes
@app.route("/recipecomps/<userViewID>/<recipeName>", methods=["POST"])
def batchSizeChange(userViewID, recipeName):
displayRecipes = showUserRecipeList(userViewID)
size = request.form.get("batchsize")
units = request.form.get("unitSys")
recipe = modelPG.Recipe.getRecipeIDByName(recipeName, userViewID)
components = modelPG.Component.getComponentsByRecipeID(recipe.id)
batchComp = []
percent_list = []
for comp in components:
percent_list.append(comp.percentage)
onehundred = converter.checkPercent(percent_list)
newPercent = converter.getPercentMult(percent_list)
if onehundred is False:
messageToUser = "Recipe does not add up to 100. Amount adjusted."
else:
messageToUser = None
x = 0
for comp in components:
batchComp.append(comp.percentage/100)
x += 1
sizeflt = float(size)
wholeNumList = []
frctnList = []
kgchecked = ""
lbschecked = ""
priceList = []
compList = []
j = 0
for i in range(len(batchComp)):
batchComp[i] = (sizeflt * batchComp[i])*newPercent
chemID = modelPG.Chem.getChemIDByName(components[j].chem.chem_name)
wholeNumList.append(int(batchComp[i]))
if units == "kg":
frctnList.append(int(converter.frctnKilosToGrams(batchComp[i])))
kgchecked = 'checked = "checked"'
kgToPounds = converter.poundsToKilos(batchComp[i])
chemPrice = pricecompute.getPrice(chemID, kgToPounds)
priceList.append(chemPrice * batchComp[i])
else:
frctnList.append(int(converter.frctnPoundsToOunces(batchComp[i])))
lbschecked = 'checked = "checked"'
chemPrice = pricecompute.getPrice(chemID, batchComp[i])
priceList.append(chemPrice * batchComp[i])
dict_of_comp = {
'a_name': components[j].chem.chem_name[:35],
'b_percent': components[j].percentage,
'c_whole': wholeNumList[i],
'd_frctn': frctnList[i],
'e_chemPrice': priceList[i]
}
compList.append(dict_of_comp)
j += 1
sumprice = sum(priceList)
if units == "kg":
surcharge = pricecompute.getSurChargeKilos(sizeflt) * len(batchComp)
session["surcharge"] = surcharge
shipping = pricecompute.getShipping(converter.poundsToKilos(sizeflt))
else:
surcharge = pricecompute.getSurChargeLbs(sizeflt) * len(batchComp)
session["surcharge"] = surcharge
shipping = pricecompute.getShipping(sizeflt)
session["shipping"] = shipping
session["pre-tax-cost"] = round(sumprice, 2)
if sizeflt == 0:
price_quote = 0
else:
price_quote = round((sumprice + surcharge), 2)
orderItems = json.dumps(compList, sort_keys=True,
separators=(',', ': '))
session["orderList"] = orderItems
if (lbschecked == 'checked = "checked"'):
session["unitSys"] = "lbs"
else:
session["unitSys"] = "kilos"
return render_template("recipecomps.html", user_id=userViewID,
recipe_name=recipeName, batchComp=batchComp,
components=components,
displayRecipes=displayRecipes,
user_notes=recipe.user_notes,
messageToUser=messageToUser, batchsize=size,
wholeNumList=wholeNumList, frctnList=frctnList,
kgchecked=kgchecked, lbschecked=lbschecked,
unitSys=units, price_quote=price_quote,
compList=compList, orderItems=orderItems)
@app.route("/editRecipe/<userViewID>/<recipeName>", methods=['GET'])
def showEditRecipeForm(userViewID, recipeName):
userLoginID = session["user_id"]
recipe_name = recipeName
if userLoginID != int(userViewID):
flash("Invalid User ID. Here are your recipes. 2")
userViewID = userLoginID
recipes = modelPG.Recipe.getRecipeNamesByUserID(userLoginID)
return render_template("user_recipes.html", user_id=userViewID,
displayRecipes=recipes)
else:
displayRecipes = showUserRecipeList(userViewID)
chems = modelPG.session.query(modelPG.Chem).all()
chemNames = [chem.chem_name for chem in chems]
recipe = modelPG.Recipe.getRecipeIDByName(recipeName, userViewID)
components = modelPG.Component.getComponentsByRecipeID(recipe.id)
user_notes = recipe.user_notes
return render_template("edit_recipe.html", chem_names=chemNames,
user_id=userViewID,
displayRecipes=displayRecipes,
recipe_name=recipe_name, components=components,
user_notes=user_notes)
@app.route("/editRecipe/<int:userViewID>/<recipeName>", methods=["POST"])
def updateRecipe(userViewID, recipeName):
user_id = userViewID
recipe = modelPG.Recipe.getRecipeIDByName(recipeName, userViewID)
recipe.recipe_name = request.form.get("recipe_name")
recipe.user_notes = request.form.get("user_notes")
recipeName = recipe.recipe_name
components = modelPG.Component.getComponentsByRecipeID(recipe.id)
# Get rid of old recipe components
for comp in components:
modelPG.session.delete(comp)
modelPG.session.commit()
# Get new values for recipe components, names and percentages
chem_list = request.form.getlist("chem")
percentages = request.form.getlist("percentage")
i = 0
for chem in chem_list:
addComp = modelPG.Component()
addComp.chem_name = chem
addComp.chem_id = modelPG.Chem.getChemIDByName(addComp.chem_name)
addComp.percentage = float(percentages[i])
addComp.recipe_id = recipe.id
if (percentages[i] != 0) or percentages[i]:
modelPG.session.add(addComp)
modelPG.session.commit()
i += 1
else:
modelPG.session.commit()
return redirect("/recipecomps/%d/%s" % (user_id, recipeName))
@app.route("/deleteRecipe/<int:userViewID>/<recipeName>", methods=['GET'])
def deleteRecipe(userViewID, recipeName):
user_id = userViewID
recipe = modelPG.Recipe.getRecipeIDByName(recipeName, userViewID)
components = modelPG.Component.getComponentsByRecipeID(recipe.id)
modelPG.session.delete(recipe)
for comp in components:
modelPG.session.delete(comp)
modelPG.session.commit()
return redirect("/userRecipes/%d" % user_id)
#This sends you to a way to send a quote to Clay Planet
@app.route("/emailCP/<int:userViewID>/<recipeName>/<batchSize>",
methods=['GET'])
def emailCP(userViewID, recipeName, batchSize):
displayRecipes = showUserRecipeList(userViewID)
user_id = userViewID
recipeName = recipeName
unitSys = session["unitSys"]
subtotal = session["pre-tax-cost"] + session["surcharge"]
shipping_cost = session["shipping"]
msgSent = False
session["batchSize"] = batchSize
tax = pricecompute.getTax(subtotal)
session["tax"] = tax
orderList = session["orderList"]
data = json.loads(orderList)
return render_template("emailCP.html", user_id=user_id,
displayRecipes=displayRecipes,
recipeName=recipeName, batchsize=batchSize,
data=data, unitSys=unitSys, subtotal=subtotal,
shipping=shipping_cost, tax=tax, msgSent=msgSent)
@app.route("/emailCP/<int:userViewID>/<recipeName>/<batchSize>",
methods=["POST"])
def emailCPSend(userViewID, recipeName, batchSize):
displayRecipes = showUserRecipeList(userViewID)
user_name = session["user_name"]
user_id = userViewID
unitSys = session["unitSys"]
batchSize = session["batchSize"]
if unitSys == "lbs":
wholesys = "lbs"
frctnsys = "oz"
else:
wholesys = "kgs"
frctnsys = "grms"
customer = session["user"]
msgToCP = request.form.get("msgToCP")
orderList = session["orderList"]
data = json.loads(orderList)
surcharge = round(session["surcharge"], 2)
tax = round(session["tax"], 2)
subtotal = round(session["pre-tax-cost"], 2)
shipping = round(session["shipping"], 2)
price_quote = tax + subtotal + shipping + surcharge
order_time = str(datetime.datetime.utcnow())
gmail_user = "glazehub@gmail.com"
gmail_pwd = os.environ.get("EMAILPASSWORD", "secretpassword")
msg = MIMEMultipart('alternative')
msg['Subject'] = "Glaze Order" + order_time
msg['From'] = gmail_user
msg['To'] = "info@clay-planet.com"
msg['CC'] = "glazehub@gmail.com"
text = "Order from: " + customer + "\n" + \
"Message from Customer: " + msgToCP + "\n" + \
"Recipe Name: " + recipeName + "\n" +\
"Pounds/Kilos: " + wholesys + " " + frctnsys + "\n\n" +\
"SubTotal: %.2f " % (subtotal+surcharge) + "\n"\
"Tax: %.2f" % tax + "\n" + \
"Shipping: %.2f" % shipping + "\n"\
"Price Quote: %.2f" % price_quote
html = render_template("email.html", recipeName=recipeName, data=data,
batchsize=batchSize, unitSys=unitSys,
customer=customer, subtotal=subtotal,
surcharge=surcharge, shipping=shipping, tax=tax,
msgToCP=msgToCP, user_name=user_name)
part1 = MIMEText(text, 'plain')
part2 = MIMEText(html, 'html')
msg.attach(part1)
msg.attach(part2)
FROM = gmail_user
TO = ["info@clay-planet.com", "glazehub@gmail.com"]
server = smtplib.SMTP("smtp.gmail.com", 587)
server.ehlo()
server.starttls()
server.login(gmail_user, gmail_pwd)
server.sendmail(FROM, TO, msg.as_string())
server.close()
msgSent = True
return render_template("emailCP.html", user_id=user_id,
displayRecipes=displayRecipes,
userName=user_name, msgSent=msgSent)
@app.route("/error")
def error():
raise Exception("Error!")
# This function displays all recipes for the particular user
def showUserRecipeList(userViewID):
userLoginID = session["user_id"]
if checkUserLoginID(userLoginID, userViewID):
recipes = modelPG.Recipe.getRecipeNamesByUserID(userLoginID)
return recipes
else:
recipes = modelPG.Recipe.getRecipeNamesByUserID(userViewID)
return recipes
# This function checks userLogin and userViewID to make sure that
# logged in user only sees their own recipes
def checkUserLoginID(userLoginID, userViewID):
if userLoginID != int(userViewID):
flash("Invalid User ID. Here are your recipes")
userViewID = userLoginID
return False
if __name__ == "__main__":
PORT = int(os.environ.get("PORT", 5000))
DEBUG = "NO_DEBUG" not in os.environ
app.run(debug=DEBUG, host="0.0.0.0", port=PORT)