-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathapp.py
More file actions
186 lines (146 loc) · 5.51 KB
/
Copy pathapp.py
File metadata and controls
186 lines (146 loc) · 5.51 KB
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
from flask import Flask, render_template, request, redirect, session, flash
from models import db, User, Product
from sqlalchemy.exc import IntegrityError
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///shop.db'
app.secret_key = "e*eh76t$%327!!626^5"
db.init_app(app)
# intialize the database and create all the tables
with app.app_context():
db.create_all()
def login_required(f):
from functools import wraps
@wraps(f)
def wrapper(*args, **kwargs):
if "username" not in session or "user_id" not in session:
return redirect("/login")
return f(*args, **kwargs)
return wrapper
@app.route("/")
@app.route("/products")
def products():
query = request.args.get("q", "")
category = request.args.get("category")
products = Product.query
if query:
products = products.filter(Product.name.ilike(f"%{query}%"))
if category:
products = products.filter(Product.category == category)
products = products.all()
categories = db.session.query(Product.category).distinct()
return render_template("products.html",
products=products,
categories=categories,
user_id = session.get("user_id"),
name=session.get("username"))
@app.route("/register", methods=["GET", "POST"])
def register():
error = None
# POST: the user has clicked on REGISTER button
# ADD LOGIC for unique usernames here
if request.method == "POST":
# # fetch all usernames from the database
# query = db.session.query(User.username)
# usernames = query.all()
# # check if the current user's username is unique
# if request.form.get("username") not in usernames:
try:
user = User(
username=request.form.get("username"),
password=request.form.get("password")
)
# write the user's data to the User table (see models.py)
db.session.add(user)
db.session.commit()
except IntegrityError as e:
error = "Username already exists!"
flash("Username already exists!")
return render_template("register.html", error=error)
else:
return redirect("/login")
# GET: the user is directed to register.html page
return render_template("register.html")
# login logic
@app.route("/login", methods=["GET", "POST"])
def login():
if request.method == "POST":
# POST: the user has clicked on login button
user = User.query.filter_by(
username=request.form.get("username"),
password=request.form.get("password")
).first()
if user:
# if the user is a valid user,
# store the user's id and the username
# in the session as key-value pairs
session["user_id"] = user.id
session["username"] = user.username
return redirect("/products")
# GET operation: load the login.html page
return render_template("login.html")
# logout logic
@app.route("/logout")
def logout():
session.clear()
return redirect("/products")
@app.route("/add_to_cart/<int:id>")
@login_required
def add_to_cart(id):
if "cart" not in session:
# if the user is shopping for the first time,
# initialize cart and add it to the session dict
session["cart"] = []
session["cart"].append(id)
session.modified = True
return redirect("/cart")
# return redirect("/products")
@app.route("/add_to_wishlist/<int:id>")
@login_required
def add_to_wishlist(id):
if "wishlist" not in session:
# if the user is shopping for the first time,
# initialize wishlist and add it to the session dict
session["wishlist"] = []
session["wishlist"].append(id)
session.modified = True
return redirect("/")
@app.route("/wishlist")
@login_required
def wishlist():
wishlisted_items = session.get("wishlist", [])
products = Product.query.filter(Product.id.in_(wishlisted_items)).all()
return render_template("wishlist.html",
products=products,
name=session.get("username"),
user_id=session.get("user_id"))
@app.route("/remove_from_cart/<int:id>")
@login_required
def remove_from_cart(id):
if "cart" in session:
session["cart"] = [i for i in session["cart"] if i != id]
return redirect("/cart")
@app.route("/cart")
@login_required
def cart():
cart_ids = session.get("cart", [])
products = Product.query.filter(Product.id.in_(cart_ids)).all()
total = sum(p.price for p in products)
return render_template("cart.html",
products=products,
total=total,
name=session.get("username"),
user_id=session.get("user_id"))
# go this route ONCE to fill your tables with items
@app.route("/seed")
def seed():
if not Product.query.first():
items = [
Product(name="iPhone 14", category="Electronics", price=80000, image="https://via.placeholder.com/150"),
Product(name="Nike Shoes", category="Footwear", price=5000, image="https://via.placeholder.com/150"),
Product(name="Laptop", category="Electronics", price=60000, image="https://via.placeholder.com/150")
]
db.session.add_all(items)
db.session.commit()
return "Data Seeded!"
if __name__ == "__main__":
app.run()