desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'Checks for existence of a token, given user_id, subject and token. :param user_id: User unique ID. :param subject: The subject of the key. Examples: - \'auth\' - \'signup\' :param token: The token string to be validated. :returns: A :class:`UserToken` or None if the token does not exist.'
@classmethod def validate_token(cls, user_id, subject, token):
return (cls.token_model.get(user=user_id, subject=subject, token=token) is not None)
'Creates a new authorization token for a given user ID. :param user_id: User unique ID. :returns: A string with the authorization token.'
@classmethod def create_auth_token(cls, user_id):
return cls.token_model.create(user_id, 'auth').token
'Deletes a given authorization token. :param user_id: User unique ID. :param token: A string with the authorization token.'
@classmethod def delete_auth_token(cls, user_id, token):
cls.token_model.get_key(user_id, 'auth', token).delete()
'Creates a new user. :param auth_id: A string that is unique to the user. Users may have multiple auth ids. Example auth ids: - own:username - own:email@example.com - google:username - yahoo:username The value of `auth_id` must be unique. :param unique_properties: Sequence of extra property names that must be unique. :...
@classmethod def create_user(cls, auth_id, unique_properties=None, **user_values):
assert (user_values.get('password') is None), 'Use password_raw instead of password to create new users.' assert (not isinstance(auth_id, list)), 'Creating a user with multiple auth_ids is not allowed, please provide a single auth_id.' if ('pass...
'Initializes a URL route. :param template: A route template to match against ``environ[\'SERVER_NAME\']``. See a syntax description in :meth:`webapp2.Route.__init__`. :param routes: A list of :class:`webapp2.Route` instances.'
def __init__(self, template, routes):
super(DomainRoute, self).__init__(routes) self.template = template
'Initializes a URL route. :param prefix: The prefix to be prepended. :param routes: A list of :class:`webapp2.Route` instances.'
def __init__(self, prefix, routes):
super(NamePrefixRoute, self).__init__(routes) self.prefix = prefix for route in self.get_routes(): setattr(route, self._attr, (prefix + getattr(route, self._attr)))
'Initializes a URL route. :param prefix: The prefix to be prepended. It must start with a slash but not end with a slash. :param routes: A list of :class:`webapp2.Route` instances.'
def __init__(self, prefix, routes):
assert (prefix.startswith('/') and (not prefix.endswith('/'))), 'Path prefixes must start with a slash but not end with a slash.' super(PathPrefixRoute, self).__init__(prefix, routes)
'Initializes a URL route. Extra arguments compared to :meth:`webapp2.Route.__init__`: :param redirect_to: A URL string or a callable that returns a URL. If set, this route is used to redirect to it. The callable is called passing ``(handler, *args, **kwargs)`` as arguments. This is a convenience to use :class:`Redirect...
def __init__(self, template, handler=None, name=None, defaults=None, build_only=False, handler_method=None, methods=None, schemes=None, redirect_to=None, redirect_to_name=None, strict_slash=False):
super(RedirectRoute, self).__init__(template, handler=handler, name=name, defaults=defaults, build_only=build_only, handler_method=handler_method, methods=methods, schemes=schemes) if (strict_slash and (not name)): raise ValueError('Routes with strict_slash must have a name.') self...
'Generator to get all routes that can be matched from a route. :yields: This route or all nested routes that can be matched.'
def get_match_routes(self):
if self.redirect_to_name: main_route = self._get_redirect_route(name=self.redirect_to_name) else: main_route = self if (not self.build_only): if (self.strict_slash is True): if self.template.endswith('/'): template = self.template[:(-1)] else: ...
'Increments the loop depth so that write functions know if they are in a loop.'
def enter_loop(self):
self._loop_depth += 1
'Reverse of enter_loop.'
def leave_loop(self):
self._loop_depth -= 1
'True if we are in a loop.'
@property def in_loop(self):
return (self._loop_depth > 0)
'Writes stuff to the stream.'
def write(self, s):
self.stream.write(s.encode(settings.FILE_CHARSET))
'Open a variable tag, write to the string to the stream and close.'
def print_expr(self, expr):
self.start_variable() self.write(expr) self.end_variable()
'Start a variable.'
def start_variable(self):
self.write(self.variable_start_string) self._post_open()
'End a variable.'
def end_variable(self, always_safe=False):
if ((not always_safe) and self.autoescape and (not self.use_jinja_autoescape)): self.write('|e') self._pre_close() self.write(self.variable_end_string)
'Starts a block.'
def start_block(self):
self.write(self.block_start_string) self._post_open()
'Ends a block.'
def end_block(self):
self._pre_close() self.write(self.block_end_string)
'Like `print_expr` just for blocks.'
def tag(self, name):
self.start_block() self.write(name) self.end_block()
'Prints a variable. This performs variable name transformation.'
def variable(self, name):
self.write(self.translate_variable_name(name))
'Writes a value as literal.'
def literal(self, value):
value = repr(value) if (value[:2] in ('u"', "u'")): value = value[1:] self.write(value)
'Dumps a list of filters.'
def filters(self, filters, is_block=False):
want_pipe = (not is_block) for (filter, args) in filters: name = self.get_filter_name(filter) if (name is None): self.warn(('Could not find filter %s' % name)) continue if ((name not in DEFAULT_FILTERS) and (name not in self._filters_warned)): ...
'Returns the location for an origin and position tuple as name and lineno.'
def get_location(self, origin, position):
if hasattr(origin, 'source'): source = origin.source name = '<unknown source>' else: source = origin.loader(origin.loadname, origin.dirs)[0] name = origin.loadname lineno = (len(_newline_re.findall(source[:position[0]])) + 1) return (name, lineno)
'Prints a warning to the error stream.'
def warn(self, message, node=None):
if ((node is not None) and hasattr(node, 'source')): (filename, lineno) = self.get_location(*node.source) message = ('[%s:%d] %s' % (filename, lineno, message)) print >>self.error_stream, message
'Performs variable name translation.'
def translate_variable_name(self, var):
if ((self.in_loop and (var == 'forloop')) or var.startswith('forloop.')): var = var[3:] for (reg, rep, unless) in self.var_re: no_unless = ((unless and unless.search(var)) or True) if (reg.search(var) and no_unless): var = reg.sub(rep, var) break return var
'Returns the filter name for a filter function or `None` if there is no such filter.'
def get_filter_name(self, filter):
if (filter not in _resolved_filters): for library in libraries.values(): for (key, value) in library.filters.iteritems(): _resolved_filters[value] = key return _resolved_filters.get(filter, None)
'Invokes the node handler for a node.'
def node(self, node):
for (cls, handler) in self.node_handlers.iteritems(): if ((type(node) is cls) or (type(node).__name__ == cls)): handler(self, node) break else: self.warn(('Untranslatable node %s.%s found' % (node.__module__, node.__class__.__name__)), node)
'Calls node() for every node in the iterable passed.'
def body(self, nodes):
for node in nodes: self.node(node)
'Test a token against a token expression. This can either be a token type or ``\'token_type:token_value\'``. This can only test against string values and types.'
def test(self, expr):
if (self.type == expr): return True elif (':' in expr): return (expr.split(':', 1) == [self.type, self.value]) return False
'Test against multiple token expressions.'
def test_any(self, *iterable):
for expr in iterable: if self.test(expr): return True return False
'Push a token back to the stream.'
def push(self, token):
self._pushed.append(token)
'Look at the next token.'
def look(self):
old_token = next(self) result = self.current self.push(result) self.current = old_token return result
'Got n tokens ahead.'
def skip(self, n=1):
for x in xrange(n): next(self)
'Perform the token test and return the token if it matched. Otherwise the return value is `None`.'
def next_if(self, expr):
if self.current.test(expr): return next(self)
'Like :meth:`next_if` but only returns `True` or `False`.'
def skip_if(self, expr):
return (self.next_if(expr) is not None)
'Go one token ahead and return the old one'
def next(self):
rv = self.current if self._pushed: self.current = self._pushed.popleft() elif (self.current.type is not TOKEN_EOF): try: self.current = self._next() except StopIteration: self.close() return rv
'Close the stream.'
def close(self):
self.current = Token(self.current.lineno, TOKEN_EOF, '') self._next = None self.closed = True
'Expect a given token type and return it. This accepts the same argument as :meth:`jinja2.lexer.Token.test`.'
def expect(self, expr):
if (not self.current.test(expr)): expr = describe_token_expr(expr) if (self.current.type is TOKEN_EOF): raise TemplateSyntaxError(('unexpected end of template, expected %r.' % expr), self.current.lineno, self.name, self.filename) raise TemplateSyntaxError(('expecte...
'Called for strings and template data to normlize it to unicode.'
def _normalize_newlines(self, value):
return newline_re.sub(self.newline_sequence, value)
'Calls tokeniter + tokenize and wraps it in a token stream.'
def tokenize(self, source, name=None, filename=None, state=None):
stream = self.tokeniter(source, name, filename, state) return TokenStream(self.wrap(stream, name, filename), name, filename)
'This is called with the stream as returned by `tokenize` and wraps every token in a :class:`Token` and converts the value.'
def wrap(self, stream, name=None, filename=None):
for (lineno, token, value) in stream: if (token in ignored_tokens): continue elif (token == 'linestatement_begin'): token = 'block_begin' elif (token == 'linestatement_end'): token = 'block_end' elif (token in ('raw_begin', 'raw_end')): ...
'This method tokenizes the text and returns the tokens in a generator. Use this method if you just want to tokenize a template.'
def tokeniter(self, source, name, filename=None, state=None):
source = '\n'.join(unicode(source).splitlines()) pos = 0 lineno = 1 stack = ['root'] if ((state is not None) and (state != 'root')): assert (state in ('variable', 'block')), 'invalid state' stack.append((state + '_begin')) else: state = 'root' statetokens = self.ru...
'Python 2.4 compatibility.'
def _remove(self, obj):
for (idx, item) in enumerate(self._queue): if (item == obj): del self._queue[idx] break
'Return an shallow copy of the instance.'
def copy(self):
rv = self.__class__(self.capacity) rv._mapping.update(self._mapping) rv._queue = deque(self._queue) return rv
'Return an item from the cache dict or `default`'
def get(self, key, default=None):
try: return self[key] except KeyError: return default
'Set `default` if the key is not in the cache otherwise leave unchanged. Return the value of this key.'
def setdefault(self, key, default=None):
try: return self[key] except KeyError: self[key] = default return default
'Clear the cache.'
def clear(self):
self._wlock.acquire() try: self._mapping.clear() self._queue.clear() finally: self._wlock.release()
'Check if a key exists in this cache.'
def __contains__(self, key):
return (key in self._mapping)
'Return the current size of the cache.'
def __len__(self):
return len(self._mapping)
'Get an item from the cache. Moves the item up so that it has the highest priority then. Raise an `KeyError` if it does not exist.'
def __getitem__(self, key):
rv = self._mapping[key] if (self._queue[(-1)] != key): try: self._remove(key) except ValueError: pass self._append(key) return rv
'Sets the value for an item. Moves the item up so that it has the highest priority then.'
def __setitem__(self, key, value):
self._wlock.acquire() try: if (key in self._mapping): try: self._remove(key) except ValueError: pass elif (len(self._mapping) == self.capacity): del self._mapping[self._popleft()] self._append(key) self._mapping[...
'Remove an item from the cache dict. Raise an `KeyError` if it does not exist.'
def __delitem__(self, key):
self._wlock.acquire() try: del self._mapping[key] try: self._remove(key) except ValueError: pass finally: self._wlock.release()
'Return a list of items.'
def items(self):
result = [(key, self._mapping[key]) for key in list(self._queue)] result.reverse() return result
'Iterate over all items.'
def iteritems(self):
return iter(self.items())
'Return a list of all values.'
def values(self):
return [x[1] for x in self.items()]
'Iterate over all values.'
def itervalue(self):
return iter(self.values())
'Return a list of all keys ordered by most recent usage.'
def keys(self):
return list(self)
'Iterate over all keys in the cache dict, ordered by the most recent usage.'
def iterkeys(self):
return reversed(tuple(self._queue))
'Iterate over the values in the cache dict, oldest items coming first.'
def __reversed__(self):
return iter(tuple(self._queue))
'Resets the cycle.'
def reset(self):
self.pos = 0
'Returns the current item.'
@property def current(self):
return self.items[self.pos]
'Goes one item ahead and returns it.'
def next(self):
rv = self.current self.pos = ((self.pos + 1) % len(self.items)) return rv
'Create a copy of this extension bound to another environment.'
def bind(self, environment):
rv = object.__new__(self.__class__) rv.__dict__.update(self.__dict__) rv.environment = environment return rv
'This method is called before the actual lexing and can be used to preprocess the source. The `filename` is optional. The return value must be the preprocessed source.'
def preprocess(self, source, name, filename=None):
return source
'It\'s passed a :class:`~jinja2.lexer.TokenStream` that can be used to filter tokens returned. This method has to return an iterable of :class:`~jinja2.lexer.Token`\s, but it doesn\'t have to return a :class:`~jinja2.lexer.TokenStream`. In the `ext` folder of the Jinja2 source distribution there is a file called `inli...
def filter_stream(self, stream):
return stream
'If any of the :attr:`tags` matched this method is called with the parser as first argument. The token the parser stream is pointing at is the name token that matched. This method has to return one or a list of multiple nodes.'
def parse(self, parser):
raise NotImplementedError()
'Return an attribute node for the current extension. This is useful to pass constants on extensions to generated template code. self.attr(\'_my_attribute\', lineno=lineno)'
def attr(self, name, lineno=None):
return nodes.ExtensionAttribute(self.identifier, name, lineno=lineno)
'Call a method of the extension. This is a shortcut for :meth:`attr` + :class:`jinja2.nodes.Call`.'
def call_method(self, name, args=None, kwargs=None, dyn_args=None, dyn_kwargs=None, lineno=None):
if (args is None): args = [] if (kwargs is None): kwargs = [] return nodes.Call(self.attr(name, lineno=lineno), args, kwargs, dyn_args, dyn_kwargs, lineno=lineno)
'Parse a translatable tag.'
def parse(self, parser):
lineno = next(parser.stream).lineno num_called_num = False plural_expr = None variables = {} while (parser.stream.current.type != 'block_end'): if variables: parser.stream.expect('comma') if parser.stream.skip_if('colon'): break name = parser.stream.ex...
'Parse until the next block tag with a given name.'
def _parse_block(self, parser, allow_pluralize):
referenced = [] buf = [] while 1: if (parser.stream.current.type == 'data'): buf.append(parser.stream.current.value.replace('%', '%%')) next(parser.stream) elif (parser.stream.current.type == 'variable_begin'): next(parser.stream) name = parser...
'Generates a useful node from the data provided.'
def _make_node(self, singular, plural, variables, plural_expr, vars_referenced, num_called_num):
if ((not vars_referenced) and (not self.environment.newstyle_gettext)): singular = singular.replace('%%', '%') if plural: plural = plural.replace('%%', '%') if (plural_expr is None): gettext = nodes.Name('gettext', 'load') node = nodes.Call(gettext, [nodes.Const(singu...
'This method iterates over all fields that are defined and yields ``(key, value)`` tuples. Per default all fields are returned, but it\'s possible to limit that to some fields by providing the `only` parameter or to exclude some using the `exclude` parameter. Both should be sets or tuples of field names.'
def iter_fields(self, exclude=None, only=None):
for name in self.fields: if ((exclude is only is None) or ((exclude is not None) and (name not in exclude)) or ((only is not None) and (name in only))): try: (yield (name, getattr(self, name))) except AttributeError: pass
'Iterates over all direct child nodes of the node. This iterates over all fields and yields the values of they are nodes. If the value of a field is a list all the nodes in that list are returned.'
def iter_child_nodes(self, exclude=None, only=None):
for (field, item) in self.iter_fields(exclude, only): if isinstance(item, list): for n in item: if isinstance(n, Node): (yield n) elif isinstance(item, Node): (yield item)
'Find the first node of a given type. If no such node exists the return value is `None`.'
def find(self, node_type):
for result in self.find_all(node_type): return result
'Find all the nodes of a given type. If the type is a tuple, the check is performed for any of the tuple items.'
def find_all(self, node_type):
for child in self.iter_child_nodes(): if isinstance(child, node_type): (yield child) for result in child.find_all(node_type): (yield result)
'Reset the context of a node and all child nodes. Per default the parser will all generate nodes that have a \'load\' context as it\'s the most common one. This method is used in the parser to set assignment targets and other nodes to a store context.'
def set_ctx(self, ctx):
todo = deque([self]) while todo: node = todo.popleft() if ('ctx' in node.fields): node.ctx = ctx todo.extend(node.iter_child_nodes()) return self
'Set the line numbers of the node and children.'
def set_lineno(self, lineno, override=False):
todo = deque([self]) while todo: node = todo.popleft() if ('lineno' in node.attributes): if ((node.lineno is None) or override): node.lineno = lineno todo.extend(node.iter_child_nodes()) return self
'Set the environment for all nodes.'
def set_environment(self, environment):
todo = deque([self]) while todo: node = todo.popleft() node.environment = environment todo.extend(node.iter_child_nodes()) return self
'Return the value of the expression as constant or raise :exc:`Impossible` if this was not possible. An :class:`EvalContext` can be provided, if none is given a default context is created which requires the nodes to have an attached environment. .. versionchanged:: 2.4 the `eval_ctx` parameter was added.'
def as_const(self, eval_ctx=None):
raise Impossible()
'Check if it\'s possible to assign something to this node.'
def can_assign(self):
return False
'Return a const object if the value is representable as constant value in the generated code, otherwise it will raise an `Impossible` exception.'
@classmethod def from_untrusted(cls, value, lineno=None, environment=None):
from compiler import has_safe_repr if (not has_safe_repr(value)): raise Impossible() return cls(value, lineno=lineno, environment=environment)
'Remember all undeclared identifiers.'
def pull_locals(self, frame):
self.undeclared_identifiers.update(frame.identifiers.undeclared)
'Render a parent block.'
def super(self, name, current):
try: blocks = self.blocks[name] index = (blocks.index(current) + 1) blocks[index] except LookupError: return self.environment.undefined(('there is no parent block called %r.' % name), name='super') return BlockReference(name, self, blocks, index)
'Returns an item from the template context, if it doesn\'t exist `default` is returned.'
def get(self, key, default=None):
try: return self[key] except KeyError: return default
'Looks up a variable like `__getitem__` or `get` but returns an :class:`Undefined` object with the name of the name looked up.'
def resolve(self, key):
if (key in self.vars): return self.vars[key] if (key in self.parent): return self.parent[key] return self.environment.undefined(name=key)
'Get a new dict with the exported variables.'
def get_exported(self):
return dict(((k, self.vars[k]) for k in self.exported_vars))
'Return a copy of the complete context as dict including the exported variables.'
def get_all(self):
return dict(self.parent, **self.vars)
'Call the callable with the arguments and keyword arguments provided but inject the active context or environment as first argument if the callable is a :func:`contextfunction` or :func:`environmentfunction`.'
@internalcode def call(__self, __obj, *args, **kwargs):
if __debug__: __traceback_hide__ = True if isinstance(__obj, _context_function_types): if getattr(__obj, 'contextfunction', 0): args = ((__self,) + args) elif getattr(__obj, 'evalcontextfunction', 0): args = ((__self.eval_ctx,) + args) elif getattr(__obj, ...
'Internal helper function to create a derived context.'
def derived(self, locals=None):
context = new_context(self.environment, self.name, {}, self.parent, True, None, locals) context.vars.update(self.vars) context.eval_ctx = self.eval_ctx context.blocks.update(((k, list(v)) for (k, v) in self.blocks.iteritems())) return context
'Lookup a variable or raise `KeyError` if the variable is undefined.'
def __getitem__(self, key):
item = self.resolve(key) if isinstance(item, Undefined): raise KeyError(key) return item
'Super the block.'
@property def super(self):
if ((self._depth + 1) >= len(self._stack)): return self._context.environment.undefined(('there is no parent block called %r.' % self.name), name='super') return BlockReference(self.name, self._context, self._stack, (self._depth + 1))
'Cycles among the arguments with the current loop index.'
def cycle(self, *args):
if (not args): raise TypeError('no items for cycling given') return args[(self.index0 % len(args))]
'Regular callback function for undefined objects that raises an `UndefinedError` on call.'
@internalcode def _fail_with_undefined_error(self, *args, **kwargs):
if (self._undefined_hint is None): if (self._undefined_obj is missing): hint = ('%r is undefined' % self._undefined_name) elif (not isinstance(self._undefined_name, basestring)): hint = ('%s has no element %r' % (object_type_repr(self._undefined_obj), self._...
'Convenience method that raises `exc` with the message, passed line number or last line number as well as the current name and filename.'
def fail(self, msg, lineno=None, exc=TemplateSyntaxError):
if (lineno is None): lineno = self.stream.current.lineno raise exc(msg, lineno, self.name, self.filename)
'Called if the parser encounters an unknown tag. Tries to fail with a human readable error message that could help to identify the problem.'
def fail_unknown_tag(self, name, lineno=None):
return self._fail_ut_eof(name, self._end_token_stack, lineno)
'Like fail_unknown_tag but for end of template situations.'
def fail_eof(self, end_tokens=None, lineno=None):
stack = list(self._end_token_stack) if (end_tokens is not None): stack.append(end_tokens) return self._fail_ut_eof(None, stack, lineno)
'Are we at the end of a tuple?'
def is_tuple_end(self, extra_end_rules=None):
if (self.stream.current.type in ('variable_end', 'block_end', 'rparen')): return True elif (extra_end_rules is not None): return self.stream.current.test_any(extra_end_rules) return False
'Return a new free identifier as :class:`~jinja2.nodes.InternalName`.'
def free_identifier(self, lineno=None):
self._last_identifier += 1 rv = object.__new__(nodes.InternalName) nodes.Node.__init__(rv, ('fi%d' % self._last_identifier), lineno=lineno) return rv
'Parse a single statement.'
def parse_statement(self):
token = self.stream.current if (token.type != 'name'): self.fail('tag name expected', token.lineno) self._tag_stack.append(token.value) pop_tag = True try: if (token.value in _statement_keywords): return getattr(self, ('parse_' + self.stream.current.value))() ...
'Parse multiple statements into a list until one of the end tokens is reached. This is used to parse the body of statements as it also parses template data if appropriate. The parser checks first if the current token is a colon and skips it if there is one. Then it checks for the block end and parses until if one of...
def parse_statements(self, end_tokens, drop_needle=False):
self.stream.skip_if('colon') self.stream.expect('block_end') result = self.subparse(end_tokens) if (self.stream.current.type == 'eof'): self.fail_eof(end_tokens) if drop_needle: next(self.stream) return result