2
0
mirror of https://github.com/inventree/InvenTree.git synced 2025-05-03 05:48:47 +00:00

Add mixin class to respond to internal events

This commit is contained in:
Oliver 2022-01-07 22:22:59 +11:00
parent 8ff3bf1ad1
commit 63eb49777a
2 changed files with 66 additions and 1 deletions

View File

@ -80,6 +80,7 @@ class ScheduleMixin:
ALLOWABLE_SCHEDULE_TYPES = ['I', 'H', 'D', 'W', 'M', 'Q', 'Y'] ALLOWABLE_SCHEDULE_TYPES = ['I', 'H', 'D', 'W', 'M', 'Q', 'Y']
# Override this in subclass model
SCHEDULED_TASKS = {} SCHEDULED_TASKS = {}
class MixinMeta: class MixinMeta:
@ -180,6 +181,69 @@ class ScheduleMixin:
logger.warning("unregister_tasks failed, database not ready") logger.warning("unregister_tasks failed, database not ready")
class EventMixin:
"""
Mixin that provides support for responding to triggered events.
Implementing classes must provide a list of tuples,
which provide pairs of 'event':'function'
Notes:
Events are called by name, and based on the django signal nomenclature,
e.g. 'part.pre_save'
Receiving functions must be prototyped to match the 'event' they receive.
Example:
EVENTS = [
('part.pre_save', 'myplugin.functions.do_stuff'),
('build.complete', 'myplugin.functions.process_completed_build'),
]
"""
# Override this in subclass model
EVENTS = []
class MixinMeta:
MIXIN_NAME = 'Events'
def __init__(self):
super().__init__()
self.add_mixin('events', 'has_events', __class__)
self.events = getattr(self, 'EVENTS', [])
self.validate_events()
@property
def has_events(self):
return bool(self.events) and len(self.events) > 0
def validate_events(self):
"""
Check that the provided event callbacks are valid
"""
if not self.has_events:
raise ValueError('EVENTS not defined')
for pair in self.events:
valid = True
if len(pair) == 2:
event = pair[0].strip()
func = pair[1].strip()
if len(event) == 0 or len(func) == 0:
valid = False
else:
valid = False
if not valid:
raise ValueError("Invalid event callback: " + str(pair))
class UrlsMixin: class UrlsMixin:
""" """
Mixin that enables custom URLs for the plugin Mixin that enables custom URLs for the plugin

View File

@ -2,10 +2,11 @@
Utility class to enable simpler imports Utility class to enable simpler imports
""" """
from ..builtin.integration.mixins import AppMixin, SettingsMixin, ScheduleMixin, UrlsMixin, NavigationMixin from ..builtin.integration.mixins import AppMixin, SettingsMixin, EventMixin, ScheduleMixin, UrlsMixin, NavigationMixin
__all__ = [ __all__ = [
'AppMixin', 'AppMixin',
'EventMixin',
'NavigationMixin', 'NavigationMixin',
'ScheduleMixin', 'ScheduleMixin',
'SettingsMixin', 'SettingsMixin',