commit | author | age
|
b488f7
|
1 |
from sqlalchemy import engine_from_config |
SP |
2 |
from sqlalchemy.orm import sessionmaker |
414b67
|
3 |
from sqlalchemy.orm import configure_mappers |
b488f7
|
4 |
import zope.sqlalchemy |
414b67
|
5 |
|
b488f7
|
6 |
# import or define all models here to ensure they are attached to the |
SP |
7 |
# Base.metadata prior to any initialization routines |
|
8 |
from .mymodel import MyModel # flake8: noqa |
|
9 |
|
|
10 |
# run configure_mappers after defining all of the models to ensure |
|
11 |
# all relationships can be setup |
414b67
|
12 |
configure_mappers() |
b488f7
|
13 |
|
SP |
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('sqla_demo.models')``. |
|
57 |
|
|
58 |
""" |
|
59 |
settings = config.get_settings() |
d83888
|
60 |
settings['tm.manager_hook'] = 'pyramid_tm.explicit_manager' |
65a6d3
|
61 |
|
b488f7
|
62 |
# use pyramid_tm to hook the transaction lifecycle to the request |
SP |
63 |
config.include('pyramid_tm') |
|
64 |
|
65a6d3
|
65 |
# use pyramid_retry to retry a request when transient exceptions occur |
SP |
66 |
config.include('pyramid_retry') |
|
67 |
|
b488f7
|
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 |
) |