FastAPI 支持依赖注入(Dependency Injection)。请设计一个复杂的依赖注入用例,并说明它是如何提高代码可重用性和测试性的。
依赖注入(Dependency Injection,简称 DI)是一种设计模式,用于解耦代码和依赖项之间的关系。FastAPI 通过强大的依赖注入系统,可以显著提高代码的可重用性和测试性。以下是一个复杂的依赖注入用例,并说明其优势:
### 复杂用例设计
假设我们有一个用户管理系统,需要实现以下功能:
1. 验证用户权限(需要访问数据库)。
2. 记录操作日志(需要日志服务)。
3. 发送通知(需要消息服务)。
这些功能依赖于多个外部服务,我们可以通过依赖注入将它们解耦。
#### 示例代码
1. 定义依赖项:
```python
from fastapi import Depends, FastAPI
from typing import Optional
# 模拟数据库服务
class DatabaseService:
def get_user_permission(self, user_id: str) -> bool:
# 模拟数据库查询
return user_id == "admin"
# 模拟日志服务
class LogService:
def log_operation(self, operation: str) -> None:
print(f"Logging operation: {operation}")
# 模拟消息服务
class MessageService:
def send_notification(self, message: str) -> None:
print(f"Sending notification: {message}")
# 定义依赖项
async def get_db_service():
return DatabaseService()
async def get_log_service():
return LogService()
async def get_message_service():
return MessageService()
app = FastAPI()
# 权限验证依赖
async def verify_permission(
user_id: str,
db: DatabaseService = Depends(get_db_service)
) -> bool:
return db.get_user_permission(user_id)
# 日志记录依赖
async def log_operation(
operation: str,
log: LogService = Depends(get_log_service)
) -> None:
log.log_operation(operation)
# 通知发送依赖
async def send_notification(
message: str,
msg: MessageService = Depends(get_message_service)
) -> None:
msg.send_notification(message)
# 路由中使用依赖
@app.post("/perform_action")
async def perform_action(
user_id: str,
action: str,
has_permission: bool = Depends(verify_permission),
log: Optional[None] = Depends(log_operation),
notify: Optional[None] = Depends(send_notification)
):
if not has_permission:
return {"message": "Permission denied"}
return {"message": f"Action {action} performed by {user_id}"}
提高可重用性
-
依赖项复用:
- 每个依赖项(如
DatabaseService)可以在多个路由中复用,无需重复初始化或配置。 - 例如,
verify_permission可以在所有需要权限验证的路由中使用。
- 每个依赖项(如
-
解耦逻辑:
- 业务逻辑(如路由处理)与具体服务(如数据库、日志)分离,便于维护和扩展。
- 例如,更换日志服务时只需修改
LogService类,无需更改路由代码。
提高测试性
-
模拟依赖项:
- 在测试中,可以轻松替换真实的依赖项为模拟对象(Mock)。
- 例如,测试
perform_action时可以模拟DatabaseService返回固定的权限结果。
-
隔离测试:
- 每个依赖项可以单独测试,无需启动整个应用。
- 例如,测试
log_operation时可以直接传入模拟的LogService。
示例测试代码
from fastapi.testclient import TestClient
client = TestClient(app)
def test_perform_action_without_permission():
# 模拟没有权限的用户
response = client.post("/perform_action", json={"user_id": "user", "action": "test"})
assert response.json() == {"message": "Permission denied"}
def test_perform_action_with_permission():
# 模拟有权限的用户
response = client.post("/perform_action", json={"user_id": "admin", "action": "test"})
assert response.json() == {"message": "Action test performed by admin"}
总结
通过依赖注入,FastAPI 实现了以下优势:
- 可重用性:解耦业务逻辑和外部服务,代码更模块化。
- 可测试性:依赖项可轻松替换,便于单元测试和集成测试。
- 灵活性:服务可以动态配置,适应不同环境(如开发、测试、生产)。
依赖注入是 FastAPI 的强大特性,尤其适合构建复杂且需要高可维护性的应用程序。