添加数据库连接
This commit is contained in:
45
mini-program/app/db.py
Normal file
45
mini-program/app/db.py
Normal 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()
|
||||
@@ -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
|
||||
|
||||
|
||||
@@ -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
|
||||
|
||||
Reference in New Issue
Block a user