Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: Add run_in_transaction decorator. #853

Draft
wants to merge 1 commit into
base: develop
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 17 additions & 0 deletions src/viur/core/decorators.py
Original file line number Diff line number Diff line change
Expand Up @@ -133,3 +133,20 @@ def decorator(func):
return decorator

return decorator(func)


def run_in_transaction(func: Callable) -> Method:
"""
Decorator, which enforces the Method to run in a transaction.
.. code-block:: python
from viur.core.decorators import run_in_transaction
def outer_method(key)
@run_in_transaction
def transaction_method(key):
db.Get(key)
return transaction_method(key)
"""

func = Method.ensure(func)
func.run_in_transaction = True
return func
3 changes: 3 additions & 0 deletions src/viur/core/module.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ def __init__(self, func: typing.Callable):
self.ssl = False
self.methods = ("GET", "POST", "HEAD")
self.seo_language_map = None
self.run_in_transaction = False

# Inspection
self.signature = inspect.signature(self._func)
Expand Down Expand Up @@ -282,6 +283,8 @@ def parse_value_by_annotation(annotation: type, name: str, value: str | list | t
raise errors.Forbidden(self.access["message"]) if self.access["message"] else errors.Forbidden()

# call with instance when provided
if self.run_in_transaction:
return db.RunInTransaction(self._func, *args, **kwargs)
if self._instance:
return self._func(self._instance, *args, **kwargs)

Expand Down