add code for level 3

This commit is contained in:
Матвей
2026-10-08 17:04:26 +03:00
parent de44fc87c7
commit b158c88087
17 changed files with 804 additions and 310 deletions
+22 -4
View File
@@ -1,6 +1,7 @@
import logging
import sys
import time
from contextlib import asynccontextmanager
from uuid import uuid4
from fastapi import FastAPI, Request
@@ -12,6 +13,7 @@ from .errors import ApiError
from .models import ErrorDetails, ErrorResponse
from .config import load_settings
from .routes import router
from .storage.postgres import PostgresStore
access_logger = logging.getLogger("messenger.access")
@@ -25,10 +27,25 @@ access_logger.setLevel(logging.INFO)
access_logger.propagate = False
@asynccontextmanager
async def lifespan(application: FastAPI):
settings = load_settings()
store = PostgresStore(settings.database_url)
await store.connect()
await store.migrate()
application.state.store = store
application.state.settings = settings
try:
yield
finally:
await store.close()
app = FastAPI(
title="MTUSI Messenger",
version="1.1.0",
redoc_url=None,
lifespan=lifespan,
)
@@ -55,7 +72,9 @@ async def add_request_id(request: Request, call_next) -> Response:
)
def error_response(request: Request, status_code: int, code: str, message: str) -> JSONResponse:
def error_response(
request: Request, status_code: int, code: str, message: str, headers: dict[str, str] | None = None
) -> JSONResponse:
request_id = request.state.request_id
body = ErrorResponse(
error=ErrorDetails(code=code, message=message, request_id=request_id)
@@ -65,7 +84,7 @@ def error_response(request: Request, status_code: int, code: str, message: str)
return JSONResponse(
status_code=status_code,
content=body.model_dump(),
headers={"X-Request-Id": request_id},
headers={"X-Request-Id": request_id, **(headers or {})},
)
@@ -73,7 +92,7 @@ def error_response(request: Request, status_code: int, code: str, message: str)
async def handle_api_error(request: Request, error: ApiError) -> JSONResponse:
"""Преобразует контролируемую ошибку API в стандартный JSON-ответ."""
return error_response(request, error.status_code, error.code, error.message)
return error_response(request, error.status_code, error.code, error.message, error.headers)
@app.exception_handler(RequestValidationError)
@@ -108,4 +127,3 @@ def main() -> None:
if __name__ == "__main__":
main()