The Pyramid documentation includes a tutorial on integrating Pyramid with SQLAlchemy .
There are two special packages that combine SQLAlchemy transactions and session management with Pyramid, pyramid_tm and zope.sqlalchemy . They take care of your sessions together:
from sqlalchemy import engine_from_config from .models import DBSession def main(global_config, **settings): """This function returns a Pyramid WSGI application.""" engine = engine_from_config(settings, 'sqlalchemy.') DBSession.configure(bind=engine)
Here we take the configuration settings from your .ini configuration file; and in models.py :
from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import ( scoped_session, sessionmaker, ) from zope.sqlalchemy import ZopeTransactionExtension DBSession = scoped_session(sessionmaker(extension=ZopeTransactionExtension())) Base = declarative_base() class YourModel(Base):
Note the use of scoped_session there, using the transaction extension to integrate with Pyramid.
Then in the views, all you have to do is use the DBSession factory session to get your sessions:
from pyramid.view import view_config from .models import ( DBSession, YourModel, ) @view_config(...) def aview(request): result = DBSession.query(YourModel).filter(...).first()
Assignment and rollback will be integrated with the request; commit on 2xx and 3xx, for example, rollback on exceptions.
Martijn pieters
source share