本文整理汇总了Python中jinja2.exceptions.TemplateError方法的典型用法代码示例。如果您正苦于以下问题:Python exceptions.TemplateError方法的具体用法?Python exceptions.TemplateError怎么用?Python exceptions.TemplateError使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类jinja2.exceptions
的用法示例。
在下文中一共展示了exceptions.TemplateError方法的13个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: main
# 需要导入模块: from jinja2 import exceptions [as 别名]
# 或者: from jinja2.exceptions import TemplateError [as 别名]
def main():
"""Regenerate pages listed in global `REGEN` list."""
env = SandboxedEnvironment(undefined=StrictUndefined)
for target, get_data, template in REGEN:
print("Regenerating", target)
data = get_data()
template_text = requests.get(template).text
try:
rendered = env.from_string(template_text).render(**data)
except TemplateError as error:
print("Error while regenerating", target)
print(error)
return 1
with open(target, "w") as target:
target.write(rendered)
return 0
示例2: process_cmds
# 需要导入模块: from jinja2 import exceptions [as 别名]
# 或者: from jinja2.exceptions import TemplateError [as 别名]
def process_cmds(cmds, overrides):
"""
:param cmds:
:param overrides:
:return:
"""
data = ''
for cmd in cmds:
if cmd.startswith('#'):
continue
else:
try:
newcmd = Environment(undefined=undefined).from_string(cmd).render(overrides)
data += "- %s\n" % newcmd.replace(": ", "':' ")
except TemplateError as e:
pprint("Error rendering cmd %s. Got: %s" % (cmd, e.message), color='red')
os._exit(1)
return data
示例3: main
# 需要导入模块: from jinja2 import exceptions [as 别名]
# 或者: from jinja2.exceptions import TemplateError [as 别名]
def main():
"""Regenerate pages listed in global `REGEN` list."""
env = SandboxedEnvironment(undefined=StrictUndefined)
for target, get_data, template in REGEN:
print("Regenerating", target)
data = get_data()
if Path(template).exists():
with open(template) as fd:
template_text = fd.read()
else:
template_text = requests.get(template).text
try:
rendered = env.from_string(template_text).render(**data)
except TemplateError as error:
print("Error while regenerating", target)
print(error)
return 1
with open(target, "w") as target:
target.write(rendered)
return 0
示例4: render_xml
# 需要导入模块: from jinja2 import exceptions [as 别名]
# 或者: from jinja2.exceptions import TemplateError [as 别名]
def render_xml(self, src_xml, context, jinja_env=None):
src_xml = src_xml.replace(r'<w:p>', '\n<w:p>')
try:
if jinja_env:
template = jinja_env.from_string(src_xml)
else:
template = Template(src_xml)
dst_xml = template.render(context)
except TemplateError as exc:
if hasattr(exc, 'lineno') and exc.lineno is not None:
line_number = max(exc.lineno - 4, 0)
exc.docx_context = map(lambda x: re.sub(r'<[^>]+>', '', x),
src_xml.splitlines()[line_number:(line_number + 7)])
raise exc
dst_xml = dst_xml.replace('\n<w:p>', '<w:p>')
dst_xml = (dst_xml
.replace('{_{', '{{')
.replace('}_}', '}}')
.replace('{_%', '{%')
.replace('%_}', '%}'))
return dst_xml
示例5: test_invalid_block_templated_message_templates
# 需要导入模块: from jinja2 import exceptions [as 别名]
# 或者: from jinja2.exceptions import TemplateError [as 别名]
def test_invalid_block_templated_message_templates(app_with_mail):
"""Test invalid templates."""
with app_with_mail.app_context():
with pytest.raises(TemplateError) as ex:
BlockTemplatedMessage("mail/blank.html")
assert "No block with name 'subject'" in str(ex.value)
with pytest.raises(TemplateError) as ex:
BlockTemplatedMessage("mail/subject_only.html")
assert "No block with name 'body_plain'" in str(ex.value)
示例6: render_block
# 需要导入模块: from jinja2 import exceptions [as 别名]
# 或者: from jinja2.exceptions import TemplateError [as 别名]
def render_block(self, template, block_name):
"""Return a Jinja2 block as a string."""
new_context = template.new_context
if block_name not in template.blocks:
raise TemplateError("No block with name '{}'".format(block_name))
lines = template.blocks[block_name](new_context(vars=self.ctx))
return "".join(lines)
示例7: render
# 需要导入模块: from jinja2 import exceptions [as 别名]
# 或者: from jinja2.exceptions import TemplateError [as 别名]
def render(self, context, language_code=DEFAULT_LANG):
"""
Render this notification template with given context and language
Returns a dict containing all content fields of the template. Example:
{'subject': 'bar', 'body': 'baz', 'html_body': '<b>foobar</b>'}
"""
env = SandboxedEnvironment(trim_blocks=True, lstrip_blocks=True, undefined=StrictUndefined)
env.filters['format_datetime'] = format_datetime
logger.debug('Rendering template for notification %s' % self.type)
activate(language_code)
try:
rendered_notification = {
attr: env.from_string(getattr(self, attr)).render(context)
for attr in ('subject', 'html_body')
}
if self.body:
rendered_notification['body'] = env.from_string(self.body).render(context)
else:
# if text body is empty use html body without tags as text body
rendered_notification['body'] = strip_tags(rendered_notification['html_body'])
return rendered_notification
except TemplateError as e:
raise NotificationTemplateException(e) from e
示例8: process_ignition_cmds
# 需要导入模块: from jinja2 import exceptions [as 别名]
# 或者: from jinja2.exceptions import TemplateError [as 别名]
def process_ignition_cmds(cmds, overrides):
"""
:param cmds:
:param overrides:
:return:
"""
path = '/usr/local/bin/first.sh'
permissions = '700'
content = ''
for cmd in cmds:
try:
newcmd = Environment(undefined=undefined).from_string(cmd).render(overrides)
content += "%s\n" % newcmd
except TemplateError as e:
pprint("Error rendering cmd %s. Got: %s" % (cmd, e.message), color='red')
os._exit(1)
if content == '':
return content
else:
if not content.startswith('#!'):
content = "#!/bin/sh\n%s" % content
content = quote(content)
data = {'filesystem': 'root', 'path': path, 'mode': int(permissions, 8),
"contents": {"source": "data:,%s" % content, "verification": {}}}
return data
示例9: check_compilation
# 需要导入模块: from jinja2 import exceptions [as 别名]
# 或者: from jinja2.exceptions import TemplateError [as 别名]
def check_compilation(self, data):
"""Tests that a template string can be successfully compiled
"""
exception = None
result = None
try:
result = utils.compile_template_string(data)
except TemplateError as error:
exception = error
return result, exception
示例10: render
# 需要导入模块: from jinja2 import exceptions [as 别名]
# 或者: from jinja2.exceptions import TemplateError [as 别名]
def render(self):
try:
return self.load_template().render(**self.template_config)
except TemplateError, e:
raise HokusaiError("Rendering template raised error %s <message '%s'>" % (e.__class__, e.message))
示例11: __init__
# 需要导入模块: from jinja2 import exceptions [as 别名]
# 或者: from jinja2.exceptions import TemplateError [as 别名]
def __init__(self, template, ctx={}, **kwargs):
"""Build message body and HTML based on the provided template.
The template needs to provide two blocks: subject and body. An optional
html block can also be provided for HTML rendered emails.
:param template: Path to the template file.
:param ctx: A mapping containing additional information passed to the
template.
:param **kwargs: Named arguments as defined in
:class:`flask_mail.Message`.
"""
self.template = template
self.id = str(uuid.uuid4())
ctx.update(dict(
spa_routes=dict(
HOST=current_app.config["SPA_HOST"],
PATHS=current_app.config["SPA_PATHS"],
),
))
self.ctx = ctx
tmpl = current_app.jinja_env.get_template(template)
kwargs["subject"] = self.render_block(tmpl, "subject").strip()
kwargs["body"] = self.render_block(tmpl, "body_plain")
try:
kwargs["html"] = self.render_block(tmpl, "body_html")
except TemplateError:
kwargs["html"] = kwargs["body"]
footer_tmpl = current_app.jinja_env.get_template(self.FOOTER_TEMPLATE)
footer_plain = self.render_block(footer_tmpl, "footer_plain")
try:
footer_html = self.render_block(footer_tmpl, "footer_html")
except TemplateError:
footer_html = footer_plain
kwargs["body"] += footer_plain
kwargs["html"] += footer_html
kwargs["body"] = kwargs["body"].strip()
kwargs["html"] = kwargs["html"].strip()
kwargs.setdefault("sender", current_app.config["MAIL_NOTIFY_SENDER"])
kwargs.setdefault("cc", current_app.config["MAIL_NOTIFY_CC"])
kwargs.setdefault("bcc", current_app.config["MAIL_NOTIFY_BCC"])
super(BlockTemplatedMessage, self).__init__(**kwargs)
示例12: convert
# 需要导入模块: from jinja2 import exceptions [as 别名]
# 或者: from jinja2.exceptions import TemplateError [as 别名]
def convert():
jinja2_env = Environment()
# Load custom filters
custom_filters = get_custom_filters()
app.logger.debug('Add the following customer filters to Jinja environment: %s' % ', '.join(custom_filters.keys()))
jinja2_env.filters.update(custom_filters)
# Load the template
try:
jinja2_tpl = jinja2_env.from_string(request.form['template'])
except (exceptions.TemplateSyntaxError, exceptions.TemplateError) as e:
return "Syntax error in jinja2 template: {0}".format(e)
dummy_values = [ 'Lorem', 'Ipsum', 'Amet', 'Elit', 'Expositum',
'Dissimile', 'Superiori', 'Laboro', 'Torquate', 'sunt',
]
values = {}
if bool(int(request.form['dummyvalues'])):
# List template variables (introspection)
vars_to_fill = meta.find_undeclared_variables(jinja2_env.parse(request.form['template']))
for v in vars_to_fill:
values[v] = choice(dummy_values)
else:
# Check JSON for errors
if request.form['input_type'] == "json":
try:
values = json.loads(request.form['values'])
except ValueError as e:
return "Value error in JSON: {0}".format(e)
# Check YAML for errors
elif request.form['input_type'] == "yaml":
try:
values = yaml.load(request.form['values'])
except (ValueError, yaml.parser.ParserError, TypeError) as e:
return "Value error in YAML: {0}".format(e)
else:
return "Undefined input_type: {0}".format(request.form['input_type'])
# If ve have empty var array or other errors we need to catch it and show
try:
rendered_jinja2_tpl = jinja2_tpl.render(values)
except (exceptions.TemplateRuntimeError, ValueError, TypeError) as e:
return "Error in your values input filed: {0}".format(e)
if bool(int(request.form['showwhitespaces'])):
# Replace whitespaces with a visible character (will be grayed with javascript)
rendered_jinja2_tpl = rendered_jinja2_tpl.replace(' ', u'•')
return escape(rendered_jinja2_tpl).replace('\n', '<br />')
示例13: output
# 需要导入模块: from jinja2 import exceptions [as 别名]
# 或者: from jinja2.exceptions import TemplateError [as 别名]
def output(folder, results, html_content=None):
can_quit = False
do_overwrite = confirm("Can the folder {path} be overwritten?".format(path=folder))
print("vvvvvvvvv")
while not can_quit:
if do_overwrite:
try:
import Send2Trash
Send2Trash.send2trash(folder)
except ImportError:
import shutil
shutil.rmtree(folder)
# end try
# end if
# write crawled data
mkdir_p(folder)
with open(path_join(folder, "api.py"), "w") as f:
f.write("[\n ")
f.write(",\n ".join([repr(result) for result in results]))
f.write("\n]")
# end for
# end with
if html_content:
with open(path_join(folder, "api.html"), "wb") as f:
f.write(html_content)
# end with
# end if
# write templates
try:
safe_to_file(folder, results)
except TemplateError as e:
if isinstance(e, TemplateSyntaxError):
logger.exception("Template error at {file}:{line}".format(file=e.filename, line=e.lineno))
else:
logger.exception("Template error.")
# end if
# end try
print("Writen to file.")
can_quit = not confirm("Write again after reloading templates?", default=True)
print("#########")
print("Exit.")
# end def