Caching modules and plugins

This commit is contained in:
Fabio Manganiello 2017-11-03 02:42:56 +01:00
parent 2de28153f0
commit 13023b660e

View file

@ -34,6 +34,9 @@ DEVICE_ID = config['device_id'] \
DEBUG = config['debug'] if 'debug' in config else False DEBUG = config['debug'] if 'debug' in config else False
modules = {}
plugins = {}
def on_open(ws): def on_open(ws):
logging.info('Connection opened') logging.info('Connection opened')
@ -48,24 +51,32 @@ def on_error(ws, error):
def _exec_func(body): def _exec_func(body):
module = None module_name = 'plugins.{}'.format(body['plugin'])
try: if module_name in modules:
module = importlib.import_module('plugins.{}'.format(body['plugin'])) module = modules[module_name]
except ModuleNotFoundError as e: else:
logging.warn('No such plugin: {}'.format(body['plugin'])) try:
return module = importlib.import_module(module_name)
modules[module_name] = module
except ModuleNotFoundError as e:
logging.warn('No such plugin: {}'.format(body['plugin']))
return
logging.info('Received push addressed to me: {}'.format(body)) logging.info('Received push addressed to me: {}'.format(body))
args = body['args'] if 'args' in body else {} args = body['args'] if 'args' in body else {}
cls = getattr( cls_name = functools.reduce(
module, functools.reduce( lambda a,b: a.title() + b.title(),
lambda a,b: a.title() + b.title(), (body['plugin'].title().split('.'))
(body['plugin'].title().split('.')) ) + 'Plugin'
) + 'Plugin'
) if cls_name in plugins:
instance = plugins[cls_name]
else:
cls = getattr(module, cls_name)
instance = cls()
plugins[cls_name] = cls
instance = cls()
out, err = instance.run(args) out, err = instance.run(args)
logging.info('Command output: {}'.format(out)) logging.info('Command output: {}'.format(out))