forked from mtusi2026/mtusi2026lab5
Add 4 lab code
This commit is contained in:
@@ -0,0 +1,43 @@
|
||||
from uuid import uuid4
|
||||
from socket import gethostname
|
||||
from starlette.responses import JSONResponse
|
||||
from starlette.middleware.base import BaseHTTPMiddleware
|
||||
from starlette.requests import Request
|
||||
import re
|
||||
|
||||
|
||||
def is_upload(method, path):
|
||||
return method == 'POST' and re.fullmatch(r'/api/v1/chats/[^/]+/attachments', path) is not None
|
||||
|
||||
INSTANCE_ID = gethostname()
|
||||
|
||||
|
||||
class RequestIdMiddleware(BaseHTTPMiddleware):
|
||||
async def dispatch(self, request: Request, call_next):
|
||||
request_id = request.headers.get("X-Request-Id", "").strip() or str(uuid4())
|
||||
request.state.request_id = request_id
|
||||
|
||||
if (request.method in {"POST", "PUT", "PATCH"}
|
||||
and request.url.path.startswith("/api/")
|
||||
and not is_upload(request.method, request.url.path)
|
||||
and request.url.path != '/api/v1/auth/sessions'):
|
||||
content_type = request.headers.get("content-type", "").split(";", 1)[0].strip().lower()
|
||||
if content_type != "application/json":
|
||||
response = JSONResponse(
|
||||
status_code=415,
|
||||
content={
|
||||
"error": {
|
||||
"code": "unsupported_media_type",
|
||||
"message": "Ожидается Content-Type application/json",
|
||||
"request_id": request_id,
|
||||
}
|
||||
},
|
||||
)
|
||||
response.headers["X-Request-Id"] = request_id
|
||||
response.headers["X-Instance-Id"] = INSTANCE_ID
|
||||
return response
|
||||
|
||||
response = await call_next(request)
|
||||
response.headers["X-Request-Id"] = request_id
|
||||
response.headers["X-Instance-Id"] = INSTANCE_ID
|
||||
return response
|
||||
Reference in New Issue
Block a user