FastAPI - 事件处理器
事件处理器是在特定标识事件发生时执行的函数。在 FastAPI 中,标识了两个此类事件:startup 和 shutdown。FastAPI 的应用对象具有 on_event() 装饰器,该装饰器使用这些事件之一作为参数。与此装饰器注册的函数会在相应事件发生时被触发。
startup 事件在开发服务器启动之前发生,注册的函数通常用于执行某些初始化任务,例如与数据库建立连接等。shutdown 事件处理器在应用关闭之前被调用。
示例 - 处理 Startup 和 Shutdown 事件
这是一个简单的 startup 和 shutdown 事件处理器的示例。应用启动时,启动时间会在控制台日志中输出。同样,当按下 ctrl+c 停止服务器时,关闭时间也会显示。
main.py
from fastapi import FastAPI
import datetime
app = FastAPI()
@app.on_event("startup")
async def startup_event():
print('服务器启动时间 :', datetime.datetime.now()) # Server started
@app.on_event("shutdown")
async def shutdown_event():
print('服务器关闭时间 :', datetime.datetime.now()) # server Shutdown
输出
它将产生以下输出 −
uvicorn main:app --reload INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) INFO: Started reloader process [28720] INFO: Started server process [28722] INFO: Waiting for application startup. Server started: 2021-11-23 23:51:45.907691 INFO: Application startup complete. INFO: Shutting down INFO: Waiting for application server Shutdown: 2021-11-23 23:51:50.82955 INFO: Application shutdown com INFO: Finished server process