-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdb_utils.py
35 lines (30 loc) · 929 Bytes
/
db_utils.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
from contextlib import contextmanager
from functools import wraps
from typing import Any, Callable, Generator
from sqlalchemy.orm import Session
@contextmanager
def session_scope() -> Generator[Session, None, None]:
"""Provide a transactional scope around a series of operations."""
session: Session = db_session()
try:
yield session
session.commit()
except Exception:
session.rollback()
raise
finally:
session.close()
def with_session(func: Callable) -> Callable[[], Any]:
@wraps(func)
def decorator(*args: Any, **kwargs: Any) -> Any:
session: Session = db_session()
try:
return_value = func(*args, session=session, **kwargs)
session.commit()
return return_value
except Exception:
session.rollback()
raise
finally:
session.close()
return decorator