-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.py
249 lines (196 loc) · 7.12 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
from flask import Flask, request, jsonify
from flask_sqlalchemy import SQLAlchemy
from flask_cors import CORS
from flask_login import (
UserMixin,
login_user,
LoginManager,
login_required,
logout_user,
current_user,
)
from werkzeug.security import generate_password_hash, check_password_hash
from keys import SECRET_KEY
app = Flask(__name__)
# Definir uma key aleatória para o Login Manager
app.config["SECRET_KEY"] = SECRET_KEY
# Definir um banco de dados para sua aplicação
app.config["SQLALCHEMY_DATABASE_URI"] = "sqlite:///ecommerce.db"
login_manager = LoginManager()
db = SQLAlchemy(app)
login_manager.init_app(app)
login_manager.login_view = "login"
# Ativando CORS para a aplicação
CORS(app)
# Modelagem
# User (id, username, password)
class User(db.Model, UserMixin):
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(80), nullable=False, unique=True)
password_hash = db.Column(db.String(128), nullable=False)
cart = db.relationship("CartItem", backref="user", lazy=True)
# Método para verificar a senha
def verify_password(self, password):
return check_password_hash(self.password_hash, password)
# Método para definir a senha com hashing
def set_password(self, password):
self.password_hash = generate_password_hash(password)
# Exemplo de criação de um usuário com hash de senha
def create_user(username, password):
new_user = User(username=username)
new_user.set_password(password) # Gera o hash da senha
db.session.add(new_user)
db.session.commit()
return new_user
# Produto (id, name, price, description)
class Product(db.Model):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(120), nullable=False)
price = db.Column(db.Float, nullable=False)
description = db.Column(db.Text, nullable=True)
# Carrinho (id, user_id, product_id)
class CartItem(db.Model):
id = db.Column(db.Integer, primary_key=True)
user_id = db.Column(db.Integer, db.ForeignKey("user.id"), nullable=False)
product_id = db.Column(db.Integer, db.ForeignKey("product.id"), nullable=False)
# Auth
@login_manager.user_loader
def load_user(user_id):
return User.query.get(int(user_id))
@app.route("/login", methods=["POST"])
def login():
data = request.json
user = User.query.filter_by(username=data.get("username")).first()
if user and user.verify_password(data.get("password")):
login_user(user)
return jsonify({"message": "Logged in successfully"})
return jsonify({"message": "Unauthorized. Invalid credentials"}), 401
@app.route("/logout", methods=["POST"])
@login_required
def logout():
logout_user()
return jsonify({"message": "Logout successfully"})
@app.route("/api/products/add", methods=["POST"])
@login_required
def add_product():
data = request.json
if "name" in data and "price" in data:
product = Product(
name=data["name"],
price=data["price"],
description=data.get("description", ""),
)
db.session.add(product)
db.session.commit()
return jsonify({"message": "Product added successfully"})
return jsonify({"message": "Invalid product data (name or price)"}), 400
@app.route("/api/products/delete/<int:product_id>", methods=["DELETE"])
@login_required
def delete_product(product_id):
product = Product.query.get(product_id)
if product:
db.session.delete(product)
db.session.commit()
return jsonify({"message": "Product deleted successfully"})
return jsonify({"message": "Product not found"}), 404
@app.route("/api/products/<int:product_id>", methods=["GET"])
def get_product_details(product_id):
product = Product.query.get(product_id)
if product:
return jsonify(
{
"id": product.id,
"name": product.name,
"price": product.price,
"description": product.description,
}
)
return jsonify({"message": "Product not found"}), 404
@app.route("/api/products/update/<int:product_id>", methods=["PUT"])
@login_required
def update_product(product_id):
product = Product.query.get(product_id)
if not product:
return jsonify({"message": "Product not found"}), 404
data = request.json
if "name" in data:
product.name = data["name"]
if "price" in data:
product.price = data["price"]
if "description" in data:
product.description = data["description"]
db.session.commit()
return jsonify({"message": "Product updated successfully"})
@app.route("/api/products", methods=["GET"])
def get_products():
products = Product.query.all()
product_list = []
for product in products:
product_data = {
"id": product.id,
"name": product.name,
"price": product.price,
"description": product.description,
}
product_list.append(product_data)
return jsonify(product_list)
# Checkout
@app.route("/api/cart/add/<int:product_id>", methods=["POST"])
@login_required
def add_to_cart(product_id):
# User
user = User.query.get(int(current_user.id))
# Product
product = Product.query.get(product_id)
if user and product:
cart_item = CartItem(user_id=user.id, product_id=product.id)
db.session.add(cart_item)
db.session.commit()
return jsonify({"message": "Product added to the cart successfully"})
return jsonify({"message": "Failed to add product to the cart"}), 400
@app.route("/api/cart/remove/<int:product_id>", methods=["DELETE"])
@login_required
def remove_from_cart(product_id):
# Produto, Usuario = Item do carrinho
cart_item = CartItem.query.filter_by(
user_id=current_user.id, product_id=product_id
).first()
if cart_item:
db.session.delete(cart_item)
db.session.commit()
return jsonify({"message": "Product removed from the cart successfully"})
return jsonify({"message": "Failed to remove product to the cart"}), 400
@app.route("/api/cart", methods=["GET"])
@login_required
def view_cart():
# Usuario
user = User.query.get(int(current_user.id))
cart_items = user.cart
cart_content = []
for cart_item in cart_items:
product = Product.query.get(cart_item.product_id)
cart_content.append(
{
"id": cart_item.id,
"user_id": cart_item.user_id,
"product_id": cart_item.product_id,
"product_name": product.name,
"product_price": product.price,
}
)
return jsonify(cart_content)
@app.route("/api/cart/checkout", methods=["POST"])
@login_required
def checkout():
user = User.query.get(int(current_user.id))
cart_items = user.cart
for cart_item in cart_items:
db.session.delete(cart_item)
db.session.commit()
return jsonify({"message": "Checkout successful. Cart has been cleared."})
@app.shell_context_processor
def make_shell_context():
return {"db": db, "User": User, "Product": Product, "CartItem": CartItem}
# Iniciar app
if __name__ == "__main__":
app.run(debug=True)