Browse Source

Add missing type hints for docs_src/background_tasks

pull/13503/head
Valentyn Druzhynin 2 weeks ago
parent
commit
e6a10e7330
  1. 6
      docs/de/docs/tutorial/background-tasks.md
  2. 8
      docs/em/docs/tutorial/background-tasks.md
  3. 6
      docs/en/docs/tutorial/background-tasks.md
  4. 6
      docs/es/docs/tutorial/background-tasks.md
  5. 8
      docs/fr/docs/tutorial/background-tasks.md
  6. 8
      docs/ja/docs/tutorial/background-tasks.md
  7. 8
      docs/ko/docs/tutorial/background-tasks.md
  8. 8
      docs/pt/docs/tutorial/background-tasks.md
  9. 6
      docs/ru/docs/tutorial/background-tasks.md
  10. 10
      docs/zh/docs/tutorial/background-tasks.md
  11. 8
      docs_src/background_tasks/tutorial001.py
  12. 10
      docs_src/background_tasks/tutorial002.py
  13. 10
      docs_src/background_tasks/tutorial002_an.py
  14. 6
      docs_src/background_tasks/tutorial002_an_py310.py
  15. 8
      docs_src/background_tasks/tutorial002_an_py39.py
  16. 6
      docs_src/background_tasks/tutorial002_py310.py

6
docs/de/docs/tutorial/background-tasks.md

