├── .gitignore ├── aula-01 ├── requirements.txt ├── app.py └── swagger.yaml ├── aula-02 ├── requirements.txt └── app.py ├── aula-03 ├── requirements.txt └── app.py ├── aula-04 ├── requirements.txt └── app.py └── aula-05 ├── aula-05 ├── requirements.txt ├── instance │ └── ecommerce.db ├── .gitignore ├── swagger.yaml └── application.py └── links.md /.gitignore: -------------------------------------------------------------------------------- 1 | .DS_Store -------------------------------------------------------------------------------- /aula-01/requirements.txt: -------------------------------------------------------------------------------- 1 | Flask==2.3.0 2 | Flask-SQLAlchemy==3.1.1 3 | Flask-Login==0.6.2 4 | Flask-Cors==3.0.10 5 | Werkzeug==2.3.0 -------------------------------------------------------------------------------- /aula-02/requirements.txt: -------------------------------------------------------------------------------- 1 | Flask==2.3.0 2 | Flask-SQLAlchemy==3.1.1 3 | Flask-Login==0.6.2 4 | Flask-Cors==3.0.10 5 | Werkzeug==2.3.0 -------------------------------------------------------------------------------- /aula-03/requirements.txt: -------------------------------------------------------------------------------- 1 | Flask==2.3.0 2 | Flask-SQLAlchemy==3.1.1 3 | Flask-Login==0.6.2 4 | Flask-Cors==3.0.10 5 | Werkzeug==2.3.0 -------------------------------------------------------------------------------- /aula-04/requirements.txt: -------------------------------------------------------------------------------- 1 | Flask==2.3.0 2 | Flask-SQLAlchemy==3.1.1 3 | Flask-Login==0.6.2 4 | Flask-Cors==3.0.10 5 | Werkzeug==2.3.0 -------------------------------------------------------------------------------- /aula-05/aula-05/requirements.txt: -------------------------------------------------------------------------------- 1 | Flask==2.3.0 2 | Flask-SQLAlchemy==3.1.1 3 | Flask-Cors==3.0.10 4 | Werkzeug==2.3.0 5 | Flask-Login==0.6.2 -------------------------------------------------------------------------------- /aula-05/aula-05/instance/ecommerce.db: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rocketseat-education/python-intro-flask/HEAD/aula-05/aula-05/instance/ecommerce.db -------------------------------------------------------------------------------- /aula-05/aula-05/.gitignore: -------------------------------------------------------------------------------- 1 | 2 | # Elastic Beanstalk Files 3 | .elasticbeanstalk/* 4 | !.elasticbeanstalk/*.cfg.yml 5 | !.elasticbeanstalk/*.global.yml 6 | -------------------------------------------------------------------------------- /aula-01/app.py: -------------------------------------------------------------------------------- 1 | # Importação 2 | from flask import Flask 3 | 4 | app = Flask(__name__) 5 | 6 | # Definir uma rota raiz (página inicial) e a função que será executada ao requisitar 7 | @app.route('/teste') 8 | def hello_world(): 9 | return 'Hello World' 10 | 11 | if __name__ == "__main__": 12 | app.run(debug=True) -------------------------------------------------------------------------------- /aula-05/links.md: -------------------------------------------------------------------------------- 1 | • Criar conta: [URL](https://aws.amazon.com/pt/free/?trk=c9dcfe7b-33fc-4345-b0c3-77b810bbd58c&sc_channel=ps&all-free-tier.sort-by=item.additionalFields.SortRank&all-free-tier.sort-order=asc&awsf.Free%20Tier%20Types=*all&awsf.Free%20Tier%20Categories=*all) 2 | • Instalar AWS CLI: https://github.com/aws/aws-cli 3 | • Instalar eb cli: https://docs.aws.amazon.com/pt_br/elasticbeanstalk/latest/dg/eb-cli3-install.html#eb-cli3-install.scripts 4 | • Tutorial: https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/create-deploy-python-flask.html 5 | -------------------------------------------------------------------------------- /aula-02/app.py: -------------------------------------------------------------------------------- 1 | # Importação 2 | from flask import Flask, request, jsonify 3 | from flask_sqlalchemy import SQLAlchemy 4 | 5 | app = Flask(__name__) 6 | app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///ecommerce.db' 7 | 8 | db = SQLAlchemy(app) 9 | 10 | # Modelagem 11 | # Produto (id, name, price, description) 12 | class Product(db.Model): 13 | id = db.Column(db.Integer, primary_key=True) 14 | name = db.Column(db.String(120), nullable=False) 15 | price = db.Column(db.Float, nullable=False) 16 | description = db.Column(db.Text, nullable=True) 17 | 18 | @app.route('/api/products/add', methods=["POST"]) 19 | def add_product(): 20 | data = request.json 21 | if 'name' in data and 'price' in data: 22 | product = Product(name=data["name"], price=data["price"], description=data.get("description", "")) 23 | db.session.add(product) 24 | db.session.commit() 25 | return jsonify({"message": "Product added successfully"}) 26 | return jsonify({"message": "Invalid product data"}), 400 27 | 28 | @app.route('/api/products/delete/', methods=["DELETE"]) 29 | def delete_product(product_id): 30 | product = Product.query.get(product_id) 31 | if product: 32 | db.session.delete(product) 33 | db.session.commit() 34 | return jsonify({"message": "Product deleted successfully"}) 35 | return jsonify({"message": "Product not found"}), 404 36 | 37 | 38 | # Definir uma rota raiz (página inicial) e a função que será executada ao requisitar 39 | @app.route('/') 40 | def hello_world(): 41 | return 'Hello World' 42 | 43 | if __name__ == "__main__": 44 | app.run(debug=True) -------------------------------------------------------------------------------- /aula-03/app.py: -------------------------------------------------------------------------------- 1 | # Importação 2 | from flask import Flask, request, jsonify 3 | from flask_sqlalchemy import SQLAlchemy 4 | from flask_cors import CORS 5 | from flask_login import UserMixin, login_user, LoginManager, login_required, logout_user 6 | 7 | app = Flask(__name__) 8 | app.config['SECRET_KEY'] = "minha_chave_123" 9 | app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///ecommerce.db' 10 | 11 | login_manager = LoginManager() 12 | db = SQLAlchemy(app) 13 | login_manager.init_app(app) 14 | login_manager.login_view = 'login' 15 | CORS(app) 16 | 17 | # Modelagem 18 | # User (id, username, password) 19 | class User(db.Model, UserMixin): 20 | id = db.Column(db.Integer, primary_key=True) 21 | username = db.Column(db.String(80), nullable=False, unique=True) 22 | password = db.Column(db.String(80), nullable=True) 23 | 24 | # Produto (id, name, price, description) 25 | class Product(db.Model): 26 | id = db.Column(db.Integer, primary_key=True) 27 | name = db.Column(db.String(120), nullable=False) 28 | price = db.Column(db.Float, nullable=False) 29 | description = db.Column(db.Text, nullable=True) 30 | 31 | # Autenticacao 32 | @login_manager.user_loader 33 | def load_user(user_id): 34 | return User.query.get(int(user_id)) 35 | 36 | @app.route('/login', methods=["POST"]) 37 | def login(): 38 | data = request.json 39 | user = User.query.filter_by(username=data.get("username")).first() 40 | 41 | if user and data.get("password") == user.password: 42 | login_user(user) 43 | return jsonify({"message": "Logged in successfully"}) 44 | 45 | return jsonify({"message": "Unauthorized. Invalid credentials"}), 401 46 | 47 | @app.route('/logout', methods=["POST"]) 48 | @login_required 49 | def logout(): 50 | logout_user() 51 | return jsonify({"message": "Logout successfully"}) 52 | 53 | @app.route('/api/products/add', methods=["POST"]) 54 | @login_required 55 | def add_product(): 56 | data = request.json 57 | if 'name' in data and 'price' in data: 58 | product = Product(name=data["name"], price=data["price"], description=data.get("description", "")) 59 | db.session.add(product) 60 | db.session.commit() 61 | return jsonify({"message": "Product added successfully"}) 62 | return jsonify({"message": "Invalid product data"}), 400 63 | 64 | @app.route('/api/products/delete/', methods=["DELETE"]) 65 | @login_required 66 | def delete_product(product_id): 67 | product = Product.query.get(product_id) 68 | if product: 69 | db.session.delete(product) 70 | db.session.commit() 71 | return jsonify({"message": "Product deleted successfully"}) 72 | return jsonify({"message": "Product not found"}), 404 73 | 74 | @app.route('/api/products/', methods=["GET"]) 75 | def get_product_details(product_id): 76 | product = Product.query.get(product_id) 77 | if product: 78 | return jsonify({ 79 | "id": product.id, 80 | "name": product.name, 81 | "price": product.price, 82 | "description": product.description 83 | }) 84 | return jsonify({"message": "Product not found"}), 404 85 | 86 | @app.route('/api/products/update/', methods=["PUT"]) 87 | @login_required 88 | def update_product(product_id): 89 | product = Product.query.get(product_id) 90 | if not product: 91 | return jsonify({"message": "Product not found"}), 404 92 | 93 | data = request.json 94 | if 'name' in data: 95 | product.name = data['name'] 96 | 97 | if 'price' in data: 98 | product.price = data['price'] 99 | 100 | if 'description' in data: 101 | product.description = data['description'] 102 | 103 | db.session.commit() 104 | return jsonify({'message': 'Product updated successfully'}) 105 | 106 | @app.route('/api/products', methods=['GET']) 107 | def get_products(): 108 | products = Product.query.all() 109 | product_list = [] 110 | for product in products: 111 | product_data = { 112 | "id": product.id, 113 | "name": product.name, 114 | "price": product.price, 115 | } 116 | product_list.append(product_data) 117 | 118 | return jsonify(product_list) 119 | 120 | 121 | # Definir uma rota raiz (página inicial) e a função que será executada ao requisitar 122 | @app.route('/') 123 | def hello_world(): 124 | return 'Hello World' 125 | 126 | if __name__ == "__main__": 127 | app.run(debug=True) -------------------------------------------------------------------------------- /aula-01/swagger.yaml: -------------------------------------------------------------------------------- 1 | swagger: '2.0' 2 | info: 3 | version: 1.0.0 4 | title: E-commerce API 5 | description: API for an e-commerce system 6 | host: 127.0.0.1:5000 7 | schemes: 8 | - http 9 | 10 | paths: 11 | 12 | /login: 13 | post: 14 | summary: Log in 15 | parameters: 16 | - name: body 17 | in: body 18 | required: true 19 | schema: 20 | type: object 21 | properties: 22 | username: 23 | type: string 24 | password: 25 | type: string 26 | responses: 27 | 200: 28 | headers: 29 | Set-Cookie: 30 | type: string 31 | 32 | description: Logged in successfully 33 | 34 | 401: 35 | description: Unauthorized. Invalid credentials 36 | 37 | /logout: 38 | post: 39 | summary: Log out 40 | responses: 41 | 200: 42 | description: Logout successfully 43 | 401: 44 | description: Unauthorized. Invalid credentials 45 | 46 | /api/products: 47 | get: 48 | summary: Get a list of products 49 | responses: 50 | 200: 51 | description: Returns a list of products 52 | schema: 53 | type: array 54 | items: 55 | $ref: '#/definitions/Product' 56 | 404: 57 | description: Not Found. No products available. 58 | 59 | /api/products/{product_id}: 60 | get: 61 | summary: Get product details by ID 62 | parameters: 63 | - name: product_id 64 | in: path 65 | type: integer 66 | required: true 67 | description: Product ID to retrieve details 68 | responses: 69 | 200: 70 | description: Returns product details 71 | schema: 72 | $ref: '#/definitions/Product' 73 | 404: 74 | description: Not Found. Product not available. 75 | 76 | /api/products/search: 77 | get: 78 | summary: Search for products 79 | parameters: 80 | - name: q 81 | in: query 82 | type: string 83 | required: true 84 | description: Search query 85 | responses: 86 | 200: 87 | description: Returns a list of products matching the search query 88 | schema: 89 | type: array 90 | items: 91 | $ref: '#/definitions/Product' 92 | 404: 93 | description: Not Found. No products found for the search query. 94 | 95 | /api/products/add: 96 | post: 97 | summary: Add a new product 98 | parameters: 99 | - name: body 100 | in: body 101 | required: true 102 | schema: 103 | $ref: '#/definitions/Product' 104 | responses: 105 | 201: 106 | description: Product added successfully 107 | 400: 108 | description: Failed to add the product 109 | 110 | /api/products/update/{product_id}: 111 | put: 112 | summary: Update a product by ID 113 | parameters: 114 | - name: product_id 115 | in: path 116 | type: integer 117 | required: true 118 | description: Product ID to update 119 | - name: body 120 | in: body 121 | required: true 122 | schema: 123 | $ref: '#/definitions/Product' 124 | responses: 125 | 200: 126 | description: Product updated successfully 127 | 404: 128 | description: Not Found. Product not available 129 | 400: 130 | description: Failed to update the product 131 | 132 | /api/products/delete/{product_id}: 133 | delete: 134 | summary: Delete a product by ID 135 | parameters: 136 | - name: product_id 137 | in: path 138 | type: integer 139 | required: true 140 | description: Product ID to delete 141 | responses: 142 | 200: 143 | description: Product deleted successfully 144 | 404: 145 | description: Not Found. Product not available 146 | 147 | /api/cart/add/{product_id}: 148 | post: 149 | summary: Add item to the cart 150 | parameters: 151 | - name: product_id 152 | in: path 153 | type: integer 154 | required: true 155 | description: Product ID to add to the cart 156 | responses: 157 | 200: 158 | description: Item added to the cart successfully 159 | 400: 160 | description: Failed to add item to the cart 161 | 162 | /api/cart/remove/{item_id}: 163 | delete: 164 | summary: Remove item from the cart 165 | parameters: 166 | - name: item_id 167 | in: path 168 | type: integer 169 | required: true 170 | description: Cart item ID to remove from the cart 171 | responses: 172 | 200: 173 | description: Item removed from the cart successfully 174 | 400: 175 | description: Failed to remove item from the cart 176 | 177 | /api/cart: 178 | get: 179 | summary: View the user's cart 180 | responses: 181 | 200: 182 | description: Returns the user's cart contents 183 | schema: 184 | type: array 185 | items: 186 | $ref: '#/definitions/CartItem' 187 | 401: 188 | description: Unauthorized. User not logged in 189 | 190 | /api/cart/checkout: 191 | post: 192 | summary: Checkout and clear the cart 193 | responses: 194 | 200: 195 | description: Checkout successful. Cart has been cleared. 196 | 401: 197 | description: Unauthorized. User not logged in 198 | 199 | definitions: 200 | User: 201 | type: object 202 | properties: 203 | id: 204 | type: integer 205 | username: 206 | type: string 207 | password: 208 | type: string 209 | cart: 210 | type: array 211 | items: 212 | $ref: '#/definitions/CartItem' 213 | 214 | Product: 215 | type: object 216 | properties: 217 | id: 218 | type: integer 219 | name: 220 | type: string 221 | price: 222 | type: number 223 | description: 224 | type: string 225 | 226 | CartItem: 227 | type: object 228 | properties: 229 | id: 230 | type: integer 231 | user_id: 232 | type: integer 233 | product_id: 234 | type: integer 235 | -------------------------------------------------------------------------------- /aula-05/aula-05/swagger.yaml: -------------------------------------------------------------------------------- 1 | swagger: '2.0' 2 | info: 3 | version: 1.0.0 4 | title: E-commerce API 5 | description: API for an e-commerce system 6 | host: 127.0.0.1:5000 7 | schemes: 8 | - http 9 | 10 | paths: 11 | 12 | /login: 13 | post: 14 | summary: Log in 15 | parameters: 16 | - name: body 17 | in: body 18 | required: true 19 | schema: 20 | type: object 21 | properties: 22 | username: 23 | type: string 24 | password: 25 | type: string 26 | responses: 27 | 200: 28 | headers: 29 | Set-Cookie: 30 | type: string 31 | 32 | description: Logged in successfully 33 | 34 | 401: 35 | description: Unauthorized. Invalid credentials 36 | 37 | /logout: 38 | post: 39 | summary: Log out 40 | responses: 41 | 200: 42 | description: Logout successfully 43 | 401: 44 | description: Unauthorized. Invalid credentials 45 | 46 | /api/products: 47 | get: 48 | summary: Get a list of products 49 | responses: 50 | 200: 51 | description: Returns a list of products 52 | schema: 53 | type: array 54 | items: 55 | $ref: '#/definitions/Product' 56 | 404: 57 | description: Not Found. No products available. 58 | 59 | /api/products/{product_id}: 60 | get: 61 | summary: Get product details by ID 62 | parameters: 63 | - name: product_id 64 | in: path 65 | type: integer 66 | required: true 67 | description: Product ID to retrieve details 68 | responses: 69 | 200: 70 | description: Returns product details 71 | schema: 72 | $ref: '#/definitions/Product' 73 | 404: 74 | description: Not Found. Product not available. 75 | 76 | /api/products/search: 77 | get: 78 | summary: Search for products 79 | parameters: 80 | - name: q 81 | in: query 82 | type: string 83 | required: true 84 | description: Search query 85 | responses: 86 | 200: 87 | description: Returns a list of products matching the search query 88 | schema: 89 | type: array 90 | items: 91 | $ref: '#/definitions/Product' 92 | 404: 93 | description: Not Found. No products found for the search query. 94 | 95 | /api/products/add: 96 | post: 97 | summary: Add a new product 98 | parameters: 99 | - name: body 100 | in: body 101 | required: true 102 | schema: 103 | $ref: '#/definitions/Product' 104 | responses: 105 | 201: 106 | description: Product added successfully 107 | 400: 108 | description: Failed to add the product 109 | 110 | /api/products/update/{product_id}: 111 | put: 112 | summary: Update a product by ID 113 | parameters: 114 | - name: product_id 115 | in: path 116 | type: integer 117 | required: true 118 | description: Product ID to update 119 | - name: body 120 | in: body 121 | required: true 122 | schema: 123 | $ref: '#/definitions/Product' 124 | responses: 125 | 200: 126 | description: Product updated successfully 127 | 404: 128 | description: Not Found. Product not available 129 | 400: 130 | description: Failed to update the product 131 | 132 | /api/products/delete/{product_id}: 133 | delete: 134 | summary: Delete a product by ID 135 | parameters: 136 | - name: product_id 137 | in: path 138 | type: integer 139 | required: true 140 | description: Product ID to delete 141 | responses: 142 | 200: 143 | description: Product deleted successfully 144 | 404: 145 | description: Not Found. Product not available 146 | 147 | /api/cart/add/{product_id}: 148 | post: 149 | summary: Add item to the cart 150 | parameters: 151 | - name: product_id 152 | in: path 153 | type: integer 154 | required: true 155 | description: Product ID to add to the cart 156 | responses: 157 | 200: 158 | description: Item added to the cart successfully 159 | 400: 160 | description: Failed to add item to the cart 161 | 162 | /api/cart/remove/{item_id}: 163 | delete: 164 | summary: Remove item from the cart 165 | parameters: 166 | - name: item_id 167 | in: path 168 | type: integer 169 | required: true 170 | description: Cart item ID to remove from the cart 171 | responses: 172 | 200: 173 | description: Item removed from the cart successfully 174 | 400: 175 | description: Failed to remove item from the cart 176 | 177 | /api/cart: 178 | get: 179 | summary: View the user's cart 180 | responses: 181 | 200: 182 | description: Returns the user's cart contents 183 | schema: 184 | type: array 185 | items: 186 | $ref: '#/definitions/CartItem' 187 | 401: 188 | description: Unauthorized. User not logged in 189 | 190 | /api/cart/checkout: 191 | post: 192 | summary: Checkout and clear the cart 193 | responses: 194 | 200: 195 | description: Checkout successful. Cart has been cleared. 196 | 401: 197 | description: Unauthorized. User not logged in 198 | 199 | definitions: 200 | User: 201 | type: object 202 | properties: 203 | id: 204 | type: integer 205 | username: 206 | type: string 207 | password: 208 | type: string 209 | cart: 210 | type: array 211 | items: 212 | $ref: '#/definitions/CartItem' 213 | 214 | Product: 215 | type: object 216 | properties: 217 | id: 218 | type: integer 219 | name: 220 | type: string 221 | price: 222 | type: number 223 | description: 224 | type: string 225 | 226 | CartItem: 227 | type: object 228 | properties: 229 | id: 230 | type: integer 231 | user_id: 232 | type: integer 233 | product_id: 234 | type: integer 235 | -------------------------------------------------------------------------------- /aula-04/app.py: -------------------------------------------------------------------------------- 1 | # Importação 2 | from flask import Flask, request, jsonify 3 | from flask_sqlalchemy import SQLAlchemy 4 | from flask_cors import CORS 5 | from flask_login import UserMixin, login_user, LoginManager, login_required, logout_user, current_user 6 | 7 | app = Flask(__name__) 8 | app.config['SECRET_KEY'] = "minha_chave_123" 9 | app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///ecommerce.db' 10 | 11 | login_manager = LoginManager() 12 | db = SQLAlchemy(app) 13 | login_manager.init_app(app) 14 | login_manager.login_view = 'login' 15 | CORS(app) 16 | 17 | # Modelagem 18 | # User (id, username, password) 19 | class User(db.Model, UserMixin): 20 | id = db.Column(db.Integer, primary_key=True) 21 | username = db.Column(db.String(80), nullable=False, unique=True) 22 | password = db.Column(db.String(80), nullable=True) 23 | cart = db.relationship('CartItem', backref='user', lazy=True) 24 | 25 | # Produto (id, name, price, description) 26 | class Product(db.Model): 27 | id = db.Column(db.Integer, primary_key=True) 28 | name = db.Column(db.String(120), nullable=False) 29 | price = db.Column(db.Float, nullable=False) 30 | description = db.Column(db.Text, nullable=True) 31 | 32 | class CartItem(db.Model): 33 | id = db.Column(db.Integer, primary_key=True) 34 | user_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False) 35 | product_id = db.Column(db.Integer, db.ForeignKey('product.id'), nullable=False) 36 | 37 | # Autenticacao 38 | @login_manager.user_loader 39 | def load_user(user_id): 40 | return User.query.get(int(user_id)) 41 | 42 | @app.route('/login', methods=["POST"]) 43 | def login(): 44 | data = request.json 45 | user = User.query.filter_by(username=data.get("username")).first() 46 | 47 | if user and data.get("password") == user.password: 48 | login_user(user) 49 | return jsonify({"message": "Logged in successfully"}) 50 | 51 | return jsonify({"message": "Unauthorized. Invalid credentials"}), 401 52 | 53 | @app.route('/logout', methods=["POST"]) 54 | @login_required 55 | def logout(): 56 | logout_user() 57 | return jsonify({"message": "Logout successfully"}) 58 | 59 | @app.route('/api/products/add', methods=["POST"]) 60 | @login_required 61 | def add_product(): 62 | data = request.json 63 | if 'name' in data and 'price' in data: 64 | product = Product(name=data["name"], price=data["price"], description=data.get("description", "")) 65 | db.session.add(product) 66 | db.session.commit() 67 | return jsonify({"message": "Product added successfully"}) 68 | return jsonify({"message": "Invalid product data"}), 400 69 | 70 | @app.route('/api/products/delete/', methods=["DELETE"]) 71 | @login_required 72 | def delete_product(product_id): 73 | product = Product.query.get(product_id) 74 | if product: 75 | db.session.delete(product) 76 | db.session.commit() 77 | return jsonify({"message": "Product deleted successfully"}) 78 | return jsonify({"message": "Product not found"}), 404 79 | 80 | @app.route('/api/products/', methods=["GET"]) 81 | def get_product_details(product_id): 82 | product = Product.query.get(product_id) 83 | if product: 84 | return jsonify({ 85 | "id": product.id, 86 | "name": product.name, 87 | "price": product.price, 88 | "description": product.description 89 | }) 90 | return jsonify({"message": "Product not found"}), 404 91 | 92 | @app.route('/api/products/update/', methods=["PUT"]) 93 | @login_required 94 | def update_product(product_id): 95 | product = Product.query.get(product_id) 96 | if not product: 97 | return jsonify({"message": "Product not found"}), 404 98 | 99 | data = request.json 100 | if 'name' in data: 101 | product.name = data['name'] 102 | 103 | if 'price' in data: 104 | product.price = data['price'] 105 | 106 | if 'description' in data: 107 | product.description = data['description'] 108 | 109 | db.session.commit() 110 | return jsonify({'message': 'Product updated successfully'}) 111 | 112 | @app.route('/api/products', methods=['GET']) 113 | def get_products(): 114 | products = Product.query.all() 115 | product_list = [] 116 | for product in products: 117 | product_data = { 118 | "id": product.id, 119 | "name": product.name, 120 | "price": product.price, 121 | } 122 | product_list.append(product_data) 123 | 124 | return jsonify(product_list) 125 | 126 | # Checkout 127 | @app.route('/api/cart/add/', methods=['POST']) 128 | @login_required 129 | def add_to_cart(product_id): 130 | # Usuario 131 | user = User.query.get(int(current_user.id)) 132 | # Produto 133 | product = Product.query.get(product_id) 134 | 135 | if user and product: 136 | print(user) 137 | print(product) 138 | return jsonify({'message': 'Item added to the cart successfully'}) 139 | return jsonify({'message': 'Failed to add item to the cart'}), 400 140 | 141 | 142 | @app.route('/api/cart/remove/', methods=['DELETE']) 143 | @login_required 144 | def remove_from_cart(product_id): 145 | # Produto, Usuario = Item no carrinho 146 | cart_item = CartItem.query.filter_by(user_id=current_user.id, product_id=product_id).first() 147 | if cart_item: 148 | db.session.delete(cart_item) 149 | db.session.commit() 150 | return jsonify({'message': 'Item removed from the cart successfully'}) 151 | return jsonify({'message': 'Failed to remove item from the cart'}), 400 152 | 153 | @app.route('/api/cart', methods=['GET']) 154 | @login_required 155 | def view_cart(): 156 | # Usuario 157 | user = User.query.get(int(current_user.id)) 158 | cart_items = user.cart 159 | cart_content = [] 160 | for cart_item in cart_items: 161 | product = Product.query.get(cart_item.product_id) 162 | cart_content.append({ 163 | "id": cart_item.id, 164 | "user_id": cart_item.user_id, 165 | "product_id": cart_item.product_id, 166 | "product_name": product.name, 167 | "product_price": product.price 168 | }) 169 | return jsonify(cart_content) 170 | 171 | @app.route('/api/cart/checkout', methods=["POST"]) 172 | @login_required 173 | def checkout(): 174 | user = User.query.get(int(current_user.id)) 175 | cart_items = user.cart 176 | for cart_item in cart_items: 177 | db.session.delete(cart_item) 178 | db.session.commit() 179 | return jsonify({'message': 'Checkout successful. Cart has been cleared.'}) 180 | 181 | if __name__ == "__main__": 182 | app.run(debug=True) -------------------------------------------------------------------------------- /aula-05/aula-05/application.py: -------------------------------------------------------------------------------- 1 | # Importação 2 | from flask import Flask, request, jsonify 3 | from flask_sqlalchemy import SQLAlchemy 4 | from flask_cors import CORS 5 | from flask_login import UserMixin, login_user, LoginManager, login_required, logout_user, current_user 6 | 7 | application = Flask(__name__) 8 | application.config['SECRET_KEY'] = "minha_chave_123" 9 | application.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///ecommerce.db' 10 | 11 | login_manager = LoginManager() 12 | db = SQLAlchemy(application) 13 | login_manager.init_app(application) 14 | login_manager.login_view = 'login' 15 | CORS(application) 16 | 17 | # Modelagem 18 | # User (id, username, password) 19 | class User(db.Model, UserMixin): 20 | id = db.Column(db.Integer, primary_key=True) 21 | username = db.Column(db.String(80), nullable=False, unique=True) 22 | password = db.Column(db.String(80), nullable=True) 23 | cart = db.relationship('CartItem', backref='user', lazy=True) 24 | 25 | # Produto (id, name, price, description) 26 | class Product(db.Model): 27 | id = db.Column(db.Integer, primary_key=True) 28 | name = db.Column(db.String(120), nullable=False) 29 | price = db.Column(db.Float, nullable=False) 30 | description = db.Column(db.Text, nullable=True) 31 | 32 | class CartItem(db.Model): 33 | id = db.Column(db.Integer, primary_key=True) 34 | user_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False) 35 | product_id = db.Column(db.Integer, db.ForeignKey('product.id'), nullable=False) 36 | 37 | # Autenticacao 38 | @login_manager.user_loader 39 | def load_user(user_id): 40 | return User.query.get(int(user_id)) 41 | 42 | @application.route('/') 43 | def initial(): 44 | return 'API up' 45 | 46 | @application.route('/login', methods=["POST"]) 47 | def login(): 48 | data = request.json 49 | user = User.query.filter_by(username=data.get("username")).first() 50 | 51 | if user and data.get("password") == user.password: 52 | login_user(user) 53 | return jsonify({"message": "Logged in successfully"}) 54 | 55 | return jsonify({"message": "Unauthorized. Invalid credentials"}), 401 56 | 57 | @application.route('/logout', methods=["POST"]) 58 | @login_required 59 | def logout(): 60 | logout_user() 61 | return jsonify({"message": "Logout successfully"}) 62 | 63 | @application.route('/api/products/add', methods=["POST"]) 64 | @login_required 65 | def add_product(): 66 | data = request.json 67 | if 'name' in data and 'price' in data: 68 | product = Product(name=data["name"], price=data["price"], description=data.get("description", "")) 69 | db.session.add(product) 70 | db.session.commit() 71 | return jsonify({"message": "Product added successfully"}) 72 | return jsonify({"message": "Invalid product data"}), 400 73 | 74 | @application.route('/api/products/delete/', methods=["DELETE"]) 75 | @login_required 76 | def delete_product(product_id): 77 | product = Product.query.get(product_id) 78 | if product: 79 | db.session.delete(product) 80 | db.session.commit() 81 | return jsonify({"message": "Product deleted successfully"}) 82 | return jsonify({"message": "Product not found"}), 404 83 | 84 | @application.route('/api/products/', methods=["GET"]) 85 | def get_product_details(product_id): 86 | product = Product.query.get(product_id) 87 | if product: 88 | return jsonify({ 89 | "id": product.id, 90 | "name": product.name, 91 | "price": product.price, 92 | "description": product.description 93 | }) 94 | return jsonify({"message": "Product not found"}), 404 95 | 96 | @application.route('/api/products/update/', methods=["PUT"]) 97 | @login_required 98 | def update_product(product_id): 99 | product = Product.query.get(product_id) 100 | if not product: 101 | return jsonify({"message": "Product not found"}), 404 102 | 103 | data = request.json 104 | if 'name' in data: 105 | product.name = data['name'] 106 | 107 | if 'price' in data: 108 | product.price = data['price'] 109 | 110 | if 'description' in data: 111 | product.description = data['description'] 112 | 113 | db.session.commit() 114 | return jsonify({'message': 'Product updated successfully'}) 115 | 116 | @application.route('/api/products', methods=['GET']) 117 | def get_products(): 118 | products = Product.query.all() 119 | product_list = [] 120 | for product in products: 121 | product_data = { 122 | "id": product.id, 123 | "name": product.name, 124 | "price": product.price, 125 | "category": "category_generic" 126 | } 127 | product_list.append(product_data) 128 | 129 | return jsonify(product_list) 130 | 131 | # Checkout 132 | @application.route('/api/cart/add/', methods=['POST']) 133 | @login_required 134 | def add_to_cart(product_id): 135 | # Usuario 136 | user = User.query.get(int(current_user.id)) 137 | # Produto 138 | product = Product.query.get(product_id) 139 | 140 | if user and product: 141 | print(user) 142 | print(product) 143 | return jsonify({'message': 'Item added to the cart successfully'}) 144 | return jsonify({'message': 'Failed to add item to the cart'}), 400 145 | 146 | 147 | @application.route('/api/cart/remove/', methods=['DELETE']) 148 | @login_required 149 | def remove_from_cart(product_id): 150 | # Produto, Usuario = Item no carrinho 151 | cart_item = CartItem.query.filter_by(user_id=current_user.id, product_id=product_id).first() 152 | if cart_item: 153 | db.session.delete(cart_item) 154 | db.session.commit() 155 | return jsonify({'message': 'Item removed from the cart successfully'}) 156 | return jsonify({'message': 'Failed to remove item from the cart'}), 400 157 | 158 | @application.route('/api/cart', methods=['GET']) 159 | @login_required 160 | def view_cart(): 161 | # Usuario 162 | user = User.query.get(int(current_user.id)) 163 | cart_items = user.cart 164 | cart_content = [] 165 | for cart_item in cart_items: 166 | product = Product.query.get(cart_item.product_id) 167 | cart_content.append({ 168 | "id": cart_item.id, 169 | "user_id": cart_item.user_id, 170 | "product_id": cart_item.product_id, 171 | "product_name": product.name, 172 | "product_price": product.price 173 | }) 174 | return jsonify(cart_content) 175 | 176 | @application.route('/api/cart/checkout', methods=["POST"]) 177 | @login_required 178 | def checkout(): 179 | user = User.query.get(int(current_user.id)) 180 | cart_items = user.cart 181 | for cart_item in cart_items: 182 | db.session.delete(cart_item) 183 | db.session.commit() 184 | return jsonify({'message': 'Checkout successful. Cart has been cleared.'}) 185 | 186 | if __name__ == "__main__": 187 | application.run(debug=True) --------------------------------------------------------------------------------