signature
stringlengths
8
3.44k
body
stringlengths
0
1.41M
docstring
stringlengths
1
122k
id
stringlengths
5
17
def options(self, *args, **kw):
kw['<STR_LIT>'] = '<STR_LIT>'<EOL>return self.open(*args, **kw)<EOL>
Like open but method is enforced to OPTIONS.
f5876:c5:m12
def trace(self, *args, **kw):
kw['<STR_LIT>'] = '<STR_LIT>'<EOL>return self.open(*args, **kw)<EOL>
Like open but method is enforced to TRACE.
f5876:c5:m13
def pbkdf2_hex(data, salt, iterations=DEFAULT_PBKDF2_ITERATIONS,<EOL>keylen=None, hashfunc=None):
rv = pbkdf2_bin(data, salt, iterations, keylen, hashfunc)<EOL>return to_native(codecs.encode(rv, '<STR_LIT>'))<EOL>
Like :func:`pbkdf2_bin` but returns a hex encoded string. .. versionadded:: 0.9 :param data: the data to derive. :param salt: the salt for the derivation. :param iterations: the number of iterations. :param keylen: the length of the resulting key. If not provided the digest size will be used. :param hashfunc: the hash function to use. This can either be the string name of a known hash function or a function from the hashlib module. Defaults to sha1.
f5877:m1
def pbkdf2_bin(data, salt, iterations=DEFAULT_PBKDF2_ITERATIONS,<EOL>keylen=None, hashfunc=None):
if isinstance(hashfunc, string_types):<EOL><INDENT>hashfunc = _hash_funcs[hashfunc]<EOL><DEDENT>elif not hashfunc:<EOL><INDENT>hashfunc = hashlib.sha1<EOL><DEDENT>salt = to_bytes(salt)<EOL>mac = hmac.HMAC(to_bytes(data), None, hashfunc)<EOL>if not keylen:<EOL><INDENT>keylen = mac.digest_size<EOL><DEDENT>def _pseudorandom(x, mac=mac):<EOL><INDENT>h = mac.copy()<EOL>h.update(x)<EOL>return bytearray(h.digest())<EOL><DEDENT>buf = bytearray()<EOL>for block in range_type(<NUM_LIT:1>, -(-keylen // mac.digest_size) + <NUM_LIT:1>):<EOL><INDENT>rv = u = _pseudorandom(salt + _pack_int(block))<EOL>for i in range_type(iterations - <NUM_LIT:1>):<EOL><INDENT>u = _pseudorandom(bytes(u))<EOL>rv = bytearray(starmap(xor, izip(rv, u)))<EOL><DEDENT>buf.extend(rv)<EOL><DEDENT>return bytes(buf[:keylen])<EOL>
Returns a binary digest for the PBKDF2 hash algorithm of `data` with the given `salt`. It iterates `iterations` time and produces a key of `keylen` bytes. By default SHA-1 is used as hash function, a different hashlib `hashfunc` can be provided. .. versionadded:: 0.9 :param data: the data to derive. :param salt: the salt for the derivation. :param iterations: the number of iterations. :param keylen: the length of the resulting key. If not provided the digest size will be used. :param hashfunc: the hash function to use. This can either be the string name of a known hash function or a function from the hashlib module. Defaults to sha1.
f5877:m2
def safe_str_cmp(a, b):
if _builtin_safe_str_cmp is not None:<EOL><INDENT>return _builtin_safe_str_cmp(a, b)<EOL><DEDENT>if len(a) != len(b):<EOL><INDENT>return False<EOL><DEDENT>rv = <NUM_LIT:0><EOL>if isinstance(a, bytes) and isinstance(b, bytes) and not PY2:<EOL><INDENT>for x, y in izip(a, b):<EOL><INDENT>rv |= x ^ y<EOL><DEDENT><DEDENT>else:<EOL><INDENT>for x, y in izip(a, b):<EOL><INDENT>rv |= ord(x) ^ ord(y)<EOL><DEDENT><DEDENT>return rv == <NUM_LIT:0><EOL>
This function compares strings in somewhat constant time. This requires that the length of at least one string is known in advance. Returns `True` if the two strings are equal or `False` if they are not. .. versionadded:: 0.7
f5877:m3
def gen_salt(length):
if length <= <NUM_LIT:0>:<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>return '<STR_LIT>'.join(_sys_rng.choice(SALT_CHARS) for _ in range_type(length))<EOL>
Generate a random string of SALT_CHARS with specified ``length``.
f5877:m4
def _hash_internal(method, salt, password):
if method == '<STR_LIT>':<EOL><INDENT>return password, method<EOL><DEDENT>if isinstance(password, text_type):<EOL><INDENT>password = password.encode('<STR_LIT:utf-8>')<EOL><DEDENT>if method.startswith('<STR_LIT>'):<EOL><INDENT>args = method[<NUM_LIT:7>:].split('<STR_LIT::>')<EOL>if len(args) not in (<NUM_LIT:1>, <NUM_LIT:2>):<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>method = args.pop(<NUM_LIT:0>)<EOL>iterations = args and int(args[<NUM_LIT:0>] or <NUM_LIT:0>) or DEFAULT_PBKDF2_ITERATIONS<EOL>is_pbkdf2 = True<EOL>actual_method = '<STR_LIT>' % (method, iterations)<EOL><DEDENT>else:<EOL><INDENT>is_pbkdf2 = False<EOL>actual_method = method<EOL><DEDENT>hash_func = _hash_funcs.get(method)<EOL>if hash_func is None:<EOL><INDENT>raise TypeError('<STR_LIT>' % method)<EOL><DEDENT>if is_pbkdf2:<EOL><INDENT>if not salt:<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>rv = pbkdf2_hex(password, salt, iterations,<EOL>hashfunc=hash_func)<EOL><DEDENT>elif salt:<EOL><INDENT>if isinstance(salt, text_type):<EOL><INDENT>salt = salt.encode('<STR_LIT:utf-8>')<EOL><DEDENT>rv = hmac.HMAC(salt, password, hash_func).hexdigest()<EOL><DEDENT>else:<EOL><INDENT>h = hash_func()<EOL>h.update(password)<EOL>rv = h.hexdigest()<EOL><DEDENT>return rv, actual_method<EOL>
Internal password hash helper. Supports plaintext without salt, unsalted and salted passwords. In case salted passwords are used hmac is used.
f5877:m5
def generate_password_hash(password, method='<STR_LIT>', salt_length=<NUM_LIT:8>):
salt = method != '<STR_LIT>' and gen_salt(salt_length) or '<STR_LIT>'<EOL>h, actual_method = _hash_internal(method, salt, password)<EOL>return '<STR_LIT>' % (actual_method, salt, h)<EOL>
Hash a password with the given method and salt with with a string of the given length. The format of the string returned includes the method that was used so that :func:`check_password_hash` can check the hash. The format for the hashed string looks like this:: method$salt$hash This method can **not** generate unsalted passwords but it is possible to set the method to plain to enforce plaintext passwords. If a salt is used, hmac is used internally to salt the password. If PBKDF2 is wanted it can be enabled by setting the method to ``pbkdf2:method:iterations`` where iterations is optional:: pbkdf2:sha1:2000$salt$hash pbkdf2:sha1$salt$hash :param password: the password to hash :param method: the hash method to use (one that hashlib supports), can optionally be in the format ``pbpdf2:<method>[:iterations]`` to enable PBKDF2. :param salt_length: the length of the salt in letters
f5877:m6
def check_password_hash(pwhash, password):
if pwhash.count('<STR_LIT:$>') < <NUM_LIT:2>:<EOL><INDENT>return False<EOL><DEDENT>method, salt, hashval = pwhash.split('<STR_LIT:$>', <NUM_LIT:2>)<EOL>return safe_str_cmp(_hash_internal(method, salt, password)[<NUM_LIT:0>], hashval)<EOL>
check a password against a given salted and hashed password value. In order to support unsalted legacy passwords this method supports plain text passwords, md5 and sha1 hashes (both salted and unsalted). Returns `True` if the password matched, `False` otherwise. :param pwhash: a hashed string like returned by :func:`generate_password_hash` :param password: the plaintext password to compare against the hash
f5877:m7
def safe_join(directory, filename):
filename = posixpath.normpath(filename)<EOL>for sep in _os_alt_seps:<EOL><INDENT>if sep in filename:<EOL><INDENT>return None<EOL><DEDENT><DEDENT>if os.path.isabs(filename) or filename.startswith('<STR_LIT>'):<EOL><INDENT>return None<EOL><DEDENT>return os.path.join(directory, filename)<EOL>
Safely join `directory` and `filename`. If this cannot be done, this function returns ``None``. :param directory: the base directory. :param filename: the untrusted filename relative to that directory.
f5877:m8
def run(namespace=None, action_prefix='<STR_LIT>', args=None):
if namespace is None:<EOL><INDENT>namespace = sys._getframe(<NUM_LIT:1>).f_locals<EOL><DEDENT>actions = find_actions(namespace, action_prefix)<EOL>if args is None:<EOL><INDENT>args = sys.argv[<NUM_LIT:1>:]<EOL><DEDENT>if not args or args[<NUM_LIT:0>] in ('<STR_LIT>', '<STR_LIT>'):<EOL><INDENT>return print_usage(actions)<EOL><DEDENT>elif args[<NUM_LIT:0>] not in actions:<EOL><INDENT>fail('<STR_LIT>' % args[<NUM_LIT:0>])<EOL><DEDENT>arguments = {}<EOL>types = {}<EOL>key_to_arg = {}<EOL>long_options = []<EOL>formatstring = '<STR_LIT>'<EOL>func, doc, arg_def = actions[args.pop(<NUM_LIT:0>)]<EOL>for idx, (arg, shortcut, default, option_type) in enumerate(arg_def):<EOL><INDENT>real_arg = arg.replace('<STR_LIT:->', '<STR_LIT:_>')<EOL>if shortcut:<EOL><INDENT>formatstring += shortcut<EOL>if not isinstance(default, bool):<EOL><INDENT>formatstring += '<STR_LIT::>'<EOL><DEDENT>key_to_arg['<STR_LIT:->' + shortcut] = real_arg<EOL><DEDENT>long_options.append(isinstance(default, bool) and arg or arg + '<STR_LIT:=>')<EOL>key_to_arg['<STR_LIT>' + arg] = real_arg<EOL>key_to_arg[idx] = real_arg<EOL>types[real_arg] = option_type<EOL>arguments[real_arg] = default<EOL><DEDENT>try:<EOL><INDENT>optlist, posargs = getopt.gnu_getopt(args, formatstring, long_options)<EOL><DEDENT>except getopt.GetoptError as e:<EOL><INDENT>fail(str(e))<EOL><DEDENT>specified_arguments = set()<EOL>for key, value in enumerate(posargs):<EOL><INDENT>try:<EOL><INDENT>arg = key_to_arg[key]<EOL><DEDENT>except IndexError:<EOL><INDENT>fail('<STR_LIT>')<EOL><DEDENT>specified_arguments.add(arg)<EOL>try:<EOL><INDENT>arguments[arg] = converters[types[arg]](value)<EOL><DEDENT>except ValueError:<EOL><INDENT>fail('<STR_LIT>' % (key, arg, value))<EOL><DEDENT><DEDENT>for key, value in optlist:<EOL><INDENT>arg = key_to_arg[key]<EOL>if arg in specified_arguments:<EOL><INDENT>fail('<STR_LIT>' % arg)<EOL><DEDENT>if types[arg] == '<STR_LIT>':<EOL><INDENT>if arg.startswith('<STR_LIT>'):<EOL><INDENT>value = '<STR_LIT>'<EOL><DEDENT>else:<EOL><INDENT>value = '<STR_LIT:yes>'<EOL><DEDENT><DEDENT>try:<EOL><INDENT>arguments[arg] = converters[types[arg]](value)<EOL><DEDENT>except ValueError:<EOL><INDENT>fail('<STR_LIT>' % (key, value))<EOL><DEDENT><DEDENT>newargs = {}<EOL>for k, v in iteritems(arguments):<EOL><INDENT>newargs[k.startswith('<STR_LIT>') and k[<NUM_LIT:3>:] or k] = v<EOL><DEDENT>arguments = newargs<EOL>return func(**arguments)<EOL>
Run the script. Participating actions are looked up in the caller's namespace if no namespace is given, otherwise in the dict provided. Only items that start with action_prefix are processed as actions. If you want to use all items in the namespace provided as actions set action_prefix to an empty string. :param namespace: An optional dict where the functions are looked up in. By default the local namespace of the caller is used. :param action_prefix: The prefix for the functions. Everything else is ignored. :param args: the arguments for the function. If not specified :data:`sys.argv` without the first argument is used.
f5878:m0
def fail(message, code=-<NUM_LIT:1>):
print('<STR_LIT>' % message, file=sys.stderr)<EOL>sys.exit(code)<EOL>
Fail with an error.
f5878:m1
def find_actions(namespace, action_prefix):
actions = {}<EOL>for key, value in iteritems(namespace):<EOL><INDENT>if key.startswith(action_prefix):<EOL><INDENT>actions[key[len(action_prefix):]] = analyse_action(value)<EOL><DEDENT><DEDENT>return actions<EOL>
Find all the actions in the namespace.
f5878:m2
def print_usage(actions):
actions = actions.items()<EOL>actions.sort()<EOL>print('<STR_LIT>' % basename(sys.argv[<NUM_LIT:0>]))<EOL>print('<STR_LIT>' % basename(sys.argv[<NUM_LIT:0>]))<EOL>print()<EOL>print('<STR_LIT>')<EOL>for name, (func, doc, arguments) in actions:<EOL><INDENT>print('<STR_LIT>' % name)<EOL>for line in doc.splitlines():<EOL><INDENT>print('<STR_LIT>' % line)<EOL><DEDENT>if arguments:<EOL><INDENT>print()<EOL><DEDENT>for arg, shortcut, default, argtype in arguments:<EOL><INDENT>if isinstance(default, bool):<EOL><INDENT>print('<STR_LIT>' % (<EOL>(shortcut and '<STR_LIT>' % shortcut or '<STR_LIT>') + '<STR_LIT>' + arg<EOL>))<EOL><DEDENT>else:<EOL><INDENT>print('<STR_LIT>' % (<EOL>(shortcut and '<STR_LIT>' % shortcut or '<STR_LIT>') + '<STR_LIT>' + arg,<EOL>argtype, default<EOL>))<EOL><DEDENT><DEDENT>print()<EOL><DEDENT>
Print the usage information. (Help screen)
f5878:m3
def analyse_action(func):
description = inspect.getdoc(func) or '<STR_LIT>'<EOL>arguments = []<EOL>args, varargs, kwargs, defaults = inspect.getargspec(func)<EOL>if varargs or kwargs:<EOL><INDENT>raise TypeError('<STR_LIT>')<EOL><DEDENT>if len(args) != len(defaults or ()):<EOL><INDENT>raise TypeError('<STR_LIT>')<EOL><DEDENT>for idx, (arg, definition) in enumerate(zip(args, defaults or ())):<EOL><INDENT>if arg.startswith('<STR_LIT:_>'):<EOL><INDENT>raise TypeError('<STR_LIT>')<EOL><DEDENT>if not isinstance(definition, tuple):<EOL><INDENT>shortcut = None<EOL>default = definition<EOL><DEDENT>else:<EOL><INDENT>shortcut, default = definition<EOL><DEDENT>argument_type = argument_types[type(default)]<EOL>if isinstance(default, bool) and default is True:<EOL><INDENT>arg = '<STR_LIT>' + arg<EOL><DEDENT>arguments.append((arg.replace('<STR_LIT:_>', '<STR_LIT:->'), shortcut,<EOL>default, argument_type))<EOL><DEDENT>return func, description, arguments<EOL>
Analyse a function.
f5878:m4
def make_shell(init_func=None, banner=None, use_ipython=True):
if banner is None:<EOL><INDENT>banner = '<STR_LIT>'<EOL><DEDENT>if init_func is None:<EOL><INDENT>init_func = dict<EOL><DEDENT>def action(ipython=use_ipython):<EOL><INDENT>"""<STR_LIT>"""<EOL>namespace = init_func()<EOL>if ipython:<EOL><INDENT>try:<EOL><INDENT>try:<EOL><INDENT>from IPython.frontend.terminal.embed import InteractiveShellEmbed<EOL>sh = InteractiveShellEmbed(banner1=banner)<EOL><DEDENT>except ImportError:<EOL><INDENT>from IPython.Shell import IPShellEmbed<EOL>sh = IPShellEmbed(banner=banner)<EOL><DEDENT><DEDENT>except ImportError:<EOL><INDENT>pass<EOL><DEDENT>else:<EOL><INDENT>sh(global_ns={}, local_ns=namespace)<EOL>return<EOL><DEDENT><DEDENT>from code import interact<EOL>interact(banner, local=namespace)<EOL><DEDENT>return action<EOL>
Returns an action callback that spawns a new interactive python shell. :param init_func: an optional initialization function that is called before the shell is started. The return value of this function is the initial namespace. :param banner: the banner that is displayed before the shell. If not specified a generic banner is used instead. :param use_ipython: if set to `True` ipython is used if available.
f5878:m5
def make_runserver(app_factory, hostname='<STR_LIT:localhost>', port=<NUM_LIT>,<EOL>use_reloader=False, use_debugger=False, use_evalex=True,<EOL>threaded=False, processes=<NUM_LIT:1>, static_files=None,<EOL>extra_files=None, ssl_context=None):
def action(hostname=('<STR_LIT:h>', hostname), port=('<STR_LIT:p>', port),<EOL>reloader=use_reloader, debugger=use_debugger,<EOL>evalex=use_evalex, threaded=threaded, processes=processes):<EOL><INDENT>"""<STR_LIT>"""<EOL>from werkzeug.serving import run_simple<EOL>app = app_factory()<EOL>run_simple(hostname, port, app, reloader, debugger, evalex,<EOL>extra_files, <NUM_LIT:1>, threaded, processes,<EOL>static_files=static_files, ssl_context=ssl_context)<EOL><DEDENT>return action<EOL>
Returns an action callback that spawns a new development server. .. versionadded:: 0.5 `static_files` and `extra_files` was added. ..versionadded:: 0.6.1 `ssl_context` was added. :param app_factory: a function that returns a new WSGI application. :param hostname: the default hostname the server should listen on. :param port: the default port of the server. :param use_reloader: the default setting for the reloader. :param use_evalex: the default setting for the evalex flag of the debugger. :param threaded: the default threading setting. :param processes: the default number of processes to start. :param static_files: optional dict of static files. :param extra_files: optional list of extra files to track for reloading. :param ssl_context: optional SSL context for running server in HTTPS mode.
f5878:m6
def iter_multi_items(mapping):
if isinstance(mapping, MultiDict):<EOL><INDENT>for item in iteritems(mapping, multi=True):<EOL><INDENT>yield item<EOL><DEDENT><DEDENT>elif isinstance(mapping, dict):<EOL><INDENT>for key, value in iteritems(mapping):<EOL><INDENT>if isinstance(value, (tuple, list)):<EOL><INDENT>for value in value:<EOL><INDENT>yield key, value<EOL><DEDENT><DEDENT>else:<EOL><INDENT>yield key, value<EOL><DEDENT><DEDENT><DEDENT>else:<EOL><INDENT>for item in mapping:<EOL><INDENT>yield item<EOL><DEDENT><DEDENT>
Iterates over the items of a mapping yielding keys and values without dropping any from more complex structures.
f5880:m1
def cache_property(key, empty, type):
return property(lambda x: x._get_cache_value(key, empty, type),<EOL>lambda x, v: x._set_cache_value(key, v, type),<EOL>lambda x: x._del_cache_value(key),<EOL>'<STR_LIT>' % key)<EOL>
Return a new property object for a cache header. Useful if you want to add support for a cache extension in a subclass.
f5880:m5
def get(self, key, default=None, type=None):
try:<EOL><INDENT>rv = self[key]<EOL>if type is not None:<EOL><INDENT>rv = type(rv)<EOL><DEDENT><DEDENT>except (KeyError, ValueError):<EOL><INDENT>rv = default<EOL><DEDENT>return rv<EOL>
Return the default value if the requested data doesn't exist. If `type` is provided and is a callable it should convert the value, return it or raise a :exc:`ValueError` if that is not possible. In this case the function will return the default as if the value was not found: >>> d = TypeConversionDict(foo='42', bar='blub') >>> d.get('foo', type=int) 42 >>> d.get('bar', -1, type=int) -1 :param key: The key to be looked up. :param default: The default value to be returned if the key can't be looked up. If not further specified `None` is returned. :param type: A callable that is used to cast the value in the :class:`MultiDict`. If a :exc:`ValueError` is raised by this callable the default value is returned.
f5880:c5:m0
def copy(self):
return TypeConversionDict(self)<EOL>
Return a shallow mutable copy of this object. Keep in mind that the standard library's :func:`copy` function is a no-op for this class like for any other python immutable type (eg: :class:`tuple`).
f5880:c6:m0
def __getitem__(self, key):
if key in self:<EOL><INDENT>return dict.__getitem__(self, key)[<NUM_LIT:0>]<EOL><DEDENT>raise exceptions.BadRequestKeyError(key)<EOL>
Return the first data value for this key; raises KeyError if not found. :param key: The key to be looked up. :raise KeyError: if the key does not exist.
f5880:c7:m3
def __setitem__(self, key, value):
dict.__setitem__(self, key, [value])<EOL>
Like :meth:`add` but removes an existing key first. :param key: the key for the value. :param value: the value to set.
f5880:c7:m4
def add(self, key, value):
dict.setdefault(self, key, []).append(value)<EOL>
Adds a new value for the key. .. versionadded:: 0.6 :param key: the key for the value. :param value: the value to add.
f5880:c7:m5
def getlist(self, key, type=None):
try:<EOL><INDENT>rv = dict.__getitem__(self, key)<EOL><DEDENT>except KeyError:<EOL><INDENT>return []<EOL><DEDENT>if type is None:<EOL><INDENT>return list(rv)<EOL><DEDENT>result = []<EOL>for item in rv:<EOL><INDENT>try:<EOL><INDENT>result.append(type(item))<EOL><DEDENT>except ValueError:<EOL><INDENT>pass<EOL><DEDENT><DEDENT>return result<EOL>
Return the list of items for a given key. If that key is not in the `MultiDict`, the return value will be an empty list. Just as `get` `getlist` accepts a `type` parameter. All items will be converted with the callable defined there. :param key: The key to be looked up. :param type: A callable that is used to cast the value in the :class:`MultiDict`. If a :exc:`ValueError` is raised by this callable the value will be removed from the list. :return: a :class:`list` of all the values for the key.
f5880:c7:m6
def setlist(self, key, new_list):
dict.__setitem__(self, key, list(new_list))<EOL>
Remove the old values for a key and add new ones. Note that the list you pass the values in will be shallow-copied before it is inserted in the dictionary. >>> d = MultiDict() >>> d.setlist('foo', ['1', '2']) >>> d['foo'] '1' >>> d.getlist('foo') ['1', '2'] :param key: The key for which the values are set. :param new_list: An iterable with the new values for the key. Old values are removed first.
f5880:c7:m7
def setdefault(self, key, default=None):
if key not in self:<EOL><INDENT>self[key] = default<EOL><DEDENT>else:<EOL><INDENT>default = self[key]<EOL><DEDENT>return default<EOL>
Returns the value for the key if it is in the dict, otherwise it returns `default` and sets that value for `key`. :param key: The key to be looked up. :param default: The default value to be returned if the key is not in the dict. If not further specified it's `None`.
f5880:c7:m8
def setlistdefault(self, key, default_list=None):
if key not in self:<EOL><INDENT>default_list = list(default_list or ())<EOL>dict.__setitem__(self, key, default_list)<EOL><DEDENT>else:<EOL><INDENT>default_list = dict.__getitem__(self, key)<EOL><DEDENT>return default_list<EOL>
Like `setdefault` but sets multiple values. The list returned is not a copy, but the list that is actually used internally. This means that you can put new values into the dict by appending items to the list: >>> d = MultiDict({"foo": 1}) >>> d.setlistdefault("foo").extend([2, 3]) >>> d.getlist("foo") [1, 2, 3] :param key: The key to be looked up. :param default: An iterable of default values. It is either copied (in case it was a list) or converted into a list before returned. :return: a :class:`list`
f5880:c7:m9
def items(self, multi=False):
for key, values in iteritems(dict, self):<EOL><INDENT>if multi:<EOL><INDENT>for value in values:<EOL><INDENT>yield key, value<EOL><DEDENT><DEDENT>else:<EOL><INDENT>yield key, values[<NUM_LIT:0>]<EOL><DEDENT><DEDENT>
Return an iterator of ``(key, value)`` pairs. :param multi: If set to `True` the iterator returned will have a pair for each value of each key. Otherwise it will only contain pairs for the first value of each key.
f5880:c7:m10
def lists(self):
for key, values in iteritems(dict, self):<EOL><INDENT>yield key, list(values)<EOL><DEDENT>
Return a list of ``(key, values)`` pairs, where values is the list of all values associated with the key.
f5880:c7:m11
def values(self):
for values in itervalues(dict, self):<EOL><INDENT>yield values[<NUM_LIT:0>]<EOL><DEDENT>
Returns an iterator of the first value on every key's value list.
f5880:c7:m13
def listvalues(self):
return itervalues(dict, self)<EOL>
Return an iterator of all values associated with a key. Zipping :meth:`keys` and this is the same as calling :meth:`lists`: >>> d = MultiDict({"foo": [1, 2, 3]}) >>> zip(d.keys(), d.listvalues()) == d.lists() True
f5880:c7:m14
def copy(self):
return self.__class__(self)<EOL>
Return a shallow copy of this object.
f5880:c7:m15
def to_dict(self, flat=True):
if flat:<EOL><INDENT>return dict(iteritems(self))<EOL><DEDENT>return dict(self.lists())<EOL>
Return the contents as regular dict. If `flat` is `True` the returned dict will only have the first item present, if `flat` is `False` all values will be returned as lists. :param flat: If set to `False` the dict returned will have lists with all the values in it. Otherwise it will only contain the first value for each key. :return: a :class:`dict`
f5880:c7:m16
def update(self, other_dict):
for key, value in iter_multi_items(other_dict):<EOL><INDENT>MultiDict.add(self, key, value)<EOL><DEDENT>
update() extends rather than replaces existing key lists.
f5880:c7:m17
def pop(self, key, default=_missing):
try:<EOL><INDENT>return dict.pop(self, key)[<NUM_LIT:0>]<EOL><DEDENT>except KeyError as e:<EOL><INDENT>if default is not _missing:<EOL><INDENT>return default<EOL><DEDENT>raise exceptions.BadRequestKeyError(str(e))<EOL><DEDENT>
Pop the first item for a list on the dict. Afterwards the key is removed from the dict, so additional values are discarded: >>> d = MultiDict({"foo": [1, 2, 3]}) >>> d.pop("foo") 1 >>> "foo" in d False :param key: the key to pop. :param default: if provided the value to return if the key was not in the dictionary.
f5880:c7:m18
def popitem(self):
try:<EOL><INDENT>item = dict.popitem(self)<EOL>return (item[<NUM_LIT:0>], item[<NUM_LIT:1>][<NUM_LIT:0>])<EOL><DEDENT>except KeyError as e:<EOL><INDENT>raise exceptions.BadRequestKeyError(str(e))<EOL><DEDENT>
Pop an item from the dict.
f5880:c7:m19
def poplist(self, key):
return dict.pop(self, key, [])<EOL>
Pop the list for a key from the dict. If the key is not in the dict an empty list is returned. .. versionchanged:: 0.5 If the key does no longer exist a list is returned instead of raising an error.
f5880:c7:m20
def popitemlist(self):
try:<EOL><INDENT>return dict.popitem(self)<EOL><DEDENT>except KeyError as e:<EOL><INDENT>raise exceptions.BadRequestKeyError(str(e))<EOL><DEDENT>
Pop a ``(key, list)`` tuple from the dict.
f5880:c7:m21
def get(self, key, default=None, type=None, as_bytes=False):
try:<EOL><INDENT>rv = self.__getitem__(key, _get_mode=True)<EOL><DEDENT>except KeyError:<EOL><INDENT>return default<EOL><DEDENT>if as_bytes:<EOL><INDENT>rv = rv.encode('<STR_LIT>')<EOL><DEDENT>if type is None:<EOL><INDENT>return rv<EOL><DEDENT>try:<EOL><INDENT>return type(rv)<EOL><DEDENT>except ValueError:<EOL><INDENT>return default<EOL><DEDENT>
Return the default value if the requested data doesn't exist. If `type` is provided and is a callable it should convert the value, return it or raise a :exc:`ValueError` if that is not possible. In this case the function will return the default as if the value was not found: >>> d = Headers([('Content-Length', '42')]) >>> d.get('Content-Length', type=int) 42 If a headers object is bound you must not add unicode strings because no encoding takes place. .. versionadded:: 0.9 Added support for `as_bytes`. :param key: The key to be looked up. :param default: The default value to be returned if the key can't be looked up. If not further specified `None` is returned. :param type: A callable that is used to cast the value in the :class:`Headers`. If a :exc:`ValueError` is raised by this callable the default value is returned. :param as_bytes: return bytes instead of unicode strings.
f5880:c10:m4
def getlist(self, key, type=None, as_bytes=False):
ikey = key.lower()<EOL>result = []<EOL>for k, v in self:<EOL><INDENT>if k.lower() == ikey:<EOL><INDENT>if as_bytes:<EOL><INDENT>v = v.encode('<STR_LIT>')<EOL><DEDENT>if type is not None:<EOL><INDENT>try:<EOL><INDENT>v = type(v)<EOL><DEDENT>except ValueError:<EOL><INDENT>continue<EOL><DEDENT><DEDENT>result.append(v)<EOL><DEDENT><DEDENT>return result<EOL>
Return the list of items for a given key. If that key is not in the :class:`Headers`, the return value will be an empty list. Just as :meth:`get` :meth:`getlist` accepts a `type` parameter. All items will be converted with the callable defined there. .. versionadded:: 0.9 Added support for `as_bytes`. :param key: The key to be looked up. :param type: A callable that is used to cast the value in the :class:`Headers`. If a :exc:`ValueError` is raised by this callable the value will be removed from the list. :return: a :class:`list` of all the values for the key. :param as_bytes: return bytes instead of unicode strings.
f5880:c10:m5
def get_all(self, name):
return self.getlist(name)<EOL>
Return a list of all the values for the named field. This method is compatible with the :mod:`wsgiref` :meth:`~wsgiref.headers.Headers.get_all` method.
f5880:c10:m6
def extend(self, iterable):
if isinstance(iterable, dict):<EOL><INDENT>for key, value in iteritems(iterable):<EOL><INDENT>if isinstance(value, (tuple, list)):<EOL><INDENT>for v in value:<EOL><INDENT>self.add(key, v)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>self.add(key, value)<EOL><DEDENT><DEDENT><DEDENT>else:<EOL><INDENT>for key, value in iterable:<EOL><INDENT>self.add(key, value)<EOL><DEDENT><DEDENT>
Extend the headers with a dict or an iterable yielding keys and values.
f5880:c10:m10
def remove(self, key):
return self.__delitem__(key, _index_operation=False)<EOL>
Remove a key. :param key: The key to be removed.
f5880:c10:m12
def pop(self, key=None, default=_missing):
if key is None:<EOL><INDENT>return self._list.pop()<EOL><DEDENT>if isinstance(key, integer_types):<EOL><INDENT>return self._list.pop(key)<EOL><DEDENT>try:<EOL><INDENT>rv = self[key]<EOL>self.remove(key)<EOL><DEDENT>except KeyError:<EOL><INDENT>if default is not _missing:<EOL><INDENT>return default<EOL><DEDENT>raise<EOL><DEDENT>return rv<EOL>
Removes and returns a key or index. :param key: The key to be popped. If this is an integer the item at that position is removed, if it's a string the value for that key is. If the key is omitted or `None` the last item is removed. :return: an item.
f5880:c10:m13
def popitem(self):
return self.pop()<EOL>
Removes a key or index and returns a (key, value) item.
f5880:c10:m14
def __contains__(self, key):
try:<EOL><INDENT>self.__getitem__(key, _get_mode=True)<EOL><DEDENT>except KeyError:<EOL><INDENT>return False<EOL><DEDENT>return True<EOL>
Check if a key is present.
f5880:c10:m15
def __iter__(self):
return iter(self._list)<EOL>
Yield ``(key, value)`` tuples.
f5880:c10:m16
def add(self, _key, _value, **kw):
if kw:<EOL><INDENT>_value = _options_header_vkw(_value, kw)<EOL><DEDENT>_value = _unicodify_header_value(_value)<EOL>self._validate_value(_value)<EOL>self._list.append((_key, _value))<EOL>
Add a new header tuple to the list. Keyword arguments can specify additional parameters for the header value, with underscores converted to dashes:: >>> d = Headers() >>> d.add('Content-Type', 'text/plain') >>> d.add('Content-Disposition', 'attachment', filename='foo.png') The keyword argument dumping uses :func:`dump_options_header` behind the scenes. .. versionadded:: 0.4.1 keyword arguments were added for :mod:`wsgiref` compatibility.
f5880:c10:m18
def add_header(self, _key, _value, **_kw):
self.add(_key, _value, **_kw)<EOL>
Add a new header tuple to the list. An alias for :meth:`add` for compatibility with the :mod:`wsgiref` :meth:`~wsgiref.headers.Headers.add_header` method.
f5880:c10:m20
def clear(self):
del self._list[:]<EOL>
Clears all headers.
f5880:c10:m21
def set(self, _key, _value, **kw):
if kw:<EOL><INDENT>_value = _options_header_vkw(_value, kw)<EOL><DEDENT>_value = _unicodify_header_value(_value)<EOL>self._validate_value(_value)<EOL>if not self._list:<EOL><INDENT>self._list.append((_key, _value))<EOL>return<EOL><DEDENT>listiter = iter(self._list)<EOL>ikey = _key.lower()<EOL>for idx, (old_key, old_value) in enumerate(listiter):<EOL><INDENT>if old_key.lower() == ikey:<EOL><INDENT>self._list[idx] = (_key, _value)<EOL>break<EOL><DEDENT><DEDENT>else:<EOL><INDENT>self._list.append((_key, _value))<EOL>return<EOL><DEDENT>self._list[idx + <NUM_LIT:1>:] = [t for t in listiter if t[<NUM_LIT:0>].lower() != ikey]<EOL>
Remove all header tuples for `key` and add a new one. The newly added key either appears at the end of the list if there was no entry or replaces the first one. Keyword arguments can specify additional parameters for the header value, with underscores converted to dashes. See :meth:`add` for more information. .. versionchanged:: 0.6.1 :meth:`set` now accepts the same arguments as :meth:`add`. :param key: The key to be inserted. :param value: The value to be inserted.
f5880:c10:m22
def setdefault(self, key, value):
if key in self:<EOL><INDENT>return self[key]<EOL><DEDENT>self.set(key, value)<EOL>return value<EOL>
Returns the value for the key if it is in the dict, otherwise it returns `default` and sets that value for `key`. :param key: The key to be looked up. :param default: The default value to be returned if the key is not in the dict. If not further specified it's `None`.
f5880:c10:m23
def __setitem__(self, key, value):
if isinstance(key, (slice, integer_types)):<EOL><INDENT>if isinstance(key, integer_types):<EOL><INDENT>value = [value]<EOL><DEDENT>value = [(k, _unicodify_header_value(v)) for (k, v) in value]<EOL>[self._validate_value(v) for (k, v) in value]<EOL>if isinstance(key, integer_types):<EOL><INDENT>self._list[key] = value[<NUM_LIT:0>]<EOL><DEDENT>else:<EOL><INDENT>self._list[key] = value<EOL><DEDENT><DEDENT>else:<EOL><INDENT>self.set(key, value)<EOL><DEDENT>
Like :meth:`set` but also supports index/slice based setting.
f5880:c10:m24
def to_list(self, charset='<STR_LIT>'):
from warnings import warn<EOL>warn(DeprecationWarning('<STR_LIT>'),<EOL>stacklevel=<NUM_LIT:2>)<EOL>return self.to_wsgi_list()<EOL>
Convert the headers into a list suitable for WSGI.
f5880:c10:m25
def to_wsgi_list(self):
if PY2:<EOL><INDENT>return [(k, v.encode('<STR_LIT>')) for k, v in self]<EOL><DEDENT>return list(self)<EOL>
Convert the headers into a list suitable for WSGI. The values are byte strings in Python 2 converted to latin1 and unicode strings in Python 3 for the WSGI server to encode. :return: list
f5880:c10:m26
def __str__(self):
strs = []<EOL>for key, value in self.to_wsgi_list():<EOL><INDENT>strs.append('<STR_LIT>' % (key, value))<EOL><DEDENT>strs.append('<STR_LIT:\r\n>')<EOL>return '<STR_LIT:\r\n>'.join(strs)<EOL>
Returns formatted headers suitable for HTTP transmission.
f5880:c10:m29
def copy(self):
return self.__class__(self.dicts[:])<EOL>
Return a shallow copy of this object.
f5880:c13:m11
def to_dict(self, flat=True):
rv = {}<EOL>for d in reversed(self.dicts):<EOL><INDENT>rv.update(d.to_dict(flat))<EOL><DEDENT>return rv<EOL>
Return the contents as regular dict. If `flat` is `True` the returned dict will only have the first item present, if `flat` is `False` all values will be returned as lists. :param flat: If set to `False` the dict returned will have lists with all the values in it. Otherwise it will only contain the first item for each key. :return: a :class:`dict`
f5880:c13:m12
def add_file(self, name, file, filename=None, content_type=None):
if isinstance(file, FileStorage):<EOL><INDENT>value = file<EOL><DEDENT>else:<EOL><INDENT>if isinstance(file, string_types):<EOL><INDENT>if filename is None:<EOL><INDENT>filename = file<EOL><DEDENT>file = open(file, '<STR_LIT:rb>')<EOL><DEDENT>if filename and content_type is None:<EOL><INDENT>content_type = mimetypes.guess_type(filename)[<NUM_LIT:0>] or'<STR_LIT>'<EOL><DEDENT>value = FileStorage(file, filename, name, content_type)<EOL><DEDENT>self.add(name, value)<EOL>
Adds a new file to the dict. `file` can be a file name or a :class:`file`-like or a :class:`FileStorage` object. :param name: the name of the field. :param file: a filename or :class:`file`-like object :param filename: an optional filename :param content_type: an optional content type
f5880:c14:m0
def copy(self):
return dict(self)<EOL>
Return a shallow mutable copy of this object. Keep in mind that the standard library's :func:`copy` function is a no-op for this class like for any other python immutable type (eg: :class:`tuple`).
f5880:c15:m1
def copy(self):
return MultiDict(self)<EOL>
Return a shallow mutable copy of this object. Keep in mind that the standard library's :func:`copy` function is a no-op for this class like for any other python immutable type (eg: :class:`tuple`).
f5880:c16:m0
def copy(self):
return OrderedMultiDict(self)<EOL>
Return a shallow mutable copy of this object. Keep in mind that the standard library's :func:`copy` function is a no-op for this class like for any other python immutable type (eg: :class:`tuple`).
f5880:c17:m1
def _value_matches(self, value, item):
return item == '<STR_LIT:*>' or item.lower() == value.lower()<EOL>
Check if a value matches a given accept item.
f5880:c18:m1
def __getitem__(self, key):
if isinstance(key, string_types):<EOL><INDENT>return self.quality(key)<EOL><DEDENT>return list.__getitem__(self, key)<EOL>
Besides index lookup (getting item n) you can also pass it a string to get the quality for the item. If the item is not in the list, the returned quality is ``0``.
f5880:c18:m2
def quality(self, key):
for item, quality in self:<EOL><INDENT>if self._value_matches(key, item):<EOL><INDENT>return quality<EOL><DEDENT><DEDENT>return <NUM_LIT:0><EOL>
Returns the quality of the key. .. versionadded:: 0.6 In previous versions you had to use the item-lookup syntax (eg: ``obj[key]`` instead of ``obj.quality(key)``)
f5880:c18:m3
def index(self, key):
if isinstance(key, string_types):<EOL><INDENT>for idx, (item, quality) in enumerate(self):<EOL><INDENT>if self._value_matches(key, item):<EOL><INDENT>return idx<EOL><DEDENT><DEDENT>raise ValueError(key)<EOL><DEDENT>return list.index(self, key)<EOL>
Get the position of an entry or raise :exc:`ValueError`. :param key: The key to be looked up. .. versionchanged:: 0.5 This used to raise :exc:`IndexError`, which was inconsistent with the list API.
f5880:c18:m6
def find(self, key):
try:<EOL><INDENT>return self.index(key)<EOL><DEDENT>except ValueError:<EOL><INDENT>return -<NUM_LIT:1><EOL><DEDENT>
Get the position of an entry or return -1. :param key: The key to be looked up.
f5880:c18:m7
def values(self):
for item in self:<EOL><INDENT>yield item[<NUM_LIT:0>]<EOL><DEDENT>
Iterate over all values.
f5880:c18:m8
def to_header(self):
result = []<EOL>for value, quality in self:<EOL><INDENT>if quality != <NUM_LIT:1>:<EOL><INDENT>value = '<STR_LIT>' % (value, quality)<EOL><DEDENT>result.append(value)<EOL><DEDENT>return '<STR_LIT:U+002C>'.join(result)<EOL>
Convert the header set into an HTTP header string.
f5880:c18:m9
def best_match(self, matches, default=None):
best_quality = -<NUM_LIT:1><EOL>result = default<EOL>for server_item in matches:<EOL><INDENT>for client_item, quality in self:<EOL><INDENT>if quality <= best_quality:<EOL><INDENT>break<EOL><DEDENT>if self._value_matches(server_item, client_item):<EOL><INDENT>best_quality = quality<EOL>result = server_item<EOL><DEDENT><DEDENT><DEDENT>return result<EOL>
Returns the best match from a list of possible matches based on the quality of the client. If two items have the same quality, the one is returned that comes first. :param matches: a list of matches to check for :param default: the value that is returned if none match
f5880:c18:m11
@property<EOL><INDENT>def best(self):<DEDENT>
if self:<EOL><INDENT>return self[<NUM_LIT:0>][<NUM_LIT:0>]<EOL><DEDENT>
The best match as value.
f5880:c18:m12
@property<EOL><INDENT>def accept_html(self):<DEDENT>
return (<EOL>'<STR_LIT>' in self or<EOL>'<STR_LIT>' in self or<EOL>self.accept_xhtml<EOL>)<EOL>
True if this object accepts HTML.
f5880:c19:m1
@property<EOL><INDENT>def accept_xhtml(self):<DEDENT>
return (<EOL>'<STR_LIT>' in self or<EOL>'<STR_LIT>' in self<EOL>)<EOL>
True if this object accepts XHTML.
f5880:c19:m2
@property<EOL><INDENT>def accept_json(self):<DEDENT>
return '<STR_LIT:application/json>' in self<EOL>
True if this object accepts JSON.
f5880:c19:m3
def _get_cache_value(self, key, empty, type):
if type is bool:<EOL><INDENT>return key in self<EOL><DEDENT>if key in self:<EOL><INDENT>value = self[key]<EOL>if value is None:<EOL><INDENT>return empty<EOL><DEDENT>elif type is not None:<EOL><INDENT>try:<EOL><INDENT>value = type(value)<EOL><DEDENT>except ValueError:<EOL><INDENT>pass<EOL><DEDENT><DEDENT>return value<EOL><DEDENT>
Used internally by the accessor properties.
f5880:c22:m1
def _set_cache_value(self, key, value, type):
if type is bool:<EOL><INDENT>if value:<EOL><INDENT>self[key] = None<EOL><DEDENT>else:<EOL><INDENT>self.pop(key, None)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>if value is None:<EOL><INDENT>self.pop(key)<EOL><DEDENT>elif value is True:<EOL><INDENT>self[key] = None<EOL><DEDENT>else:<EOL><INDENT>self[key] = value<EOL><DEDENT><DEDENT>
Used internally by the accessor properties.
f5880:c22:m2
def _del_cache_value(self, key):
if key in self:<EOL><INDENT>del self[key]<EOL><DEDENT>
Used internally by the accessor properties.
f5880:c22:m3
def to_header(self):
return dump_header(self)<EOL>
Convert the stored values into a cache control header.
f5880:c22:m4
def add(self, header):
self.update((header,))<EOL>
Add a new header to the set.
f5880:c26:m1
def remove(self, header):
key = header.lower()<EOL>if key not in self._set:<EOL><INDENT>raise KeyError(header)<EOL><DEDENT>self._set.remove(key)<EOL>for idx, key in enumerate(self._headers):<EOL><INDENT>if key.lower() == header:<EOL><INDENT>del self._headers[idx]<EOL>break<EOL><DEDENT><DEDENT>if self.on_update is not None:<EOL><INDENT>self.on_update(self)<EOL><DEDENT>
Remove a header from the set. This raises an :exc:`KeyError` if the header is not in the set. .. versionchanged:: 0.5 In older versions a :exc:`IndexError` was raised instead of a :exc:`KeyError` if the object was missing. :param header: the header to be removed.
f5880:c26:m2
def update(self, iterable):
inserted_any = False<EOL>for header in iterable:<EOL><INDENT>key = header.lower()<EOL>if key not in self._set:<EOL><INDENT>self._headers.append(header)<EOL>self._set.add(key)<EOL>inserted_any = True<EOL><DEDENT><DEDENT>if inserted_any and self.on_update is not None:<EOL><INDENT>self.on_update(self)<EOL><DEDENT>
Add all the headers from the iterable to the set. :param iterable: updates the set with the items from the iterable.
f5880:c26:m3
def discard(self, header):
try:<EOL><INDENT>return self.remove(header)<EOL><DEDENT>except KeyError:<EOL><INDENT>pass<EOL><DEDENT>
Like :meth:`remove` but ignores errors. :param header: the header to be discarded.
f5880:c26:m4
def find(self, header):
header = header.lower()<EOL>for idx, item in enumerate(self._headers):<EOL><INDENT>if item.lower() == header:<EOL><INDENT>return idx<EOL><DEDENT><DEDENT>return -<NUM_LIT:1><EOL>
Return the index of the header in the set or return -1 if not found. :param header: the header to be looked up.
f5880:c26:m5
def index(self, header):
rv = self.find(header)<EOL>if rv < <NUM_LIT:0>:<EOL><INDENT>raise IndexError(header)<EOL><DEDENT>return rv<EOL>
Return the index of the header in the set or raise an :exc:`IndexError`. :param header: the header to be looked up.
f5880:c26:m6
def clear(self):
self._set.clear()<EOL>del self._headers[:]<EOL>if self.on_update is not None:<EOL><INDENT>self.on_update(self)<EOL><DEDENT>
Clear the set.
f5880:c26:m7
def as_set(self, preserve_casing=False):
if preserve_casing:<EOL><INDENT>return set(self._headers)<EOL><DEDENT>return set(self._set)<EOL>
Return the set as real python set type. When calling this, all the items are converted to lowercase and the ordering is lost. :param preserve_casing: if set to `True` the items in the set returned will have the original case like in the :class:`HeaderSet`, otherwise they will be lowercase.
f5880:c26:m8
def to_header(self):
return '<STR_LIT:U+002CU+0020>'.join(map(quote_header_value, self._headers))<EOL>
Convert the header set into an HTTP header string.
f5880:c26:m9
def as_set(self, include_weak=False):
rv = set(self._strong)<EOL>if include_weak:<EOL><INDENT>rv.update(self._weak)<EOL><DEDENT>return rv<EOL>
Convert the `ETags` object into a python set. Per default all the weak etags are not part of this set.
f5880:c27:m1
def is_weak(self, etag):
return etag in self._weak<EOL>
Check if an etag is weak.
f5880:c27:m2
def contains_weak(self, etag):
return self.is_weak(etag) or self.contains(etag)<EOL>
Check if an etag is part of the set including weak and strong tags.
f5880:c27:m3
def contains(self, etag):
if self.star_tag:<EOL><INDENT>return True<EOL><DEDENT>return etag in self._strong<EOL>
Check if an etag is part of the set ignoring weak tags. It is also possible to use the ``in`` operator.
f5880:c27:m4
def contains_raw(self, etag):
etag, weak = unquote_etag(etag)<EOL>if weak:<EOL><INDENT>return self.contains_weak(etag)<EOL><DEDENT>return self.contains(etag)<EOL>
When passed a quoted tag it will check if this tag is part of the set. If the tag is weak it is checked against weak and strong tags, otherwise strong only.
f5880:c27:m5
def to_header(self):
if self.star_tag:<EOL><INDENT>return '<STR_LIT:*>'<EOL><DEDENT>return '<STR_LIT:U+002CU+0020>'.join(<EOL>['<STR_LIT>' % x for x in self._strong] +<EOL>['<STR_LIT>' % x for x in self._weak]<EOL>)<EOL>
Convert the etags set into a HTTP header string.
f5880:c27:m6
def to_header(self):
if self.date is not None:<EOL><INDENT>return http_date(self.date)<EOL><DEDENT>if self.etag is not None:<EOL><INDENT>return quote_etag(self.etag)<EOL><DEDENT>return '<STR_LIT>'<EOL>
Converts the object back into an HTTP header.
f5880:c28:m1
def range_for_length(self, length):
if self.units != '<STR_LIT>' or length is None or len(self.ranges) != <NUM_LIT:1>:<EOL><INDENT>return None<EOL><DEDENT>start, end = self.ranges[<NUM_LIT:0>]<EOL>if end is None:<EOL><INDENT>end = length<EOL>if start < <NUM_LIT:0>:<EOL><INDENT>start += length<EOL><DEDENT><DEDENT>if is_byte_range_valid(start, end, length):<EOL><INDENT>return start, min(end, length)<EOL><DEDENT>
If the range is for bytes, the length is not None and there is exactly one range and it is satisfiable it returns a ``(start, stop)`` tuple, otherwise `None`.
f5880:c29:m1
def make_content_range(self, length):
rng = self.range_for_length(length)<EOL>if rng is not None:<EOL><INDENT>return ContentRange(self.units, rng[<NUM_LIT:0>], rng[<NUM_LIT:1>], length)<EOL><DEDENT>
Creates a :class:`~werkzeug.datastructures.ContentRange` object from the current range and given content length.
f5880:c29:m2
def to_header(self):
ranges = []<EOL>for begin, end in self.ranges:<EOL><INDENT>if end is None:<EOL><INDENT>ranges.append(begin >= <NUM_LIT:0> and '<STR_LIT>' % begin or str(begin))<EOL><DEDENT>else:<EOL><INDENT>ranges.append('<STR_LIT>' % (begin, end - <NUM_LIT:1>))<EOL><DEDENT><DEDENT>return '<STR_LIT>' % (self.units, '<STR_LIT:U+002C>'.join(ranges))<EOL>
Converts the object back into an HTTP header.
f5880:c29:m3
def set(self, start, stop, length=None, units='<STR_LIT>'):
assert is_byte_range_valid(start, stop, length),'<STR_LIT>'<EOL>self._units = units<EOL>self._start = start<EOL>self._stop = stop<EOL>self._length = length<EOL>if self.on_update is not None:<EOL><INDENT>self.on_update(self)<EOL><DEDENT>
Simple method to update the ranges.
f5880:c30:m2
def unset(self):
self.set(None, None, units=None)<EOL>
Sets the units to `None` which indicates that the header should no longer be used.
f5880:c30:m3