python
runtime_error
ai_generated
true
RuntimeError: Unable to set headers after the response has started
ID: python/starlette-middleware-response-already-started
80%Fix Rate
84%Confidence
0Evidence
2024-10-05First Seen
Version Compatibility
| Version | Status | Introduced | Deprecated | Notes |
|---|---|---|---|---|
| 0.30+ | active | — | — | — |
Root Cause
A middleware tries to mutate headers after `await send(message)` has already sent `http.response.start`.
generic中文
中间件在 `await send(message)` 已发送 `http.response.start` 后尝试修改头。
Workarounds
-
95% success
async def __call__(self, scope, receive, send): async def send_wrapper(message): if message['type'] == 'http.response.start': message['headers'].append((b'x-custom', b'1')) await send(message) await self.app(scope, receive, send_wrapper) -
90% success
from starlette.middleware.base import BaseHTTPMiddleware class M(BaseHTTPMiddleware): async def dispatch(self, request, call_next): resp = await call_next(request) resp.headers['x-custom'] = '1' return resp
Dead Ends
Common approaches that don't work:
-
85% fail
Headers are silently missing; client sees wrong behavior.
-
95% fail
State flag doesn't alter ASGI message ordering.