Last active
May 23, 2017 23:27
-
-
Save knowsuchagency/64b67433d8d196ccc3657ac3c9fb5009 to your computer and use it in GitHub Desktop.
transaction manager recipe for pyramid sqlalchemy session
This file contains 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 contextlib import contextmanager | |
from functools import singledispatch, partial | |
from pathlib import Path | |
import pkg_resources | |
# development config uri for base distribution | |
DEVELOPMENT_CONFIG_URI = pkg_resources. \ | |
get_distribution('distribution_package_name').get_resource_filename( | |
pkg_resources.ResourceManager(), | |
'development.ini' | |
) | |
@contextmanager | |
@singledispatch | |
def dbsession(settings): | |
""" | |
A context manager that allows us to connect to the database | |
given pastedeploy settings. | |
i.e. | |
from pyramid.paster import get_appsettings | |
import pyramid_project.models as models | |
config_uri = '/path/to/development.ini' | |
settings = get_appsettings(config_uri) | |
with models.dbsession(settings) as session: | |
... do stuff | |
""" | |
engine = get_engine(settings) | |
session_factory = get_session_factory(engine) | |
with transaction.manager: | |
session = get_tm_session(session_factory, transaction.manager) | |
yield session | |
@dbsession.register(str) | |
def _(config_uri): | |
""" | |
Given a path to a configuration file, yield a dbsession. | |
i.e. | |
import pyramid_project.models as models | |
config_uri = '/path/to/development.ini' | |
with models.dbsession(config_uri) as session: | |
... do stuff | |
""" | |
path = Path(config_uri) | |
settings = get_appsettings(str(path.absolute())) | |
with dbsession(settings) as session: | |
yield session | |
# default context manager for use during development | |
development_session = partial(dbsession, DEVELOPMENT_CONFIG_URI) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment