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

相关推荐
Psycho_MrZhang4 小时前
Django/Flask/FastAPI简要对比分析
django·flask·fastapi
曲幽1 天前
FastAPI + SQLite:从基础CRUD到安全并发的实战指南
python·sqlite·fastapi·web·jwt·form·sqlalchemy·oauth2
Psycho_MrZhang1 天前
FastAPI 设计思想总结
fastapi
七夜zippoe1 天前
依赖注入:构建可测试的Python应用架构
开发语言·python·架构·fastapi·依赖注入·反转
山沐与山1 天前
【Python】深入理解Python Web框架:从Flask到FastAPI的并发之路
python·flask·fastapi
西西弗Sisyphus2 天前
Python FastAPI 和 Uvicorn 同步 (Synchronous) vs 异步 (Asynchronous)
python·fastapi·uvicorn
钱彬 (Qian Bin)2 天前
项目实践14—全球证件智能识别系统(切换回SQLite数据库并基于Docker实现离线部署和日常管理)
运维·docker·容器·fastapi·证件识别
闲人编程2 天前
电商平台用户系统API设计
数据库·后端·消息队列·fastapi·监控·容器化·codecapsule
曲幽2 天前
FastAPI + TinyDB并发陷阱与实战:告别数据错乱的解决方案
python·json·fastapi·web·并发·queue·lock·文件锁·tinydb
natide2 天前
Llama2 API部署错误调试
fastapi·llama