Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pyramid with SQLAlchemy: scoped or non-scoped database session

For older versions of pyramid the setup for sqlalchemy session was done with scooped_session similar to this

DBSession = scoped_session(
    sessionmaker(
        autoflush=True,
        expire_on_commit=False,
        extension=zope.sqlalchemy.ZopeTransactionExtension()
    )

However I see that newer tutorials as well the pyramid docs 'promotes' sqlalchemy with no threadlocals where the DBSession is attached to the request object.

Is the 'old' way broken and what is the advantage of the no threadlocals ?

like image 291
silviud Avatar asked Dec 02 '16 00:12

silviud


1 Answers

I spearheaded this transition with help from several other contributors who had blogged [1] about some advantages. It basically boils down to following the pyramid philosophy of making it possible for applications to be written that do not require any global variables. This is really important when writing reusable, composable code. It makes your code's dependencies (api surface) clear, instead of having random functions dependent on your database, despite their function signatures / member variables not exposing those dependencies. This also makes it easier to test code because you don't have to worry as much about threadlocal variables. With globals you need to track down what modules may be holding references to them and patch them to use the new object. Without globals, you simply pass in the objects you want to use and the code uses them, just like any other parameter to a function or state on an object.

A lot of people complain about having to pass their database to tons of functions. This is a smell and just means you aren't designing your apis well. Many times you can structure things as an object that's created once per-request and stores the handle as something like self.dbsession, and each method on the object now has access to it.

[1] https://metaclassical.com/testing-pyramid-apps-without-a-scoped-session/

like image 157
Michael Merickel Avatar answered Sep 19 '22 23:09

Michael Merickel