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
Provenance
- Commit
9966017- Tree
2fecf52- Author
Kenneth Reitz <me@kennethreitz.com>- Committer
Kenneth Reitz <me@kennethreitz.com>- Parent
53c7b77
1 file changed+109 added−0 removed
modified:requests/utils.py+109 added
10 unmodified lines11 12 import cgi13 import codecs14 import cookielib15+import os16+import random17 import re18 import zlib19 20+from urllib2 import parse_http_list as _parse_list_header21 22+23+# From mitsuhiko/werkzeug (used with permission).24+def parse_list_header(value):25+ """Parse lists as described by RFC 2068 Section 2.26+27+ 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.31+32+ It basically works like :func:`parse_set_header` just that items33+ may appear multiple times and case sensitivity is preserved.34+35+ The return value is a standard :class:`list`:36+37+ >>> parse_list_header('token, "quoted value"')38+ ['token', 'quoted value']39+40+ To create a header from the :class:`list` again, use the41+ :func:`dump_header` function.42+43+ :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 result52+53+54+# From mitsuhiko/werkzeug (used with permission).55+def 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:58+59+ >>> 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')]64+65+ If there is no value for a key it will be `None`:66+67+ >>> parse_dict_header('key_without_value')68+ {'key_without_value': None}69+70+ To create a header from the :class:`dict` again, use the71+ :func:`dump_header` function.72+73+ :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 result86+87+88+# From mitsuhiko/werkzeug (used with permission).89+def 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.93+94+ :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]102+103+ # 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 value111+112+113 def header_expand(headers):114 """Returns an HTTP Header value string from a dictionary.115 116 Example expansion::39 unmodified lines156 return ''.join(collector)157 158 159 160+def 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)173+174+175 def dict_from_cookiejar(cj):176 """Returns a key/value dictionary from a CookieJar.177 178 :param cj: CookieJar object to extract cookies from.185 unmodified lines