Python & FastAPI•Part 3: Asynchronous Programming & Concurrency (26 - 40)
Blocking the Event Loop & offloading to threads:
In Simple Words:
Running synchronous blocking code (time.sleep, requests.get, image processing) in an async route freezes the single event loop thread for all users!
Fix: Offload to a background thread using asyncio.to_thread().
python
import time, asyncio
def cpu_heavy_hash(password: str) -> str:
time.sleep(2) # Synchronous blocking hash simulation
return f"hashed_{password}"
async def handle_signup(password: str):
# Runs the blocking function in a separate OS worker thread:
hashed = await asyncio.to_thread(cpu_heavy_hash, password)
return {"status": "ok", "hash": hashed}