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

相关推荐
曲幽16 小时前
FastAPI压力测试实战:Locust模拟真实用户并发及优化建议
python·fastapi·web·locust·asyncio·test·uvicorn·workers
曲幽2 天前
FastAPI实战:打造本地文生图接口,ollama+diffusers让AI绘画更听话
python·fastapi·web·cors·diffusers·lcm·ollama·dreamshaper8·txt2img
曲幽3 天前
我用FastAPI接ollama大模型,差点被asyncio整崩溃(附对话窗口实战)
python·fastapi·web·async·httpx·asyncio·ollama
闲云一鹤4 天前
Python 入门(二)- 使用 FastAPI 快速生成后端 API 接口
python·fastapi
曲幽4 天前
FastAPI + Ollama 实战:搭一个能查天气的AI助手
python·ai·lora·torch·fastapi·web·model·ollama·weatherapi
百锦再5 天前
Django实现接口token检测的实现方案
数据库·python·django·sqlite·flask·fastapi·pip
Li emily5 天前
解决了股票实时数据接口延迟问题
人工智能·fastapi
司徒轩宇5 天前
FastAPI + Uvicorn 深度理解与异步模型解析
fastapi
郝学胜-神的一滴6 天前
FastAPI:Python 高性能 Web 框架的优雅之选
开发语言·前端·数据结构·python·算法·fastapi
yaoty7 天前
Python日志存储:从单机同步到分布式异步的7种方案
fastapi·日志·logger