Completed
Push — master ( fe66bc...2a24eb )
by Manas
18:11
created

FormatResultAction   A

Complexity

Total Complexity 8

Size/Duplication

Total Lines 36
Duplicated Lines 0 %
Metric Value
wmc 8
dl 0
loc 36
rs 10
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):
23
        context = {
24
            'six': six,
25
            'execution': execution
26
        }
27
        template = self.default_template
28
29
        alias_id = execution['context'].get('action_alias_ref', {}).get('id', None)
30
        if alias_id:
31
            alias = self.client.managers['ActionAlias'].get_by_id(alias_id)
32
33
            context.update({
34
                'alias': alias
35
            })
36
37
            result = getattr(alias, 'result', None)
38
            if result:
39
                if not result.get('enabled', True):
40
                    raise Exception("Output of this template is disabled.")
41
                if 'format' in alias.result:
42
                    template = alias.result['format']
43
44
        return self.jinja.from_string(template).render(context)
45