跳至內容

依賴項 - 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.dev.org.tw/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.dev.org.tw/tutorial/security/) and
    in the
    [FastAPI docs for OAuth2 scopes](https://fastapi.dev.org.tw/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)