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

相关推荐
bloglin999991 天前
fastapi和flaskapi有什么区别
fastapi
GeekABC4 天前
FastAPI系列06:FastAPI响应(Response)
开发语言·python·fastapi·web
高效匠人4 天前
FastAPI + Redis Pub/Sub + WebSocket 组合解决方案的详细介绍
redis·websocket·fastapi
Nick_zcy5 天前
开发基于python的商品推荐系统,前端框架和后端框架的选择比较
开发语言·python·前端框架·flask·fastapi
uncle_ll6 天前
FastAPI 零基础入门指南:10 分钟搭建高性能 API
后端·python·微服务·api·fastapi
坐吃山猪6 天前
Python-Agent调用多个Server-FastAPI版本
开发语言·python·fastapi
像风一样自由20208 天前
FastMCP与FastAPI:构建自定义MCP服务器
服务器·microsoft·fastapi
数据智能老司机8 天前
使用 FastAPI 构建生成式 AI 服务——与生成模型的实时通信
llm·openai·fastapi
数据智能老司机8 天前
使用 FastAPI 构建生成式 AI 服务——AI集成与模型服务
llm·openai·fastapi
十分钟空间9 天前
有哪些常用的Python后端开发框架?
python·flask·fastapi