platypush/platypush/procedure/__init__.py

70 lines
2.1 KiB
Python
Raw Normal View History

import logging
from ..config import Config
from ..message.request import Request
from ..message.response import Response
class Procedure(object):
""" Procedure class. A procedure is a pre-configured list of requests """
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
for req in requests:
req.backend = self.backend
@classmethod
def build(cls, name, async, requests, backend=None, id=None, **kwargs):
reqs = []
for request_config in requests:
request_config['origin'] = Config.get('device_id')
request_config['id'] = id
if 'target' not in request_config:
request_config['target'] = request_config['origin']
request = Request.build(request_config)
reqs.append(request)
return cls(name=name, async=async, requests=reqs, backend=backend, **kwargs)
def execute(self, n_tries=1):
"""
Execute the requests in the procedure
Params:
n_tries -- Number of tries in case of failure before raising a RuntimeError
"""
logging.info('Executing request {}'.format(self.name))
context = {}
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)
if isinstance(response.output, dict):
for (k,v) in response.output.items():
context[k] = v
context['output'] = response.output
context['errors'] = response.errors
return response
# vim:sw=4:ts=4:et: