As a Pylons user I'm trying to switch to Pyramid now trying to understand differences.
In Pylons I was used to define Session in myproj.model.meta
as:
Session = scoped_session(sessionmaker())
then import it in myproj.model
to define model and so on then in app refer to:
root = Session.query(MyModel).filter(...)...
now using a default template in Pyramid (pyramid_routesalchemy) I define Session as before (except calling it DBSession
and adding an extension):
DBSession = scoped_session(sessionmaker(extension=ZopeTransactionExtension()))
but in views.py
I don't use it directly but instantiate it:
dbsession = DBSession()
root = dbsession.query(MyModel).filter(...)...
Why? What are the differences?
Moreover, what are the differences from Pyramid
import transaction
...
model = MyModel(name=u'root', value=55)
session.add(model)
session.flush()
transaction.commit()
to Pylons
model = MyModel(name=u'root', value=55)
session.add(model)
session.commit()
Actually the way you are looking up your sqlalchemy session instance for querying doesn't really have anything to do with pylons and/or pyramid. Pylons may have suggested one of the ways as being the "standard" pylons way but that's it. The only real difference between the ways you're getting your session is in the example using ZopeTransactionExtension.
ZopeTransactionExtension is a little piece that makes sure every session that opens joins an active transaction. So if you were to open 5 session's, they will all join the same transaction. That way if you commit or rollback the transaction, all the work done by the either of the 5 sessions will follow suit. The transaction module ("transaction.commit()") is key here.
pyramid_tm tries to make setting up a transaction straightforward ... it starts one upon request entry, all scoped database sessions join it... and then at the end of the request, if it discovered an error, it will rollback the transaction. Otherwise, the transaction will be committed. That way view-level code never has to create or close/commit/rollback the transaction manually.
Mostly session.flush() is for making sure your database model instances get their primary keys filled in without committing the transaction.
So inside a view all you gotta do is:
def myview(request):
session = DBsession()
session.add(model)
pyramid_tm will make sure session is committed or rolled back appropriately.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With