跳到内容

依赖项 - Depends()Security()

Depends()

依赖项主要通过特殊的函数 Depends() 来处理,该函数接受一个可调用对象。

以下是它的参考及其参数。

您可以直接从 fastapi 中导入它

from fastapi import Depends

fastapi.Depends

Depends(dependency=None, *, use_cache=True)

声明 FastAPI 依赖项。

它接受一个可调用对象(如函数)。

不要直接调用它,FastAPI 会为您调用它,只需直接传递对象。

FastAPI 依赖项文档 中了解更多信息。

示例

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
参数 描述
dependency

一个可调用对象(如函数)。

不要直接调用它,FastAPI 会为您调用它,只需直接传递对象。

类型: Optional[Callable[..., Any]] 默认值: None

use_cache

默认情况下,在请求中第一次调用依赖项后,如果在请求的剩余部分再次声明了该依赖项(例如,如果几个依赖项需要该依赖项),则该值将在请求的剩余部分中重复使用。

use_cache 设置为 False 可禁用此行为,并确保在同一请求中再次调用该依赖项(如果多次声明)。

类型: bool 默认值: True

源代码位于 fastapi/param_functions.py
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
def Depends(  # noqa: N802
    dependency: Annotated[
        Optional[Callable[..., Any]],
        Doc(
            """
            A "dependable" callable (like a function).

            Don't call it directly, FastAPI will call it for you, just pass the object
            directly.
            """
        ),
    ] = None,
    *,
    use_cache: Annotated[
        bool,
        Doc(
            """
            By default, after a dependency is called the first time in a request, if
            the dependency is declared again for the rest of the request (for example
            if the dependency is needed by several dependencies), the value will be
            re-used for the rest of the request.

            Set `use_cache` to `False` to disable this behavior and ensure the
            dependency is called again (if declared more than once) in the same request.
            """
        ),
    ] = True,
) -> Any:
    """
    Declare a FastAPI dependency.

    It takes a single "dependable" callable (like a function).

    Don't call it directly, FastAPI will call it for you.

    Read more about it in the
    [FastAPI docs for Dependencies](https://fastapi.org.cn/tutorial/dependencies/).

    **Example**

    ```python
    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
    ```
    """
    return params.Depends(dependency=dependency, use_cache=use_cache)

Security()

对于许多场景,您可以使用依赖项处理安全(授权、身份验证等),使用 Depends()

但是,当您还想声明 OAuth2 范围时,可以使用 Security() 而不是 Depends()

您可以直接从 fastapi 中导入 Security()

from fastapi import Security

fastapi.Security

Security(dependency=None, *, scopes=None, use_cache=True)

声明 FastAPI 安全依赖项。

与常规依赖项唯一的区别是,它可以声明 OAuth2 范围,这些范围将与 OpenAPI 集成,以及自动 UI 文档(默认情况下位于 /docs)。

它接受一个可调用对象(如函数)。

不要直接调用它,FastAPI 会为您调用它,只需直接传递对象。

FastAPI 安全文档FastAPI OAuth2 范围文档 中了解更多信息。

示例

from typing import Annotated

from fastapi import Security, FastAPI

from .db import User
from .security import get_current_active_user

app = FastAPI()

@app.get("/users/me/items/")
async def read_own_items(
    current_user: Annotated[User, Security(get_current_active_user, scopes=["items"])]
):
    return [{"item_id": "Foo", "owner": current_user.username}]
参数 描述
dependency

一个可调用对象(如函数)。

不要直接调用它,FastAPI 会为您调用它,只需直接传递对象。

类型: Optional[Callable[..., Any]] 默认值: None

scopes

使用此安全依赖项的路径操作所需的 OAuth2 范围。

"范围" 一词来自 OAuth2 规范,它似乎有意含糊不清且可以解释。它通常指权限,在某些情况下指角色。

这些范围与 OpenAPI 集成(以及 /docs 上的 API 文档)。因此,它们在 OpenAPI 规范中可见。

类型: Optional[Sequence[str]] 默认值: None

use_cache

默认情况下,在请求中第一次调用依赖项后,如果在请求的剩余部分再次声明了该依赖项(例如,如果几个依赖项需要该依赖项),则该值将在请求的剩余部分中重复使用。

use_cache 设置为 False 可禁用此行为,并确保在同一请求中再次调用该依赖项(如果多次声明)。

类型: bool 默认值: True

源代码位于 fastapi/param_functions.py
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
def Security(  # noqa: N802
    dependency: Annotated[
        Optional[Callable[..., Any]],
        Doc(
            """
            A "dependable" callable (like a function).

            Don't call it directly, FastAPI will call it for you, just pass the object
            directly.
            """
        ),
    ] = None,
    *,
    scopes: Annotated[
        Optional[Sequence[str]],
        Doc(
            """
            OAuth2 scopes required for the *path operation* that uses this Security
            dependency.

            The term "scope" comes from the OAuth2 specification, it seems to be
            intentionaly vague and interpretable. It normally refers to permissions,
            in cases to roles.

            These scopes are integrated with OpenAPI (and the API docs at `/docs`).
            So they are visible in the OpenAPI specification.
            )
            """
        ),
    ] = None,
    use_cache: Annotated[
        bool,
        Doc(
            """
            By default, after a dependency is called the first time in a request, if
            the dependency is declared again for the rest of the request (for example
            if the dependency is needed by several dependencies), the value will be
            re-used for the rest of the request.

            Set `use_cache` to `False` to disable this behavior and ensure the
            dependency is called again (if declared more than once) in the same request.
            """
        ),
    ] = True,
) -> Any:
    """
    Declare a FastAPI Security dependency.

    The only difference with a regular dependency is that it can declare OAuth2
    scopes that will be integrated with OpenAPI and the automatic UI docs (by default
    at `/docs`).

    It takes a single "dependable" callable (like a function).

    Don't call it directly, FastAPI will call it for you.

    Read more about it in the
    [FastAPI docs for Security](https://fastapi.org.cn/tutorial/security/) and
    in the
    [FastAPI docs for OAuth2 scopes](https://fastapi.org.cn/advanced/security/oauth2-scopes/).

    **Example**

    ```python
    from typing import Annotated

    from fastapi import Security, FastAPI

    from .db import User
    from .security import get_current_active_user

    app = FastAPI()

    @app.get("/users/me/items/")
    async def read_own_items(
        current_user: Annotated[User, Security(get_current_active_user, scopes=["items"])]
    ):
        return [{"item_id": "Foo", "owner": current_user.username}]
    ```
    """
    return params.Security(dependency=dependency, scopes=scopes, use_cache=use_cache)