forked from mtusi2026/mtusi2026lab2
feat: перевести API на password/Basic/Bearer и PostgreSQL с Redis-кэшем
Co-authored-by: aider (deepseek/deepseek-chat) <aider@aider.chat>
This commit is contained in:
+26
-3
@@ -3,13 +3,16 @@ import logging
|
||||
import os
|
||||
import uuid
|
||||
|
||||
import redis
|
||||
from fastapi import FastAPI, Request
|
||||
from fastapi.exceptions import RequestValidationError
|
||||
from fastapi.responses import JSONResponse
|
||||
from starlette.exceptions import HTTPException as StarletteHTTPException
|
||||
|
||||
from .db import apply_migrations, make_pool
|
||||
from .errors import ApiError, error_body
|
||||
from .handlers import router
|
||||
from .sessions import SessionStore
|
||||
from .store import Store
|
||||
|
||||
logging.basicConfig(
|
||||
@@ -18,8 +21,24 @@ logging.basicConfig(
|
||||
)
|
||||
logger = logging.getLogger("messenger")
|
||||
|
||||
app = FastAPI(title="MTUSI Messenger", version="1.1.0")
|
||||
app.state.store = Store()
|
||||
app = FastAPI(title="MTUSI Messenger", version="1.2.0")
|
||||
|
||||
_pool = make_pool()
|
||||
apply_migrations(_pool)
|
||||
|
||||
_cache: redis.Redis | None = None
|
||||
_cache_url = os.environ.get("CACHE_URL")
|
||||
if _cache_url:
|
||||
_cache = redis.Redis.from_url(
|
||||
_cache_url,
|
||||
socket_timeout=float(os.environ.get("REDIS_SOCKET_TIMEOUT", "1")),
|
||||
socket_connect_timeout=float(os.environ.get("REDIS_SOCKET_TIMEOUT", "1")),
|
||||
decode_responses=False,
|
||||
)
|
||||
|
||||
app.state.pool = _pool
|
||||
app.state.store = Store(_pool)
|
||||
app.state.sessions = SessionStore(_pool, _cache)
|
||||
app.include_router(router)
|
||||
|
||||
|
||||
@@ -41,10 +60,14 @@ async def request_id_middleware(request: Request, call_next):
|
||||
@app.exception_handler(ApiError)
|
||||
async def api_error_handler(request: Request, exc: ApiError) -> JSONResponse:
|
||||
request_id = getattr(request.state, "request_id", uuid.uuid4().hex)
|
||||
headers = {"X-Request-Id": request_id}
|
||||
challenge = getattr(exc, "challenge", None)
|
||||
if challenge:
|
||||
headers["WWW-Authenticate"] = challenge
|
||||
return JSONResponse(
|
||||
error_body(exc.code, exc.message, request_id),
|
||||
status_code=exc.status,
|
||||
headers={"X-Request-Id": request_id},
|
||||
headers=headers,
|
||||
)
|
||||
|
||||
|
||||
|
||||
Reference in New Issue
Block a user