flask-sqlalchemy icon indicating copy to clipboard operation
flask-sqlalchemy copied to clipboard

Specify custom session class

Open sssilver opened this issue 10 years ago • 3 comments

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.

sssilver avatar Aug 08 '15 10:08 sssilver

It looks like the best option right now is to subclass the SQLAlchemy class and override the create_session method.

justanr avatar Aug 10 '15 12:08 justanr

Should we label this as an enhancement then?

sssilver avatar Aug 13 '15 04:08 sssilver

Related to: https://github.com/pallets/flask-sqlalchemy/issues/438

rsyring avatar Mar 08 '19 16:03 rsyring

fixed in #1087

davidism avatar Sep 18 '22 17:09 davidism