为什么需要异步

大量 IO 等待场景下,同步代码会把线程阻塞在等待上。asyncio 让单线程能同时处理数百个 IO 操作,适合爬虫、API 聚合、WebSocket 服务等场景。

基础概念

并发执行多个任务

import asyncio, httpx

async def fetch(url):
    async with httpx.AsyncClient() as c:
        r = await c.get(url)
        return r.status_code

async def main():
    urls = ["https://example.com"] * 10
    results = await asyncio.gather(*[fetch(u) for u in urls])
    print(results)

asyncio.run(main())

FastAPI 中的注意事项

数据库驱动必须使用异步版本(asyncpg、aiomysql),否则在 async def 路由中调用同步 IO 会阻塞整个事件循环。