easyvvuq.encoders.jinja_encoder

 1import os
 2# from string import Template
 3from jinja2 import Template
 4import logging
 5
 6__copyright__ = """
 7
 8    Copyright 2018 Robin A. Richardson, David W. Wright
 9
10    This file is part of EasyVVUQ
11
12    EasyVVUQ is free software: you can redistribute it and/or modify
13    it under the terms of the Lesser GNU General Public License as published by
14    the Free Software Foundation, either version 3 of the License, or
15    (at your option) any later version.
16
17    EasyVVUQ is distributed in the hope that it will be useful,
18    but WITHOUT ANY WARRANTY; without even the implied warranty of
19    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
20    Lesser GNU General Public License for more details.
21
22    You should have received a copy of the Lesser GNU General Public License
23    along with this program.  If not, see <https://www.gnu.org/licenses/>.
24
25"""
26__license__ = "LGPL"
27
28
29class JinjaEncoder:
30    """JinjaEncoder for substituting values into application template input.
31    Uses the jinja2 template system, which supports more complex expressions than
32    the GenericEncoder.
33    See https://jinja.palletsprojects.com/en/2.10.x/templates/ for template syntax.
34
35    Parameters
36    ----------
37
38    Attributes
39    ----------
40
41    """
42
43    def __init__(self, template_fname,
44                 target_filename="app_input.txt"):
45
46        self.target_filename = target_filename
47        self.template_fname = template_fname
48        self.fixture_support = True
49
50    def encode(self, params={}, target_dir=''):
51        """Substitutes `params` into a template application input, saves in
52        `target_dir`
53
54        Parameters
55        ----------
56        params        : dict
57            Parameter information in dictionary.
58        target_dir    : str
59            Path to directory where application input will be written.
60        """
61
62        local_params = params
63
64        try:
65            with open(self.template_fname, 'r') as template_file:
66                template_txt = template_file.read()
67                self.template = Template(template_txt, autoescape=True)
68        except FileNotFoundError:
69            raise RuntimeError(
70                "the template file specified ({}) does not exist".format(self.template_fname))
71
72        if not target_dir:
73            raise RuntimeError('No target directory specified to encoder')
74
75        try:
76            app_input_txt = self.template.render(local_params)
77        except KeyError as e:
78            self._log_substitution_failure(e)
79
80        # Write target input file
81        target_file_path = os.path.join(target_dir, self.target_filename)
82        with open(target_file_path, 'w') as fp:
83            fp.write(app_input_txt)
84
85    def _log_substitution_failure(self, exception):
86        reasoning = (f"\nFailed substituting into template "
87                     f"{self.template_fname}.\n"
88                     f"KeyError: {str(exception)}.\n")
89        logging.error(reasoning)
90
91        raise KeyError(reasoning)
class JinjaEncoder:
30class JinjaEncoder:
31    """JinjaEncoder for substituting values into application template input.
32    Uses the jinja2 template system, which supports more complex expressions than
33    the GenericEncoder.
34    See https://jinja.palletsprojects.com/en/2.10.x/templates/ for template syntax.
35
36    Parameters
37    ----------
38
39    Attributes
40    ----------
41
42    """
43
44    def __init__(self, template_fname,
45                 target_filename="app_input.txt"):
46
47        self.target_filename = target_filename
48        self.template_fname = template_fname
49        self.fixture_support = True
50
51    def encode(self, params={}, target_dir=''):
52        """Substitutes `params` into a template application input, saves in
53        `target_dir`
54
55        Parameters
56        ----------
57        params        : dict
58            Parameter information in dictionary.
59        target_dir    : str
60            Path to directory where application input will be written.
61        """
62
63        local_params = params
64
65        try:
66            with open(self.template_fname, 'r') as template_file:
67                template_txt = template_file.read()
68                self.template = Template(template_txt, autoescape=True)
69        except FileNotFoundError:
70            raise RuntimeError(
71                "the template file specified ({}) does not exist".format(self.template_fname))
72
73        if not target_dir:
74            raise RuntimeError('No target directory specified to encoder')
75
76        try:
77            app_input_txt = self.template.render(local_params)
78        except KeyError as e:
79            self._log_substitution_failure(e)
80
81        # Write target input file
82        target_file_path = os.path.join(target_dir, self.target_filename)
83        with open(target_file_path, 'w') as fp:
84            fp.write(app_input_txt)
85
86    def _log_substitution_failure(self, exception):
87        reasoning = (f"\nFailed substituting into template "
88                     f"{self.template_fname}.\n"
89                     f"KeyError: {str(exception)}.\n")
90        logging.error(reasoning)
91
92        raise KeyError(reasoning)

JinjaEncoder for substituting values into application template input. Uses the jinja2 template system, which supports more complex expressions than the GenericEncoder. See https://jinja.palletsprojects.com/en/2.10.x/templates/ for template syntax.

Parameters
  • Attributes
  • ----------
JinjaEncoder(template_fname, target_filename='app_input.txt')
44    def __init__(self, template_fname,
45                 target_filename="app_input.txt"):
46
47        self.target_filename = target_filename
48        self.template_fname = template_fname
49        self.fixture_support = True
target_filename
template_fname
fixture_support
def encode(self, params={}, target_dir=''):
51    def encode(self, params={}, target_dir=''):
52        """Substitutes `params` into a template application input, saves in
53        `target_dir`
54
55        Parameters
56        ----------
57        params        : dict
58            Parameter information in dictionary.
59        target_dir    : str
60            Path to directory where application input will be written.
61        """
62
63        local_params = params
64
65        try:
66            with open(self.template_fname, 'r') as template_file:
67                template_txt = template_file.read()
68                self.template = Template(template_txt, autoescape=True)
69        except FileNotFoundError:
70            raise RuntimeError(
71                "the template file specified ({}) does not exist".format(self.template_fname))
72
73        if not target_dir:
74            raise RuntimeError('No target directory specified to encoder')
75
76        try:
77            app_input_txt = self.template.render(local_params)
78        except KeyError as e:
79            self._log_substitution_failure(e)
80
81        # Write target input file
82        target_file_path = os.path.join(target_dir, self.target_filename)
83        with open(target_file_path, 'w') as fp:
84            fp.write(app_input_txt)

Substitutes params into a template application input, saves in target_dir

Parameters
  • params (dict): Parameter information in dictionary.
  • target_dir (str): Path to directory where application input will be written.