From 655f4348c44880f0ab8169c5208c4cb30b74bd8e Mon Sep 17 00:00:00 2001 From: Tordor <3262978839@qq.com> Date: Wed, 14 Jan 2026 18:04:09 +0800 Subject: [PATCH] =?UTF-8?q?=E5=88=9D=E5=A7=8B=E5=8C=96=E6=95=B0=E6=8D=AE?= =?UTF-8?q?=E5=BA=93=E8=BF=9E=E6=8E=A5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .gitignore | 1 + lifespan.py | 8 ++++++++ model/__init__.py | 20 ++++++++++++++++++++ model/model.py | 0 4 files changed, 29 insertions(+) create mode 100644 model/__init__.py create mode 100644 model/model.py diff --git a/.gitignore b/.gitignore index 397f6db..a460751 100644 --- a/.gitignore +++ b/.gitignore @@ -14,3 +14,4 @@ wheels/ # prod file .sqlite fallback.log +database.db \ No newline at end of file diff --git a/lifespan.py b/lifespan.py index 7f17b10..1d1a569 100644 --- a/lifespan.py +++ b/lifespan.py @@ -3,6 +3,13 @@ from contextlib import asynccontextmanager from fastapi import FastAPI from uvicorn.server import logger +def init_database(): + from model import create_db_and_tables + + logger.info("[数据库] 初始化数据库 📦") + create_db_and_tables() + logger.info("[数据库] 数据库初始化完成 ✅") + def active_config(): logger.info(f"[激活配置] 加载配置 ⚙️") @@ -22,6 +29,7 @@ def import_router(app: FastAPI): async def lifespan(app: FastAPI): logger.info(f"[生命周期] 应用启动 🚀") active_config() + init_database() import_router(app) yield logger.info(f"[生命周期] 应用关闭 🔧✅") diff --git a/model/__init__.py b/model/__init__.py new file mode 100644 index 0000000..3ede093 --- /dev/null +++ b/model/__init__.py @@ -0,0 +1,20 @@ +from sqlmodel import Session, SQLModel, create_engine +from config import setting + + +PGSQL = setting.env.PGSQL or "sqlite:///database.db" + +engine = create_engine(str(PGSQL)) + + +def create_db_and_tables(): + SQLModel.metadata.create_all(engine) + + +def get_engine(): + return engine + + +def get_session(): + return Session(get_engine()) + diff --git a/model/model.py b/model/model.py new file mode 100644 index 0000000..e69de29