platypush/platypush/plugins/__init__.py

57 lines
1.8 KiB
Python
Raw Normal View History

2017-12-11 03:53:26 +01:00
import logging
2018-11-01 19:42:40 +01:00
from functools import wraps
from platypush.event import EventGenerator
from platypush.message.response import Response
2020-09-27 01:33:38 +02:00
from platypush.utils import get_decorators, get_plugin_name_by_class
2019-12-17 00:56:28 +01:00
def action(f):
2018-11-01 19:42:40 +01:00
@wraps(f)
def _execute_action(*args, **kwargs):
response = Response()
result = f(*args, **kwargs)
if result and isinstance(result, Response):
result.errors = result.errors \
if isinstance(result.errors, list) else [result.errors]
response = result
elif isinstance(result, tuple) and len(result) == 2:
response.errors = result[1] \
if isinstance(result[1], list) else [result[1]]
if len(response.errors) == 1 and response.errors[0] is None:
response.errors = []
response.output = result[0]
else:
response = Response(output=result, errors=[])
return response
# Propagate the docstring
_execute_action.__doc__ = f.__doc__
return _execute_action
class Plugin(EventGenerator):
2017-12-18 01:10:51 +01:00
""" Base plugin class """
2017-11-03 15:06:29 +01:00
2017-12-18 01:10:51 +01:00
def __init__(self, **kwargs):
super().__init__()
2020-09-27 01:33:38 +02:00
self.logger = logging.getLogger('platypush:plugin:' + get_plugin_name_by_class(self.__class__))
2018-06-06 20:09:18 +02:00
if 'logging' in kwargs:
self.logger.setLevel(getattr(logging, kwargs['logging'].upper()))
self.registered_actions = set(
get_decorators(self.__class__, climb_class_hierarchy=True).get('action', [])
)
def run(self, method, *args, **kwargs):
assert method in self.registered_actions, '{} is not a registered action on {}'.\
format(method, self.__class__.__name__)
return getattr(self, method)(*args, **kwargs)
2017-10-31 09:20:35 +01:00
# vim:sw=4:ts=4:et: