依赖项 - 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
|
类型: |
use_cache
|
默认情况下,在一个请求中首次调用依赖项后,如果在该请求的后续过程中再次声明该依赖项(例如多个依赖项需要同一个依赖项时),该值将在后续请求过程中被复用。 将 在 FastAPI 子依赖项文档 中了解更多信息。
类型: |
scope
|
主要用于带有
在 FastAPI 带有 yield 的依赖项文档 中了解更多信息。
类型: |
源代码位于 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
|
类型: |
scopes
|
使用此安全依赖项的*路径操作*所需的 OAuth2 范围。 术语“scope”(范围)源自 OAuth2 规范,它似乎被故意设计得较为模糊且具有解释性。它通常指代权限,在某些情况下指代角色。 这些范围与 OpenAPI(以及位于 在 FastAPI OAuth2 范围文档 中了解更多信息。
类型: |
use_cache
|
默认情况下,在一个请求中首次调用依赖项后,如果在该请求的后续过程中再次声明该依赖项(例如多个依赖项需要同一个依赖项时),该值将在后续请求过程中被复用。 将 在 FastAPI 子依赖项文档 中了解更多信息。
类型: |
源代码位于 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)