2

I would like to use psycopg2 (directly, without SQLAlchemy). Also, I would prefer using a connection pool to avoid initializing database connections on every request, as opposed to what (I think?) official docs recommend.

However, Flask app context has approximately the same lifetime as request context, which is the lifetime of the request, so defining the pool there would not make sense. The only cross-request place I found is in a global variable on module level, which seems to work, but I'm worried if this is safe?

In other words, where is the correct place to initialize a DB connection pool in a Flask application so that it is used across requests?

johndodo
  • 17,247
  • 15
  • 96
  • 113

0 Answers0