Skip to content

Instantly share code, notes, and snippets.

@afonasev
Last active June 9, 2020 14:16
Show Gist options
  • Save afonasev/6cc720832d9bce1179458f4b8fdfab34 to your computer and use it in GitHub Desktop.
Save afonasev/6cc720832d9bce1179458f4b8fdfab34 to your computer and use it in GitHub Desktop.
Sqlalcheny sugar for sessions
from contextlib import ContextDecorator
from functools import wraps
from typing import Any, Callable, Optional, Type
class SessionContext(ContextDecorator):
"""
class Session(SessionContext):
scoped_session = ...
with Session():
session.add(...)
Examples:
with Session() as s:
s.add(...)
@Session()
def func():
session.add()
with Session(commit=False):
session.add(...)
session.commit()
"""
scoped_session: _scoped_session
def __init__(self, commit: bool = True) -> None:
self._commit = commit
def __enter__(self) -> _scoped_session:
return self.scoped_session
def __exit__(self, error: Optional[Type], value: Any, traceback: Any) -> None:
try:
if not error and self._commit:
self.scoped_session.commit()
finally:
self.scoped_session.remove() # with rollback
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment