背景

  • 可以定义需要在应用程序启动之前或应用程序关闭时执行的事件处理程序(函数)
  • 这些函数可以用 async def 或普通 def 

注意:只会执行主应用程序的事件处理程序,而不会执行子应用程序

 

实际代码



#!usr/bin/env python
# -*- coding:utf-8 _*-
"""
# author: 小菠萝测试笔记
# time: 2021/10/4 7:26 下午
# file: 45_event.py
"""
import uvicorn
from fastapi import FastAPI

app = FastAPI()

items = {}


# 添加在应用程序启动之前运行的函数
@app.on_event("startup")
async def startup_event():
print("启动应用程序啦")
items["foo"] = {"name": "Fighters"}
items["bar"] = {"name": "Tenders"}


# 添加在应用程序关闭时运行的函数
@app.on_event("shutdown")
async def shutdown_event():
print("关闭应用程序啦")
with open("log.txt", mode="a") as log:
log.write("Application shutdown")


@app.get("/items/{item_id}")
def read_items(item_id: str):
return items[item_id]


if __name__ == '__main__':
uvicorn.run(app="45_event:app", reload=True, host="127.0.0.1", port=8080)


 

startup

  • 模拟初始化数据库,设置一些值到 items 中
  • 可以拥有多个事件处理函数

 

启动应用程序和关闭应用程序

FastAPI(55)- Events: startup - shutdown 启动/关闭事件_初始化

 

请求结果

FastAPI(55)- Events: startup - shutdown 启动/关闭事件_初始化_02