Skip to content

Commit 1b99dad

Browse files
docs: add instruction to use mptt_sqlalchemy with flask_sqlalchemy
1 parent 6b20cbc commit 1b99dad

File tree

1 file changed

+31
-2
lines changed

1 file changed

+31
-2
lines changed

docs/initialize.rst

Lines changed: 31 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -25,8 +25,8 @@ Create model with MPTT mixin:
2525
2626
2727
28-
Session
29-
-------
28+
Session factory wrapper
29+
-----------------------
3030

3131
For the automatic tree maintainance triggered after session flush to work
3232
correctly, wrap the Session factory with :mod:`sqlalchemy_mptt.mptt_sessionmaker`
@@ -41,6 +41,35 @@ correctly, wrap the Session factory with :mod:`sqlalchemy_mptt.mptt_sessionmaker
4141
engine = create_engine('...')
4242
Session = mptt_sessionmaker(sessionmaker(bind=engine))
4343
44+
Using session factory wrapper with flask_sqlalchemy
45+
---------------------------------------------------
46+
47+
If you use Flask and SQLAlchemy, you probably use also flask_sqlalchemy
48+
extension for integration. In that case the Session creation is not directly
49+
accessible. The following allows you to use the wrapper:
50+
51+
.. code-block:: python
52+
:linenos:
53+
54+
from sqlalchemy_mptt import mptt_sessionmaker
55+
from flask_sqlalchemy import SQLAlchemy
56+
57+
# instead of creating db object directly
58+
db = SQLAlchemy()
59+
60+
# subclass the db manager and insert the wrapper at session creation
61+
class CustomSQLAlchemy(SQLAlchemy):
62+
"""A custom SQLAlchemy manager, to have control on session creation"""
63+
64+
def create_session(self, options):
65+
"""Override the original session factory creation"""
66+
Session = super().create_session(options)
67+
# Use wrapper from sqlalchemy_mptt that manage tree tables
68+
return mptt_sessionmaker(Session)
69+
70+
# then
71+
db = CustomSQLAlchemy()
72+
4473
4574
Events
4675
------

0 commit comments

Comments
 (0)