初始化数据库连接
This commit is contained in:
1
.gitignore
vendored
1
.gitignore
vendored
@@ -14,3 +14,4 @@ wheels/
|
||||
# prod file
|
||||
.sqlite
|
||||
fallback.log
|
||||
database.db
|
||||
@@ -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
20
model/__init__.py
Normal 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
0
model/model.py
Normal file
Reference in New Issue
Block a user