Python jinja2.exceptions.UndefinedError() Examples

The following are 5 code examples of jinja2.exceptions.UndefinedError(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module jinja2.exceptions , or try the search function .
Example #1
Source File: try_default.py    From infrared with Apache License 2.0 7 votes vote down vote up
def try_default(value, default, ignore=False):
    """
    This filter ignores undefined variables and returns
    default value, if default value is undefined and 'ignore'
    options is enabled then return 'False' otherwise raise
    exception 'UndefinedError'.
    """

    if not isinstance(value, Undefined):
        return value
    elif not isinstance(default, Undefined):
        return default
    elif isinstance(default, Undefined) and ignore:
        return False
    else:
        raise UndefinedError("One of the nested variables are undefined") 
Example #2
Source File: templating.py    From k8s-handle with Apache License 2.0 6 votes vote down vote up
def generate_by_context(self, context):
        if context is None:
            raise RuntimeError('Can\'t generate templates from None context')

        templates = self._preprocess_templates(context.get('templates', []))
        if len(templates) == 0:
            templates = context.get('kubectl', [])
            if len(templates) == 0:
                return

        output = []
        for template in self._iterate_entries(templates):
            try:
                path = self._generate_file(template, settings.TEMP_DIR, context)
                log.info('File "{}" successfully generated'.format(path))
                output.append(path)
            except TemplateNotFound as e:
                raise TemplateRenderingError(
                    "Processing {}: template {} hasn't been found".format(template['template'], e.name))
            except (UndefinedError, TemplateSyntaxError) as e:
                raise TemplateRenderingError('Unable to render {}, due to: {}'.format(template, e))
        return output 
Example #3
Source File: test.py    From osmbot with GNU General Public License v3.0 6 votes vote down vote up
def test_templates(self):
        """
        Just to check templates syntax

        :return: None
        """

        from jinja2 import Environment, exceptions
        jinja_env = Environment(extensions=['jinja2.ext.i18n'])
        templates = os.listdir('bot/templates')
        for template in templates:
            print('Testing template:{}'.format(template))
            with open(os.path.join('bot/templates', template)) as f:
                template_text = unicode(f.read())
            try:
                jinja_env.from_string(template_text).render()
            except exceptions.TemplateAssertionError:
                pass
            except exceptions.UndefinedError:
                pass 
Example #4
Source File: templates.py    From loom with GNU Affero General Public License v3.0 5 votes vote down vote up
def _validate_output_source(self, output_source, input_context):
        try:
            render_from_template(
                output_source.get('filename'), input_context)
            render_string_or_list(
                output_source.get('filenames'),
                input_context)
            render_from_template(
                output_source.get('glob'), input_context)
        except UndefinedError as e:
            raise serializers.ValidationError({
                'source':
                'Error "%s" in output source "%s"' %
                (e, output_source)}) 
Example #5
Source File: tester.py    From st2 with Apache License 2.0 4 votes vote down vote up
def evaluate(self):
        """
        Evaluate trigger instance against the rule.

        :return: ``True`` if the rule matches, ``False`` otherwise.
        :rtype: ``boolean``
        """

        rule_db = self._get_rule_db()
        trigger_instance_db, trigger_db = self._get_trigger_instance_db()

        # The trigger check needs to be performed here as that is not performed
        # by RulesMatcher.
        if rule_db.trigger != trigger_db.ref:
            LOG.info('rule.trigger "%s" and trigger.ref "%s" do not match.',
                     rule_db.trigger, trigger_db.ref)
            return False

        # Check if rule matches criteria.
        matcher = RulesMatcher(trigger_instance=trigger_instance_db, trigger=trigger_db,
                               rules=[rule_db], extra_info=True)
        matching_rules = matcher.get_matching_rules()

        # Rule does not match so early exit.
        if len(matching_rules) < 1:
            return False

        # Check if rule can be enforced
        enforcer = RuleEnforcer(trigger_instance=trigger_instance_db, rule=rule_db)

        runner_type_db = mock.Mock()
        runner_type_db.runner_parameters = {}
        action_db = mock.Mock()
        action_db.parameters = {}
        params = rule_db.action.parameters  # pylint: disable=no-member

        context, additional_contexts = enforcer.get_action_execution_context(action_db=action_db,
                                                                             trace_context=None)

        # Note: We only return partially resolved parameters.
        # To be able to return all parameters we would need access to corresponding ActionDB,
        # RunnerTypeDB and ConfigDB object, but this would add a dependency on the database and the
        # tool is meant to be used standalone.
        try:
            params = enforcer.get_resolved_parameters(action_db=action_db,
                                                      runnertype_db=runner_type_db,
                                                      params=params,
                                                      context=context,
                                                      additional_contexts=additional_contexts)

            LOG.info('Action parameters resolved to:')
            for param in six.iteritems(params):
                LOG.info('\t%s: %s', param[0], param[1])
            return True
        except (UndefinedError, ValueError) as e:
            LOG.error('Failed to resolve parameters\n\tOriginal error : %s', six.text_type(e))
            return False
        except:
            LOG.exception('Failed to resolve parameters.')
            return False