'Set connection-level configuration options on all sessions on a connection

I am running a multi-process app. I need to set application_name for each process for my PostgreSQL connections dynamically based on variables. I am currently doing this inside a Session, which causes the changes not to propagate to other Sessions within the same Connection.

from flask_sqlalchemy import SQLAlchemy

db = SQLAlchemy()
app = Flask(name)
db.init_app(app)

# more initialization

@app.before_first_request
def on_flask_ready(*args, **kwargs):
    """
    Configure the PostgreSQL Database connection with a human-readable name for tracking purposes.
    """
    with app.app_context():
        # How does this need to change?
        db.session.execute("set application_name=:name", params={'name': 'web-server'})
        db.session.commit()

When later functions use Sessions, I need that configuration option to still be set.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source