安装
pip install fastapi
如果除了 FastAPI 和基本的依赖之外,还要安装推荐依赖之外,可以安装额外的依赖:
pip install fastapi[standard]
使用
通过中间件获取请求和响应
- python - FastAPI - How to get the response body in Middleware - Stack Overflow
- python - FastAPI middleware peeking into responses - Stack Overflow
自动加载路由
import importlibfrom pathlib import Path
# 获取当前文件目录routers_dir = Path(__file__).absolute().parent
# 遍历 routers 目录下的所有文件routers = []for file_path in list(routers_dir.glob("*.py")): file_name = file_path.stem
# 忽略 __init__ 文件 if file_name == "__init__": continue
# 构建路由的完整路径 module_path = f"app.routers.{file_name}" module = importlib.import_module(module_path)
# 获取模块中的 router 变量,并添加到列表中 router = getattr(module, "router") routers.append(router)
后台任务
后台任务通过 BackgroundTasks 实现,另外虽然函数参数传递,但是文档并不会显示相关信息。
from fastapi import BackgroundTasks, FastAPI
app = FastAPI()
def write_notification(email: str, message=""): with open("log.txt", mode="w") as email_file: content = f"notification for {email}: {message}" email_file.write(content)
@app.post("/send-notification/{email}")async def send_notification(email: str, background_tasks: BackgroundTasks): background_tasks.add_task(write_notification, email, message="some notification") return {"message": "Notification sent in the background"}
.add_task() 参数:
- 任务函数
- 参数
- 关键字参数
关闭文档接口
参考 [[metadata]]