feat: перенос логики с 4лабф
This commit is contained in:
@@ -0,0 +1,16 @@
|
||||
from .errors import (
|
||||
INSTANCE_ID_HEADER,
|
||||
REQUEST_ID_HEADER,
|
||||
error_response,
|
||||
get_request_id,
|
||||
)
|
||||
from .streams import content_disposition, request_chunks
|
||||
|
||||
__all__ = [
|
||||
"REQUEST_ID_HEADER",
|
||||
"INSTANCE_ID_HEADER",
|
||||
"error_response",
|
||||
"get_request_id",
|
||||
"request_chunks",
|
||||
"content_disposition",
|
||||
]
|
||||
@@ -0,0 +1,33 @@
|
||||
from collections.abc import Mapping
|
||||
|
||||
from fastapi import Request
|
||||
from fastapi.responses import JSONResponse
|
||||
|
||||
from domain.errors import ErrorBodySchema, ErrorCode, ErrorSchema
|
||||
|
||||
REQUEST_ID_HEADER = "X-Request-Id"
|
||||
INSTANCE_ID_HEADER = "X-Instance-Id"
|
||||
|
||||
|
||||
def get_request_id(request: Request) -> str:
|
||||
"""ID запроса, назначенный RequestContextMiddleware"""
|
||||
request_id: str = request.state.request_id
|
||||
return request_id
|
||||
|
||||
|
||||
def error_response(
|
||||
request_id: str,
|
||||
status_code: int,
|
||||
code: ErrorCode,
|
||||
message: str,
|
||||
headers: Mapping[str, str] | None = None,
|
||||
) -> JSONResponse:
|
||||
"""Ответ в едином формате ошибки контракта"""
|
||||
body = ErrorSchema(
|
||||
error=ErrorBodySchema(code=code, message=message, request_id=request_id)
|
||||
)
|
||||
return JSONResponse(
|
||||
status_code=status_code,
|
||||
content=body.model_dump(mode="json"),
|
||||
headers={**(headers or {}), REQUEST_ID_HEADER: request_id},
|
||||
)
|
||||
@@ -0,0 +1,28 @@
|
||||
from collections.abc import AsyncIterator
|
||||
from urllib.parse import quote
|
||||
|
||||
from fastapi import Request
|
||||
from starlette.requests import ClientDisconnect
|
||||
|
||||
from domain.errors import InvalidRequestError
|
||||
|
||||
|
||||
async def request_chunks(request: Request) -> AsyncIterator[bytes]:
|
||||
"""
|
||||
Тело запроса потоком, без буферизации целиком. Обрыв соединения клиентом
|
||||
— доменная ошибка, а не необработанное исключение (500 в журнале).
|
||||
"""
|
||||
try:
|
||||
async for chunk in request.stream():
|
||||
if chunk:
|
||||
yield chunk
|
||||
except ClientDisconnect:
|
||||
raise InvalidRequestError("Загрузка прервана клиентом") from None
|
||||
|
||||
|
||||
def content_disposition(filename: str) -> str:
|
||||
"""
|
||||
inline с именем по RFC 6266/5987: имя целиком percent-encoded, поэтому
|
||||
кавычки, ; и переводы строк не могут разорвать заголовок.
|
||||
"""
|
||||
return f"inline; filename*=UTF-8''{quote(filename, safe='')}"
|
||||
Reference in New Issue
Block a user