Python jinja2.UndefinedError() Examples

The following are 10 code examples of jinja2.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 , or try the search function .
Example #1
Source File: test_jinja_globals.py    From aiohttp-jinja2 with Apache License 2.0 6 votes vote down vote up
def test_helpers_disabled(aiohttp_client):

    async def index(request):
        with pytest.raises(jinja2.UndefinedError,
                           match="'url' is undefined"):
            aiohttp_jinja2.render_template('tmpl.jinja2', request, {})
        return web.Response()

    app = web.Application()
    aiohttp_jinja2.setup(
        app,
        default_helpers=False,
        loader=jinja2.DictLoader(
            {'tmpl.jinja2': "{{ url('index')}}"})
    )

    app.router.add_route('GET', '/', index)
    client = await aiohttp_client(app)

    resp = await client.get('/')
    assert 200 == resp.status 
Example #2
Source File: taskinstance.py    From airflow with Apache License 2.0 6 votes vote down vote up
def get_rendered_template_fields(self):
        """
        Fetch rendered template fields from DB if Serialization is enabled.
        Else just render the templates
        """
        from airflow.models.renderedtifields import RenderedTaskInstanceFields
        if STORE_SERIALIZED_DAGS:
            rtif = RenderedTaskInstanceFields.get_templated_fields(self)
            if rtif:
                for field_name, rendered_value in rtif.items():
                    setattr(self.task, field_name, rendered_value)
            else:
                try:
                    self.render_templates()
                except (TemplateAssertionError, UndefinedError) as e:
                    raise AirflowException(
                        "Webserver does not have access to User-defined Macros or Filters "
                        "when Dag Serialization is enabled. Hence for the task that have not yet "
                        "started running, please use 'airflow tasks render' for debugging the "
                        "rendering of template_fields."
                    ) from e
        else:
            self.render_templates() 
Example #3
Source File: mail.py    From king-phisher with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def load_html_file(self):
		"""
		Load the configured HTML file into the WebKit engine so the contents can
		be previewed.
		"""
		html_file = self.config.get('mailer.html_file')
		if not (html_file and os.path.isfile(html_file) and os.access(html_file, os.R_OK)):
			return

		try:
			with codecs.open(html_file, 'r', encoding='utf-8') as file_h:
				html_data = file_h.read()
		except UnicodeDecodeError:
			self.info_bar_label.set_text("Source file is not UTF-8 encoded.")
			return

		try:
			html_data = mailer.render_message_template(html_data, self.config)
		except jinja2.TemplateSyntaxError as error:
			self.info_bar_label.set_text("Template syntax error: {error.message} on line {error.lineno}.".format(error=error))
			self.info_bar.show()
		except jinja2.UndefinedError as error:
			self.info_bar_label.set_text("Template undefined error: {error.message}.".format(error=error))
			self.info_bar.show()
		except TypeError as error:
			self.info_bar_label.set_text("Template type error: {0}.".format(error.args[0]))
			self.info_bar.show()
		else:
			html_file_uri = urllib.parse.urlparse(html_file, 'file').geturl()
			self.webview.load_html_data(html_data, html_file_uri)
			self.info_bar.hide() 
Example #4
Source File: util.py    From pyinfra with MIT License 5 votes vote down vote up
def get_arg_value(state, host, arg):
    '''
    Runs string arguments through the jinja2 templating system with a state and
    host. Used to avoid string formatting in deploy operations which result in
    one operation per host/variable. By parsing the commands after we generate
    the ``op_hash``, multiple command variations can fall under one op.
    '''

    if isinstance(arg, six.string_types):
        data = {
            'host': host,
            'inventory': state.inventory,
        }

        try:
            return get_template(arg, is_string=True).render(data)
        except (TemplateSyntaxError, UndefinedError) as e:
            raise PyinfraError('Error in template string: {0}'.format(e))

    elif isinstance(arg, list):
        return [get_arg_value(state, host, value) for value in arg]

    elif isinstance(arg, tuple):
        return tuple(get_arg_value(state, host, value) for value in arg)

    elif isinstance(arg, dict):
        return {
            key: get_arg_value(state, host, value)
            for key, value in six.iteritems(arg)
        }

    return arg 
