flask-sqlalchemy
flask-sqlalchemy copied to clipboard
Specify custom session class
Hello,
SQLAlchemy allows us to use custom session classes in case we wanna override default behavior:
sqlalchemy.orm.scoped_session(
sqlalchemy.orm.sessionmaker(
autocommit=False,
autoflush=False,
bind=self.engine,
class_=NoDeleteSession # Custom session class
)
)
This is critical, as in most business programs operations like DELETE do not physically delete data, but mark it as deleted instead:
class NoDeleteSession(sqlalchemy.orm.session.Session):
def __init__(self, bind=None, autoflush=True, expire_on_commit=True,
_enable_transaction_accounting=True,
autocommit=False, twophase=False,
weak_identity_map=True, binds=None, extension=None,
info=None, query_cls=sqlalchemy.orm.query.Query):
self._persist_deleted = set()
super(NoDeleteSession, self).__init__(
bind=bind,
autoflush=autoflush,
expire_on_commit=expire_on_commit,
_enable_transaction_accounting=_enable_transaction_accounting,
autocommit=autocommit,
twophase=twophase,
weak_identity_map=weak_identity_map,
binds=binds,
extension=extension,
info=info,
query_cls=query_cls
)
def delete(self, instance):
# Do not actually delete the instance. Set the is_deleted flag instead.
instance.is_deleted = True
self._persist_deleted.add(instance)
Going through the flask-sqlalchemy source code and documentation, it seems that this isn't currently supported. Can we have this functionality?
Thanks.
It looks like the best option right now is to subclass the SQLAlchemy class and override the create_session method.
Should we label this as an enhancement then?
Related to: https://github.com/pallets/flask-sqlalchemy/issues/438
fixed in #1087