Pyramid with SQLAlchemy: database session with scope or non scope

For older versions of the pyramid, the setup for the sqlalchemy session was done with a scooped_session like this

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

However, I see that the new tutorials, as well as the pyramid docs, β€œpromote” sqlalchemy without threadlocals, where DBSession joins the query object.

Is the "old" way broken and what is the advantage of not having threadlocals?

+5
source share
1 answer

I led this transition with the help of several other contributors who shared blogs [1] about some of the benefits. This basically comes down to the following pyramid principle, which allows you to write applications that do not require global variables. This is really important when writing reusable, composite code. This makes your dependencies in the code (api surface) clear, instead of having random functions depending on your database, even though their function signatures / members are not exposed to these dependencies. It also simplifies code verification because you don’t have to worry about stream variables. Using global variables, you need to track which modules can contain references to them, and correct them to use the new object. Without globals, you simply pass the objects you want to use, and the code uses them, like any other parameter for the function or state of the object.

Many people complain about the need to transfer their database to many functions. It smells and just means you are not developing your apis well. Many times you can structure objects as an object created once for each request and store the descriptor as something like self.dbsession , and each method of the object now has access to it.

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

+8
source

Source: https://habr.com/ru/post/1260676/


All Articles