初始化数据库连接

This commit is contained in:
2026-01-14 18:04:09 +08:00
parent 4620e349d9
commit 655f4348c4
4 changed files with 29 additions and 0 deletions

1
.gitignore vendored
View File

@@ -14,3 +14,4 @@ wheels/
# prod file
.sqlite
fallback.log
database.db

View File

@@ -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"[生命周期] 应用关闭 🔧✅")

20
model/__init__.py Normal file
View File

@@ -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())

0
model/model.py Normal file
View File