feat-(move2lab2, postgres settings, repo base and other)

This commit is contained in:
2026-11-03 04:24:22 +03:00
parent 65003b6119
commit 273519109e
34 changed files with 1396 additions and 0 deletions
+78
View File
@@ -0,0 +1,78 @@
from fastapi import FastAPI, Request, HTTPException
from fastapi.exceptions import RequestValidationError
from fastapi.responses import JSONResponse
import os
from src.api.dependencies import generate_id, create_error_response
from src.api.routes.health import health
from src.api.routes.users import user
from src.api.routes.chats import chat
from src.api.routes.messages import message
from src.lifespan import lifespan
application = FastAPI(title="MTUSI Messenger", version="1.0.0", lifespan=lifespan)
@application.middleware("http")
async def add_request_id(request: Request, call_next):
request_id = generate_id()
request.state.request_id = request_id
response = await call_next(request)
response.headers["X-Request-Id"] = request_id
return response
@application.exception_handler(RequestValidationError)
async def validation_exception_handler(request: Request, exc: RequestValidationError):
messages = []
for err in exc.errors():
loc = '.'.join(str(p) for p in err["loc"] if p not in ('body',))
msg = err.get("msg", "invalid")
if msg.startswith("Value error, "):
msg = msg[len("Value error, "):]
messages.append(f"{loc}: {msg}" if loc else msg)
detail = "; ".join(messages) or "invalid request"
request_id = getattr(request.state, "request_id", "")
return JSONResponse(
status_code=400,
content={"error": {
"code": "invalid_request",
"message": detail,
"request_id": request_id
}
},
headers={"X-Request-Id": request_id},
)
@application.exception_handler(HTTPException)
async def http_exception_handler(request: Request, exc: HTTPException):
request_id = getattr(request.state, "request_id", None)
if request_id is None:
request_id = generate_id()
code_map = {
400: "invalid_request",
401: "unauthorized",
404: "not_found",
409: "conflict",
413: "payload_too_large",
415: "unsupported_media_type",
429: "rate_limited",
503: "unavailable"
}
code = code_map.get(exc.status_code, "internal_error")
return create_error_response(message=str(exc.detail), code=code, status_code=exc.status_code, request_id=request_id)
@application.exception_handler(Exception)
async def global_exception_handler(request: Request, exc: Exception):
request_id = getattr(request.state, "request_id", None)
if request_id is None:
request_id = generate_id()
print(f'Internal Error: {exc}')
return create_error_response(message="Internal Server Error", code="internal_error", status_code=500, request_id=request_id)
application.include_router(health.router, prefix="/health", tags=["Health"])
application.include_router(user.router, prefix="/api", tags=["Users"])
application.include_router(chat.router, prefix="/api", tags=["Chats"])
application.include_router(message.router, prefix="/api", tags=["Messages"])