Avoiding “MySQL server has gone away” on infrequently used Python / Flask server with SQLAlchemy

后端 未结 7 899
别跟我提以往
别跟我提以往 2020-12-07 11:15

How can Flask / SQLAlchemy be configured to create a new database connection if one is not present?

I have an infrequently visited Python / Flask server which uses S

7条回答
  •  再見小時候
    2020-12-07 11:34

    2018 answer: In SQLAlchemy v1.2.0+, you have the connection pool pre-ping feature available to address this issue of "MySQL server has gone away".

    Connection pool pre-ping - The connection pool now includes an optional "pre ping" feature that will test the "liveness" of a pooled connection for every connection checkout, transparently recycling the DBAPI connection if the database is disconnected. This feature eliminates the need for the "pool recycle" flag as well as the issue of errors raised when a pooled connection is used after a database restart.

    Pessimistic testing of connections upon checkout is possible with the new argument:

    engine = create_engine("mysql+pymysql://user:pw@host/db", pool_pre_ping=True)
    

提交回复
热议问题