@ -15,7 +15,7 @@ Hierzu zählen beispielsweise:
Importieren Sie zunächst `BackgroundTasks` und definieren Sie einen Parameter in Ihrer *Pfadoperation-Funktion* mit der Typdeklaration `BackgroundTasks`:
{* ../../docs_src/background_tasks/tutorial001.py hl[1,13] *}
{* ../../docs_src/background_tasks/tutorial001.py hl[3,16] *}
**FastAPI** erstellt für Sie das Objekt vom Typ `BackgroundTasks` und übergibt es als diesen Parameter.
@ -31,13 +31,13 @@ In diesem Fall schreibt die Taskfunktion in eine Datei (den Versand einer E-Mail
Und da der Schreibvorgang nicht `async` und `await` verwendet, definieren wir die Funktion mit normalem `def`:
{* ../../docs_src/background_tasks/tutorial001.py hl[6:9] *}
{* ../../docs_src/background_tasks/tutorial001.py hl[8:11] *}
## Den Hintergrundtask hinzufügen
Übergeben Sie innerhalb Ihrer *Pfadoperation-Funktion* Ihre Taskfunktion mit der Methode `.add_task()` an das *Hintergrundtasks*-Objekt:
{* ../../docs_src/background_tasks/tutorial001.py hl[14] *}
{* ../../docs_src/background_tasks/tutorial001.py hl[18] *}
`.add_task()` erhält als Argumente:

8
docs/em/docs/tutorial/background-tasks.md

@ -15,7 +15,7 @@
🥇, 🗄 `BackgroundTasks` & 🔬 🔢 👆 *➡ 🛠️ 🔢* ⏮️ 🆎 📄 `BackgroundTasks`:
{* ../../docs_src/background_tasks/tutorial001.py hl[1,13] *}
{* ../../docs_src/background_tasks/tutorial001.py hl[3,16] *}
**FastAPI** 🔜 ✍ 🎚 🆎 `BackgroundTasks` 👆 & 🚶‍♀️ ⚫️ 👈 🔢.
@ -31,13 +31,13 @@
& ✍ 🛠️ 🚫 ⚙️ `async` & `await`, 👥 🔬 🔢 ⏮️ 😐 `def`:
{* ../../docs_src/background_tasks/tutorial001.py hl[6:9] *}
{* ../../docs_src/background_tasks/tutorial001.py hl[8:11] *}
## 🚮 🖥 📋
🔘 👆 *➡ 🛠️ 🔢*, 🚶‍♀️ 👆 📋 🔢 *🖥 📋* 🎚 ⏮️ 👩‍🔬 `.add_task()`:
{* ../../docs_src/background_tasks/tutorial001.py hl[14] *}
{* ../../docs_src/background_tasks/tutorial001.py hl[18] *}
`.add_task()` 📨 ❌:
@ -51,7 +51,7 @@
**FastAPI** 💭 ⚫️❔ 🔠 💼 & ❔ 🏤-⚙️ 🎏 🎚, 👈 🌐 🖥 📋 🔗 👯‍♂️ & 🏃 🖥 ⏮️:
{* ../../docs_src/background_tasks/tutorial002.py hl[13,15,22,25] *}
{* ../../docs_src/background_tasks/tutorial002.py hl[14,17,24,27] *}
👉 🖼, 📧 🔜 ✍ `log.txt` 📁 *⏮️* 📨 📨.

6
docs/en/docs/tutorial/background-tasks.md

@ -15,7 +15,7 @@ This includes, for example:
First, import `BackgroundTasks` and define a parameter in your *path operation function* with a type declaration of `BackgroundTasks`:
{* ../../docs_src/background_tasks/tutorial001.py hl[1,13] *}
{* ../../docs_src/background_tasks/tutorial001.py hl[3,16] *}
**FastAPI** will create the object of type `BackgroundTasks` for you and pass it as that parameter.
@ -31,13 +31,13 @@ In this case, the task function will write to a file (simulating sending an emai
And as the write operation doesn't use `async` and `await`, we define the function with normal `def`:
{* ../../docs_src/background_tasks/tutorial001.py hl[6:9] *}
{* ../../docs_src/background_tasks/tutorial001.py hl[8:11] *}
## Add the background task
Inside of your *path operation function*, pass your task function to the *background tasks* object with the method `.add_task()`:
{* ../../docs_src/background_tasks/tutorial001.py hl[14] *}
{* ../../docs_src/background_tasks/tutorial001.py hl[18] *}
`.add_task()` receives as arguments:

6
docs/es/docs/tutorial/background-tasks.md

@ -15,7 +15,7 @@ Esto incluye, por ejemplo:
Primero, importa `BackgroundTasks` y define un parámetro en tu *path operation function* con una declaración de tipo de `BackgroundTasks`:
{* ../../docs_src/background_tasks/tutorial001.py hl[1,13] *}
{* ../../docs_src/background_tasks/tutorial001.py hl[3,16] *}
**FastAPI** creará el objeto de tipo `BackgroundTasks` por ti y lo pasará como ese parámetro.
@ -31,13 +31,13 @@ En este caso, la función de tarea escribirá en un archivo (simulando el envío
Y como la operación de escritura no usa `async` y `await`, definimos la función con un `def` normal:
{* ../../docs_src/background_tasks/tutorial001.py hl[6:9] *}
{* ../../docs_src/background_tasks/tutorial001.py hl[8:11] *}
## Agregar la tarea en segundo plano
Dentro de tu *path operation function*, pasa tu función de tarea al objeto de *background tasks* con el método `.add_task()`:
{* ../../docs_src/background_tasks/tutorial001.py hl[14] *}
{* ../../docs_src/background_tasks/tutorial001.py hl[18] *}
`.add_task()` recibe como argumentos:

8
docs/fr/docs/tutorial/background-tasks.md

@ -16,7 +16,7 @@ Cela comprend, par exemple :
Pour commencer, importez `BackgroundTasks` et définissez un paramètre dans votre *fonction de chemin* avec `BackgroundTasks` comme type déclaré.
{* ../../docs_src/background_tasks/tutorial001.py hl[1,13] *}
{* ../../docs_src/background_tasks/tutorial001.py hl[3,16] *}
**FastAPI** créera l'objet de type `BackgroundTasks` pour vous et le passera comme paramètre.
@ -30,14 +30,14 @@ Dans cet exemple, la fonction de tâche écrira dans un fichier (afin de simuler
L'opération d'écriture n'utilisant ni `async` ni `await`, on définit la fonction avec un `def` normal.
{* ../../docs_src/background_tasks/tutorial001.py hl[6:9] *}
{* ../../docs_src/background_tasks/tutorial001.py hl[8:11] *}
## Ajouter une tâche d'arrière-plan
Dans votre *fonction de chemin*, passez votre fonction de tâche à l'objet de type `BackgroundTasks` (`background_tasks` ici) grâce à la méthode `.add_task()` :
{* ../../docs_src/background_tasks/tutorial001.py hl[14] *}
{* ../../docs_src/background_tasks/tutorial001.py hl[18] *}
`.add_task()` reçoit comme arguments :
@ -51,7 +51,7 @@ Utiliser `BackgroundTasks` fonctionne aussi avec le système d'injection de dép
**FastAPI** sait quoi faire dans chaque cas et comment réutiliser le même objet, afin que tous les paramètres de type `BackgroundTasks` soient fusionnés et que les tâches soient exécutées en arrière-plan :
{* ../../docs_src/background_tasks/tutorial002.py hl[13,15,22,25] *}
{* ../../docs_src/background_tasks/tutorial002.py hl[14,17,24,27] *}
Dans cet exemple, les messages seront écrits dans le fichier `log.txt` après que la réponse soit envoyée.

8
docs/ja/docs/tutorial/background-tasks.md

@ -15,7 +15,7 @@
まず初めに、`BackgroundTasks` をインポートし、` BackgroundTasks` の型宣言と共に、*path operation 関数* のパラメーターを定義します:
{* ../../docs_src/background_tasks/tutorial001.py hl[1,13] *}
{* ../../docs_src/background_tasks/tutorial001.py hl[3,16] *}
**FastAPI** は、`BackgroundTasks` 型のオブジェクトを作成し、そのパラメーターに渡します。
@ -31,13 +31,13 @@
また、書き込み操作では `async``await` を使用しないため、通常の `def` で関数を定義します。
{* ../../docs_src/background_tasks/tutorial001.py hl[6:9] *}
{* ../../docs_src/background_tasks/tutorial001.py hl[8:11] *}
## バックグラウンドタスクの追加
*path operations 関数* 内で、`.add_task()` メソッドを使用してタスク関数を *background tasks* オブジェクトに渡します。
{* ../../docs_src/background_tasks/tutorial001.py hl[14] *}
{* ../../docs_src/background_tasks/tutorial001.py hl[18] *}
`.add_task()` は以下の引数を受け取ります:
@ -51,7 +51,7 @@
**FastAPI** は、それぞれの場合の処理​​方法と同じオブジェクトの再利用方法を知っているため、すべてのバックグラウンドタスクがマージされ、バックグラウンドで後で実行されます。
{* ../../docs_src/background_tasks/tutorial002.py hl[13,15,22,25] *}
{* ../../docs_src/background_tasks/tutorial002.py hl[14,17,24,27] *}
この例では、レスポンスが送信された *後* にメッセージが `log.txt` ファイルに書き込まれます。

8
docs/ko/docs/tutorial/background-tasks.md

@ -15,7 +15,7 @@ FastAPI에서는 응답을 반환한 후에 실행할 백그라운드 작업을
먼저 아래와 같이 `BackgroundTasks`를 임포트하고, `BackgroundTasks`_경로 작동 함수_ 에서 매개변수로 가져오고 정의합니다.
{* ../../docs_src/background_tasks/tutorial001.py hl[1,13] *}
{* ../../docs_src/background_tasks/tutorial001.py hl[3,16] *}
**FastAPI** 는 `BackgroundTasks` 개체를 생성하고, 매개 변수로 전달합니다.
@ -31,13 +31,13 @@ FastAPI에서는 응답을 반환한 후에 실행할 백그라운드 작업을
그리고 이 작업은 `async``await`를 사용하지 않으므로 일반 `def` 함수로 선언합니다.
{* ../../docs_src/background_tasks/tutorial001.py hl[6:9] *}
{* ../../docs_src/background_tasks/tutorial001.py hl[8:11] *}
## 백그라운드 작업 추가
_경로 작동 함수_ 내에서 작업 함수를 `.add_task()` 함수 통해 _백그라운드 작업_ 개체에 전달합니다.
{* ../../docs_src/background_tasks/tutorial001.py hl[14] *}
{* ../../docs_src/background_tasks/tutorial001.py hl[18] *}
`.add_task()` 함수는 다음과 같은 인자를 받습니다 :
@ -51,7 +51,7 @@ _경로 작동 함수_ 내에서 작업 함수를 `.add_task()` 함수 통해 _
**FastAPI**는 각 경우에 수행할 작업과 동일한 개체를 내부적으로 재사용하기에, 모든 백그라운드 작업이 함께 병합되고 나중에 백그라운드에서 실행됩니다.
{* ../../docs_src/background_tasks/tutorial002.py hl[13,15,22,25] *}
{* ../../docs_src/background_tasks/tutorial002.py hl[14,17,24,27] *}
이 예제에서는 응답이 반환된 후에 `log.txt` 파일에 메시지가 기록됩니다.

8
docs/pt/docs/tutorial/background-tasks.md

@ -15,7 +15,7 @@ Isso inclui, por exemplo:
Primeiro, importe `BackgroundTasks` e defina um parâmetro em sua _função de operação de caminho_ com uma declaração de tipo de `BackgroundTasks`:
{* ../../docs_src/background_tasks/tutorial001.py hl[1,13] *}
{* ../../docs_src/background_tasks/tutorial001.py hl[3,16] *}
O **FastAPI** criará o objeto do tipo `BackgroundTasks` para você e o passará como esse parâmetro.
@ -31,13 +31,13 @@ Nesse caso, a função de tarefa gravará em um arquivo (simulando o envio de um
E como a operação de gravação não usa `async` e `await`, definimos a função com `def` normal:
{* ../../docs_src/background_tasks/tutorial001.py hl[6:9] *}
{* ../../docs_src/background_tasks/tutorial001.py hl[8:11] *}
## Adicionar a tarefa em segundo plano
Dentro de sua _função de operação de caminho_, passe sua função de tarefa para o objeto _tarefas em segundo plano_ com o método `.add_task()`:
{* ../../docs_src/background_tasks/tutorial001.py hl[14] *}
{* ../../docs_src/background_tasks/tutorial001.py hl[18] *}
`.add_task()` recebe como argumentos:
@ -51,7 +51,7 @@ Usar `BackgroundTasks` também funciona com o sistema de injeção de dependênc
O **FastAPI** sabe o que fazer em cada caso e como reutilizar o mesmo objeto, de forma que todas as tarefas em segundo plano sejam mescladas e executadas em segundo plano posteriormente:
{* ../../docs_src/background_tasks/tutorial002.py hl[13,15,22,25] *}
{* ../../docs_src/background_tasks/tutorial002.py hl[14,17,24,27] *}
Neste exemplo, as mensagens serão gravadas no arquivo `log.txt` _após_ o envio da resposta.

6
docs/ru/docs/tutorial/background-tasks.md

@ -15,7 +15,7 @@
Сначала импортируйте `BackgroundTasks`, потом добавьте в функцию параметр с типом `BackgroundTasks`:
{* ../../docs_src/background_tasks/tutorial001.py hl[1,13] *}
{* ../../docs_src/background_tasks/tutorial001.py hl[3,16] *}
**FastAPI** создаст объект класса `BackgroundTasks` для вас и запишет его в параметр.
@ -31,13 +31,13 @@
Так как операция записи не использует `async` и `await`, мы определим ее как обычную `def`:
{* ../../docs_src/background_tasks/tutorial001.py hl[6:9] *}
{* ../../docs_src/background_tasks/tutorial001.py hl[8:11] *}
## Добавление фоновой задачи
Внутри функции вызовите метод `.add_task()` у объекта *background tasks* и передайте ему функцию, которую хотите выполнить в фоне:
{* ../../docs_src/background_tasks/tutorial001.py hl[14] *}
{* ../../docs_src/background_tasks/tutorial001.py hl[18] *}
`.add_task()` принимает следующие аргументы:

10
docs/zh/docs/tutorial/background-tasks.md

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

8
docs_src/background_tasks/tutorial001.py

@ -1,15 +1,19 @@
from typing import Dict
from fastapi import BackgroundTasks, FastAPI
app = FastAPI()
def write_notification(email: str, message=""):
def write_notification(email: str, message: str = "") -> None:
with open("log.txt", mode="w") as email_file:
content = f"notification for {email}: {message}"
email_file.write(content)
@app.post("/send-notification/{email}")
async def send_notification(email: str, background_tasks: BackgroundTasks):
async def send_notification(
email: str, background_tasks: BackgroundTasks
) -> Dict[str, str]:
background_tasks.add_task(write_notification, email, message="some notification")
return {"message": "Notification sent in the background"}

10
docs_src/background_tasks/tutorial002.py

@ -1,16 +1,18 @@
from typing import Union
from typing import Dict, Union
from fastapi import BackgroundTasks, Depends, FastAPI
app = FastAPI()
def write_log(message: str):
def write_log(message: str) -> None:
with open("log.txt", mode="a") as log:
log.write(message)
def get_query(background_tasks: BackgroundTasks, q: Union[str, None] = None):
def get_query(
background_tasks: BackgroundTasks, q: Union[str, None] = None
) -> Union[str, None]:
if q:
message = f"found query: {q}\n"
background_tasks.add_task(write_log, message)
@ -20,7 +22,7 @@ def get_query(background_tasks: BackgroundTasks, q: Union[str, None] = None):
@app.post("/send-notification/{email}")
async def send_notification(
email: str, background_tasks: BackgroundTasks, q: str = Depends(get_query)
):
) -> Dict[str, str]:
message = f"message to {email}\n"
background_tasks.add_task(write_log, message)
return {"message": "Message sent"}

10
docs_src/background_tasks/tutorial002_an.py

@ -1,4 +1,4 @@
from typing import Union
from typing import Dict, Union
from fastapi import BackgroundTasks, Depends, FastAPI
from typing_extensions import Annotated
@ -6,12 +6,14 @@ from typing_extensions import Annotated
app = FastAPI()
def write_log(message: str):
def write_log(message: str) -> None:
with open("log.txt", mode="a") as log:
log.write(message)
def get_query(background_tasks: BackgroundTasks, q: Union[str, None] = None):
def get_query(
background_tasks: BackgroundTasks, q: Union[str, None] = None
) -> Union[str, None]:
if q:
message = f"found query: {q}\n"
background_tasks.add_task(write_log, message)
@ -21,7 +23,7 @@ def get_query(background_tasks: BackgroundTasks, q: Union[str, None] = None):
@app.post("/send-notification/{email}")
async def send_notification(
email: str, background_tasks: BackgroundTasks, q: Annotated[str, Depends(get_query)]
):
) -> Dict[str, str]:
message = f"message to {email}\n"
background_tasks.add_task(write_log, message)
return {"message": "Message sent"}

6
docs_src/background_tasks/tutorial002_an_py310.py

@ -5,12 +5,12 @@ from fastapi import BackgroundTasks, Depends, FastAPI
app = FastAPI()
def write_log(message: str):
def write_log(message: str) -> None:
with open("log.txt", mode="a") as log:
log.write(message)
def get_query(background_tasks: BackgroundTasks, q: str | None = None):
def get_query(background_tasks: BackgroundTasks, q: str | None = None) -> str | None:
if q:
message = f"found query: {q}\n"
background_tasks.add_task(write_log, message)
@ -20,7 +20,7 @@ def get_query(background_tasks: BackgroundTasks, q: str | None = None):
@app.post("/send-notification/{email}")
async def send_notification(
email: str, background_tasks: BackgroundTasks, q: Annotated[str, Depends(get_query)]
):
) -> dict[str, str]:
message = f"message to {email}\n"
background_tasks.add_task(write_log, message)
return {"message": "Message sent"}

8
docs_src/background_tasks/tutorial002_an_py39.py

@ -5,12 +5,14 @@ from fastapi import BackgroundTasks, Depends, FastAPI
app = FastAPI()
def write_log(message: str):
def write_log(message: str) -> None:
with open("log.txt", mode="a") as log:
log.write(message)
def get_query(background_tasks: BackgroundTasks, q: Union[str, None] = None):
def get_query(
background_tasks: BackgroundTasks, q: Union[str, None] = None
) -> Union[str, None]:
if q:
message = f"found query: {q}\n"
background_tasks.add_task(write_log, message)
@ -20,7 +22,7 @@ def get_query(background_tasks: BackgroundTasks, q: Union[str, None] = None):
@app.post("/send-notification/{email}")
async def send_notification(
email: str, background_tasks: BackgroundTasks, q: Annotated[str, Depends(get_query)]
):
) -> dict[str, str]:
message = f"message to {email}\n"
background_tasks.add_task(write_log, message)
return {"message": "Message sent"}

6
docs_src/background_tasks/tutorial002_py310.py

@ -3,12 +3,12 @@ from fastapi import BackgroundTasks, Depends, FastAPI
app = FastAPI()
def write_log(message: str):
def write_log(message: str) -> None:
with open("log.txt", mode="a") as log:
log.write(message)
def get_query(background_tasks: BackgroundTasks, q: str | None = None):
def get_query(background_tasks: BackgroundTasks, q: str | None = None) -> str | None:
if q:
message = f"found query: {q}\n"
background_tasks.add_task(write_log, message)
@ -18,7 +18,7 @@ def get_query(background_tasks: BackgroundTasks, q: str | None = None):
@app.post("/send-notification/{email}")
async def send_notification(
email: str, background_tasks: BackgroundTasks, q: str = Depends(get_query)
):
) -> dict[str, str]:
message = f"message to {email}\n"
background_tasks.add_task(write_log, message)
return {"message": "Message sent"}

Loading…
Cancel
Save