Forums

Lost connection to MySQL server during query

In the near past I got this error a lot: Lost connection to MySQL server during query

The I added this to my Flask App:

app.config['SQLALCHEMY_POOL_RECYCLE'] = 499

app.config['SQLALCHEMY_POOL_TIMEOUT'] = 20

Which reduced the amount of times I get this error but it still shows up every once in awhile. Usually after not visiting the website for about 12 hours.

See https://help.pythonanywhere.com/pages/UsingSQLAlchemywithMySQL/

ok so I assume that means lower the config I set to 499 to 280.

app.config['SQLALCHEMY_POOL_RECYCLE'] = 280

Like that?

engine = create_engine('mysql+mysqldb://...', pool_recycle=280)

Or do I also have to add the 'engine'?

Assuming that the app.config dictionary is applied to your database connection, your first line looks good.

Hi

I have also face the same error after I had placed pool_timeout=20, pool_recycle=200 in my code.

db.create_engine('mysql+pymysql://'+db_userid+':'+db_pass+'@'+db_host+'/'+db_name, pool_timeout=20, pool_recycle=200)

I would like to know what is the significance of pool_timeout. Should it be increased to 60 seconds ? What happens if I only keep pool_recycle = 200 and remove the argument of pool_timeout, something like below code snippet?

With reference to the this link https://help.pythonanywhere.com/pages/UsingSQLAlchemywithMySQL/ there is only pool_recycle provided in the line, so little bit confused as we can bypass the pool_timeout argument

db.create_engine('mysql+pymysql://'+db_userid+':'+db_pass+'@'+db_host+'/'+db_name, pool_recycle=200)

Thanks in advance

The only one you need to set for PythonAnywhere specifically is pool_recycle, which needs to be less than 300 seconds. pool_timeout controls how long it will wait to try to connect to MySQL when creating a new connection (docs), and the default is fine.

As to why you're getting that error -- are you creating the database engine at module level (that is, outside a function)? That might cause a problem, as then the same engine would be shared between your different worker processes, so they'd interfere with each other. If you're using Flask, then I'd recommend using the Flask-SQLAlchemy plugin rather than using SQLAlchemy directly, as it handles production environments with multiple worker processes nicely.

Yes, i have created database engine at module level i.e outside all functions where we define all the global variables, so that the same db engine can be used multiple times in different functions. The db engine is used 3 or 4 times in separate functions throughout the module.

I will change the same and create a separate db engine object local to the function.

Let us know if it works for you.

Thanks , this works. :)

Excellent! :)