Skip to content

Commit 1517322

Browse files
committed
Improve multithreading documentation
1 parent 26afc5f commit 1517322

File tree

1 file changed

+42
-7
lines changed

1 file changed

+42
-7
lines changed

docs/manager/session.md

Lines changed: 42 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,18 @@
1-
Using the session is the same as standard SQLAlchemy, we just retrieve the session class
2-
using the `get_session()` method.
1+
Using the session is the same as standard SQLAlchemy. The recommended approach
2+
is using the `get_session()` context manager, so you don't need to manage the
3+
session life cycle.
34

45
```python
56
# Persist an object
67
o = ImperativeModel()
78
o.name = "John"
8-
with sa_manager.get_bind().session_class()() as session:
9+
with sa_manager.get_session() as session:
910
session.add(o)
1011
session.commit()
1112

12-
# or using the get_session() helper method for better readability
13-
with sa_manager.get_session() as session:
13+
# We can also get the `session_class` property of the bind,
14+
# but t
15+
with sa_manager.get_bind().session_class()() as session:
1416
session.add(o)
1517
session.commit()
1618
```
@@ -24,14 +26,47 @@ among the threads and produce undesired changes in the database.
2426

2527
This is not thread safe:
2628

29+
/// note | db.py (a module to have an easy to use session)
2730
```python
2831
session = sa_manager.get_session()
32+
```
33+
///
34+
35+
36+
/// note | some_other_module.py (a module to have an easy-to=use session)
37+
```python
38+
from db import session
39+
2940
session.add(model)
3041
session.commit()
3142
```
43+
///
44+
45+
46+
This instead would be thread safe:
47+
48+
/// note | some_other_module.py (a module to have an easy-to=use session)
49+
50+
```python
51+
def do_something():
52+
session = sa_manager.get_session()
53+
session.add(model)
54+
session.commit()
55+
session.close()
56+
57+
do_something()
58+
```
59+
60+
The `do_something` function can be also in another method, as long as
61+
the `session` variable has no global scope it will be safe.
62+
///
63+
64+
/// tip | Using the `get_session()` context manager is much easier
65+
66+
///
3267

33-
If you truly need to have a long-lived session you'll need to use a scoped session,
34-
something like this:
68+
If you truly need to have a long-lived session in a variable with global scope,
69+
you'll need to use a scoped session like this:
3570

3671
```python
3772
from sqlalchemy.orm import scoped_session

0 commit comments

Comments
 (0)