Support for synchronous and asynchronous procedures

This commit is contained in:
Fabio Manganiello 2018-01-06 00:21:25 +01:00
parent b98fe01352
commit f83aedf0f1
4 changed files with 26 additions and 12 deletions

View file

@ -12,7 +12,7 @@ from .event.processor import EventProcessor
from .message.event import Event, StopEvent
from .message.request import Request
from .message.response import Response
from .procedure import Procedure
__author__ = 'Fabio Manganiello <blacklight86@gmail.com>'
__version__ = '0.6.5'

View file

@ -78,8 +78,13 @@ class Config(object):
hook_name = '.'.join(key.split('.')[2:])
self.event_hooks[hook_name] = self._config[key]
elif key.startswith('procedure.'):
procedure_name = '.'.join(key.split('.')[1:])
self.procedures[procedure_name] = self._config[key]
tokens = key.split('.')
async = True if tokens[1] == 'async' else False
procedure_name = '.'.join(tokens[2:])
self.procedures[procedure_name] = {
'async': async,
'actions': self._config[key]
}
else:
self.plugins[key] = self._config[key]

View file

@ -60,7 +60,10 @@ class Request(Message):
logging.info('Executing procedure request: {}'.format(self.action))
proc_name = self.action.split('.')[-1]
proc_config = Config.get_procedures()[proc_name]
proc = Procedure.build(name=proc_name, requests=proc_config, backend=self.backend, id=self.id)
proc = Procedure.build(name=proc_name, requests=proc_config['actions'],
async=proc_config['async'],
backend=self.backend, id=self.id)
return proc.execute(*args, **kwargs)

View file

@ -7,14 +7,17 @@ from ..message.response import Response
class Procedure(object):
""" Procedure class. A procedure is a pre-configured list of requests """
def __init__(self, name, requests, backend=None):
def __init__(self, name, async, requests, backend=None):
"""
Params:
name -- Procedure name
async -- Whether the actions in the procedure are supposed to
be executed sequentially or in parallel (True or False)
requests -- List of platylist.message.request.Request objects
"""
self.name = name
self.async = async
self.requests = requests
self.backend = backend
@ -22,7 +25,7 @@ class Procedure(object):
req.backend = self.backend
@classmethod
def build(cls, name, requests, backend=None, id=None, **kwargs):
def build(cls, name, async, requests, backend=None, id=None, **kwargs):
reqs = []
for request_config in requests:
request_config['origin'] = Config.get('device_id')
@ -33,7 +36,7 @@ class Procedure(object):
request = Request.build(request_config)
reqs.append(request)
return cls(name=name, requests=reqs, backend=backend, **kwargs)
return cls(name=name, async=async, requests=reqs, backend=backend, **kwargs)
def execute(self, n_tries=1):
"""
@ -47,6 +50,9 @@ class Procedure(object):
response = Response()
for request in self.requests:
if self.async:
request.execute(n_tries, async=True, **context)
else:
response = request.execute(n_tries, async=False, **context)
context = { k:v for (k,v) in response.output.items() } \
if isinstance(response.output, dict) else {}