添加数据库连接

This commit is contained in:
ChengCan
2026-03-26 10:26:25 +08:00
parent d5c397b68c
commit f9ca4a32a3
3 changed files with 58 additions and 0 deletions

45
mini-program/app/db.py Normal file
View File

@@ -0,0 +1,45 @@
from collections.abc import Generator
from sqlalchemy import create_engine, text
from sqlalchemy.orm import Session, sessionmaker
try:
# For module mode: `uvicorn app.main:app`
from app.settings import settings
except ModuleNotFoundError:
# For script mode: `python app/main.py` or VS Code "Run Python File"
from settings import settings
engine = create_engine(
settings.mysql_dsn,
pool_size=5,
max_overflow=10,
pool_pre_ping=True,
pool_recycle=1800,
future=True,
)
SessionLocal = sessionmaker(
bind=engine,
autocommit=False,
autoflush=False,
expire_on_commit=False,
)
def get_db() -> Generator[Session, None, None]:
db = SessionLocal()
try:
yield db
finally:
db.close()
def check_db_connection() -> None:
with engine.connect() as conn:
conn.execute(text("SELECT 1"))
def close_db_engine() -> None:
engine.dispose()

View File

@@ -4,10 +4,12 @@ from fastapi import FastAPI
try:
# For module mode: `uvicorn app.main:app`
from app.db import check_db_connection, close_db_engine
from app.routers.health import router as health_router
from app.settings import settings
except ModuleNotFoundError:
# For script mode: `python app/main.py` or VS Code "Run Python File"
from db import check_db_connection, close_db_engine
from routers.health import router as health_router
from settings import settings
@@ -18,6 +20,15 @@ def create_app() -> FastAPI:
version=settings.app_version,
description=settings.app_description,
)
@app.on_event("startup")
def on_startup() -> None:
check_db_connection()
@app.on_event("shutdown")
def on_shutdown() -> None:
close_db_engine()
app.include_router(health_router)
return app

View File

@@ -2,3 +2,5 @@ fastapi==0.115.11
uvicorn[standard]==0.34.0
pydantic-settings==2.8.1
python-dotenv==1.0.1
SQLAlchemy==2.0.38
PyMySQL==1.1.1