Skip to content

Instantly share code, notes, and snippets.

@tschieggm
Created December 27, 2013 20:11
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save tschieggm/8152002 to your computer and use it in GitHub Desktop.

This is an anti-pattern explicitly called out in the SqlAlchemy documents.

From the docs

 ### this is the **wrong way to do it** ###

class ThingOne(object):
    def go(self):
        session = Session()
        try:
            session.query(FooBar).update({"x": 5})
            session.commit()
        except:
            session.rollback()
            raise

class ThingTwo(object):
    def go(self):
        session = Session()
        try:
            session.query(Widget).update({"q": 18})
            session.commit()
        except:
            session.rollback()
            raise

def run_my_program():
    ThingOne().go()
    ThingTwo().go()

Also from the docs:

tl;dr;

As a general rule, keep the lifecycle of the session separate and external from functions and objects that access and/or manipulate > database data.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment