fix(db): Fix handler for get product with categories
This commit is contained in:
1 parent
cfd5228f67
commit
b7c831f0c3
2 files changed
+134
-117
No files matched your search
+31
-22
@@ -7,47 +7,56 @@ 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 параметров
|
||||
|
||||
# Словарь для маппинга внешних ключей → внутренние имена в БД
|
||||
filter_mapping = {
|
||||
'attr_1': 'diameter',
|
||||
'attr_2': 'length',
|
||||
'attr_3': 'wall_thickness',
|
||||
'attr_4': 'color',
|
||||
'attr_5': 'application_type',
|
||||
'attr_6': 'stiffness_class',
|
||||
'attr_7': 'angle',
|
||||
'attr_8': 'fitting_type',
|
||||
}
|
||||
|
||||
filters = {}
|
||||
excluded_params = ['categoryId', 'page', 'limit']
|
||||
|
||||
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
|
||||
|
||||
# Получаем товары
|
||||
if key in excluded_params:
|
||||
continue
|
||||
|
||||
# Преобразуем ключ, если он есть в маппинге, иначе оставляем как есть
|
||||
real_key = filter_mapping.get(key, key)
|
||||
|
||||
# Разделяем значения по запятой
|
||||
if ',' in value:
|
||||
filters[real_key] = value.split(',')
|
||||
else:
|
||||
filters[real_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
|
||||
|
||||
|
||||
Reference in new issue
Block a user