跳到内容

依赖项 - 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 会为您调用,只需直接传递对象即可。

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

use_cache

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

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

类型: bool 默认值: True

scope

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

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

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

源代码在 fastapi/param_functions.py
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
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
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,
    scope: Annotated[
        Union[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.
            """
        ),
    ] = 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 范围时,可以使用 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

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

“范围”一词来自 OAuth2 规范,它似乎被故意含糊不清且可随意解释。它通常指权限,在某些情况下也指角色。

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

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

use_cache

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

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

类型: bool 默认值: True

源代码在 fastapi/param_functions.py
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
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
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
            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.
            )
            """
        ),
    ] = 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)