Last active
August 17, 2016 20:09
-
-
Save mmerickel/84b34ee5d68ed20dae10 to your computer and use it in GitHub Desktop.
sqlalchemy with no threadlocals
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 pyramid.config import Configurator | |
from pyramid.view import view_config | |
def main(global_config, **app_settings): | |
config = Configurator(settings=app_settings) | |
config.include('.model') | |
config.scan(__name__) | |
return config.make_wsgi_app() | |
@view_config() | |
def dummy_view(context, request): | |
# request.db.query(...) | |
return request.response |
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 import engine_from_config | |
from sqlalchemy.orm import sessionmaker | |
import zope.sqlalchemy | |
def includeme(config): | |
settings = config.get_settings() | |
dbmaker = init_model(settings) | |
config.add_request_method( | |
lambda r: get_dbsession(r, dbmaker), | |
'dbsession', | |
reify=True, | |
) | |
config.include('pyramid_tm') | |
def get_dbsession(request, dbmaker): | |
dbsession = dbmaker() | |
zope.sqlalchemy.register(dbsession, transaction_manager=request.tm) | |
return dbsession | |
def init_model(settings, prefix='sqlalchemy.'): | |
engine = engine_from_config(settings, prefix) | |
dbmaker = sessionmaker() | |
dbmaker.configure(bind=engine) | |
return dbmaker |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment