Michael Merickel
2017-06-18 75c30dfe18b26ca04efae2acbe35052fa0d93ed6
commit | author | age
b50a19 1 from sqlalchemy import engine_from_config
SP 2 from sqlalchemy.orm import sessionmaker
3 from sqlalchemy.orm import configure_mappers
4 import zope.sqlalchemy
5
6 # import or define all models here to ensure they are attached to the
7 # Base.metadata prior to any initialization routines
293942 8 from .mymodel import MyModel  # flake8: noqa
b50a19 9
SP 10 # run configure_mappers after defining all of the models to ensure
11 # all relationships can be setup
12 configure_mappers()
13
14
15 def get_engine(settings, prefix='sqlalchemy.'):
16     return engine_from_config(settings, prefix)
17
18
19 def get_session_factory(engine):
20     factory = sessionmaker()
21     factory.configure(bind=engine)
22     return factory
23
24
25 def get_tm_session(session_factory, transaction_manager):
26     """
27     Get a ``sqlalchemy.orm.Session`` instance backed by a transaction.
28
29     This function will hook the session to the transaction manager which
30     will take care of committing any changes.
31
32     - When using pyramid_tm it will automatically be committed or aborted
33       depending on whether an exception is raised.
34
35     - When using scripts you should wrap the session in a manager yourself.
36       For example::
37
38           import transaction
39
40           engine = get_engine(settings)
41           session_factory = get_session_factory(engine)
42           with transaction.manager:
43               dbsession = get_tm_session(session_factory, transaction.manager)
44
45     """
46     dbsession = session_factory()
47     zope.sqlalchemy.register(
48         dbsession, transaction_manager=transaction_manager)
49     return dbsession
50
51
52 def includeme(config):
53     """
54     Initialize the model for a Pyramid app.
55
56     Activate this setup using ``config.include('tutorial.models')``.
57
58     """
59     settings = config.get_settings()
d83888 60     settings['tm.manager_hook'] = 'pyramid_tm.explicit_manager'
b50a19 61
SP 62     # use pyramid_tm to hook the transaction lifecycle to the request
63     config.include('pyramid_tm')
64
2c0e3e 65     # use pyramid_retry to retry a request when transient exceptions occur
SP 66     config.include('pyramid_retry')
67
b50a19 68     session_factory = get_session_factory(get_engine(settings))
SP 69     config.registry['dbsession_factory'] = session_factory
70
71     # make request.dbsession available for use in Pyramid
72     config.add_request_method(
73         # r.tm is the transaction manager used by pyramid_tm
74         lambda r: get_tm_session(session_factory, r.tm),
75         'dbsession',
76         reify=True
77     )