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: on action decorator #1090

Draft
wants to merge 4 commits 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
51 changes: 51 additions & 0 deletions src/viur/core/decorators.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,8 @@
import abc
import collections
import logging
import typing as t

from viur.core.module import Method

__all__ = [
Expand Down Expand Up @@ -142,3 +146,50 @@ def decorator(func):
return decorator

return decorator(func)


class OnAction(abc.ABC):
@property
@abc.abstractmethod
def action_name(self) -> str:
...

def __init__(self, fn: t.Callable):
self.fn = fn

def __call__(self, *args, **kwargs):
return self.fn(*args, **kwargs)

def __set_name__(self, owner, name):
self.fn.class_name = owner.__name__
if not hasattr(owner, "on_handlers"):
owner.on_handlers: dict[str, list[t.Callable]] = collections.defaultdict(list)
owner.on_handlers[self.action_name].append(self.fn)

@classmethod
def dispatch(cls, caller, *args, raise_error: bool = True, **kwargs):
from viur.core import conf
for handler in caller.on_handlers[cls.action_name]:
if conf.debug.trace:
logging.debug(f"Calling {handler=} with {args=} and {kwargs=}")
try:
handler(caller, *args, **kwargs)
except Exception as exc:
if raise_error:
raise
else:
logging.exception(f"Calling {handler=} with {args=} and {kwargs=} failed: {exc}")

@classmethod
def create(cls, action_name: str) -> "t.Self":
return type(f"{action_name}Action", (cls,), {"action_name": action_name})


on_add = OnAction.create("add")
on_added = OnAction.create("added")
on_edit = OnAction.create("edit")
on_edited = OnAction.create("edited")
on_delete = OnAction.create("delete")
on_deleted = OnAction.create("deleted")
on_clone = OnAction.create("clone")
on_cloned = OnAction.create("cloned")
7 changes: 7 additions & 0 deletions src/viur/core/prototypes/list.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
from viur.core.cache import flushCache
from viur.core.skeleton import SkeletonInstance
from .skelmodule import SkelModule, DEFAULT_ORDER_TYPE
from ..decorators import OnAction, on_add, on_added, on_clone, on_cloned, on_edit, on_edited


class List(SkelModule):
Expand Down Expand Up @@ -565,6 +566,7 @@ def onAdd(self, skel: SkeletonInstance):

.. seealso:: :func:`add`, :func:`onAdded`
"""
on_add.dispatch(self, skel)
pass

def onAdded(self, skel: SkeletonInstance):
Expand All @@ -582,6 +584,7 @@ def onAdded(self, skel: SkeletonInstance):
flushCache(kind=skel.kindName)
if user := current.user.get():
logging.info(f"""User: {user["name"]!r} ({user["key"]!r})""")
on_added.dispatch(self, skel)

def onEdit(self, skel: SkeletonInstance):
"""
Expand All @@ -593,6 +596,7 @@ def onEdit(self, skel: SkeletonInstance):

.. seealso:: :func:`edit`, :func:`onEdited`
"""
on_edit.dispatch(self, skel)
pass

def onEdited(self, skel: SkeletonInstance):
Expand All @@ -610,6 +614,7 @@ def onEdited(self, skel: SkeletonInstance):
flushCache(key=skel["key"])
if user := current.user.get():
logging.info(f"""User: {user["name"]!r} ({user["key"]!r})""")
on_edited.dispatch(self, skel)

def onView(self, skel: SkeletonInstance):
"""
Expand Down Expand Up @@ -664,6 +669,7 @@ def onClone(self, skel: SkeletonInstance, src_skel: SkeletonInstance):
.. seealso:: :func:`clone`, :func:`onCloned`
"""
pass
on_clone.dispatch(self, skel)

def onCloned(self, skel: SkeletonInstance, src_skel: SkeletonInstance):
"""
Expand All @@ -681,6 +687,7 @@ def onCloned(self, skel: SkeletonInstance, src_skel: SkeletonInstance):

if user := utils.getCurrentUser():
logging.info(f"""User: {user["name"]!r} ({user["key"]!r})""")
on_cloned.dispatch(self, skel)


List.admin = True
Expand Down
Loading