我们从Python开源项目中,提取了以下28个代码示例,用于说明如何使用jinja2.TemplateSyntaxError()。
def write(self, file_path: Path, template: str, context: dict={}, preserve: bool = False): """Using a template file name it renders a template into a file given a context """ if not context: context = self.context error = False try: self._write(file_path, template, context, preserve) except TemplateSyntaxError as exc: message = '{0}:{1} error: {2}'.format(exc.filename, exc.lineno, exc.message) click.secho(message, fg='red') error = True except TemplateNotFound as exc: message = '{0} error: Template not found'.format(exc.name) click.secho(message, fg='red') error = True except TemplateError as exc: message = 'error: {0}'.format(exc.message) click.secho(message, fg='red') error = True if error and Generator.strict: sys.exit(-1)
def load_config(path='.boss.yml'): loader = j.FileSystemLoader('.') try: template = loader.load(j.Environment(), path, os.environ) yml = template.render() doc = yaml.load(yml) return transform_config(doc) except j.TemplateNotFound: error = 'Error loading {}: not found'.format(path) raise ConfigurationError(error) except j.TemplateSyntaxError as e: error = 'Error loading {}: {}, line {}'.format(path, e, e.lineno) raise ConfigurationError(error) except IOError as e: error = 'Error loading {}: {}'.format(path, e.strerror) raise ConfigurationError(error) except v.Invalid as e: error = 'Error validating {}: {}'.format(path, e) raise ConfigurationError(error)
def get_template(self, template_name): try: return Template(self.env.get_template(template_name)) except jinja2.TemplateNotFound as exc: six.reraise( TemplateDoesNotExist, TemplateDoesNotExist(exc.name, backend=self), sys.exc_info()[2], ) except jinja2.TemplateSyntaxError as exc: new = TemplateSyntaxError(exc.args) new.template_debug = get_exception_info(exc) six.reraise(TemplateSyntaxError, new, sys.exc_info()[2])
def test_syntax_error(self): # XXX: the .*? is necessary for python3 which does not hide # some of the stack frames we don't want to show. Not sure # what's up with that, but that is not that critical. Should # be fixed though. self.assert_traceback_matches(lambda: env.get_template('syntaxerror.html'), r'''(?sm) File ".*?syntaxerror.html", line 4, in (template|<module>) \{% endif %\}.*? (jinja2\.exceptions\.)?TemplateSyntaxError: Encountered unknown tag 'endif'. Jinja was looking for the following tags: 'endfor' or 'else'. The innermost block that needs to be closed is 'for'. ''')
def test_regular_syntax_error(self): def test(): raise TemplateSyntaxError('wtf', 42) self.assert_traceback_matches(test, r''' File ".*debug.pyc?", line \d+, in test raise TemplateSyntaxError\('wtf', 42\) (jinja2\.exceptions\.)?TemplateSyntaxError: wtf line 42''')
def get_template(self, template_name): try: return Template(self.env.get_template(template_name), self) except jinja2.TemplateNotFound as exc: six.reraise( TemplateDoesNotExist, TemplateDoesNotExist(exc.name, backend=self), sys.exc_info()[2], ) except jinja2.TemplateSyntaxError as exc: new = TemplateSyntaxError(exc.args) new.template_debug = get_exception_info(exc) six.reraise(TemplateSyntaxError, new, sys.exc_info()[2])
def parse(self, template_name): with io.open(template_name, mode='rb') as file: try: template = self.env.parse(file.read().decode(self.charset)) except jinja2.TemplateSyntaxError as e: raise TemplateSyntaxError(str(e)) except jinja2.TemplateNotFound as e: raise TemplateDoesNotExist(str(e)) return template
def fail(self, message): raise TemplateSyntaxError(message, self.token.lineno, self.stream.name, self.stream.filename)
def __process_template__(self, renderer, template_name, out_dir, add_model_name=None): try: tmplSplit = template_name.split('.') if add_model_name is None: outfile = tmplSplit[0] + '.' + tmplSplit[1] else: outfile = tmplSplit[0] + '_' + \ add_model_name + '.' + tmplSplit[1] renderer.write(out_dir / outfile, template_name) except j2.TemplateSyntaxError as e: print("Exception in ", template_name, ":") raise e
def test_extract_jinja_error_syntax_error(data_dir): tpl_name = 'template_with_syntax_error.txt' try: templates.render(unicode(data_dir), tpl_name, {}) except jinja2.TemplateSyntaxError: stack, error = templates.extract_jinja_error(sys.exc_info()) tpl_path = data_dir.join(tpl_name) assert stack == [ ' File "%s", line 1' % tpl_path, ' {{ foo', ] assert error == "Syntax error: unexpected end of template, expected " \ "'end of print statement'"
def extract_jinja_error(exc_info, fnames_prefix=None): ''' Extract relevant informations from a Jinja2 exception. *exc_info* should be a ``(exc_type, exc_value, traceback)`` tuple, as returned by :func:`sys.exc_info`. Return a ``(stack, error)`` tuple, where *stack* a list of lines describing the stack that led to the error, and *error* the description of the error. Raise a :class:`TypeError` if the error is not a supported Jinja2 error. ''' exc_type, exc_value, tb = exc_info if exc_type is jinja2.UndefinedError: prefix = u'Undefined variable' elif exc_type is jinja2.TemplateSyntaxError: prefix = u'Syntax error' else: raise TypeError(exc_type) stack_lines = [] jinja_tb = [x for x in traceback.extract_tb(tb) if x[2] in ('top-level template code', 'template')] for file_name, line, func_name, text in jinja_tb: if fnames_prefix is not None: file_name = file_name[len(fnames_prefix) + 1:] stack_lines.append(u' File "%s", line %s' % (file_name, line)) stack_lines.append(u' %s' % text) error_details = unicode(exc_value) error_details = error_details.rstrip('.') return stack_lines, u'%s: %s' % (prefix, error_details)
def test_template_string_error_broken_string(self, brigade): with pytest.raises(BrigadeExecutionError) as e: brigade.run(text.template_string, template=broken_j2) assert len(e.value.failed_hosts) == len(brigade.inventory.hosts) for exc in e.value.failed_hosts.values(): assert isinstance(exc, TemplateSyntaxError)
def test_template_file_error_broken_file(self, brigade): with pytest.raises(BrigadeExecutionError) as e: brigade.run(text.template_file, template='broken.j2', path=data_dir) assert len(e.value.failed_hosts) == len(brigade.inventory.hosts) for exc in e.value.failed_hosts.values(): assert isinstance(exc, TemplateSyntaxError)
def get_template(self, template_name): try: return Template(self.env.get_template(template_name)) except jinja2.TemplateNotFound as exc: six.reraise(TemplateDoesNotExist, TemplateDoesNotExist(exc.args), sys.exc_info()[2]) except jinja2.TemplateSyntaxError as exc: six.reraise(TemplateSyntaxError, TemplateSyntaxError(exc.args), sys.exc_info()[2])
def run(self, results): """Writes report. @param results: Cuckoo results dict. @raise CuckooReportError: if fails to write report. """ if not HAVE_JINJA2: raise CuckooReportError("Failed to generate HTML report: " "Jinja2 Python library is not installed") shots_path = os.path.join(self.analysis_path, "shots") if os.path.exists(shots_path): shots = [] counter = 1 for shot_name in os.listdir(shots_path): if not shot_name.endswith(".jpg"): continue shot_path = os.path.join(shots_path, shot_name) if os.path.getsize(shot_path) == 0: continue shot = {} shot["id"] = os.path.splitext(File(shot_path).get_name())[0] shot["data"] = base64.b64encode(open(shot_path, "rb").read()) shots.append(shot) counter += 1 shots.sort(key=lambda shot: shot["id"]) results["shots"] = shots else: results["shots"] = [] env = Environment(autoescape=True) env.loader = FileSystemLoader(os.path.join(CUCKOO_ROOT, "data", "html")) try: tpl = env.get_template("report.html") html = tpl.render({"results": results, "summary_report" : False}) except UndefinedError as e: raise CuckooReportError("Failed to generate summary HTML report: {} ".format(e)) except TemplateNotFound as e: raise CuckooReportError("Failed to generate summary HTML report: {} {} ".format(e, e.name)) except (TemplateSyntaxError, TemplateAssertionError) as e: raise CuckooReportError("Failed to generate summary HTML report: {} on {}, line {} ".format(e, e.name, e.lineno)) try: with codecs.open(os.path.join(self.reports_path, "report.html"), "w", encoding="utf-8") as report: report.write(html) except (TypeError, IOError) as e: raise CuckooReportError("Failed to write HTML report: %s" % e) return True