python type_error ai_generated true

类型错误:'str'对象无法解释为整数

TypeError: 'str' object cannot be interpreted as an integer

ID: python/starlette-route-parameter-type-mismatch

其他格式: JSON · Markdown 中文 · English
80%修复率
82%置信度
0证据数
2024-10-01首次发现

版本兼容性

版本状态引入弃用备注
3.x active

根因分析

预期为整数的路由参数以字符串形式传递,未进行转换。

English

A route parameter expected as an integer is passed as a string without conversion.

generic

解决方案

  1. 90% 成功率 Convert the parameter to int explicitly
    async def get_item(item_id: str):
        item_id = int(item_id)
  2. 95% 成功率 Use Starlette's path converter for int
    @app.route('/items/{item_id:int}')
    async def get_item(item_id: int):
        ...

无效尝试

常见但无效的做法:

  1. Using str() on the parameter 80% 失败

    Doesn't convert to int; keeps it as string.

  2. Ignoring the type and using the string directly 70% 失败

    May cause errors in logic expecting an integer.