Example #5
Source File: test_baseoperator.py    From airflow with Apache License 2.0 5 votes vote down vote up
def test_render_template_field_undefined_strict(self):
        """Test render_template with template_undefined configured."""
        with DAG("test-dag", start_date=DEFAULT_DATE, template_undefined=jinja2.StrictUndefined):
            task = DummyOperator(task_id="op1")

        with self.assertRaises(jinja2.UndefinedError):
            task.render_template("{{ foo }}", {}) 
Example #6
Source File: jinja2.py    From forge with Apache License 2.0 5 votes vote down vote up
def warn(self):
        try:
            self._fail_with_undefined_error()
        except UndefinedError, e:
            msg = str(e) 
Example #7
Source File: misc.py    From catcher with Apache License 2.0 5 votes vote down vote up
def render(source: str, variables: dict) -> str:
    template = Template(source)
    holder = FiltersHolder()
    for filter_mod, value in holder.filters.items():
        template.environment.filters[filter_mod] = value
    for fun_mod, value in holder.functions.items():
        template.globals[fun_mod] = value
    try:
        return template.render(variables)
    except UndefinedError as e:
        debug(e.message)
        return source 
Example #8
Source File: template_utils_test.py    From upvote with Apache License 2.0 5 votes vote down vote up
def testUndefinedError(self):
    with self.assertRaises(jinja2.UndefinedError):
      template_utils._RenderTemplate('test', 'complex.html') 
Example #9
Source File: virtual_machine.py    From PerfKitBenchmarker with Apache License 2.0 5 votes vote down vote up
def RenderTemplate(self, template_path, remote_path, context):
    """Renders a local Jinja2 template and copies it to the remote host.

    The template will be provided variables defined in 'context', as well as a
    variable named 'vm' referencing this object.

    Args:
      template_path: string. Local path to jinja2 template.
      remote_path: string. Remote path for rendered file on the remote vm.
      context: dict. Variables to pass to the Jinja2 template during rendering.

    Raises:
      jinja2.UndefinedError: if template contains variables not present in
        'context'.
      RemoteCommandError: If there was a problem copying the file.
    """
    with open(template_path) as fp:
      template_contents = fp.read()

    environment = jinja2.Environment(undefined=jinja2.StrictUndefined)
    template = environment.from_string(template_contents)
    prefix = 'pkb-' + os.path.basename(template_path)

    with vm_util.NamedTemporaryFile(prefix=prefix, dir=vm_util.GetTempDir(),
                                    delete=False, mode='w') as tf:
      tf.write(template.render(vm=self, **context))
      tf.close()
      self.RemoteCopy(tf.name, remote_path) 
Example #10
Source File: alerta_telegram.py    From alerta-contrib with MIT License 4 votes vote down vote up
def post_receive(self, alert):

        if alert.repeat:
            return

        try:
            text = self.template.render(alert.__dict__)
        except UndefinedError:
            text = "Something bad has happened but also we " \
                   "can't handle your telegram template message."

        LOG.debug('Telegram: message=%s', text)

        if TELEGRAM_WEBHOOK_URL:
            keyboard = {
                'inline_keyboard': [
                    [
                        {'text': 'ack', 'callback_data': '/ack ' + alert.id},
                        {'text': 'close', 'callback_data': '/close ' + alert.id},
                        {'text': 'blackout',
                         'callback_data': '/blackout ' + alert.id}
                    ]
                ]
            }
        else:
            keyboard = None

        if TELEGRAM_SOUND_NOTIFICATION_SEVERITY:
            disable_notification = True
            if alert.severity in TELEGRAM_SOUND_NOTIFICATION_SEVERITY:
                disable_notification = False
        else:
            disable_notification = False

        LOG.debug('Telegram: post_receive sendMessage disable_notification=%s', str(disable_notification))

        try:
            response = self.bot.sendMessage(TELEGRAM_CHAT_ID,
                                            text,
                                            parse_mode='Markdown',
                                            disable_notification=disable_notification,
                                            reply_markup=keyboard)
        except telepot.exception.TelegramError as e:
            raise RuntimeError("Telegram: ERROR - %s, description= %s, json=%s",
                               e.error_code,
                               e.description,
                               e.json)
        except Exception as e:
            raise RuntimeError("Telegram: ERROR - %s", e)

        LOG.debug('Telegram: %s', response)