python
type_error
ai_generated
true
值错误:路径参数 'id' 的类型无效:应为 int,实际为 str
ValueError: Invalid type for path parameter 'id': expected int, got str
ID: python/starlette-route-param-type
80%修复率
85%置信度
0证据数
2024-11-03首次发现
版本兼容性
| 版本 | 状态 | 引入 | 弃用 | 备注 |
|---|---|---|---|---|
| 3.x | active | — | — | — |
根因分析
Starlette 路由路径参数必须进行类型转换;如果 URL 提供字符串但处理程序期望 int,转换失败时会报错。
English
Starlette route path parameters must be type-converted; if the URL provides a string but the handler expects int, this error occurs if conversion fails.
解决方案
-
95% 成功率 Use int type hint in the route parameter
async def handler(request): id = request.path_params['id'] # id is already an int -
90% 成功率 Add a converter in the route pattern
routes = [Route('/items/{id:int}', handler)]
无效尝试
常见但无效的做法:
-
Using a string parameter and converting manually
70% 失败
Starlette auto-converts based on type hints; manual conversion may cause mismatch.
-
Not specifying a type hint
80% 失败
Without type hint, Starlette treats it as str.