Search code examples
pythonpostgresqlflaskflask-sqlalchemyrds

How can I change the Flask-SQLAlchemy URI after a certain period of time?


I'm using Flask-SQLAlchemy to connect to a Postgres database on AWS RDS. The password to connect to the database expires every 15 minutes, after which I need to generate a new one for new connections to the database (open connections are fine).

I can't figure out how to configure Flask-SQLAlchemy to use a function to generate the SQLALCHEMY_DATABASE_URI configuration parameter. All the documentation and discussion around this points at using a static value set at startup.

I know how to do this using regular SQLAlchemy with scoped sessions, etc. But I was really hoping for a solution using Flask-SQLALchemy.


Solution

  • For completeness' sake, I got this working using a custom connection function like @DanilaGanchar suggested.

    To configure this in Flask-SQLAlchemy, you need to use v2.4.0 or greater (which was incidentally only released the day before I asked this question). That version has a SQLALCHEMY_ENGINE_OPTIONS config, which allows passing in a dictionary of kwargs for SQLAlchemy's create_engine function.

    One important note is that Flask-SQLAlchemy still expects a value for SQLALCHEMY_DATABASE_URI, even if your creator function is handling creating the connection anyway.

    So the full solution looks like

    # config.py
    
    def _get_conection():
        # Get all your connection information
        return psycopg2.connect(host=host, port=5432, password=password, ...
    
    SQLALCHEMY_DATABASE_URI = "postgresql+pyscopg2://"
    SQLALCHEMY_ENGINE_OPTIONS = {"creator": _get_connection}
    # More settings etc.
    
    # app.py
    
    from app import config
    from app.db import db
    
    def create_app():
        app = Flask(__name__)
        app.config_from_object(config)
        db.init_app(app)
        return app