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

相关推荐
摸鱼仙人~3 天前
ImportError: cannot import name ‘FixtureDef‘ from ‘pytest‘
conda·pytest·fastapi
安迪小宝4 天前
20 FastAPI 性能优化
oracle·性能优化·fastapi
_.Switch9 天前
FastAPI 高并发与性能优化
网络·数据库·python·性能优化·fastapi
安迪小宝12 天前
11 FastAPI文档自定义
fastapi
drebander13 天前
[特殊字符] 基于 FastAPI 和 React 构建车牌号识别网站
前端·react.js·fastapi
m0_7482329213 天前
纯 Python、Django、FastAPI、Flask、Pyramid、Jupyter、dbt 解析和差异分析
python·django·fastapi
一见已难忘16 天前
Flask与FastAPI对比选择最佳Python Web框架的指南
python·flask·fastapi
亿牛云爬虫专家17 天前
FastAPI与Selenium:打造高效的Web数据抓取服务
爬虫·python·selenium·fastapi·图片·代理ip·pixabay
股票数据接口19 天前
2025年度Python最新整理的免费股票数据API接口
开发语言·python·fastapi
老大白菜20 天前
在 Ubuntu 中使用 FastAPI 创建一个简单的 Web 应用程序
前端·ubuntu·fastapi