FastAPI

 

2023-11-24

通过中间件获取请求和响应

middleware#获取请求和响应

自动加载路由

1
import importlib
2
from pathlib import Path
3
4
# 获取当前文件目录
5
routers_dir = Path(__file__).absolute().parent
6
7
# 遍历 routers 目录下的所有文件
8
routers = []
9
for file_path in list(routers_dir.glob("*.py")):
10
file_name = file_path.stem
11
12
# 忽略 __init__ 文件
13
if file_name == "__init__":
14
continue
15
16
# 构建路由的完整路径
17
module_path = f"app.routers.{file_name}"
18
module = importlib.import_module(module_path)
19
20
# 获取模块中的 router 变量,并添加到列表中
21
router = getattr(module, "router")
22
routers.append(router)

后台任务

后台任务通过 BackgroundTasks 实现,另外虽然函数参数传递,但是文档并不会显示相关信息。

1
from fastapi import BackgroundTasks, FastAPI
2
3
app = FastAPI()
4
5
def write_notification(email: str, message=""):
6
with open("log.txt", mode="w") as email_file:
7
content = f"notification for {email}: {message}"
8
email_file.write(content)
9
10
11
@app.post("/send-notification/{email}")
12
async def send_notification(email: str, background_tasks: BackgroundTasks):
13
background_tasks.add_task(write_notification, email, message="some notification")
14
return {"message": "Notification sent in the background"}

.add_task() 参数:

  • 任务函数
  • 参数
  • 关键字参数

关闭文档接口

参考 metadata#禁用文档

身份验证