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

简介: FastAPI(55)- Events: startup - shutdown 启动/关闭事件

背景


  • 可以定义需要在应用程序启动之前或应用程序关闭时执行的事件处理程序(函数)
  • 这些函数可以用 async def 或普通 def
  • 注意:只会执行主应用程序的事件处理程序,而不会执行子应用程序

 

实际代码


#!usr/bin/env python
# -*- coding:utf-8 _*-
"""
# author: 小菠萝测试笔记
# blog:  https://www.cnblogs.com/poloyy/
# 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 中
  • 可以拥有多个事件处理函数

 

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

image.png

请求结果

image.png


相关文章
|
9月前
|
开发工具
编写start、stop、status三个脚本程序,用来启动、停止各种系统服务。
编写start、stop、status三个脚本程序,用来启动、停止各种系统服务。
90 0
|
Java 应用服务中间件
weblogic开启debug模式启动时出现ERROR: Cannot load this JVM TI agent twice
weblogic开启debug模式启动时出现ERROR: Cannot load this JVM TI agent twice
348 0
|
Linux 流计算
Flink - 本地执行 Failed to start the Queryable State Data Server
Flink 本地执行任务报错 Failed to start the Queryable State Data Server 以及 Unable to start Queryable State Server. All ports in provided range are occupied. 根据报错分析是因为本地端口被占用,没有足够端口供 Flink 本地客户端启动,所以解决方法就是处理被占用的端口。...
117 0
Flink - 本地执行 Failed to start the Queryable State Data Server
appmon:start().启动错误
appmon:start().启动错误
157 0
在windowService用Process.Start()启动程序没有界面-记录
原文:在windowService用Process.Start()启动程序没有界面-记录 1.在服务程序安装时编程实现,ProjectInstaller.cs   using System; using System.
945 0