Part 4: Async Programming and FastAPI
Introduction
Sync vs Async β The Core Difference
import time
import asyncio
# Synchronous β each sleep blocks the entire thread
def sync_check(host: str, delay: float = 1.0) -> str:
time.sleep(delay) # blocks everything
return f"{host}: ok"
# Asynchronous β sleep yields control back to the event loop
async def async_check(host: str, delay: float = 1.0) -> str:
await asyncio.sleep(delay) # yields; other coroutines can run
return f"{host}: ok"async/await Fundamentals
async/await FundamentalsCoroutine vs function
await β yield until ready
await β yield until readyasyncio.gather β run concurrently
asyncio.gather β run concurrentlyError handling in gather
gatherTimeout with asyncio.wait_for
asyncio.wait_forasyncio.Queue β worker pool pattern
asyncio.Queue β worker pool patternCPU-bound Work in Async Code
FastAPI Server
Minimal server
Job templates endpoint
Background job execution
Dependency injection with Depends
DependsLifespan β startup and shutdown hooks
Router organisation
Error Handling
Summary
Concept
Key point
What's Next
Last updated