跳转至

第六章:异步 Web 框架

FastAPI

安装

pip install fastapi uvicorn

异步路由

from fastapi import FastAPI
import asyncio

app = FastAPI()

@app.get("/")
async def root():
    await asyncio.sleep(1)  # 模拟异步操作
    return {"message": "Hello World"}

@app.get("/users/{user_id}")
async def get_user(user_id: int):
    # 异步数据库查询
    user = await get_user_from_db(user_id)
    return user

并发处理

from fastapi import FastAPI
import aiohttp

app = FastAPI()

@app.get("/fetch-all")
async def fetch_all():
    urls = ["https://api1.com", "https://api2.com"]

    async with aiohttp.ClientSession() as session:
        tasks = [session.get(url) for url in urls]
        responses = await asyncio.gather(*tasks)

    return {"count": len(responses)}

小结

异步 Web 框架要点:

  • FastAPI:异步路由、并发处理
  • uvicorn:ASGI 服务器

下一章我们将学习异步任务队列。