8000 DisableAutoflush · sqlalchemy/sqlalchemy Wiki · GitHub
[go: up one dir, main page]

Skip to content

DisableAutoflush

Mike Bayer edited this page Feb 13, 2014 · 1 revision

Disable Autoflush

"autoflush" on a Session can be controlled at any time by setting the value of the autoflush attribute. Here we illustrate common patterns for implementing blocks of code with autoflush temporarily disabled.

Note: This feature is now included as of SQLAlchemy 0.7.6:

#!python
# 0.7.6 and above
with session.no_autoflush:
    myobject.foobar.add(someobj)

Method one - the with method:

#!python
class no_autoflush(object):
    def __init__(self, session):
        self.session = session
        self.autoflush = session.autoflush

    def __enter__(self):
        self.session.autoflush = False

    def __exit__(self, type, value, traceback):
        self.session.autoflush = self.autoflush

usage:

#!python
with no_autoflush(mysession):
    myobject.foobar.add(someobj)

Method two: decorator

#!python
from functools import update_wrapper

def no_autoflush(scoped_session):
    def decorate(fn):
        def go(*args, **kw):
            session = scoped_session()
            autoflush = session.autoflush
            session.autoflush = False
            try:
                return fn(*args, **kw)
            finally:
                session.autoflush = autoflush
            
        return update_wrapper(go, fn)
    return decorate

This method is more appropriate with a ScopedSession since the decorator is typically declared at the class level. Usage:

#!python
Session = scoped_session(sessionmaker())

@no_autoflush(Session)
def do_something():
    Session.add(someobj)
    someobj.collection.add(someotherobj)
Clone this wiki locally
0