Forums

mysql and SQLAlchemy behaves weirdly when using app factory in flask

I wrote a simple flask web app that uses flask + mysql from Python anywhere. I initially just wrote an app.py which seemed to run fine (in terms of connection to mysql and queries). Later I switched to app factory pattern and it was largely the same code. Once I reload webapp, it works fine in terms of connections. After 5 to 10 minutes, I just get errors for any view that uses SQL queries and it fails to connect to database properly. Anyone else faced similar issues? Am I missing something dumb when I do this?

PythonAnywhere’s MySQL servers will automatically close idle connections after about 5 minutes. If your application opens a database connection at startup (or in a global context) and tries to reuse it later, it may have gone stale by the time it’s accessed again.

This used to “just work” in simpler scripts because the app likely re-established the connection on each run. But in an app factory setup with long-lived contexts, connection management becomes your responsibility.

It might make more sense to:

  • Open a new connection inside each request/view, and close it when done.
  • Do not use a global connection object that persists across requests.

You might also want to consider Flask-SQLAlchemy to optimise your SQL connections and pool recycle them.

Some related conversation:

Thank you! I fixed the issue based on your suggestions :)

Glad we could help!