python
runtime_error
ai_generated
true
RuntimeError: 响应已开始,无法设置头。
RuntimeError: Unable to set headers after the response has started
ID: python/starlette-middleware-response-already-started
80%修复率
84%置信度
0证据数
2024-10-05首次发现
版本兼容性
| 版本 | 状态 | 引入 | 弃用 | 备注 |
|---|---|---|---|---|
| 0.30+ | active | — | — | — |
根因分析
中间件在 `await send(message)` 已发送 `http.response.start` 后尝试修改头。
English
A middleware tries to mutate headers after `await send(message)` has already sent `http.response.start`.
解决方案
-
95% 成功率
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% 成功率
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
无效尝试
常见但无效的做法:
-
85% 失败
Headers are silently missing; client sees wrong behavior.
-
95% 失败
State flag doesn't alter ASGI message ordering.