Writing a Postgresql connector in FlaskSQLAlchemy

We want to use the postgresql database for authentification of our web application. The username and password is stored clientside in a SecureCookie (see flask.session). This cookie has to be read before every request and the database connection has to be established:

from flask import request_started, session
request_started.connect(connect_db, app)

def connect_db(app, data=session):
    if 'u' in data and 'p' in data:
        app.config['SQLALCHEMY_DATABASE_URI'] = \
            app.config.get('DATABASE') % (data.get('u'), data.get('p'))

A few problems arise with this scenario:

1) The database connector in FlaskSQLAlchemy has to be reset, because reading the connector of another user is not wanted.

subclassing of SQLAlchemy this way solves this issue:

from flaskext.sqlalchemy import SQLAlchemy, get_state

class MySQLAlchemy(SQLAlchemy):
    """ subclass of Flask-SQLAlchemy, because we need to clean the
    connector on every request. Improvement: save connector for every
    user session?!

    def get_engine(self, app, bind=None):
        """Returns a specific engine.
        changed for using a new connector on EVERY request.
        with self._engine_lock:
            connector = self.make_connector(app, bind)
            state = get_state(app)
            state.connectors[bind] = connector
            return connector.get_engine()

2) Armin added an AssertionError if the request was already handled (see commit 5500986971b28f270a27db633acf19984eee609e). In our case the request is handled more than one time on every request. Because of this problem we use version 0.7.3 of Flask and not 0.8 at the moment.

This assertion is totally reasonable, but there should be an option to disable it!

One possible solution may be this branch: first-request-decorator on github/mfa.