forked from mtusi2026/mtusi2026lab3
Исправить балансировку и миграции лабы 3
This commit is contained in:
+20
-2
@@ -10,6 +10,7 @@ from datetime import datetime, timezone
|
||||
|
||||
import asyncpg
|
||||
from fastapi import FastAPI, Header, Request
|
||||
from fastapi.exceptions import RequestValidationError
|
||||
from fastapi.responses import JSONResponse, Response
|
||||
from pydantic import BaseModel, ConfigDict, Field, ValidationError
|
||||
|
||||
@@ -34,6 +35,8 @@ async def tagging_middleware(request: Request, call_next):
|
||||
request_id = uuid.uuid4().hex
|
||||
request.state.request_id = request_id
|
||||
try:
|
||||
if request.url.path.startswith("/api/") and not await _dependencies_ready():
|
||||
raise unavailable("database or session store not ready")
|
||||
response = await call_next(request)
|
||||
except ApiError as exc:
|
||||
response = _error_response(exc, request_id)
|
||||
@@ -44,6 +47,10 @@ async def tagging_middleware(request: Request, call_next):
|
||||
return response
|
||||
|
||||
|
||||
async def _dependencies_ready() -> bool:
|
||||
return await db.ping() and await sessions.ping()
|
||||
|
||||
|
||||
def _error_response(exc: ApiError, request_id: str) -> JSONResponse:
|
||||
headers = {}
|
||||
if exc.status == 401:
|
||||
@@ -66,6 +73,14 @@ async def api_error_handler(request: Request, exc: ApiError):
|
||||
return _error_response(exc, getattr(request.state, "request_id", uuid.uuid4().hex))
|
||||
|
||||
|
||||
@app.exception_handler(RequestValidationError)
|
||||
async def request_validation_error_handler(request: Request, exc: RequestValidationError):
|
||||
return _error_response(
|
||||
bad_request("invalid request parameters"),
|
||||
getattr(request.state, "request_id", uuid.uuid4().hex),
|
||||
)
|
||||
|
||||
|
||||
def iso(value: datetime) -> str:
|
||||
return value.astimezone(timezone.utc).isoformat().replace("+00:00", "Z")
|
||||
|
||||
@@ -111,7 +126,10 @@ def decode_cursor(value: str) -> dict:
|
||||
try:
|
||||
padded = value + "=" * (-len(value) % 4)
|
||||
raw = base64.urlsafe_b64decode(padded.encode())
|
||||
return json.loads(raw)
|
||||
payload = json.loads(raw)
|
||||
if not isinstance(payload, dict):
|
||||
raise bad_request("malformed cursor")
|
||||
return payload
|
||||
except (binascii.Error, ValueError, UnicodeDecodeError):
|
||||
raise bad_request("malformed cursor")
|
||||
|
||||
@@ -210,7 +228,7 @@ async def health_ready():
|
||||
@app.post("/api/v1/users", status_code=201)
|
||||
async def register_user(request: Request):
|
||||
body = await parse_body(request, CreateUser)
|
||||
if not USERNAME_RE.match(body.username):
|
||||
if not USERNAME_RE.fullmatch(body.username):
|
||||
raise bad_request("username must match ^[a-z0-9_]{3,32}$")
|
||||
if not body.display_name.strip():
|
||||
raise bad_request("display_name must not be blank")
|
||||
|
||||
Reference in New Issue
Block a user