python
data_error
ai_generated
true
键错误:'Authorization'
KeyError: 'Authorization'
ID: python/starlette-request-headers-missing
80%修复率
88%置信度
0证据数
2024-04-25首次发现
版本兼容性
| 版本 | 状态 | 引入 | 弃用 | 备注 |
|---|---|---|---|---|
| 3.x | active | — | — | — |
根因分析
在 Starlette 中直接访问 request.headers['Authorization'],但请求未包含该头部。
English
在 Starlette 中直接访问 request.headers['Authorization'],但请求未包含该头部。
解决方案
-
95% 成功率
auth = request.headers.get('Authorization') if auth is None: return JSONResponse({'error': 'missing'}, status_code=401) -
90% 成功率
auth = request.headers.get('Authorization', '')
无效尝试
常见但无效的做法:
-
50% 失败
头部名称不区分大小写,但拼写错误会导致返回 None,后续逻辑出错。
-
60% 失败
未处理缺失头部的情况,可能导致未授权访问。