91 lines
2.7 KiB
Python

import sys
import os
import asyncio
from pathlib import Path
backend_dir = Path(__file__).parent.parent.parent
if str(backend_dir) not in sys.path:
sys.path.insert(0, str(backend_dir))
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from contextlib import asynccontextmanager
from dishka.integrations.fastapi import setup_dishka
from dishka import Container
from src.shared.config import settings
from src.shared.exceptions import LawyerAIException
from src.shared.di_container import create_container
from src.presentation.middleware.error_handler import exception_handler
from src.presentation.api.v1 import users, collections, documents, conversations, messages, rag
from src.infrastructure.database.base import engine, Base
@asynccontextmanager
async def lifespan(app: FastAPI):
"""Управление жизненным циклом приложения"""
try:
async with engine.begin() as conn:
await conn.run_sync(Base.metadata.create_all)
except Exception as e:
print(f"Примечание при создании таблиц: {e}")
yield
if hasattr(app.state, 'container') and hasattr(app.state.container, 'close'):
if asyncio.iscoroutinefunction(app.state.container.close):
await app.state.container.close()
else:
app.state.container.close()
await engine.dispose()
app = FastAPI(
title=settings.APP_NAME,
description="API для системы ИИ-юриста",
version="1.0.0",
lifespan=lifespan
)
container = create_container()
setup_dishka(container, app)
app.state.container = container
app.add_middleware(
CORSMiddleware,
allow_origins=settings.CORS_ORIGINS,
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
app.add_exception_handler(LawyerAIException, exception_handler)
app.include_router(users.router, prefix="/api/v1")
app.include_router(collections.router, prefix="/api/v1")
app.include_router(documents.router, prefix="/api/v1")
app.include_router(conversations.router, prefix="/api/v1")
app.include_router(messages.router, prefix="/api/v1")
app.include_router(rag.router, prefix="/api/v1")
try:
from src.presentation.api.v1 import admin
app.include_router(admin.router, prefix="/api/v1")
except (ImportError, AttributeError) as e:
print(f"Админ-панель не загружена: {e}")
pass
@app.get("/")
async def root():
"""Корневой эндпоинт"""
return {
"message": "Добро пожаловать в API ИИ-юриста",
"version": "1.0.0",
"docs": "/docs"
}
@app.get("/health")
async def health_check():
"""Проверка здоровья приложения"""
return {"status": "ok"}