flask_sqlalchemy_session is an alternative flask sqlalchemy module that doesn't have a tight coupling between sqlalchemy and flask. Which is nice if your code isn't using flask all the time (say you have some command line apps too).
Anyway... what do you think about adding support in for it? Below is what I'm using so far. Seems to work for me :) If you'll accept something like this, I can work up a pull request.
class PretendFlaskSQLAlchemyDb(object):
""" This is a pretend db object, so we can just pass in a session.
"""
def __init__(self, session):
self.session = session
class SQLAlchemyUserDatastore(SQLAlchemyDatastore, UserDatastore):
"""A SQLAlchemy datastore implementation for Flask-Security that assumes the
use of the Flask-SQLAlchemy extension.
"""
def __init__(self, db, user_model, role_model):
SQLAlchemyDatastore.__init__(self, db)
UserDatastore.__init__(self, user_model, role_model)
def get_user(self, identifier):
if self._is_numeric(identifier):
return self.db.session.query(self.user_model).get(identifier)
for attr in get_identity_attributes():
query = getattr(self.user_model, attr).ilike(identifier)
rv = self.db.session.query(self.user_model).filter(query).first()
if rv is not None:
return rv
def _is_numeric(self, value):
try:
int(value)
except (TypeError, ValueError):
return False
return True
def find_user(self, **kwargs):
return self.db.session.query(self.user_model).filter_by(**kwargs).first()
def find_role(self, role):
return self.db.session.query(self.user_model).filter_by(name=role).first()
class SQLAlchemySessionUserDatastore(SQLAlchemyUserDatastore):
"""A SQLAlchemy datastore implementation for Flask-Security that assumes the
use of the flask_sqlalchemy_session extension.
"""
def __init__(self, session, user_model, role_model):
SQLAlchemyUserDatastore.__init__(self,
PretendFlaskSQLAlchemyDb(session),
user_model,
role_model)