FastAPI 学习之路(五十四)startup 和 shutdown

在实际开发中,总会遇到这样的场景,我们想在启动或者终止的时候,做一些事情,那么应该如何实现呢?fastapi其实给我们提供了这样的操作:

复制代码
from fastapi import FastAPI


app = FastAPI()


@app.on_event("startup")
def startup_event():
    print("this is startup")


@app.on_event("shutdown")
def shutdown_event():
    print("this is shutdown")

其实很简单,我们注入这两个事件即可。在结束的时候,如果有IO的操作那么必须走同步的方式,不能用异步的方式。

那么实际开发中如何使用呢?比如:

1.数据库的连接,断开连接,可以在开始和结束前。

2.redis的链接和断开链接

3.初始化一些前置条件

4.终止程序前需要处理一些后续,清理之类。

相关推荐
fengbingchun11 小时前
线性规划饮食问题求解:FastAPI作为服务端+libhv作为客户端实现
fastapi·libhv·pyomo
zhangsan093314 小时前
web框架(Django 与 FastAPI)
django·fastapi
jingyucsdn21 小时前
网页端 VUE+C#/FastAPI获取客户端IP和hostname
网络协议·tcp/ip·fastapi
掘金-我是哪吒3 天前
分布式微服务系统架构第144集:FastAPI全栈开发教育系统
分布式·微服务·架构·系统架构·fastapi
jingyucsdn9 天前
AsyncIOScheduler与BackgroundScheduler的线程模型对比
fastapi
jingyucsdn10 天前
FastAPI集成APsecheduler的BackgroundScheduler+mongodb(精简)
fastapi
几道之旅10 天前
前端antd,后端fastapi,解决文件上传
前端·fastapi
Hello_WOAIAI11 天前
python中使用高并发分布式队列库celery的那些坑
python·fastapi
ZHOU_WUYI13 天前
FastAPI在 Nginx 和 Docker 环境中的部署
nginx·docker·fastapi
王学政213 天前
FastAPI 中间件
fastapi