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