Перенос lab1
This commit is contained in:
+99
@@ -0,0 +1,99 @@
|
||||
"""Точка входа: FastAPI-приложение, middleware и обработка ошибок."""
|
||||
import logging
|
||||
import os
|
||||
import uuid
|
||||
|
||||
from fastapi import FastAPI, Request
|
||||
from fastapi.exceptions import RequestValidationError
|
||||
from fastapi.responses import JSONResponse
|
||||
from starlette.exceptions import HTTPException as StarletteHTTPException
|
||||
|
||||
from .errors import ApiError, error_body
|
||||
from .handlers import router
|
||||
from .store import Store
|
||||
|
||||
logging.basicConfig(
|
||||
level=logging.INFO,
|
||||
format="%(asctime)s %(levelname)s %(name)s %(message)s",
|
||||
)
|
||||
logger = logging.getLogger("messenger")
|
||||
|
||||
app = FastAPI(title="MTUSI Messenger", version="1.1.0")
|
||||
app.state.store = Store()
|
||||
app.include_router(router)
|
||||
|
||||
|
||||
@app.middleware("http")
|
||||
async def request_id_middleware(request: Request, call_next):
|
||||
request_id = request.headers.get("X-Request-Id") or uuid.uuid4().hex
|
||||
request.state.request_id = request_id
|
||||
try:
|
||||
response = await call_next(request)
|
||||
except ApiError as exc:
|
||||
response = JSONResponse(
|
||||
error_body(exc.code, exc.message, request_id),
|
||||
status_code=exc.status,
|
||||
)
|
||||
response.headers["X-Request-Id"] = request_id
|
||||
return response
|
||||
|
||||
|
||||
@app.exception_handler(ApiError)
|
||||
async def api_error_handler(request: Request, exc: ApiError) -> JSONResponse:
|
||||
request_id = getattr(request.state, "request_id", uuid.uuid4().hex)
|
||||
return JSONResponse(
|
||||
error_body(exc.code, exc.message, request_id),
|
||||
status_code=exc.status,
|
||||
headers={"X-Request-Id": request_id},
|
||||
)
|
||||
|
||||
|
||||
@app.exception_handler(RequestValidationError)
|
||||
async def validation_error_handler(request: Request, exc: RequestValidationError) -> JSONResponse:
|
||||
request_id = getattr(request.state, "request_id", uuid.uuid4().hex)
|
||||
return JSONResponse(
|
||||
error_body("invalid_request", "Некорректный запрос", request_id),
|
||||
status_code=400,
|
||||
headers={"X-Request-Id": request_id},
|
||||
)
|
||||
|
||||
|
||||
@app.exception_handler(StarletteHTTPException)
|
||||
async def http_error_handler(request: Request, exc: StarletteHTTPException) -> JSONResponse:
|
||||
"""Ошибки разбора тела (невалидный JSON/байты) FastAPI отдаёт как HTTPException 400."""
|
||||
request_id = getattr(request.state, "request_id", uuid.uuid4().hex)
|
||||
if exc.status_code == 400:
|
||||
return JSONResponse(
|
||||
error_body("invalid_request", "Некорректный запрос", request_id),
|
||||
status_code=400,
|
||||
headers={"X-Request-Id": request_id},
|
||||
)
|
||||
return JSONResponse(
|
||||
error_body("not_found" if exc.status_code == 404 else "internal_error",
|
||||
str(exc.detail), request_id),
|
||||
status_code=exc.status_code,
|
||||
headers={"X-Request-Id": request_id},
|
||||
)
|
||||
|
||||
|
||||
@app.exception_handler(Exception)
|
||||
async def unhandled_error_handler(request: Request, exc: Exception) -> JSONResponse:
|
||||
request_id = getattr(request.state, "request_id", uuid.uuid4().hex)
|
||||
logger.exception("unhandled error request_id=%s", request_id)
|
||||
return JSONResponse(
|
||||
error_body("internal_error", "Внутренняя ошибка", request_id),
|
||||
status_code=500,
|
||||
headers={"X-Request-Id": request_id},
|
||||
)
|
||||
|
||||
|
||||
def main() -> None:
|
||||
import uvicorn
|
||||
|
||||
host = os.environ.get("APP_HOST", "0.0.0.0")
|
||||
port = int(os.environ.get("APP_PORT", "8080"))
|
||||
uvicorn.run(app, host=host, port=port, log_level="info")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Reference in New Issue
Block a user