dressed_for_succes_store/backend/app/main.py

84 lines
2.7 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import os
import logging
from pathlib import Path
from fastapi import FastAPI, Request
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import JSONResponse
from fastapi.staticfiles import StaticFiles
from sqlalchemy.exc import SQLAlchemyError
from contextlib import asynccontextmanager
from app.config import settings
from app.routers import router
from app.core import Base, engine, SessionLocal
from app.services import meilisearch_service
from app.scripts.sync_meilisearch import sync_products, sync_categories, sync_collections, sync_sizes
logging.basicConfig(level=logging.INFO)
# Создаем таблицы в базе данных
Base.metadata.create_all(bind=engine)
@asynccontextmanager
async def lifespan(app: FastAPI):
# Инициализируем Meilisearch
logging.info("Инициализация Meilisearch...")
try:
# Инициализируем индексы
meilisearch_service.initialize_indexes()
# Создаем сессию базы данных
db = SessionLocal()
try:
# Синхронизируем данные с Meilisearch
sync_categories(db)
sync_collections(db)
sync_sizes(db)
sync_products(db)
logging.info("Синхронизация с Meilisearch завершена успешно")
except Exception as e:
logging.error(f"Ошибка при синхронизации данных с Meilisearch: {str(e)}")
finally:
db.close()
except Exception as e:
logging.error(f"Ошибка при инициализации Meilisearch: {str(e)}")
yield
# Создаем экземпляр приложения FastAPI
app = FastAPI(
title="Dressed for Success API",
description="API для интернет-магазина одежды",
version="1.0.0",
lifespan=lifespan
)
# Настраиваем CORS
app.add_middleware(
CORSMiddleware,
allow_origins=["*"], # В продакшене нужно указать конкретные домены
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
# Обработка ошибок SQLAlchemy
@app.exception_handler(SQLAlchemyError)
async def sqlalchemy_exception_handler(request: Request, exc: SQLAlchemyError):
return JSONResponse(
status_code=500,
content={"detail": "Ошибка базы данных", "error": str(exc)},
)
# Подключаем роутеры
app.include_router(router, prefix="/api")
# Корневой маршрут
@app.get("/")
async def root():
return {"message": "Добро пожаловать в API интернет-магазина Dressed for Success"}