85 lines
3.0 KiB
Python
85 lines
3.0 KiB
Python
from flask import jsonify, request
|
||
from db.handlers.product_handler import get_products_with_filters, get_product_by_id
|
||
from flask import Blueprint
|
||
|
||
# Создаем blueprint для API
|
||
api_product = Blueprint('api_product', __name__, url_prefix='/products')
|
||
|
||
@api_product.route('/', methods=['GET'], strict_slashes=False)
|
||
def get_products():
|
||
"""
|
||
Получение товаров с фильтрацией и пагинацией
|
||
GET /api/products?categoryId=1&page=1&limit=9&color=серый&size=110х2,2х500
|
||
"""
|
||
try:
|
||
# Получаем обязательный параметр categoryId
|
||
category_id = request.args.get('categoryId', type=int)
|
||
if not category_id:
|
||
return jsonify({"error": "categoryId is required"}), 400
|
||
|
||
# Получаем параметры пагинации
|
||
page = request.args.get('page', 1, type=int)
|
||
limit = request.args.get('limit', 9, type=int)
|
||
|
||
# Валидация параметров
|
||
if page < 1:
|
||
page = 1
|
||
if limit < 1 or limit > 100:
|
||
limit = 9
|
||
|
||
# Собираем фильтры из query параметров
|
||
filters = {}
|
||
excluded_params = ['categoryId', 'page', 'limit']
|
||
|
||
for key, value in request.args.items():
|
||
if key not in excluded_params:
|
||
if ',' in value:
|
||
filters[key] = value.split(',')
|
||
else:
|
||
filters[key] = value
|
||
|
||
# Получаем товары
|
||
result = get_products_with_filters(
|
||
category_id=category_id,
|
||
page=page,
|
||
limit=limit,
|
||
filters=filters if filters else None
|
||
)
|
||
|
||
return jsonify(result), 200
|
||
|
||
except Exception as e:
|
||
return jsonify({"error": str(e)}), 500
|
||
|
||
@api_product.route('/<int:product_id>', methods=['GET'], strict_slashes=False)
|
||
def get_product(product_id):
|
||
"""
|
||
Получение товара по ID
|
||
GET /api/products/{id}
|
||
"""
|
||
try:
|
||
product = get_product_by_id(product_id)
|
||
if product:
|
||
return jsonify(product), 200
|
||
return jsonify({"error": "Product not found"}), 404
|
||
except Exception as e:
|
||
return jsonify({"error": str(e)}), 500
|
||
|
||
@api_product.route('/fetchById', methods=['GET'], strict_slashes=False)
|
||
def get_product_by_id_param():
|
||
"""
|
||
Альтернативный маршрут для получения товара через query параметр
|
||
GET /api/products/fetchById?id=101
|
||
"""
|
||
try:
|
||
product_id = request.args.get('id', type=int)
|
||
if not product_id:
|
||
return jsonify({"error": "id parameter is required"}), 400
|
||
|
||
product = get_product_by_id(product_id)
|
||
if product:
|
||
return jsonify(product), 200
|
||
return jsonify({"error": "Product not found"}), 404
|
||
except Exception as e:
|
||
return jsonify({"error": str(e)}), 500
|