fix(api): fix err with filters
This commit is contained in:
1 parent
ba81b2cf32
commit
77ebb0e3a8
2 files changed
+67
-80
No files matched your search
+31
-18
@@ -2,9 +2,19 @@ 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')
|
||||
|
||||
def clean_filter_value(value):
|
||||
"""Очищает значение фильтра от мусора. Возвращает очищенное значение или None, если оно пустое."""
|
||||
if value is None:
|
||||
return None
|
||||
if isinstance(value, str):
|
||||
cleaned = value.strip().rstrip('/')
|
||||
if not cleaned:
|
||||
return None
|
||||
return cleaned
|
||||
return value
|
||||
|
||||
@api_product.route('/', methods=['GET'], strict_slashes=False)
|
||||
def get_products():
|
||||
try:
|
||||
@@ -20,14 +30,14 @@ def get_products():
|
||||
if limit < 1 or limit > 100:
|
||||
limit = 9
|
||||
|
||||
# Словарь для маппинга внешних ключей → внутренние имена в БД
|
||||
# ✅ ИСПРАВЛЕННЫЙ МАППИНГ
|
||||
filter_mapping = {
|
||||
'attr_1': 'diameter',
|
||||
'attr_2': 'length',
|
||||
'attr_3': 'wall_thickness',
|
||||
'attr_3': 'wall_thickness', # (опционально) тоже толщина
|
||||
'attr_4': 'color',
|
||||
'attr_5': 'application_type',
|
||||
'attr_6': 'stiffness_class',
|
||||
'attr_5': 'stiffness_class', # SN2, SN4
|
||||
'attr_6': 'wall_thickness', # <- теперь attr_6 ищет толщину стенки
|
||||
'attr_7': 'angle',
|
||||
'attr_8': 'fitting_type',
|
||||
}
|
||||
@@ -39,14 +49,24 @@ def get_products():
|
||||
if key in excluded_params:
|
||||
continue
|
||||
|
||||
# Преобразуем ключ, если он есть в маппинге, иначе оставляем как есть
|
||||
real_key = filter_mapping.get(key, key)
|
||||
|
||||
# Разделяем значения по запятой
|
||||
if ',' in value:
|
||||
filters[real_key] = value.split(',')
|
||||
parts = value.split(',')
|
||||
cleaned_parts = []
|
||||
for part in parts:
|
||||
cleaned = clean_filter_value(part)
|
||||
if cleaned is not None:
|
||||
cleaned_parts.append(cleaned)
|
||||
if cleaned_parts:
|
||||
filters[real_key] = cleaned_parts
|
||||
else:
|
||||
filters[real_key] = value
|
||||
cleaned = clean_filter_value(value)
|
||||
if cleaned is not None:
|
||||
filters[real_key] = cleaned
|
||||
|
||||
# Отладочный вывод (убедитесь, что здесь видно правильный ключ)
|
||||
print("=== FINAL FILTERS ===", filters)
|
||||
|
||||
result = get_products_with_filters(
|
||||
category_id=category_id,
|
||||
@@ -60,12 +80,9 @@ def get_products():
|
||||
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:
|
||||
@@ -74,17 +91,13 @@ def get_product(product_id):
|
||||
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
|
||||
|
||||
Reference in new issue
Block a user