FastAPI และการทำงานแบบอะซิงโครนัส
ทำความเข้าใจว่า FastAPI จัดการฟังก์ชันแบบอะซิงโครนัสโดยธรรมชาติอย่างไร และวิธีเขียนโค้ดที่มีประสิทธิภาพโดยไม่บล็อกการทำงาน
FastAPI และการทำงานแบบอะซิงโครนัส เป็นบทเรียน FastAPI Backend Development Bootcamp ฟรีบน CoddyKit นี่คือบทเรียนที่ 2 จากทั้งหมด 4 บทเรียน คุณสามารถอ่านบทเรียนทั้งหมดด้านล่างฟรี — จากนั้นลองปฏิบัติด้วยตัวคุณเองในเบราว์เซอร์พร้อมตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7 บทเรียนนี้เป็นส่วนหนึ่งของเส้นทางการเรียน FastAPI Backend Development Bootcamp และความก้าวหน้าของคุณจะซิงค์ข้ามเว็บและแอป CoddyKit คอร์ส FastAPI Backend Development Bootcamp มีบทเรียนทั้งหมด 4 บทเรียน
บางส่วนของบทเรียนนี้ยังไม่ได้รับการแปล และแสดงเป็นภาษาอังกฤษ
FastAPI's Async Foundation
FastAPI is built for speed! It leverages Python's asynchronous features to handle many requests concurrently, especially I/O-bound tasks.
This means your API can stay responsive even when waiting for external resources like databases or other APIs.
Sync vs. Async Endpoints
In FastAPI, you can define two main types of endpoint functions:
- Synchronous (
def): These functions block the event loop while they run. If one request takes long, others might wait. - Asynchronous (
async def): These functions can 'pause' and let other tasks run while they await an operation (like reading from a database), making your API non-blocking.
Simple Synchronous Endpoint
Here's a standard synchronous endpoint. While simple, if time.sleep() were a real, slow database call, it would block other requests until it completes.
Try running it and observe the delay if you try to make multiple requests quickly.
from fastapi import FastAPI
import uvicorn
import time
app = FastAPI()
@app.get("/sync_hello")
def sync_hello():
time.sleep(2) # Simulate a blocking I/O operation
return {"message": "Hello from sync endpoint!"}
if __name__ == "__main__":
uvicorn.run(app, host="0.0.0.0", port=8000)Defining Asynchronous Endpoints
To make your endpoint non-blocking, use async def. This tells FastAPI (and Python) that this function can be suspended and resumed.
Inside an async def function, you use the await keyword to wait for other asynchronous operations to complete without blocking the entire application.
Your First Async Endpoint
This example uses asyncio.sleep(), which is an asynchronous sleep function. Notice the await keyword before it.
This allows FastAPI to handle other requests while this one 'sleeps', making the server more responsive.
from fastapi import FastAPI
import uvicorn
import asyncio
app = FastAPI()
@app.get("/async_hello")
async def async_hello():
await asyncio.sleep(2) # Simulate non-blocking I/O
return {"message": "Hello from async endpoint!"}
if __name__ == "__main__":
uvicorn.run(app, host="0.0.0.0", port=8000)When to Go Async
async def shines for I/O-bound operations. These are tasks that spend most of their time waiting for something else to happen, such as:
- Making requests to external APIs (e.g.,
httpx). - Querying a database (e.g.,
asyncpg,SQLModel). - Reading/writing files from disk.
- Network communication.
For CPU-bound tasks (heavy calculations), async def doesn't speed up the task itself, but it can help keep the server responsive.
Interacting with Async Libraries
When your FastAPI async def endpoint needs to interact with another asynchronous library (like an async HTTP client or an async database driver), you must use await.
Failing to use await will result in the awaitable object being returned directly, not its resolved result, which is usually not what you want!
Conceptual Async API Call
Imagine fetching data from another service. An async HTTP client allows this without blocking. Here's how it conceptually looks within an async def endpoint:
We simulate network latency with asyncio.sleep to show the non-blocking nature.
from fastapi import FastAPI
import uvicorn
import asyncio
app = FastAPI()
@app.get("/fetch_data")
async def fetch_external_data():
# In a real app, you'd use an async HTTP client like 'httpx'
# async with httpx.AsyncClient() as client:
# response = await client.get("https://api.example.com/data")
# data = response.json()
await asyncio.sleep(1) # Simulate network latency
return {"data": "Fetched async data!"}
if __name__ == "__main__":
uvicorn.run(app, host="0.0.0.0", port=8000)Uvicorn: The Async Engine
FastAPI relies on an ASGI server like Uvicorn. Uvicorn is what actually runs your async def functions efficiently.
- It manages the Python event loop, which orchestrates when different asynchronous tasks get to run.
- When an
awaitis encountered, Uvicorn can switch to another ready task, making your API highly concurrent.
This 'context switching' is what allows FastAPI to handle many requests without waiting for each one to finish entirely.
Quick Check: Async Use
You are building a FastAPI endpoint that needs to fetch data from a slow external API (an I/O-bound task). Which of the following is the best way to define this endpoint to ensure your FastAPI application remains responsive?
Recap: Async FastAPI
We've explored how FastAPI harnesses Python's asynchronous features:
- Use
async deffor endpoint functions that perform I/O-bound operations. - Use
awaitwhen calling other asynchronous functions or libraries within anasync def. - This non-blocking approach, powered by Uvicorn and the event loop, allows your FastAPI application to handle many concurrent requests efficiently, leading to highly responsive APIs.
Next, we'll look at how to offload truly long-running or CPU-bound tasks to background processes!
คำถามที่พบบ่อย
บทเรียน “FastAPI และการทำงานแบบอะซิงโครนัส” ฟรีหรือไม่
ใช่ — ข้อความเต็มของ “FastAPI และการทำงานแบบอะซิงโครนัส” ฟรีให้อ่านที่นี่บนเว็บ เพื่อปฏิบัติแบบโต้ตอบ (ตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7) และปลดล็อคส่วนที่เหลือของคอร์ส FastAPI Backend Development Bootcamp ให้อัปเกรดเป็น CoddyKit PRO คอร์ส FastAPI Backend Development Bootcamp มีบทเรียนทั้งหมด 4 บทเรียน
คุณจะเรียนรู้อะไรในบทเรียน “FastAPI และการทำงานแบบอะซิงโครนัส”
ทำความเข้าใจว่า FastAPI จัดการฟังก์ชันแบบอะซิงโครนัสโดยธรรมชาติอย่างไร และวิธีเขียนโค้ดที่มีประสิทธิภาพโดยไม่บล็อกการทำงาน คุณปฏิบัติ FastAPI Backend Development Bootcamp ด้วยโค้ดที่ใช้งานได้จริงที่คุณเรียกใช้โดยตรงในเบราว์เซอร์ และติวเตอร์ AI ตลอด 24/7 ตอบคำถามของคุณขณะที่คุณไปผ่านบทเรียน
คุณต้องมีประสบการณ์ก่อนที่จะเริ่มเรียน FastAPI Backend Development Bootcamp หรือไม่
ไม่จำเป็นต้องมีประสบการณ์มาก่อน FastAPI Backend Development Bootcamp บน CoddyKit ออกแบบมาสำหรับผู้เริ่มต้นไปจนถึงผู้เรียนขั้นสูง คุณสามารถเริ่มต้นที่นี่หรือเริ่มจากตัวแรกและเรียนด้วยความเร็วของคุณเอง นี่คือบทเรียนที่ 2 จากทั้งหมด 4 บทเรียน
บทเรียน “FastAPI และการทำงานแบบอะซิงโครนัส” ใช้เวลานานแค่ไหน
บทเรียน CoddyKit ส่วนใหญ่ใช้เวลาประมาณ 5–10 นาที แต่ละบทเรียนจึงสั้นและเป็นแบบโต้ตอบ คุณสามารถก้าวหน้าอย่างต่อเนื่องและกลับมาเรียนต่อจากตรงที่เพิ่งหยุดบนเว็บและแอปได้เลย
ฉันเขียนและรันโค้ดในบทเรียน FastAPI Backend Development Bootcamp นี้ได้ไหม
ได้ บทเรียน FastAPI Backend Development Bootcamp ทุกบทมีตัวแก้ไขโค้ดในตัว คุณจึงเขียนและรันโค้ดจริงได้เลยในเบราว์เซอร์ และได้รับข้อเสนอแนะจาก AI ในทันที — ไม่ต้องติดตั้งในเครื่องของคุณ
บทเรียนทั้งหมดในหลักสูตรนี้
- ทบทวน Async/Await ใน Python
- FastAPI และการทำงานแบบอะซิงโครนัส
- การทำงานเบื้องหลัง
- WebSockets เพื่อการสื่อสารแบบเรียลไทม์