本文整理匯總了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()
示例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
示例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()
示例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
示例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 }}", {})
示例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)
示例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
示例8: testUndefinedError
# 需要導入模塊: import jinja2 [as 別名]
# 或者: from jinja2 import UndefinedError [as 別名]
def testUndefinedError(self):
with self.assertRaises(jinja2.UndefinedError):
template_utils._RenderTemplate('test', 'complex.html')
示例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)
示例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)