Completed
Pull Request — master (#2402)
by Manas
06:31
created

FormatResultAction._get_execution()   A

Complexity

Conditions 3

Size

Total Lines 8

Duplication

Lines 0
Ratio 0 %
Metric Value
cc 3
dl 0
loc 8
rs 9.4285
1
import jinja2
2
import six
3
import os
4
5
from st2actions.runners.pythonrunner import Action
6
from st2client.client import Client
7
8
9
class FormatResultAction(Action):
10
    def __init__(self, config):
11
        super(FormatResultAction, self).__init__(config)
12
        api_url = os.environ.get('ST2_ACTION_API_URL', None)
13
        token = os.environ.get('ST2_ACTION_AUTH_TOKEN', None)
14
        self.client = Client(api_url=api_url, token=token)
15
        self.jinja = jinja2.Environment(trim_blocks=True, lstrip_blocks=True)
16
        self.jinja.tests['in'] = lambda item, list: item in list
17
18
        path = os.path.dirname(os.path.realpath(__file__))
19
        with open(os.path.join(path, 'templates/default.j2'), 'r') as f:
20
            self.default_template = f.read()
21
22
    def run(self, execution_id):
23
        execution = self._get_execution(execution_id)
24
        context = {
25
            'six': six,
26
            'execution': execution
27
        }
28
        template = self.default_template
29
30
        alias_id = execution['context'].get('action_alias_ref', {}).get('id', None)
31
        if alias_id:
32
            alias = self.client.managers['ActionAlias'].get_by_id(alias_id)
33
34
            context.update({
35
                'alias': alias
36
            })
37
38
            result = getattr(alias, 'result', None)
39
            if result:
40
                if not result.get('enabled', True):
41
                    raise Exception("Output of this template is disabled.")
42
                if 'format' in alias.result:
43
                    template = alias.result['format']
44
45
        return self.jinja.from_string(template).render(context)
46
47
    def _get_execution(self, execution_id):
48
        if not execution_id:
49
            raise ValueError('Invalid execution_id provided.')
50
        execution = self.client.liveactions.get_by_id(id=execution_id)
51
        if not execution:
52
            return None
53
        excludes = ["trigger", "trigger_type", "trigger_instance", "liveaction"]
54
        return execution.to_dict(exclude_attributes= excludes)
55