solution
This commit is contained in:
+120
@@ -0,0 +1,120 @@
|
||||
"""Сборка приложения FastAPI: зависимости, миграции, обработчики ошибок."""
|
||||
|
||||
import asyncio
|
||||
import uuid
|
||||
from contextlib import asynccontextmanager
|
||||
from typing import Optional
|
||||
|
||||
from fastapi import FastAPI, Request
|
||||
from fastapi.exceptions import RequestValidationError
|
||||
from sqlalchemy.exc import InterfaceError, OperationalError
|
||||
from sqlalchemy.exc import TimeoutError as PoolTimeoutError
|
||||
from starlette.exceptions import HTTPException as StarletteHTTPException
|
||||
|
||||
from .cache import create_cache
|
||||
from .config import Settings
|
||||
from .db import create_engine, create_sessionmaker
|
||||
from .errors import ApiError, error_response
|
||||
from .logging_setup import get_logger, setup_logging
|
||||
from .middleware import RequestContextMiddleware
|
||||
from .migrate import check_schema
|
||||
from .routes import api, router
|
||||
|
||||
DB_UNAVAILABLE = (
|
||||
OperationalError,
|
||||
InterfaceError,
|
||||
PoolTimeoutError,
|
||||
OSError,
|
||||
asyncio.TimeoutError,
|
||||
)
|
||||
|
||||
|
||||
def create_app(settings: Optional[Settings] = None) -> FastAPI:
|
||||
"""Создать приложение FastAPI с заданными настройками."""
|
||||
settings = settings or Settings.from_env()
|
||||
setup_logging(settings.log_level)
|
||||
|
||||
@asynccontextmanager
|
||||
async def lifespan(app: FastAPI):
|
||||
"""Старт: кэш, движок, проверка версии схемы. Остановка: закрыть соединения."""
|
||||
get_logger().info(
|
||||
"config env=%s pool=%d+%d ttl=%ds store=%s cache=%s",
|
||||
settings.env,
|
||||
settings.db_pool_size,
|
||||
settings.db_max_overflow,
|
||||
settings.session_ttl_seconds,
|
||||
settings.session_store,
|
||||
"redis" if settings.cache_url else "off",
|
||||
)
|
||||
app.state.cache = create_cache(settings)
|
||||
engine = create_engine(settings)
|
||||
app.state.engine = engine
|
||||
app.state.sessionmaker = create_sessionmaker(engine)
|
||||
try:
|
||||
await check_schema(engine)
|
||||
app.state.ready = True
|
||||
get_logger().info("startup: приложение готово")
|
||||
yield
|
||||
finally:
|
||||
app.state.ready = False
|
||||
await app.state.cache.close()
|
||||
await engine.dispose()
|
||||
get_logger().info("shutdown: соединения с БД закрыты")
|
||||
|
||||
app = FastAPI(title="Messenger API", version="1.3.0", lifespan=lifespan)
|
||||
app.state.settings = settings
|
||||
app.state.ready = False
|
||||
app.router.redirect_slashes = False
|
||||
app.state.instance_id = uuid.uuid4().hex
|
||||
app.add_middleware(RequestContextMiddleware, instance_id=app.state.instance_id)
|
||||
|
||||
@app.exception_handler(ApiError)
|
||||
async def handle_api_error(request: Request, exc: ApiError):
|
||||
"""ApiError -> ответ в общем формате."""
|
||||
return error_response(
|
||||
request.state.request_id, exc.status, exc.code, exc.message, exc.headers
|
||||
)
|
||||
|
||||
@app.exception_handler(StarletteHTTPException)
|
||||
async def handle_http_error(request: Request, exc: StarletteHTTPException):
|
||||
"""404 и 405 -> ответ в общем формате."""
|
||||
if exc.status_code == 404:
|
||||
return error_response(
|
||||
request.state.request_id, 404, "not_found", "Объект не найден"
|
||||
)
|
||||
headers = dict(exc.headers) if exc.headers else None
|
||||
return error_response(
|
||||
request.state.request_id,
|
||||
exc.status_code,
|
||||
"invalid_request",
|
||||
"Запрос не поддерживается",
|
||||
headers,
|
||||
)
|
||||
|
||||
@app.exception_handler(RequestValidationError)
|
||||
async def handle_validation_error(request: Request, exc: RequestValidationError):
|
||||
"""Ошибки разбора параметров -> 400."""
|
||||
return error_response(
|
||||
request.state.request_id,
|
||||
400,
|
||||
"invalid_request",
|
||||
"Неверные параметры запроса",
|
||||
)
|
||||
|
||||
async def handle_db_unavailable(request: Request, exc: Exception):
|
||||
"""Недоступная БД или пул -> 503 без деталей."""
|
||||
get_logger().error(
|
||||
"db_unavailable request_id=%s type=%s",
|
||||
request.state.request_id,
|
||||
type(exc).__name__,
|
||||
)
|
||||
return error_response(
|
||||
request.state.request_id, 503, "unavailable", "Сервис временно недоступен"
|
||||
)
|
||||
|
||||
for error_type in DB_UNAVAILABLE:
|
||||
app.add_exception_handler(error_type, handle_db_unavailable)
|
||||
|
||||
app.include_router(router)
|
||||
app.include_router(api)
|
||||
return app
|
||||
Reference in New Issue
Block a user