0Pricing
FastAPI Backend Development Bootcamp · 课时

执行后台任务

学习将长时间运行的操作转移到后台任务中,避免 API 阻塞并改善用户体验。

执行后台任务 是 CoddyKit 上的免费 FastAPI Backend Development Bootcamp 课时。 这是第 3 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 FastAPI Backend Development Bootcamp 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 FastAPI Backend Development Bootcamp 课程共包含 4 节课。

本课时的部分内容尚未翻译,以英文显示。

Slow Endpoints & UX

Imagine your API needs to do something time-consuming, like sending an email or processing a large file, after a user request.

If your API waits for these tasks to finish before responding, the user experiences a slow, unresponsive application. This is called a blocking operation.

Bad user experience often leads to users abandoning your app!

Blocking vs. Non-Blocking APIs

Think of it like ordering food:

  • Blocking: You order, and the waiter waits for your food to be cooked, served, and eaten before taking the next order. (Terrible service!)
  • Non-Blocking: You order, the waiter takes your order to the kitchen, and immediately takes the next customer's order. Your food is prepared in the background.

We want our APIs to be non-blocking for a smooth user experience.

Meet FastAPI's BackgroundTasks

FastAPI provides a simple way to run operations in the 'background' after sending the HTTP response to the client. This is done using the BackgroundTasks dependency.

BackgroundTasks lets you add functions to a list that will be executed once the main API route has completed and the response has been delivered.

Injecting BackgroundTasks

To use background tasks, you simply declare a parameter with the type BackgroundTasks in your path operation function. FastAPI will automatically inject an instance of it.

  • Import BackgroundTasks from fastapi.
  • Declare a parameter, e.g., background_tasks: BackgroundTasks.
  • Use background_tasks.add_task() to schedule a function.

First Background Task Demo

Let's see a basic example. This task will print a message after the API response is sent. Remember to run uvicorn main:app --reload.

from fastapi import FastAPI, BackgroundTasks
import time

app = FastAPI()

def write_notification(email: str, message=""):
    time.sleep(2) # Simulate a long operation
    with open("log.txt", mode="a") as email_file:
        email_file.write(f"notification for {email}: {message}\n")
    print(f"Notification written for {email}")

@app.post("/send-notification/{email}")
async def send_notification(email: str, background_tasks: BackgroundTasks):
    background_tasks.add_task(write_notification, email, message="Welcome to CoddyKit!")
    return {"message": "Notification sent in background!"}

Understanding Execution Flow

It's crucial to understand when background tasks execute:

  • The path operation function runs.
  • The HTTP response is sent back to the client.
  • Then, the functions added to BackgroundTasks are executed.

This means the client doesn't wait for these tasks to complete, improving perceived performance.

Passing Arguments to Tasks

You can pass any arguments your background function needs to add_task(). The first argument is the function itself, followed by its arguments.

Arguments can be positional or keyword arguments, just like calling a regular Python function.

For example: background_tasks.add_task(my_function, arg1, arg2=value).

Simulating Email Send

A common scenario for background tasks is sending emails. This can take a few seconds, which would block your user if done directly in the API route.

Here, we simulate sending an email to multiple recipients. Try it from the /docs UI!

from fastapi import FastAPI, BackgroundTasks
import asyncio # For async sleep

app = FastAPI()

async def send_email_async(recipients: list, subject: str, body: str):
    print(f"Starting email send to {recipients}...")
    await asyncio.sleep(3) # Simulate network delay for sending email
    print(f"Email '{subject}' sent to {recipients} with body: '{body}'")

@app.post("/send-marketing-email/")
async def marketing_campaign(
    recipients: list[str],
    subject: str,
    body: str,
    background_tasks: BackgroundTasks
):
    # The actual email sending is offloaded
    background_tasks.add_task(send_email_async, recipients, subject, body)
    return {"message": "Marketing email campaign initiated in background!"}

Important Considerations

While powerful, BackgroundTasks are not for everything:

  • Short-lived: Best for tasks that complete relatively quickly (seconds to a few minutes).
  • No persistence: If your FastAPI process crashes, scheduled tasks are lost.
  • No retry: They don't have built-in retry mechanisms for failed tasks.
  • Not for heavy computation: For very long-running, CPU-intensive, or fault-tolerant tasks, consider dedicated task queues like Celery, Redis Queue (RQ), or similar.

Background Task Check

You've learned about using BackgroundTasks. Which of the following statements about FastAPI's BackgroundTasks is true?

Recap: Background Tasks

We've explored how FastAPI's BackgroundTasks help keep your API responsive:

  • They run after the HTTP response is sent.
  • They're great for non-critical, relatively short-lived operations like sending notifications.
  • You declare them as a dependency and use add_task().
  • For truly long-running or critical tasks, consider external task queues.

By using background tasks, you ensure a smoother experience for your API users!

常见问题解答

「执行后台任务」课时是免费的吗?

是的 — 「执行后台任务」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 FastAPI Backend Development Bootcamp 课程的其余内容,请升级到 CoddyKit PRO。 FastAPI Backend Development Bootcamp 课程共包含 4 节课。

「执行后台任务」这节课中我会学到什么?

学习将长时间运行的操作转移到后台任务中,避免 API 阻塞并改善用户体验。 你通过在浏览器中直接运行的动手代码来练习 FastAPI Backend Development Bootcamp,全天候 AI 导师会在你学习这节课的过程中回答你的问题。

学习 FastAPI Backend Development Bootcamp 需要有经验吗?

无需任何先前经验。CoddyKit 上的 FastAPI Backend Development Bootcamp 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 3 节课,共 4 节。

「执行后台任务」课时需要多长时间?

大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。

我能在这节 FastAPI Backend Development Bootcamp 课中编写并运行代码吗?

能。每节 FastAPI Backend Development Bootcamp 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。

此课程中的所有课时

  1. Python 异步编程复习
  2. FastAPI 与异步操作
  3. 执行后台任务
  4. 使用 WebSockets 实现实时通信
← 返回 FastAPI Backend Development Bootcamp