当前位置: 首页>>代码示例>>Python>>正文


Python jinja2.UndefinedError方法代码示例

本文整理汇总了Python中jinja2.UndefinedError方法的典型用法代码示例。如果您正苦于以下问题:Python jinja2.UndefinedError方法的具体用法?Python jinja2.UndefinedError怎么用?Python jinja2.UndefinedError使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在jinja2的用法示例。


在下文中一共展示了jinja2.UndefinedError方法的10个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: get_rendered_template_fields

# 需要导入模块: import jinja2 [as 别名]
# 或者: from jinja2 import UndefinedError [as 别名]
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() 
开发者ID:apache,项目名称:airflow,代码行数:25,代码来源:taskinstance.py

示例2: test_helpers_disabled

# 需要导入模块: import jinja2 [as 别名]
# 或者: from jinja2 import UndefinedError [as 别名]
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 
开发者ID:aio-libs,项目名称:aiohttp-jinja2,代码行数:23,代码来源:test_jinja_globals.py

示例3: load_html_file

# 需要导入模块: import jinja2 [as 别名]
# 或者: from jinja2 import UndefinedError [as 别名]
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() 
开发者ID:rsmusllp,项目名称:king-phisher,代码行数:33,代码来源:mail.py

示例4: get_arg_value

# 需要导入模块: import jinja2 [as 别名]
# 或者: from jinja2 import UndefinedError [as 别名]
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 
开发者ID:Fizzadar,项目名称:pyinfra,代码行数:34,代码来源:util.py

示例5: test_render_template_field_undefined_strict

# 需要导入模块: import jinja2 [as 别名]
# 或者: from jinja2 import UndefinedError [as 别名]
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 }}", {}) 
开发者ID:apache,项目名称:airflow,代码行数:9,代码来源:test_baseoperator.py

示例6: warn

# 需要导入模块: import jinja2 [as 别名]
# 或者: from jinja2 import UndefinedError [as 别名]
def warn(self):
        try:
            self._fail_with_undefined_error()
        except UndefinedError, e:
            msg = str(e) 
开发者ID:datawire,项目名称:forge,代码行数:7,代码来源:jinja2.py

示例7: render

# 需要导入模块: import jinja2 [as 别名]
# 或者: from jinja2 import UndefinedError [as 别名]
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 
开发者ID:comtihon,项目名称:catcher,代码行数:14,代码来源:misc.py

示例8: testUndefinedError

# 需要导入模块: import jinja2 [as 别名]
# 或者: from jinja2 import UndefinedError [as 别名]
def testUndefinedError(self):
    with self.assertRaises(jinja2.UndefinedError):
      template_utils._RenderTemplate('test', 'complex.html') 
开发者ID:google,项目名称:upvote,代码行数:5,代码来源:template_utils_test.py

示例9: RenderTemplate

# 需要导入模块: import jinja2 [as 别名]
# 或者: from jinja2 import UndefinedError [as 别名]
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) 
开发者ID:GoogleCloudPlatform,项目名称:PerfKitBenchmarker,代码行数:30,代码来源:virtual_machine.py

示例10: post_receive

# 需要导入模块: import jinja2 [as 别名]
# 或者: from jinja2 import UndefinedError [as 别名]
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) 
开发者ID:alerta,项目名称:alerta-contrib,代码行数:53,代码来源:alerta_telegram.py


注:本文中的jinja2.UndefinedError方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。