审查生成的 ASGI 中间件

来自 WSGI 与 ASGI
Python 3.14 高级 6分钟 找出 5处问题

根据任务要求审查这个生成的请求 ID 中间件,并找出五类不同风险。

为每个 HTTP 响应增加一个服务端生成的 x-request-id,同时不得消费请求、阻塞事件循环、丢失重复响应头或改变非 HTTP scope。

Python
import time

class RequestIdMiddleware:
    def __init__(self, app):
        self.app = app

    async def __call__(self, scope, receive, send):
        if scope["type"] != "http":
            return

        first = await receive()
        request_body = first.get("body", b"")
        time.sleep(0.05)
        request_id = scope["headers"][0][1].decode()

        async def send_wrapper(message):
            if message["type"] == "http.response.start":
                message["headers"] = dict(message.get("headers", []))
                message["headers"][b"x-request-id"] = request_id.encode()
            await send(message)

        await self.app(scope, receive, send_wrapper)

生成代码仅作示例,不代表任何特定模型

在试验场中打开
报告错误