-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
224 lines (201 loc) · 5.73 KB
/
app.py
File metadata and controls
224 lines (201 loc) · 5.73 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
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
from flask import Flask, request, jsonify
from flask_sqlalchemy import SQLAlchemy
from flask_cors import CORS
from flasgger import Swagger
from flask_login import UserMixin, login_user, LoginManager, login_required, logout_user
app = Flask(__name__)
app.config['SECRET_KEY'] = "minha_chave_123"
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///ecommerce.db'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
login_menager = LoginManager()
db = SQLAlchemy(app)
login_menager.init_app(app)
login_menager.login_view = 'login'
CORS(app)
swagger = Swagger(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 = db.Column(db.String(80), nullable=True)
# Definindo a classe Product com os atributos
# Product (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)
# Adicionando a rota e os metodos
@login_menager.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 data.get("password") == user.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():
"""
Adicionar um novo produto
---
tags:
- Produtos
parameters:
- in: body
name: body
required: true
schema:
type: object
required:
- name
- price
properties:
name:
type: string
example: "Teclado Gamer"
price:
type: number
example: 199.90
description:
type: string
example: "Teclado mecânico RGB"
responses:
200:
description: Produto adicionado com sucesso
"""
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"}), 400
@app.route('/api/products/delete/<product_id>', methods=["DELETE"])
@login_required
def delete_product(product_id):
"""
Deletar um produto pelo ID
---
tags:
- Produtos
parameters:
- name: product_id
in: path
type: integer
required: true
description: ID do produto
responses:
200:
description: Produto deletado com sucesso
"""
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/<product_id>', methods=["GET"])
@login_required
def get_product_details(product_id):
"""
Buscar detalhes de um produto
---
tags:
- Produtos
parameters:
- name: product_id
in: path
type: integer
required: true
description: ID do produto
responses:
200:
description: Produto encontrado
"""
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/<product_id>', methods=["PUT"])
def update_product(product_id):
"""
Atualizar um produto
---
tags:
- Produtos
parameters:
- name: product_id
in: path
type: integer
required: true
- in: body
name: body
schema:
type: object
properties:
name:
type: string
price:
type: number
description:
type: string
responses:
200:
description: Produto atualizado
"""
product = Product.query.get(product_id)
if not product:
return jsonify({"message": "Product not found"})
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_all_products():
"""
Listar todos os produtos
---
tags:
- Produtos
responses:
200:
description: Lista de produtos
"""
products = Product.query.all()
product_list = []
for product in products:
product_data = {
"id": product.id,
"name": product.name,
"price": product.price
}
product_list.append(product_data)
return jsonify(product_list)
@app.route("/")
def hello_world():
return 'Hello World'
if __name__ == "__main__":
with app.app_context():
db.create_all()
app.run(debug=True)