Last active
August 29, 2015 14:06
-
-
Save inklesspen/bd5954372cc20540bb3e to your computer and use it in GitHub Desktop.
Pyramid SQLAlchemy session setup
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from sqlalchemy.orm import sessionmaker | |
from sqlalchemy import create_engine | |
from zope.sqlalchemy import register | |
def get_sessionmaker(url, zope=True): | |
"""Configure a sessionmaker for use by requests. | |
By default, sessions will attach themselves to the current transaction | |
manager. Then can be turned off by setting ``zope=False``. | |
""" | |
engine = create_engine(url) | |
maker = sessionmaker() | |
if zope: | |
register(maker) | |
maker.configure(bind=engine) | |
return maker | |
def includeme(config): | |
settings = config.get_settings() | |
config.include('pyramid_tm') | |
sessionmaker = get_sessionmaker(settings['database']['engine_url']) | |
# Every request will have a db_session property. The first time | |
# you use it, it creates a session, and then replaces the property | |
# with that session. | |
config.add_request_method(lambda request: sessionmaker(), 'db_session', reify=True) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment