本文整理匯總了Python中jinja2.TemplateError方法的典型用法代碼示例。如果您正苦於以下問題:Python jinja2.TemplateError方法的具體用法?Python jinja2.TemplateError怎麽用?Python jinja2.TemplateError使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類jinja2
的用法示例。
在下文中一共展示了jinja2.TemplateError方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: prepare_template
# 需要導入模塊: import jinja2 [as 別名]
# 或者: from jinja2 import TemplateError [as 別名]
def prepare_template(flags, module):
jinja_env = Environment(lstrip_blocks=True, trim_blocks=True)
for name, function in inspect.getmembers(module, inspect.isfunction):
jinja_env.filters[name] = function
if flags.template:
jinja_env.loader = FileSystemLoader(os.path.dirname(flags.template))
template = jinja_env.get_template(os.path.basename(flags.template))
else:
jinja_env.loader = PackageLoader('swg2rst')
try:
template = jinja_env.get_template('main.{}'.format(flags.format))
except TemplateError as err:
sys.exit(u'Template Error: {}'.format(err.message))
return template
示例2: _interpolatestr
# 需要導入模塊: import jinja2 [as 別名]
# 或者: from jinja2 import TemplateError [as 別名]
def _interpolatestr(self, s):
try:
si = jinja2env.from_string(s).render(self._data)
except TemplateError as e:
# FIXME: this seems to be broken for unicode str?
raise HiYaPyCoImplementationException('error interpolating string "%s" : %s' % (s, e,))
if not s == si:
if self.castinterpolated:
if not re.match( r'^\d+\.*\d*$', si):
try:
si = bool(strtobool(si))
except ValueError:
pass
else:
try:
if '.' in si:
si = float(si)
else:
si = int(si)
except ValueError:
pass
logger.debug('interpolated "%s" to "%s" (type: %s)' % (s, si, type(si),))
return si
示例3: __init__
# 需要導入模塊: import jinja2 [as 別名]
# 或者: from jinja2 import TemplateError [as 別名]
def __init__(self, templates_dir: str):
self.__templates_dir = templates_dir
self.__iface_templ = 'ifcfg-iface.j2'
self.__vlan_templ = 'ifcfg-bondX.vlan.j2'
self.__bond_templ = 'ifcfg-bondX.j2'
self.__ign_templ = 'bondX-ignition.j2'
self.__nmstate_templ = 'nmstate-bondX.yaml.j2'
try:
self.__env = jinja2.Environment(
loader=jinja2.FileSystemLoader(self.__templates_dir),
keep_trailing_newline=True
)
except jinja2.TemplateError as e:
print(
"error loading templates directory",
self.__templates_dir, ":", e)
sys.exit(1)
示例4: __process_phy_devices
# 需要導入模塊: import jinja2 [as 別名]
# 或者: from jinja2 import TemplateError [as 別名]
def __process_phy_devices(
self, phy_devices: list, bond_device: str) -> list:
results = list()
for dev in phy_devices:
try:
dev['bond_device'] = bond_device
template = self.__env.get_template(self.__iface_templ)
output = template.render(dev)
dev['b64'] = base64.b64encode(
output.encode('utf-8')).decode('utf-8')
dev['filename'] = 'ifcfg-' + dev.get('device')
results.append(dev)
except jinja2.TemplateError as e:
print("error processing", self.__iface_templ, ":", e)
sys.exit(1)
return results
示例5: __process_vlans
# 需要導入模塊: import jinja2 [as 別名]
# 或者: from jinja2 import TemplateError [as 別名]
def __process_vlans(
self, vlans: list, bond_device: str) -> list:
results = list()
for vlan in vlans:
try:
vlan['bond_device'] = bond_device
template = self.__env.get_template(self.__vlan_templ)
output = template.render(vlan)
vlan['b64'] = base64.b64encode(
output.encode('utf-8')).decode('utf-8')
vlan['filename'] = 'ifcfg-' + vlan.get('bond_device') + '.' \
+ str(vlan.get('id'))
del(vlan['bond_device'])
results.append(vlan)
except jinja2.TemplateError as e:
print("error processing", self.__vlan_templ, ":", e)
sys.exit(1)
return results
示例6: __generate_ifcfg_files
# 需要導入模塊: import jinja2 [as 別名]
# 或者: from jinja2 import TemplateError [as 別名]
def __generate_ifcfg_files(self, template_data: dict) -> dict:
try:
bond_templ = self.__env.get_template(self.__bond_templ)
bond_output = bond_templ.render(template_data)
except jinja2.TemplateError as e:
print("error processing", self.__bond_templ, ":", e)
sys.exit(1)
bond_device = template_data.get('device')
template_data['b64'] = base64.b64encode(
bond_output.encode('utf-8')).decode('utf-8')
template_data['filename'] = 'ifcfg-' + template_data.get('device')
phy_devices = template_data.get('phy_devices')
template_data['phy_devices'] = self.__process_phy_devices(
phy_devices, bond_device)
vlans = template_data.get('vlans')
template_data['vlans'] = self.__process_vlans(vlans, bond_device)
return template_data
示例7: template_exception_handler
# 需要導入模塊: import jinja2 [as 別名]
# 或者: from jinja2 import TemplateError [as 別名]
def template_exception_handler(fn, error_context, filename=None):
"""Calls the given function, attempting to catch any template-related errors, and
converts the error to a Statik TemplateError instance. Returns the result returned
by the function itself."""
error_message = None
if filename:
error_context.update(filename=filename)
try:
return fn()
except jinja2.TemplateSyntaxError as exc:
error_context.update(filename=exc.filename, line_no=exc.lineno)
error_message = exc.message
except jinja2.TemplateError as exc:
error_message = exc.message
except Exception as exc:
error_message = "%s" % exc
raise TemplateError(message=error_message, context=error_context)
示例8: test_load_rules
# 需要導入模塊: import jinja2 [as 別名]
# 或者: from jinja2 import TemplateError [as 別名]
def test_load_rules(self, iter_entry_points):
eps = iter_entry_points.return_value.__iter__.return_value = [
mock.Mock(ep_name='ep0', rules=[('>', 'allura')]),
mock.Mock(ep_name='ep1', rules=[('=', 'allura')]),
mock.Mock(ep_name='ep2', rules=[('<', 'allura')]),
]
for ep in eps:
ep.name = ep.ep_name
ep.load.return_value.template_path_rules = ep.rules
order_rules, replacement_rules = PackagePathLoader()._load_rules()
assert_equal(order_rules, [('ep0', 'allura'), ('allura', 'ep2')])
assert_equal(replacement_rules, {'allura': 'ep1'})
eps = iter_entry_points.return_value.__iter__.return_value = [
mock.Mock(ep_name='ep0', rules=[('?', 'allura')]),
]
for ep in eps:
ep.name = ep.ep_name
ep.load.return_value.template_path_rules = ep.rules
assert_raises(jinja2.TemplateError, PackagePathLoader()._load_rules)
示例9: test_override_disable
# 需要導入模塊: import jinja2 [as 別名]
# 或者: from jinja2 import TemplateError [as 別名]
def test_override_disable(self, fs_loader):
ppl = PackagePathLoader()
ppl.init_paths = mock.Mock()
fs_loader().get_source.side_effect = jinja2.TemplateNotFound('test')
assert_raises(
jinja2.TemplateError,
ppl.get_source, 'env', 'allura.ext.admin:templates/audit.html')
assert_equal(fs_loader().get_source.call_count, 1)
fs_loader().get_source.reset_mock()
with mock.patch.dict(config, {'disable_template_overrides': False}):
assert_raises(
jinja2.TemplateError,
ppl.get_source, 'env', 'allura.ext.admin:templates/audit.html')
assert_equal(fs_loader().get_source.call_count, 2)
示例10: _sort_paths
# 需要導入模塊: import jinja2 [as 別名]
# 或者: from jinja2 import TemplateError [as 別名]
def _sort_paths(self, paths, rules):
"""
Process all '>' and '<' rules, providing a partial ordering
of the paths based on the given rules.
The rules should already have been pre-processed by _load_rules
to a list of partial ordering pairs ('a', 'b') indicating that
path 'a' should come before path 'b'.
"""
names = [p[0] for p in paths]
# filter rules that reference non-existent paths to prevent "loops" in
# the graph
rules = [r for r in rules if r[0] in names and r[1] in names]
ordered_paths = topological_sort(names, rules)
if ordered_paths is None:
raise jinja2.TemplateError(
'Loop detected in ordering of overrides')
return paths.sort(key=lambda p: ordered_paths.index(p[0]))
示例11: _init_file_template
# 需要導入模塊: import jinja2 [as 別名]
# 或者: from jinja2 import TemplateError [as 別名]
def _init_file_template(path, run_dest=None, filters=None):
"""Returns template for path or None if path is not a text file.
Raises TemplateError if path does not exist or cannot be parsed as
a template.
"""
if not os.path.exists(path):
raise TemplateError("%s does not exist" % path)
if not util.is_text_file(path):
return None
dirname, basename = os.path.split(path)
templates_home = _local_path("templates")
env = jinja2.Environment(
loader=jinja2.FileSystemLoader([dirname, templates_home]),
autoescape=jinja2.select_autoescape(['html', 'xml']),
)
RunFilters(run_dest).install(env)
if filters:
env.filters.update(filters)
try:
return env.get_template(basename)
except jinja2.TemplateError as e:
raise TemplateError(e)
示例12: evaluate_block
# 需要導入模塊: import jinja2 [as 別名]
# 或者: from jinja2 import TemplateError [as 別名]
def evaluate_block(self, template, context=None, escape=None, safe_wrapper=None):
"""Evaluate a template block."""
if context is None:
context = {}
try:
with self._evaluation_context(escape, safe_wrapper):
template = self._environment.from_string(template)
return template.render(**context)
except jinja2.TemplateError as error:
raise EvaluationError(error.args[0])
finally:
self._escape = None
示例13: evaluate_inline
# 需要導入模塊: import jinja2 [as 別名]
# 或者: from jinja2 import TemplateError [as 別名]
def evaluate_inline(self, expression, context=None, escape=None, safe_wrapper=None):
"""Evaluate an inline expression."""
if context is None:
context = {}
try:
with self._evaluation_context(escape, safe_wrapper):
compiled = self._environment.compile_expression(expression)
return compiled(**context)
except jinja2.TemplateError as error:
raise EvaluationError(error.args[0])
示例14: renders
# 需要導入模塊: import jinja2 [as 別名]
# 或者: from jinja2 import TemplateError [as 別名]
def renders(name, source, **variables):
"""
Renders a string as a jinja template. The name is used where
filename would normally appear in error messages.
"""
try:
return Template(source, undefined=WarnUndefined).render(**variables)
except TemplateError, e:
raise TaskError("%s: %s" % (name, e))
示例15: render
# 需要導入模塊: import jinja2 [as 別名]
# 或者: from jinja2 import TemplateError [as 別名]
def render(self, content, context=None):
from jinja2 import TemplateError
try:
return True, self.template.render(context or self.context(content))
except TemplateError:
logger.warning("Jinja render failed", exc_info=True)
return False, None