feat(api): added controllers for api
This commit is contained in:
1 parent
b9c1a1c018
commit
90630d393f
3 files changed
+127
-23
No files matched your search
+30
-5
@@ -1,7 +1,32 @@
|
|||||||
from flask import Blueprint, request
|
from flask import jsonify
|
||||||
|
from db.handlers.catigory_handler import get_all_categories_with_attributes, get_category_by_id
|
||||||
|
from flask import Blueprint
|
||||||
|
|
||||||
type = Blueprint("type", __name__)
|
# Создаем blueprint для API
|
||||||
|
api_category = Blueprint('api_category', __name__, url_prefix='/api/categories')
|
||||||
|
|
||||||
@product.route('/types', method = ['GET'])
|
@api_category.route('/categories', methods=['GET'])
|
||||||
def GetTypes():
|
def get_categories():
|
||||||
return
|
"""
|
||||||
|
Получение всех категорий с атрибутами
|
||||||
|
GET /api/categories
|
||||||
|
"""
|
||||||
|
try:
|
||||||
|
categories = get_all_categories_with_attributes()
|
||||||
|
return jsonify(categories), 200
|
||||||
|
except Exception as e:
|
||||||
|
return jsonify({"error": str(e)}), 500
|
||||||
|
|
||||||
|
@api_category.route('/categories/<int:category_id>', methods=['GET'])
|
||||||
|
def get_category(category_id):
|
||||||
|
"""
|
||||||
|
Получение категории по ID
|
||||||
|
GET /api/categories/{id}
|
||||||
|
"""
|
||||||
|
try:
|
||||||
|
category = get_category_by_id(category_id)
|
||||||
|
if category:
|
||||||
|
return jsonify(category), 200
|
||||||
|
return jsonify({"error": "Category not found"}), 404
|
||||||
|
except Exception as e:
|
||||||
|
return jsonify({"error": str(e)}), 500
|
||||||
+82
-3
@@ -1,5 +1,84 @@
|
|||||||
from flask import Blueprint, request
|
from flask import jsonify, request
|
||||||
|
from db.handlers.product_handler import get_products_with_filters, get_product_by_id
|
||||||
|
from flask import Blueprint
|
||||||
|
|
||||||
product = Blueprint("product", __name__)
|
# Создаем blueprint для API
|
||||||
|
api_product = Blueprint('api_product', __name__, url_prefix='/api')
|
||||||
|
|
||||||
@product.route('')
|
@api_product.route('/products', methods=['GET'])
|
||||||
|
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('/products/<int:product_id>', methods=['GET'])
|
||||||
|
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('/products/fetchById', methods=['GET'])
|
||||||
|
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
|
||||||
@@ -1,26 +1,26 @@
|
|||||||
from sys import exit
|
from sys import exit
|
||||||
from flask import Flask
|
from flask import Flask
|
||||||
|
from flask_cors import CORS
|
||||||
from db.InitializeDB import init_database
|
from db.InitializeDB import init_database
|
||||||
from json import dumps
|
|
||||||
from db.InitializeDBData import init_tables
|
from db.InitializeDBData import init_tables
|
||||||
from db.handlers.catigory_handler import GetAllCategories
|
|
||||||
from utils.loadDotENV import initializeENV
|
from utils.loadDotENV import initializeENV
|
||||||
from utils.mail import send_pdf_to_email
|
from api.categories import api_category
|
||||||
|
from api.product import api_product
|
||||||
|
|
||||||
# Инициализация
|
# Инициализация
|
||||||
initializeENV()
|
initializeENV()
|
||||||
|
init_database()
|
||||||
init_tables()
|
init_tables()
|
||||||
|
|
||||||
# Получаем категории
|
# Создаем приложение Flask
|
||||||
categories = GetAllCategories()
|
|
||||||
print("Категории из БД:", dumps(categories, indent=2, ensure_ascii=False))
|
|
||||||
|
|
||||||
# ОТПРАВЛЯЕМ ПИСЬМО СРАЗУ ПРИ ЗАПУСКЕ
|
|
||||||
send_pdf_to_email(
|
|
||||||
recipient_email="remizov.kirill2005@yandex.ru",
|
|
||||||
pdf_filename="1.pdf",
|
|
||||||
subject="Отчет по трубам ПВХ",
|
|
||||||
body_text=f"Привет! В базе {len(categories)} категорий. Файл во вложении."
|
|
||||||
)
|
|
||||||
|
|
||||||
app = Flask(__name__)
|
app = Flask(__name__)
|
||||||
|
CORS(app)
|
||||||
|
|
||||||
|
# Регистрируем blueprint
|
||||||
|
app.register_blueprint(api_category)
|
||||||
|
app.register_blueprint(api_product)
|
||||||
|
|
||||||
|
@app.route('/health', methods=['GET'])
|
||||||
|
def health_check():
|
||||||
|
"""Проверка работоспособности API"""
|
||||||
|
return {"status": "ok", "message": "API is running"}, 200
|
||||||
Reference in new issue
Block a user