Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
def __init__(self, value, template, namespaces=None, lineno=-1, offset=-1):
if ' in ' not in value:
raise TemplateSyntaxError('"in" keyword missing in "for" directive',
template.filepath, lineno, offset)
assign, value = value.split(' in ', 1)
ast = _parse(assign, 'exec')
value = 'iter(%s)' % value.strip()
self.assign = _assignment(ast.body[0].value)
self.filename = template.filepath
Directive.__init__(self, value, template, namespaces, lineno, offset)
offset = text.find(PREFIX, pos)
if offset < 0 or offset == end - 1:
break
next = text[offset + 1]
if next == '{':
if offset > pos:
yield False, text[pos:offset]
pos = offset + 2
level = 1
while level:
match = token_re.match(text, pos)
if match is None or not match.group():
# if there isn't a match or the match is the empty
# string, we're not going to match up braces ever
raise TemplateSyntaxError('invalid syntax', filepath,
*textpos[1:])
pos = match.end()
tstart, tend = match.regs[3]
token = text[tstart:tend]
if token == '{':
level += 1
elif token == '}':
level -= 1
yield True, text[offset + 2:pos - 1]
elif next in NAMESTART:
if offset > pos:
yield False, text[pos:offset]
pos = offset
pos += 1
while pos < end:
def __init__(self, message, filename=None, lineno=-1, offset=-1):
"""Create the exception
:param message: the error message
:param filename: the filename of the template
:param lineno: the number of line in the template at which the error
occurred
:param offset: the column number at which the error occurred
"""
if isinstance(message, SyntaxError) and message.lineno is not None:
message = str(message).replace(' (line %d)' % message.lineno, '')
TemplateError.__init__(self, message, filename, lineno)
class BadDirectiveError(TemplateSyntaxError):
"""Exception raised when an unknown directive is encountered when parsing
a template.
An unknown directive is any attribute using the namespace for directives,
with a local name that doesn't match any registered directive.
"""
def __init__(self, name, filename=None, lineno=-1):
"""Create the exception
:param name: the name of the directive
:param filename: the filename of the template
:param lineno: the number of line in the template at which the error
occurred
"""
TemplateSyntaxError.__init__(self, 'bad directive "%s"' % name,
prefixes = {}
fallbacks = []
includes = []
xinclude_ns = Namespace(self.XINCLUDE_NAMESPACE)
for kind, data, pos in stream:
stream = streams[-1]
if kind is START:
# Record any directive attributes in start tags
tag, attrs = data
if tag in xinclude_ns:
if tag.localname == 'include':
include_href = attrs.get('href')
if not include_href:
raise TemplateSyntaxError('Include misses required '
'attribute "href"',
self.filepath, *pos[1:])
includes.append((include_href, attrs.get('parse')))
streams.append([])
elif tag.localname == 'fallback':
streams.append([])
fallbacks.append(streams[-1])
else:
stream.append((kind, (tag, attrs), pos))
elif kind is END:
if fallbacks and data == xinclude_ns['fallback']:
assert streams.pop() is fallbacks[-1]
elif data == xinclude_ns['include']:
fallback = None
if len(fallbacks) == len(includes):
self.vars = []
value = value.strip()
try:
ast = _parse(value, 'exec')
for node in ast.body:
if not isinstance(node, _ast.Assign):
raise TemplateSyntaxError('only assignment allowed in '
'value of the "with" directive',
template.filepath, lineno, offset)
self.vars.append(([_assignment(n) for n in node.targets],
Expression(node.value, template.filepath,
lineno, lookup=template.lookup)))
except SyntaxError, err:
err.msg += ' in expression "%s" of "%s" directive' % (value,
self.tagname)
raise TemplateSyntaxError(err, template.filepath, lineno,
offset + (err.offset or 0))
for kind, data, pos in source:
if kind is TEXT:
for kind, data, pos in interpolate(data, self.filepath, pos[1],
pos[2], lookup=self.lookup):
stream.append((kind, data, pos))
elif kind is PI and data[0] == 'python':
if not self.allow_exec:
raise TemplateSyntaxError('Python code blocks not allowed',
self.filepath, *pos[1:])
try:
suite = Suite(data[1], self.filepath, pos[1],
lookup=self.lookup)
except SyntaxError, err:
raise TemplateSyntaxError(err, self.filepath,
pos[1] + (err.lineno or 1) - 1,
pos[2] + (err.offset or 0))
stream.append((EXEC, suite, pos))
elif kind is COMMENT:
if not data.lstrip().startswith('!'):
stream.append((kind, data, pos))
else:
stream.append((kind, data, pos))
return stream
self.vars = []
value = value.strip()
try:
ast = _parse(value, 'exec')
for node in ast.body:
if not isinstance(node, _ast.Assign):
raise TemplateSyntaxError('only assignment allowed in '
'value of the "with" directive',
template.filepath, lineno, offset)
self.vars.append(([_assignment(n) for n in node.targets],
Expression(node.value, template.filepath,
lineno, lookup=template.lookup)))
except SyntaxError as err:
err.msg += ' in expression "%s" of "%s" directive' % (value,
self.tagname)
raise TemplateSyntaxError(err, template.filepath, lineno,
offset + (err.offset or 0))
def __init__(self, value, template, namespaces=None, lineno=-1, offset=-1):
Directive.__init__(self, None, template, namespaces, lineno, offset)
self.vars = []
value = value.strip()
try:
ast = _parse(value, 'exec')
for node in ast.body:
if not isinstance(node, _ast.Assign):
raise TemplateSyntaxError('only assignment allowed in '
'value of the "with" directive',
template.filepath, lineno, offset)
self.vars.append(([_assignment(n) for n in node.targets],
Expression(node.value, template.filepath,
lineno, lookup=template.lookup)))
except SyntaxError as err:
err.msg += ' in expression "%s" of "%s" directive' % (value,
self.tagname)
raise TemplateSyntaxError(err, template.filepath, lineno,
offset + (err.offset or 0))
prefixes = {}
fallbacks = []
includes = []
xinclude_ns = Namespace(self.XINCLUDE_NAMESPACE)
for kind, data, pos in stream:
stream = streams[-1]
if kind is START:
# Record any directive attributes in start tags
tag, attrs = data
if tag in xinclude_ns:
if tag.localname == 'include':
include_href = attrs.get('href')
if not include_href:
raise TemplateSyntaxError('Include misses required '
'attribute "href"',
self.filepath, *pos[1:])
includes.append((include_href, attrs.get('parse')))
streams.append([])
elif tag.localname == 'fallback':
streams.append([])
fallbacks.append(streams[-1])
else:
stream.append((kind, (tag, attrs), pos))
elif kind is END:
if fallbacks and data == xinclude_ns['fallback']:
assert streams.pop() is fallbacks[-1]
elif data == xinclude_ns['include']:
fallback = None
if len(fallbacks) == len(includes):
def _parse_expr(cls, expr, template, lineno=-1, offset=-1):
"""Parses the given expression, raising a useful error message when a
syntax error is encountered.
"""
try:
return expr and Expression(expr, template.filepath, lineno,
lookup=template.lookup) or None
except SyntaxError, err:
err.msg += ' in expression "%s" of "%s" directive' % (expr,
cls.tagname)
raise TemplateSyntaxError(err, template.filepath, lineno,
offset + (err.offset or 0))
_parse_expr = classmethod(_parse_expr)