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


相关文章
|
4天前
|
Java 数据库连接 开发者
Java的Shutdown Hook机制:优雅地关闭应用程序
Java的Shutdown Hook机制:优雅地关闭应用程序
22 1
|
4天前
|
网络协议 Linux API
Linux网络编程:shutdown() 与 close() 函数详解:剖析 shutdown()、close() 函数的实现原理、参数说明和使用技巧
Linux网络编程:shutdown() 与 close() 函数详解:剖析 shutdown()、close() 函数的实现原理、参数说明和使用技巧
112 0
|
10月前
|
开发工具
编写start、stop、status三个脚本程序,用来启动、停止各种系统服务。
编写start、stop、status三个脚本程序,用来启动、停止各种系统服务。
101 0
|
Shell
奥比中光ROS启动节点运行异常退出:[camera/driver-2] process has finished cleanly
奥比中光ROS启动节点运行异常退出:[camera/driver-2] process has finished cleanly
356 0
奥比中光ROS启动节点运行异常退出:[camera/driver-2] process has finished cleanly
appmon:start().启动错误
appmon:start().启动错误
158 0
在windowService用Process.Start()启动程序没有界面-记录
原文:在windowService用Process.Start()启动程序没有界面-记录 1.在服务程序安装时编程实现,ProjectInstaller.cs   using System; using System.
951 0