การทำงานเบื้องหลัง
เรียนรู้การย้ายการทำงานที่ใช้เวลานานไปยังงานเบื้องหลัง เพื่อป้องกัน API หยุดรอและปรับปรุงประสบการณ์ผู้ใช้
การทำงานเบื้องหลัง เป็นบทเรียน FastAPI Backend Development Bootcamp ฟรีบน CoddyKit นี่คือบทเรียนที่ 3 จากทั้งหมด 4 บทเรียน คุณสามารถอ่านบทเรียนทั้งหมดด้านล่างฟรี — จากนั้นลองปฏิบัติด้วยตัวคุณเองในเบราว์เซอร์พร้อมตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7 บทเรียนนี้เป็นส่วนหนึ่งของเส้นทางการเรียน 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
BackgroundTasksfromfastapi. - 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
BackgroundTasksare 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 ตลอด 24/7) และปลดล็อคส่วนที่เหลือของคอร์ส FastAPI Backend Development Bootcamp ให้อัปเกรดเป็น CoddyKit PRO คอร์ส FastAPI Backend Development Bootcamp มีบทเรียนทั้งหมด 4 บทเรียน
คุณจะเรียนรู้อะไรในบทเรียน “การทำงานเบื้องหลัง”
เรียนรู้การย้ายการทำงานที่ใช้เวลานานไปยังงานเบื้องหลัง เพื่อป้องกัน API หยุดรอและปรับปรุงประสบการณ์ผู้ใช้ คุณปฏิบัติ FastAPI Backend Development Bootcamp ด้วยโค้ดที่ใช้งานได้จริงที่คุณเรียกใช้โดยตรงในเบราว์เซอร์ และติวเตอร์ AI ตลอด 24/7 ตอบคำถามของคุณขณะที่คุณไปผ่านบทเรียน
คุณต้องมีประสบการณ์ก่อนที่จะเริ่มเรียน FastAPI Backend Development Bootcamp หรือไม่
ไม่จำเป็นต้องมีประสบการณ์มาก่อน FastAPI Backend Development Bootcamp บน CoddyKit ออกแบบมาสำหรับผู้เริ่มต้นไปจนถึงผู้เรียนขั้นสูง คุณสามารถเริ่มต้นที่นี่หรือเริ่มจากตัวแรกและเรียนด้วยความเร็วของคุณเอง นี่คือบทเรียนที่ 3 จากทั้งหมด 4 บทเรียน
บทเรียน “การทำงานเบื้องหลัง” ใช้เวลานานแค่ไหน
บทเรียน CoddyKit ส่วนใหญ่ใช้เวลาประมาณ 5–10 นาที แต่ละบทเรียนจึงสั้นและเป็นแบบโต้ตอบ คุณสามารถก้าวหน้าอย่างต่อเนื่องและกลับมาเรียนต่อจากตรงที่เพิ่งหยุดบนเว็บและแอปได้เลย
ฉันเขียนและรันโค้ดในบทเรียน FastAPI Backend Development Bootcamp นี้ได้ไหม
ได้ บทเรียน FastAPI Backend Development Bootcamp ทุกบทมีตัวแก้ไขโค้ดในตัว คุณจึงเขียนและรันโค้ดจริงได้เลยในเบราว์เซอร์ และได้รับข้อเสนอแนะจาก AI ในทันที — ไม่ต้องติดตั้งในเครื่องของคุณ
บทเรียนทั้งหมดในหลักสูตรนี้
- ทบทวน Async/Await ใน Python
- FastAPI และการทำงานแบบอะซิงโครนัส
- การทำงานเบื้องหลัง
- WebSockets เพื่อการสื่อสารแบบเรียลไทม์