|
|
@ -15,9 +15,7 @@ |
|
|
|
|
|
|
|
首先导入 `BackgroundTasks` 并在 *路径操作函数* 中使用类型声明 `BackgroundTasks` 定义一个参数: |
|
|
|
|
|
|
|
```Python hl_lines="1 13" |
|
|
|
{!../../docs_src/background_tasks/tutorial001.py!} |
|
|
|
``` |
|
|
|
{* ../../docs_src/background_tasks/tutorial001.py hl[1, 13] *} |
|
|
|
|
|
|
|
**FastAPI** 会创建一个 `BackgroundTasks` 类型的对象并作为该参数传入。 |
|
|
|
|
|
|
@ -33,17 +31,13 @@ |
|
|
|
|
|
|
|
由于写操作不使用 `async` 和 `await`,我们用普通的 `def` 定义函数: |
|
|
|
|
|
|
|
```Python hl_lines="6-9" |
|
|
|
{!../../docs_src/background_tasks/tutorial001.py!} |
|
|
|
``` |
|
|
|
{* ../../docs_src/background_tasks/tutorial001.py hl[6:9] *} |
|
|
|
|
|
|
|
## 添加后台任务 |
|
|
|
|
|
|
|
在你的 *路径操作函数* 里,用 `.add_task()` 方法将任务函数传到 *后台任务* 对象中: |
|
|
|
|
|
|
|
```Python hl_lines="14" |
|
|
|
{!../../docs_src/background_tasks/tutorial001.py!} |
|
|
|
``` |
|
|
|
{* ../../docs_src/background_tasks/tutorial001.py hl[14] *} |
|
|
|
|
|
|
|
`.add_task()` 接收以下参数: |
|
|
|
|
|
|
@ -59,25 +53,19 @@ |
|
|
|
|
|
|
|
//// tab | Python 3.10+ |
|
|
|
|
|
|
|
```Python hl_lines="13 15 22 25" |
|
|
|
{!> ../../docs_src/background_tasks/tutorial002_an_py310.py!} |
|
|
|
``` |
|
|
|
{* ../../docs_src/background_tasks/tutorial002_an_py310.py hl[13, 15, 22, 25] *} |
|
|
|
|
|
|
|
//// |
|
|
|
|
|
|
|
//// tab | Python 3.9+ |
|
|
|
|
|
|
|
```Python hl_lines="13 15 22 25" |
|
|
|
{!> ../../docs_src/background_tasks/tutorial002_an_py39.py!} |
|
|
|
``` |
|
|
|
{* ../../docs_src/background_tasks/tutorial002_an_py39.py hl[13, 15, 22, 25] *} |
|
|
|
|
|
|
|
//// |
|
|
|
|
|
|
|
//// tab | Python 3.8+ |
|
|
|
|
|
|
|
```Python hl_lines="14 16 23 26" |
|
|
|
{!> ../../docs_src/background_tasks/tutorial002_an.py!} |
|
|
|
``` |
|
|
|
{* ../../docs_src/background_tasks/tutorial002_an.py hl[14, 16, 23, 26] *} |
|
|
|
|
|
|
|
//// |
|
|
|
|
|
|
@ -89,9 +77,7 @@ |
|
|
|
|
|
|
|
/// |
|
|
|
|
|
|
|
```Python hl_lines="11 13 20 23" |
|
|
|
{!> ../../docs_src/background_tasks/tutorial002_py310.py!} |
|
|
|
``` |
|
|
|
{* ../../docs_src/background_tasks/tutorial002_py310.py hl[11, 13, 20, 23] *} |
|
|
|
|
|
|
|
//// |
|
|
|
|
|
|
@ -103,9 +89,7 @@ |
|
|
|
|
|
|
|
/// |
|
|
|
|
|
|
|
```Python hl_lines="13 15 22 25" |
|
|
|
{!> ../../docs_src/background_tasks/tutorial002.py!} |
|
|
|
``` |
|
|
|
{* ../../docs_src/background_tasks/tutorial002.py hl[13, 15, 22, 25] *} |
|
|
|
|
|
|
|
//// |
|
|
|
|
|
|
|