59 lines
1.5 KiB
Python
59 lines
1.5 KiB
Python
from sqlalchemy import create_engine, text, MetaData
|
||
from sqlalchemy.ext.declarative import declarative_base
|
||
from sqlalchemy.orm import sessionmaker
|
||
from sqlalchemy.pool import QueuePool
|
||
from .config import settings
|
||
|
||
# Railway数据库引擎(账号表)
|
||
railway_engine = create_engine(
|
||
settings.RAILWAY_DATABASE_URL,
|
||
poolclass=QueuePool,
|
||
pool_pre_ping=True,
|
||
echo=False,
|
||
pool_size=20,
|
||
max_overflow=30,
|
||
pool_timeout=60,
|
||
pool_recycle=3600,
|
||
pool_reset_on_return='commit'
|
||
)
|
||
|
||
# Tunnel数据库引擎(业务数据表)
|
||
tunnel_engine = create_engine(
|
||
settings.TUNNEL_DATABASE_URL,
|
||
poolclass=QueuePool,
|
||
pool_pre_ping=True,
|
||
echo=False,
|
||
pool_size=100,
|
||
max_overflow=200,
|
||
pool_timeout=60,
|
||
pool_recycle=3600,
|
||
pool_reset_on_return='commit'
|
||
)
|
||
|
||
RailwaySessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=railway_engine)
|
||
TunnelSessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=tunnel_engine)
|
||
|
||
RailwayBase = declarative_base()
|
||
TunnelBase = declarative_base()
|
||
|
||
def get_railway_db():
|
||
"""Railway数据库依赖注入"""
|
||
db = RailwaySessionLocal()
|
||
try:
|
||
yield db
|
||
finally:
|
||
db.close()
|
||
|
||
def get_tunnel_db():
|
||
"""Tunnel数据库依赖注入"""
|
||
db = TunnelSessionLocal()
|
||
try:
|
||
yield db
|
||
finally:
|
||
db.close()
|
||
|
||
def init_db():
|
||
"""初始化数据库"""
|
||
RailwayBase.metadata.create_all(bind=railway_engine)
|
||
TunnelBase.metadata.create_all(bind=tunnel_engine)
|