Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is having multiple SQLAlchemy sessions in the same controller okay, or should I put them all into one session?

So I have a controller that renders a page. In the controller, I call multiple functions from the model that create its own sessions. For example:

def page(request):
    userid = authenticated_userid(request)
    user = User.get_by_id(userid)
    things = User.get_things()

    return {'user': user, 'things': things}

Where in the model I have:

class User:
    ...

    def get_by_id(self, userid):
        return DBSession.query(User)...

    def get_things(self):
        return DBSession.query(Thing)...

My question is, is creating a new session for each function optimal, or should I start a session in the controller and use the same session throughout the controller (assuming I'm both querying as well as inserting into the database in the controller)? Ex.

def page(request):
    session = DBSession()
    userid = authenticated_userid(request)
    user = User.get_by_id(userid, session)
    things = User.get_things(session)
    ...
    return {'user': user, 'things': things}

class User:
    ...

    def get_by_id(self, userid, session=None):
        if not session:
            session = DBSession()
        return session.query(User)...

    def get_things(self, session=None):
        if not session:
            session = DBSession()
        return session.query(Thing)...
like image 379
Jonathan Ong Avatar asked Nov 26 '25 13:11

Jonathan Ong


1 Answers

Your first code is OK, if your DBSession is a ScopedSession. DBSession() is not a constructor then, but just an accessor function to thread-local storage. You might speed up things a bit by passing the session explicitly, but premature optimization is the root of all evil.