Files
mtusi2026lab3/app/api/middleware.py
T

39 lines
1.2 KiB
Python

import logging
from uuid import uuid4
from starlette.datastructures import MutableHeaders
from .errors import error_response
logger = logging.getLogger('app')
class RequestContext:
def __init__(self, app) -> None:
self.app = app
async def __call__(self, scope, receive, send) -> None:
if scope['type'] != 'http':
await self.app(scope, receive, send)
return
request_id = uuid4().hex
scope.setdefault('state', {})['request_id'] = request_id
started = False
async def send_wrapper(message) -> None:
nonlocal started
if message['type'] == 'http.response.start':
started = True
MutableHeaders(scope=message)['X-Request-Id'] = request_id
await send(message)
try:
await self.app(scope, receive, send_wrapper)
except Exception:
logger.exception(f'unhandled error request_id={request_id} path={scope.get("path")}')
if started:
raise
response = error_response(500, 'внутренняя ошибка', request_id)
await response(scope, receive, send_wrapper)