swag-shop/app/api/routes/product_routes.py

58 lines
1.5 KiB
Python
Raw Normal View History

2024-03-05 16:01:26 +01:00
from flask import jsonify, abort, request
2024-03-10 22:47:42 +01:00
from flask_jwt_extended import jwt_required, get_jwt_identity
2024-03-05 16:01:26 +01:00
2024-03-13 21:40:55 +01:00
from app.doc.product_swag import get_products_swagger, get_product_info_swagger
2024-03-12 20:12:19 +01:00
from flasgger import swag_from
2024-03-05 16:01:26 +01:00
from app.api import bp_product
from app.services.product_service import ProductService
2024-03-10 17:11:26 +01:00
@bp_product.route('/get', methods=['GET'])
2024-03-12 20:12:19 +01:00
@swag_from(get_products_swagger)
2024-03-10 17:11:26 +01:00
def get_products():
page = request.args.get('page', default=0, type=int)
if page < 0:
return abort(400)
result, status_code = ProductService.get_products(page)
return result, status_code
2024-03-05 16:01:26 +01:00
@bp_product.route('/<int:id>', methods=['GET'])
2024-03-13 21:40:55 +01:00
@swag_from(get_product_info_swagger)
2024-03-08 14:05:22 +01:00
def get_product_info(id: int):
fields = ['name', 'price', 'image', 'image_name', 'seller']
2024-03-05 16:01:26 +01:00
2024-03-08 14:05:22 +01:00
fields_param = request.args.get('fields')
2024-03-10 21:19:34 +01:00
fields_param_list = fields_param.split(',') if fields_param else fields
common_fields = list(set(fields) & set(fields_param_list))
2024-03-08 14:05:22 +01:00
2024-03-10 21:19:34 +01:00
result, status_code = ProductService.get_product_info(common_fields, id)
2024-03-05 16:01:26 +01:00
2024-03-10 21:19:34 +01:00
return result, status_code
2024-03-05 16:01:26 +01:00
2024-03-10 22:47:42 +01:00
2024-03-05 16:01:26 +01:00
@bp_product.route('/create', methods=['POST'])
2024-03-10 22:47:42 +01:00
@jwt_required()
2024-03-05 16:01:26 +01:00
def create_product_listing():
2024-03-10 22:47:42 +01:00
user_id = get_jwt_identity()
name = request.json.get('name')
2024-03-10 22:47:42 +01:00
price = request.json.get('price')
if name is None or price is None:
2024-03-10 22:48:25 +01:00
return abort(400)
2024-03-10 22:47:42 +01:00
float_price = float(price)
if not isinstance(float_price, float):
2024-03-10 22:48:25 +01:00
return abort(400)
2024-03-10 22:47:42 +01:00
result, status_code = ProductService.create_listing(user_id, name, float_price)
return result, status_code