import sys from pathlib import Path # Добавляем корневую директорию проекта в PYTHONPATH при прямом запуске # Это нужно, чтобы Python мог найти модуль 'app' # Проверяем, запускается ли файл напрямую, проверяя имя скрипта if sys.argv and len(sys.argv) > 0: script_path = Path(sys.argv[0]).resolve() current_file = Path(__file__).resolve() # Если скрипт запускается напрямую (не через модуль) if script_path == current_file or script_path.name == current_file.name: project_root = current_file.parent.parent # new-planet-backend if str(project_root) not in sys.path: sys.path.insert(0, str(project_root)) from fastapi import FastAPI, Request from fastapi.exceptions import RequestValidationError from starlette.exceptions import HTTPException as StarletteHTTPException from app.core.config import settings from app.core.logging import setup_logging from app.api.v1.router import api_router from app.middleware import ( setup_cors, validation_exception_handler, http_exception_handler, general_exception_handler, RateLimitMiddleware, ) from contextlib import asynccontextmanager # Настройка логирования logger = setup_logging(settings.DEBUG and "DEBUG" or "INFO") @asynccontextmanager async def lifespan(app: FastAPI): """Lifecycle events""" # Startup logger.info("Starting up...") from app.services.cache_service import cache_service await cache_service.connect() yield # Shutdown logger.info("Shutting down...") await cache_service.disconnect() app = FastAPI( title=settings.PROJECT_NAME, version=settings.VERSION, openapi_url=f"{settings.API_V1_STR}/openapi.json", docs_url="/docs", redoc_url="/redoc", lifespan=lifespan ) # Middleware setup_cors(app) if settings.RATE_LIMIT_ENABLED: app.add_middleware(RateLimitMiddleware) # Exception handlers app.add_exception_handler(RequestValidationError, validation_exception_handler) app.add_exception_handler(StarletteHTTPException, http_exception_handler) app.add_exception_handler(Exception, general_exception_handler) # Routers app.include_router(api_router, prefix=settings.API_V1_STR) @app.get("/") async def root(): """Root endpoint""" return { "message": "Новая Планета API", "version": settings.VERSION, "docs": "/docs" } @app.get("/health") async def health_check(): """Health check endpoint""" return {"status": "healthy"} if __name__ == "__main__": import uvicorn uvicorn.run( "app.main:app", host="127.0.0.1", port=8000, reload=settings.DEBUG )