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.终止程序前需要处理一些后续,清理之类。

相关推荐
JamSlade8 小时前
流式响应 sse 系统全流程 react + fastapi为例子
前端·react.js·fastapi
无敌糖果10 小时前
FastAPI请求会话context上下文中间件
fastapi
sen_shan11 小时前
《FastAPI零基础入门与进阶实战》第21篇:告别 /path/ vs /path:静默斜杠修正中间件
fastapi
东方佑4 天前
基于FastAPI与LangChain的Excel智能数据分析API开发实践
langchain·excel·fastapi
杰瑞学AI8 天前
我的全栈学习之旅:FastAPI (持续更新!!!)
后端·python·websocket·学习·http·restful·fastapi
Python私教11 天前
浏览器不再拦请求:FastAPI 跨域(CORS)配置全解析
fastapi
带娃的IT创业者13 天前
第2集:技术选型的智慧:Flask vs FastAPI,GLM-4 vs GPT
python·gpt·flask·fastapi·glm·技术选型
万粉变现经纪人16 天前
如何解决 pip install 安装报错 ImportError: cannot import name ‘xxx’ from ‘yyy’ 问题
python·selenium·测试工具·flask·scikit-learn·fastapi·pip
闲人编程18 天前
2025年,如何选择Python Web框架:Django, Flask还是FastAPI?
前端·后端·python·django·flask·fastapi·web
chao_78918 天前
Union 和 Optional 区别
开发语言·数据结构·python·fastapi