Python jinja2.TemplateError() Examples
The following are 25
code examples of jinja2.TemplateError().
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: bonding.py From baremetal-deploy with Apache License 2.0 | 6 votes |
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
Example #2
Source File: package_path_loader.py From allura with Apache License 2.0 | 6 votes |
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]))
Example #3
Source File: test_package_path_loader.py From allura with Apache License 2.0 | 6 votes |
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)
Example #4
Source File: test_package_path_loader.py From allura with Apache License 2.0 | 6 votes |
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)
Example #5
Source File: templating.py From statik with MIT License | 6 votes |
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)
Example #6
Source File: bonding.py From baremetal-deploy with Apache License 2.0 | 6 votes |
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
Example #7
Source File: bonding.py From baremetal-deploy with Apache License 2.0 | 6 votes |
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
Example #8
Source File: bonding.py From baremetal-deploy with Apache License 2.0 | 6 votes |
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)
Example #9
Source File: __init__.py From hiyapyco with GNU General Public License v3.0 | 6 votes |
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
Example #10
Source File: publish.py From guildai with Apache License 2.0 | 6 votes |
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)
Example #11
Source File: swagger2rst.py From swagger2rst with MIT License | 6 votes |
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
Example #12
Source File: publish.py From guildai with Apache License 2.0 | 5 votes |
def runfile_link(self, path): if self.run_dest is None: raise TemplateError( "runfile_link cannot be used in this context " "(not publishing a run" ) if not isinstance(path, six.string_types): return "" maybe_runfile = os.path.join(self.run_dest, "runfiles", path) if os.path.isfile(maybe_runfile): return "runfiles/" + path return None
Example #13
Source File: bonding.py From baremetal-deploy with Apache License 2.0 | 5 votes |
def __render_ignition(self, parameters: dict) -> Text: try: template = self.__env.get_template(self.__ign_templ) return template.render(parameters) except jinja2.TemplateError as e: print("error processing", self.__ign_templ, ":", e) sys.exit(1)
Example #14
Source File: publish.py From guildai with Apache License 2.0 | 5 votes |
def __str__(self): if hasattr(self._e, "filename"): return self._default_str() else: return super(TemplateError, self).__str__()
Example #15
Source File: errors.py From signac-flow with BSD 3-Clause "New" or "Revised" License | 5 votes |
def err(self, msg, caller): raise jinja2.TemplateError(msg)
Example #16
Source File: inheritance.py From Flask with Apache License 2.0 | 5 votes |
def test_double_extends(self): """Ensures that a template with more than 1 {% extends ... %} usage raises a ``TemplateError``. """ try: tmpl = env.get_template('doublee') except Exception as e: assert isinstance(e, TemplateError)
Example #17
Source File: publish.py From guildai with Apache License 2.0 | 5 votes |
def __init__(self, e): super(TemplateError, self).__init__(e) self._e = e
Example #18
Source File: inheritance.py From Flask with Apache License 2.0 | 5 votes |
def test_double_extends(self): """Ensures that a template with more than 1 {% extends ... %} usage raises a ``TemplateError``. """ try: tmpl = env.get_template('doublee') except Exception as e: assert isinstance(e, TemplateError)
Example #19
Source File: package_path_loader.py From allura with Apache License 2.0 | 5 votes |
def _load_rules(self): """ Load and pre-process the rules from the entry points. Rules are specified per-tool as a list of the form: template_path_rules = [ ['>', 'tool1'], # this tool must be resolved before tool1 ['<', 'tool2'], # this tool must be resolved after tool2 ['=', 'tool3'], # this tool replaces all of tool3's templates ] Returns two lists of rules, order_rules and replacement_rules. order_rules represents all of the '>' and '<' rules and are returned as a list of pairs of the form ('a', 'b') indicating that path 'a' must come before path 'b'. replacement_rules represent all of the '=' rules and are returned as a dictionary mapping the paths to replace to the paths to replace with. """ order_rules = [] replacement_rules = {} for ep in iter_entry_points(self.override_entrypoint): for rule in getattr(ep.load(), 'template_path_rules', []): if rule[0] == '>': order_rules.append((ep.name, rule[1])) elif rule[0] == '=': replacement_rules[rule[1]] = ep.name elif rule[0] == '<': order_rules.append((rule[1], ep.name)) else: raise jinja2.TemplateError( 'Unknown template path rule in %s: %s' % ( ep.name, ' '.join(rule))) return order_rules, replacement_rules
Example #20
Source File: __init__.py From resolwe with Apache License 2.0 | 5 votes |
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
Example #21
Source File: inheritance.py From Flask-P2P with MIT License | 5 votes |
def test_double_extends(self): """Ensures that a template with more than 1 {% extends ... %} usage raises a ``TemplateError``. """ try: tmpl = env.get_template('doublee') except Exception as e: assert isinstance(e, TemplateError)
Example #22
Source File: jinja_transform.py From kibitzr with MIT License | 5 votes |
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
Example #23
Source File: jinja2.py From forge with Apache License 2.0 | 5 votes |
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))
Example #24
Source File: __init__.py From resolwe with Apache License 2.0 | 5 votes |
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])
Example #25
Source File: swagger2rst.py From swagger2rst with MIT License | 4 votes |
def main(): if sys.version_info.major == 2: sys.stdout = codecs.getwriter('utf-8')(sys.stdout) args = parse_argv() available_formats = ('rst',) if args.format not in available_formats: sys.exit('Invalid output format') doc_module = importlib.import_module('swg2rst.utils.{}'.format(args.format)) _file = sys.stdin if args.path == '-' else _open_file(args.path) try: doc = _parse_file(_file) except ValueError: sys.exit('Invalid file format. File must be in "yaml" or "json" format.') finally: if args.path != '-': _file.close() if doc is None: sys.exit('File is empty') examples = None if args.examples: with _open_file(args.examples) as _file: try: examples = _parse_file(_file) except ValueError: sys.exit('Invalid examples file format. File must be in "yaml" or "json" format.') try: swagger_doc = doc_module.SwaggerObject(doc, examples=examples) except ConverterError as err: sys.exit(err) template = prepare_template(args, doc_module) try: rst_doc = template.render(doc=swagger_doc, inline=args.inline) except (ConverterError, TemplateError) as err: status = err if isinstance(err, TemplateError): status = 'Template Error: {}'.format(err) sys.exit(status) if args.output: with codecs.open(args.output, mode='w', encoding='utf-8') as f: f.write(rst_doc) else: sys.stdout.write(rst_doc)