-
Notifications
You must be signed in to change notification settings - Fork 34
/
application.py
282 lines (249 loc) · 11.8 KB
/
application.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
from cs50 import SQL
from flask_session import Session
from flask import Flask, render_template, redirect, request, session, jsonify
from datetime import datetime
# # Instantiate Flask object named app
app = Flask(__name__)
# # Configure sessions
app.config["SESSION_PERMANENT"] = False
app.config["SESSION_TYPE"] = "filesystem"
Session(app)
# Creates a connection to the database
db = SQL ( "sqlite:///data.db" )
@app.route("/")
def index():
shirts = db.execute("SELECT * FROM shirts ORDER BY team ASC")
shirtsLen = len(shirts)
# Initialize variables
shoppingCart = []
shopLen = len(shoppingCart)
totItems, total, display = 0, 0, 0
if 'user' in session:
shoppingCart = db.execute("SELECT team, image, SUM(qty), SUM(subTotal), price, id FROM cart GROUP BY team")
shopLen = len(shoppingCart)
for i in range(shopLen):
total += shoppingCart[i]["SUM(subTotal)"]
totItems += shoppingCart[i]["SUM(qty)"]
shirts = db.execute("SELECT * FROM shirts ORDER BY team ASC")
shirtsLen = len(shirts)
return render_template ("index.html", shoppingCart=shoppingCart, shirts=shirts, shopLen=shopLen, shirtsLen=shirtsLen, total=total, totItems=totItems, display=display, session=session )
return render_template ( "index.html", shirts=shirts, shoppingCart=shoppingCart, shirtsLen=shirtsLen, shopLen=shopLen, total=total, totItems=totItems, display=display)
@app.route("/buy/")
def buy():
# Initialize shopping cart variables
shoppingCart = []
shopLen = len(shoppingCart)
totItems, total, display = 0, 0, 0
qty = int(request.args.get('quantity'))
if session:
# Store id of the selected shirt
id = int(request.args.get('id'))
# Select info of selected shirt from database
goods = db.execute("SELECT * FROM shirts WHERE id = :id", id=id)
# Extract values from selected shirt record
# Check if shirt is on sale to determine price
if(goods[0]["onSale"] == 1):
price = goods[0]["onSalePrice"]
else:
price = goods[0]["price"]
team = goods[0]["team"]
image = goods[0]["image"]
subTotal = qty * price
# Insert selected shirt into shopping cart
db.execute("INSERT INTO cart (id, qty, team, image, price, subTotal) VALUES (:id, :qty, :team, :image, :price, :subTotal)", id=id, qty=qty, team=team, image=image, price=price, subTotal=subTotal)
shoppingCart = db.execute("SELECT team, image, SUM(qty), SUM(subTotal), price, id FROM cart GROUP BY team")
shopLen = len(shoppingCart)
# Rebuild shopping cart
for i in range(shopLen):
total += shoppingCart[i]["SUM(subTotal)"]
totItems += shoppingCart[i]["SUM(qty)"]
# Select all shirts for home page view
shirts = db.execute("SELECT * FROM shirts ORDER BY team ASC")
shirtsLen = len(shirts)
# Go back to home page
return render_template ("index.html", shoppingCart=shoppingCart, shirts=shirts, shopLen=shopLen, shirtsLen=shirtsLen, total=total, totItems=totItems, display=display, session=session )
@app.route("/update/")
def update():
# Initialize shopping cart variables
shoppingCart = []
shopLen = len(shoppingCart)
totItems, total, display = 0, 0, 0
qty = int(request.args.get('quantity'))
if session:
# Store id of the selected shirt
id = int(request.args.get('id'))
db.execute("DELETE FROM cart WHERE id = :id", id=id)
# Select info of selected shirt from database
goods = db.execute("SELECT * FROM shirts WHERE id = :id", id=id)
# Extract values from selected shirt record
# Check if shirt is on sale to determine price
if(goods[0]["onSale"] == 1):
price = goods[0]["onSalePrice"]
else:
price = goods[0]["price"]
team = goods[0]["team"]
image = goods[0]["image"]
subTotal = qty * price
# Insert selected shirt into shopping cart
db.execute("INSERT INTO cart (id, qty, team, image, price, subTotal) VALUES (:id, :qty, :team, :image, :price, :subTotal)", id=id, qty=qty, team=team, image=image, price=price, subTotal=subTotal)
shoppingCart = db.execute("SELECT team, image, SUM(qty), SUM(subTotal), price, id FROM cart GROUP BY team")
shopLen = len(shoppingCart)
# Rebuild shopping cart
for i in range(shopLen):
total += shoppingCart[i]["SUM(subTotal)"]
totItems += shoppingCart[i]["SUM(qty)"]
# Go back to cart page
return render_template ("cart.html", shoppingCart=shoppingCart, shopLen=shopLen, total=total, totItems=totItems, display=display, session=session )
@app.route("/filter/")
def filter():
if request.args.get('continent'):
query = request.args.get('continent')
shirts = db.execute("SELECT * FROM shirts WHERE continent = :query ORDER BY team ASC", query=query )
if request.args.get('sale'):
query = request.args.get('sale')
shirts = db.execute("SELECT * FROM shirts WHERE onSale = :query ORDER BY team ASC", query=query)
if request.args.get('id'):
query = int(request.args.get('id'))
shirts = db.execute("SELECT * FROM shirts WHERE id = :query ORDER BY team ASC", query=query)
if request.args.get('kind'):
query = request.args.get('kind')
shirts = db.execute("SELECT * FROM shirts WHERE kind = :query ORDER BY team ASC", query=query)
if request.args.get('price'):
query = request.args.get('price')
shirts = db.execute("SELECT * FROM shirts ORDER BY onSalePrice ASC")
shirtsLen = len(shirts)
# Initialize shopping cart variables
shoppingCart = []
shopLen = len(shoppingCart)
totItems, total, display = 0, 0, 0
if 'user' in session:
# Rebuild shopping cart
shoppingCart = db.execute("SELECT team, image, SUM(qty), SUM(subTotal), price, id FROM cart GROUP BY team")
shopLen = len(shoppingCart)
for i in range(shopLen):
total += shoppingCart[i]["SUM(subTotal)"]
totItems += shoppingCart[i]["SUM(qty)"]
# Render filtered view
return render_template ("index.html", shoppingCart=shoppingCart, shirts=shirts, shopLen=shopLen, shirtsLen=shirtsLen, total=total, totItems=totItems, display=display, session=session )
# Render filtered view
return render_template ( "index.html", shirts=shirts, shoppingCart=shoppingCart, shirtsLen=shirtsLen, shopLen=shopLen, total=total, totItems=totItems, display=display)
@app.route("/checkout/")
def checkout():
order = db.execute("SELECT * from cart")
# Update purchase history of current customer
for item in order:
db.execute("INSERT INTO purchases (uid, id, team, image, quantity) VALUES(:uid, :id, :team, :image, :quantity)", uid=session["uid"], id=item["id"], team=item["team"], image=item["image"], quantity=item["qty"] )
# Clear shopping cart
db.execute("DELETE from cart")
shoppingCart = []
shopLen = len(shoppingCart)
totItems, total, display = 0, 0, 0
# Redirect to home page
return redirect('/')
@app.route("/remove/", methods=["GET"])
def remove():
# Get the id of shirt selected to be removed
out = int(request.args.get("id"))
# Remove shirt from shopping cart
db.execute("DELETE from cart WHERE id=:id", id=out)
# Initialize shopping cart variables
totItems, total, display = 0, 0, 0
# Rebuild shopping cart
shoppingCart = db.execute("SELECT team, image, SUM(qty), SUM(subTotal), price, id FROM cart GROUP BY team")
shopLen = len(shoppingCart)
for i in range(shopLen):
total += shoppingCart[i]["SUM(subTotal)"]
totItems += shoppingCart[i]["SUM(qty)"]
# Turn on "remove success" flag
display = 1
# Render shopping cart
return render_template ("cart.html", shoppingCart=shoppingCart, shopLen=shopLen, total=total, totItems=totItems, display=display, session=session )
@app.route("/login/", methods=["GET"])
def login():
return render_template("login.html")
@app.route("/new/", methods=["GET"])
def new():
# Render log in page
return render_template("new.html")
@app.route("/logged/", methods=["POST"] )
def logged():
# Get log in info from log in form
user = request.form["username"].lower()
pwd = request.form["password"]
#pwd = str(sha1(request.form["password"].encode('utf-8')).hexdigest())
# Make sure form input is not blank and re-render log in page if blank
if user == "" or pwd == "":
return render_template ( "login.html" )
# Find out if info in form matches a record in user database
query = "SELECT * FROM users WHERE username = :user AND password = :pwd"
rows = db.execute ( query, user=user, pwd=pwd )
# If username and password match a record in database, set session variables
if len(rows) == 1:
session['user'] = user
session['time'] = datetime.now( )
session['uid'] = rows[0]["id"]
# Redirect to Home Page
if 'user' in session:
return redirect ( "/" )
# If username is not in the database return the log in page
return render_template ( "login.html", msg="Wrong username or password." )
@app.route("/history/")
def history():
# Initialize shopping cart variables
shoppingCart = []
shopLen = len(shoppingCart)
totItems, total, display = 0, 0, 0
# Retrieve all shirts ever bought by current user
myShirts = db.execute("SELECT * FROM purchases WHERE uid=:uid", uid=session["uid"])
myShirtsLen = len(myShirts)
# Render table with shopping history of current user
return render_template("history.html", shoppingCart=shoppingCart, shopLen=shopLen, total=total, totItems=totItems, display=display, session=session, myShirts=myShirts, myShirtsLen=myShirtsLen)
@app.route("/logout/")
def logout():
# clear shopping cart
db.execute("DELETE from cart")
# Forget any user_id
session.clear()
# Redirect user to login form
return redirect("/")
@app.route("/register/", methods=["POST"] )
def registration():
# Get info from form
username = request.form["username"]
password = request.form["password"]
confirm = request.form["confirm"]
fname = request.form["fname"]
lname = request.form["lname"]
email = request.form["email"]
# See if username already in the database
rows = db.execute( "SELECT * FROM users WHERE username = :username ", username = username )
# If username already exists, alert user
if len( rows ) > 0:
return render_template ( "new.html", msg="Username already exists!" )
# If new user, upload his/her info into the users database
new = db.execute ( "INSERT INTO users (username, password, fname, lname, email) VALUES (:username, :password, :fname, :lname, :email)",
username=username, password=password, fname=fname, lname=lname, email=email )
# Render login template
return render_template ( "login.html" )
@app.route("/cart/")
def cart():
if 'user' in session:
# Clear shopping cart variables
totItems, total, display = 0, 0, 0
# Grab info currently in database
shoppingCart = db.execute("SELECT team, image, SUM(qty), SUM(subTotal), price, id FROM cart GROUP BY team")
# Get variable values
shopLen = len(shoppingCart)
for i in range(shopLen):
total += shoppingCart[i]["SUM(subTotal)"]
totItems += shoppingCart[i]["SUM(qty)"]
# Render shopping cart
return render_template("cart.html", shoppingCart=shoppingCart, shopLen=shopLen, total=total, totItems=totItems, display=display, session=session)
# @app.errorhandler(404)
# def pageNotFound( e ):
# if 'user' in session:
# return render_template ( "404.html", session=session )
# return render_template ( "404.html" ), 404
# Only needed if Flask run is not used to execute the server
#if __name__ == "__main__":
# app.run( host='0.0.0.0', port=8080 )