Skip to content
Myr

Add new utilities from werkzeug

Before adoption: this commit came in with the history the project adopted, so no landing records it.

authored by Kenneth Reitz · committed by Kenneth Reitz · parent 53c7b77 · Browse files · 1 file+109 added−0 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

1 file+109 added−0 removed

  • other:+109 added−0 removed

1 file+109 added−0 removed

modified:requests/utils.py+109 added
10 unmodified lines
1112import cgi13import codecs14import cookielib15import os16import random17import re18import zlib1920from urllib2 import parse_http_list as _parse_list_header212223# From mitsuhiko/werkzeug (used with permission).24def parse_list_header(value):25 """Parse lists as described by RFC 2068 Section 2.2627 In particular, parse comma-separated lists where the elements of28 the list may include quoted-strings. A quoted-string could29 contain a comma. A non-quoted string could have quotes in the30 middle. Quotes are removed automatically after parsing.3132 It basically works like :func:`parse_set_header` just that items33 may appear multiple times and case sensitivity is preserved.3435 The return value is a standard :class:`list`:3637 >>> parse_list_header('token, "quoted value"')38 ['token', 'quoted value']3940 To create a header from the :class:`list` again, use the41 :func:`dump_header` function.4243 :param value: a string with a list header.44 :return: :class:`list`45 """46 result = []47 for item in _parse_list_header(value):48 if item[:1] == item[-1:] == '"':49 item = unquote_header_value(item[1:-1])50 result.append(item)51 return result525354# From mitsuhiko/werkzeug (used with permission).55def parse_dict_header(value):56 """Parse lists of key, value pairs as described by RFC 2068 Section 2 and57 convert them into a python dict:5859 >>> d = parse_dict_header('foo="is a fish", bar="as well"')60 >>> type(d) is dict61 True62 >>> sorted(d.items())63 [('bar', 'as well'), ('foo', 'is a fish')]6465 If there is no value for a key it will be `None`:6667 >>> parse_dict_header('key_without_value')68 {'key_without_value': None}6970 To create a header from the :class:`dict` again, use the71 :func:`dump_header` function.7273 :param value: a string with a dict header.74 :return: :class:`dict`75 """76 result = {}77 for item in _parse_list_header(value):78 if '=' not in item:79 result[item] = None80 continue81 name, value = item.split('=', 1)82 if value[:1] == value[-1:] == '"':83 value = unquote_header_value(value[1:-1])84 result[name] = value85 return result868788# From mitsuhiko/werkzeug (used with permission).89def unquote_header_value(value, is_filename=False):90 r"""Unquotes a header value. (Reversal of :func:`quote_header_value`).91 This does not use the real unquoting but what browsers are actually92 using for quoting.9394 :param value: the header value to unquote.95 """96 if value and value[0] == value[-1] == '"':97 # this is not the real unquoting, but fixing this so that the98 # RFC is met will result in bugs with internet explorer and99 # probably some other browsers as well. IE for example is100 # uploading files with "C:\foo\bar.txt" as filename101 value = value[1:-1]102103 # if this is a filename and the starting characters look like104 # a UNC path, then just return the value without quotes. Using the105 # replace sequence below on a UNC path has the effect of turning106 # the leading double slash into a single slash and then107 # _fix_ie_filename() doesn't work correctly. See #458.108 if not is_filename or value[:2] != '\\\\':109 return value.replace('\\\\', '\\').replace('\\"', '"')110 return value111112113def header_expand(headers):114 """Returns an HTTP Header value string from a dictionary.115116 Example expansion::
39 unmodified lines
156 return ''.join(collector)157158159160def randombytes(n):161 """Return n random bytes."""162 # Use /dev/urandom if it is available. Fall back to random module163 # if not. It might be worthwhile to extend this function to use164 # other platform-specific mechanisms for getting random bytes.165 if os.path.exists("/dev/urandom"):166 f = open("/dev/urandom")167 s = f.read(n)168 f.close()169 return s170 else:171 L = [chr(random.randrange(0, 256)) for i in range(n)]172 return "".join(L)173174175def dict_from_cookiejar(cj):176 """Returns a key/value dictionary from a CookieJar.177178 :param cj: CookieJar object to extract cookies from.
185 unmodified lines