I am using a Flask app with SQLAlchemy and a uWSGI server. It is a known issue that uWSGI's duplicates connection through all the processes during forking. The information about how to fix this issue is a bit scatted in the web, but the two main options seems to be:
- Using
lazy-apps = truewithin uWSGI's config (Which is not recommended because it consumes a lot of memory) - Using uWSGI's
@postforkdecorator to close the connection after forking to start new fresh connections for each new process, but it's unclear for me when and how should be used within the Flask app.
This the sample of my app:
# file: my_app/app.py db = SQLAlchemy() def create_app(): app = Flask(__name__) app.config.from_pyfile(f'../config/settings.py') db.init_app(app) db.create_all(app=app) return app Sample of the run.py file:
# file: run.py from my_app/app import create_app app = create_app() if "__main__" == __name__: app.run(debug=app.config["DEBUG"], port=5000) So the question is where and how should the postfork executed to properly setup uWSGI's server to use isolated connections on each process without using lazy-apps = true?