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

相关推荐
SmartBrain20 小时前
技术洞察:SpringAI与LangGraph选型对比
人工智能·spring boot·架构·langchain·aigc·fastapi
那个松鼠很眼熟w20 小时前
python fastapi 快速创建web应用
python·fastapi
SmartBrain2 天前
FastAPI实战(第三部分):浏览历史的接口开发详解
数据库·人工智能·aigc·fastapi
布局呆星2 天前
Python 入门:FastAPI + SQLite3 + Requests 基础教学
python·sqlite·fastapi
忘忧记2 天前
pythonQT版本的图书管理系统
python·fastapi
PieroPc3 天前
生成 自己喜欢 Fastapi 写法的文件和目录 (应用放在fnosDocker 上)
fastapi
dreams_dream3 天前
FastAPI
fastapi
SmartBrain3 天前
FastAPI实战(第二部分):用户注册接口开发详解
数据库·人工智能·python·fastapi
ん贤3 天前
Scrapy 嵌入 FastAPI 的坑:Asyncio/Twisted 桥接 + 代理池设计
python·scrapy·fastapi
PieroPc4 天前
使用 uvicorn + NSSM(作为 Windows 服务)
windows·fastapi·nssm·uvicorn