Being new to SQLAlchemy, I was wondering at what time would Session() should be called, in say, a view. Should it be defined as a global variable, or should a new session be created for each request.
Being new to SQLAlchemy, I was wondering at what time would Session() should be
Share
I strongly recommend you follow the Pyramid SQLAlchemy tutorial. It teaches you how to use SQLAlchemy with Pyramid in a simple Wiki application.
You’ll note that tutorial a
models.pymodule is created which defines aDBSessionitem. This gives you access to the SQLAlchemy session, scoped to a Pyramid thread and tied to the Pyramid transaction model, and which is imported whenever you need the session:In
models.pythe DBSession variable is defined as follows:Note the
ZopeTransactionExtension; Pyramid automatically starts a new transaction with each request, committing it on successful responses, aborting it when an exception occurs. This relieves you of most transaction handling duties. Just remember to.flushyour session when you need to see updates to the database (such as auto-incrementing primary keys).Again, the tutorial expands on all this and more.