伪代码
from sqlalchemy import create_engine
import settings
# 创建mysql连接池
mysql_engine = create_engine(settings.SQLALCHEMY_DATABASE_URI, pool_size=2, pool_pre_ping=True)
# 生成对象直接引用
mysql_session = sessionmaker(autocommit=False, autoflush=False, bind=mysql_engine)
# 使用方式一:定义生成器
def get_db() -> Generator:
try:
db = mysql_session()
yield db
finally:
db.close()
# 使用方式二:打开使用
with mysql_session() as mysql_db :
mysql_db.xxxxxx
发表回复