跳到内容

依赖项 - Depends()Security()

Depends()

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

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

您可以直接从 fastapi 导入它。

from fastapi import Depends

fastapi.Depends

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

声明一个 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 会为你调用,只需直接传递对象即可。

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

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

use_cache

默认情况下,在一个请求中首次调用依赖项后,如果在该请求的后续过程中再次声明该依赖项(例如多个依赖项需要同一个依赖项时),该值将在后续请求过程中被复用。

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

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

类型: bool 默认值: True

scope

主要用于带有 yield 的依赖项,定义依赖函数何时开始(yield 之前的代码)以及何时结束(yield 之后的代码)。

  • "function":在处理请求的*路径操作函数*之前启动依赖项,在*路径操作函数*结束后结束依赖项,但在响应发送回客户端之前。因此,依赖函数将在*路径操作函数*周围执行。
  • "request":在处理请求的*路径操作函数*之前启动依赖项(类似于使用 "function" 时),但在响应发送回客户端之后结束。因此,依赖函数将在请求和响应周期的周围执行。

FastAPI 带有 yield 的依赖项文档 中了解更多信息。

类型: Literal['function', 'request'] | None 默认值: None

源代码位于 fastapi/param_functions.py
def Depends(  # noqa: N802
    dependency: Annotated[
        Callable[..., Any] | None,
        Doc(
            """
            A "dependable" callable (like a function).

            Don't call it directly, FastAPI will call it for you, just pass the object
            directly.

            Read more about it in the
            [FastAPI docs for Dependencies](https://fastapi.org.cn/tutorial/dependencies/)
            """
        ),
    ] = 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.

            Read more about it in the
            [FastAPI docs about sub-dependencies](https://fastapi.org.cn/tutorial/dependencies/sub-dependencies/#using-the-same-dependency-multiple-times)
            """
        ),
    ] = True,
    scope: Annotated[
        Literal["function", "request"] | None,
        Doc(
            """
            Mainly for dependencies with `yield`, define when the dependency function
            should start (the code before `yield`) and when it should end (the code
            after `yield`).

            * `"function"`: start the dependency before the *path operation function*
                that handles the request, end the dependency after the *path operation
                function* ends, but **before** the response is sent back to the client.
                So, the dependency function will be executed **around** the *path operation
                **function***.
            * `"request"`: start the dependency before the *path operation function*
                that handles the request (similar to when using `"function"`), but end
                **after** the response is sent back to the client. So, the dependency
                function will be executed **around** the **request** and response cycle.

            Read more about it in the
            [FastAPI docs for FastAPI Dependencies with yield](https://fastapi.org.cn/tutorial/dependencies/dependencies-with-yield/#early-exit-and-scope)
            """
        ),
    ] = None,
) -> 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, scope=scope)

Security()

在许多场景中,你可以使用 Depends() 通过依赖项来处理安全性(授权、认证等)。

但当你还想声明 OAuth2 范围(scopes)时,可以使用 Security() 代替 Depends()

你可以直接从 fastapi 导入 Security()

from fastapi import Security

fastapi.Security

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

声明一个 FastAPI 安全依赖项。

它与常规依赖项的唯一区别在于,它可以声明将与 OpenAPI 和自动 UI 文档(默认在 /docs)集成的 OAuth2 范围。

它接收单个“可依赖的”可调用对象(如函数)。

不要直接调用它,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 会为你调用,只需直接传递对象即可。

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

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

scopes

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

术语“scope”(范围)源自 OAuth2 规范,它似乎被故意设计得较为模糊且具有解释性。它通常指代权限,在某些情况下指代角色。

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

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

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

use_cache

默认情况下,在一个请求中首次调用依赖项后,如果在该请求的后续过程中再次声明该依赖项(例如多个依赖项需要同一个依赖项时),该值将在后续请求过程中被复用。

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

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

类型: bool 默认值: True

源代码位于 fastapi/param_functions.py
def Security(  # noqa: N802
    dependency: Annotated[
        Callable[..., Any] | None,
        Doc(
            """
            A "dependable" callable (like a function).

            Don't call it directly, FastAPI will call it for you, just pass the object
            directly.

            Read more about it in the
            [FastAPI docs for Dependencies](https://fastapi.org.cn/tutorial/dependencies/)
            """
        ),
    ] = None,
    *,
    scopes: Annotated[
        Sequence[str] | None,
        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
            intentionally 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.

            Read more about it in the
            [FastAPI docs about OAuth2 scopes](https://fastapi.org.cn/advanced/security/oauth2-scopes/)
            """
        ),
    ] = 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.

            Read more about it in the
            [FastAPI docs about sub-dependencies](https://fastapi.org.cn/tutorial/dependencies/sub-dependencies/#using-the-same-dependency-multiple-times)
            """
        ),
    ] = 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)