跳到内容

fast-api-non-annotated-dependency (FAST002)

派生自 FastAPI 代码检查器。

有时提供修复。

作用

识别 FastAPI 路由中已弃用的 Depends 或类似用法。

为什么这不好?

FastAPI 文档建议使用 typing.Annotated 来定义路由依赖项和参数,而不是使用 DependsQuery 或类似项作为参数的默认值。在所有地方使用这种方法有助于确保定义依赖项和参数的一致性和清晰度。

Annotated 已添加到 Python 3.9 的 typing 模块中;但是,第三方 typing_extensions 包提供了一个反向移植版本,可以在旧版本的 Python 上使用。

示例

from fastapi import Depends, FastAPI

app = FastAPI()


async def common_parameters(q: str | None = None, skip: int = 0, limit: int = 100):
    return {"q": q, "skip": skip, "limit": limit}


@app.get("/items/")
async def read_items(commons: dict = Depends(common_parameters)):
    return commons

建议改为

from typing import Annotated

from fastapi import Depends, FastAPI

app = FastAPI()


async def common_parameters(q: str | None = None, skip: int = 0, limit: int = 100):
    return {"q": q, "skip": skip, "limit": limit}


@app.get("/items/")
async def read_items(commons: Annotated[dict, Depends(common_parameters)]):
    return commons

修复安全性

此修复总是不安全的,因为添加/删除/更改函数参数的默认值可能会改变运行时行为。此外,已弃用用法中的注释可能会被删除。

Availability(可用性)

由于此规则依赖于 Python 3.9 之前的版本的第三方 typing_extensions 模块,如果目标版本 < 3.9 并且 lint.typing-extensions linter 选项禁用了 typing_extensions 导入,则不会发出诊断信息,也不会提供修复。

Options (选项)