Исходники, миграции, Dockerfile и стенд lab4 нужны как основа асинхронной обработки вложений. Co-authored-by: Cursor <cursoragent@cursor.com>
50 lines
1.4 KiB
Python
50 lines
1.4 KiB
Python
from typing import Dict, Optional
|
|
|
|
from starlette.responses import JSONResponse
|
|
|
|
|
|
ERROR_CODES = {
|
|
400: "invalid_request",
|
|
401: "unauthorized",
|
|
404: "not_found",
|
|
409: "conflict",
|
|
413: "payload_too_large",
|
|
415: "unsupported_media_type",
|
|
429: "rate_limited",
|
|
503: "unavailable",
|
|
500: "internal_error",
|
|
}
|
|
|
|
BASIC_CHALLENGE = 'Basic realm="messenger", charset="UTF-8"'
|
|
BEARER_CHALLENGE = 'Bearer realm="messenger"'
|
|
|
|
|
|
class AppError(Exception):
|
|
def __init__(self, status: int, message: str, www_authenticate: str | None = None) -> None:
|
|
super().__init__(message)
|
|
self.status = status
|
|
self.message = message
|
|
self.www_authenticate = www_authenticate
|
|
|
|
|
|
def error_response(
|
|
status: int,
|
|
message: str,
|
|
request_id: str,
|
|
extra_headers: Optional[Dict[str, str]] = None,
|
|
) -> JSONResponse:
|
|
code = ERROR_CODES.get(status, "internal_error")
|
|
headers = {"X-Request-Id": request_id, "Content-Type": "application/json"}
|
|
if extra_headers:
|
|
headers.update(extra_headers)
|
|
return JSONResponse(
|
|
status_code=status,
|
|
headers=headers,
|
|
content={"error": {"code": code, "message": message, "request_id": request_id}},
|
|
)
|
|
|
|
|
|
def from_app_error(exc: AppError, request_id: str) -> JSONResponse:
|
|
extra = {"WWW-Authenticate": exc.www_authenticate} if exc.www_authenticate else None
|
|
return error_response(exc.status, exc.message, request_id, extra)
|