I am using the sqlalchemy expression language for its notation and connection pooling to create dao objects for communicating with the persistence layer. I wanted to get some opinions on how I should approach setting up the metadata and engine so that they are available to the applications view callables. According to sqlalchemy’s documentation http://docs.sqlalchemy.org/en/rel_0_7/core/connections.html, they are typically bound and declared global, however I’ve neither this or the singleton approach are good ideas. Any thoughts would be appreciated…
This is what my __init__.py file looks like inside my project’s directory:
from pyramid.config import Configurator
from sqlalchemy import engine_from_config, MetaData, create_engine
from pyramid_beaker import session_factory_from_settings
db_url = 'postgresql://user:password@localhost/dbname'
engine = create_engine(db_url)
meta = MetaData()
def main(global_config, **settings):
meta.bind = engine
.
.
.
[other configuration settings]
The Pyramid documentation includes a tutorial on integrating Pyramid with SQLAlchemy.
There are two special packages that integrate SQLAlchemy transactions and session management with Pyramid,
pyramid_tmandzope.sqlalchemy. These together take care of your sessions:Here we take the configuration settings from your
.iniconfiguration file; and inmodels.py:Note the use of a
scoped_sessionthere, using the transaction extension to integrate with Pyramid.Then in views, all you need to do is use the
DBSessionsession factory to get your sessions:Committing and rolling back will be integrated with the request; commit on 2xx and 3xx, rollback on exceptions, for example.