直接上代码:
from MySQLdb.constants.CLIENT import MULTI_STATEMENTS, MULTI_RESULTS
from sqlalchemy import create_engine, event
from sqlalchemy.exc import DisconnectionError
from connection.connect import Connect
engine_mysql = create_engine("mysql+mysqldb://{}:{}@{}/{}".format(
MYSQL_SERVER_USER,
MYSQL_SERVER_PASS,
MYSQL_SERVER_ADDRESS,
MYSQL_DATABASE_NAME), pool_timeout=60,
connect_args={'charset': 'utf8', 'autocommit': 'true', 'client_flag': MULTI_STATEMENTS | MULTI_RESULTS}, echo=True,
max_overflow=20,
pool_size=100, pool_recycle=10, echo_pool=True)
# 主要在这里,添加Listener 每次访问前做验证是否连接
def checkout_listener(dbapi_con, con_record, con_proxy):
try:
try:
dbapi_con.ping(False)
except TypeError:
dbapi_con.ping()
except dbapi_con.OperationalError as exc:
if exc.args[0] in (2006, 2013, 2014, 2045, 2055):
raise DisconnectionError()
else:
raise
event.listen(engine_mysql, 'checkout', checkout_listener)