作用
需要在应用程序启动之前或者关闭时进行,例如数据库迁移,定时任务·····
实际代码
main.py
import uvicorn
from app import create_app
app = create_app()
if __name__ == '__main__':
uvicorn.run(
app='main:app',
host='0.0.0.0',
port=8000,
reload=True
)
#!/usr/bin/python
# -*- coding: utf-8 -*-
# @time : 2023/2/3 11:28
# @author : pugongying
# @description : 初始化项目
from fastapi import FastAPI
from app.xxx import task_init
from app.config import log_init
from app.middleware import middleware_init
from app.plan import plan
from app.routers import router_init
async def start_event():
task_init()
plan.run_plan()
print('系统启动')
async def shutdown_event():
print('系统关闭')
def create_app():
app = FastAPI(title="xxx服务",
description="xxx服务接口文档",
version="1.0.0",
on_startup=[start_event],
on_shutdown=[shutdown_event]
)
# 初始化日志
log_init()
# 初始化路由
router_init(app)
# 初始化中间件
middleware_init(app)
# 建表
# db_init(app)
return app
标签:__,FastAPI,app,init,shutdown,import,event
From: https://www.cnblogs.com/pgyLang/p/17195473.html