异步编程
- 适用情况:当API需要进行I/O操作,如数据库查询、文件读取、网络请求等,这些操作往往会等待外部资源响应,占用线程资源,导致性能下降。使用异步编程可以在等待时释放线程,让其处理其他请求,提高整体吞吐量。例如在一个需要调用外部第三方接口获取数据的API中,使用异步编程能避免等待第三方接口响应时阻塞整个应用。
- 实施步骤:
- 使用
async
关键字定义异步函数。比如数据库查询函数可以写成async def get_user_from_db(user_id):
。
- 在FastAPI路由中使用异步函数作为处理函数。例如
@app.get("/users/{user_id}") async def get_user(user_id: int): user = await get_user_from_db(user_id); return user
。
- 确保使用的数据库驱动、网络请求库等支持异步操作。如使用
asyncpg
作为PostgreSQL的异步驱动,aiohttp
进行异步网络请求。
缓存机制
- 适用情况:对于一些不经常变化的数据,频繁查询数据库或进行复杂计算获取相同结果会浪费资源。例如在一个新闻网站的API中,新闻的基本信息(标题、简介等)短时间内不会改变,适合使用缓存。
- 实施步骤:
- 选择缓存工具,如
aiocache
。安装pip install aiocache
。
- 在FastAPI应用中配置缓存。例如:
from aiocache import Cache
from fastapi import FastAPI
app = FastAPI()
cache = Cache(Cache.MEMORY)
@app.get("/news/{news_id}")
async def get_news(news_id: int):
news = await cache.get(news_id)
if news is None:
# 从数据库获取新闻
news = await get_news_from_db(news_id)
await cache.set(news_id, news)
return news
- 设置合理的缓存过期时间,根据数据更新频率调整。
中间件优化
- 适用情况:中间件可以在请求处理前后执行一些通用逻辑,如日志记录、身份验证、响应压缩等。例如在一个企业级API中,需要对每个请求进行身份验证,使用中间件能统一处理,且不影响业务逻辑。
- 实施步骤:
- 创建中间件函数。例如身份验证中间件:
from fastapi import Request, HTTPException
async def auth_middleware(request: Request, call_next):
token = request.headers.get("Authorization")
if not token or not is_valid_token(token):
raise HTTPException(status_code=401, detail="Unauthorized")
response = await call_next(request)
return response
- 将中间件添加到FastAPI应用中。
app.middleware("http")(auth_middleware)
。
- 对于响应压缩中间件,可使用
python -m pip install fastapi - compress
,然后在应用中添加from fastapi_compress import FastAPICompress; FastAPICompress(app)
。