Add to_key_val_lists to avoid repetition.
Before adoption: this commit came in with the history the project adopted, so no landing records it.
It uses the same logic whenever we're trying to use a list of key values and avoid what I had started doing -- using the same pattern everywhere. proxies, and headers should both be covered by this commit.
authored by Ian Cordasco · committed by Ian Cordasco · parent d82d124 · Browse files · 3 files·+45 added−42 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
3 files+45 added−42 removed
- other:+45 added−42 removed
Provenance
- Commit
1722f28- Tree
51abef7- Author
Ian Cordasco <graffatcolmingov@gmail.com>- Committer
Ian Cordasco <graffatcolmingov@gmail.com>- Parent
d82d124
3 files changed+45 added−42 removed
modified:requests/models.py+4 added-23 removed
27 unmodified lines28 URLRequired, SSLError, MissingSchema, InvalidSchema, InvalidURL)29 from .utils import (30 get_encoding_from_headers, stream_untransfer, guess_filename, requote_uri,31 stream_decode_response_unicode, get_netrc_auth, get_environ_proxies,32- DEFAULT_CA_BUNDLE_PATH)32+ to_key_val_list, DEFAULT_CA_BUNDLE_PATH)33 from .compat import (34 cookielib, urlparse, urlunparse, urljoin, urlsplit, urlencode, str, bytes,35 StringIO, is_py2, chardet, json, builtin_str)36 279 unmodified lines316 return data317 elif hasattr(data, 'read'):318 return data319 elif hasattr(data, '__iter__'):320- try:321- dict(data)322- except ValueError:323- raise ValueError('Unable to encode lists with elements that '324- 'are not 2-tuples.')325-326- params = list(data.items() if isinstance(data, dict) else data)320 result = []328- for k, vs in params:321+ for k, vs in to_key_val_list(data):322 for v in isinstance(vs, list) and vs or [vs]:323 result.append(324 (k.encode('utf-8') if isinstance(k, str) else k,325 v.encode('utf-8') if isinstance(v, str) else v))5 unmodified lines331 332 if (not files) or isinstance(self.data, str):333 return None334 342- try:343- fields = list(self.data.items())344- except AttributeError:345- dict(self.data)346- fields = list(self.data)335+ fields = to_key_val_list(self.data)336+ files = to_key_val_list(files)337 348- try:349- dict(files)350- except ValueError:351- raise ValueError('Unable to encode lists with elements that '352- 'are not 2-tuples.')353-354- if isinstance(files, dict):355- files = files.items()356-338 for (k, v) in files:339 # support for explicit filename340 if isinstance(v, (tuple, list)):341 fn, fp = v497 unmodified linesmodified:requests/sessions.py+14 added-19 removed
13 unmodified lines14 from .cookies import cookiejar_from_dict, remove_cookie_by_name15 from .defaults import defaults16 from .models import Request17 from .hooks import dispatch_hook18-from .utils import header_expand18+from .utils import header_expand, to_key_val_list19 from .packages.urllib3.poolmanager import PoolManager20 21 22 def merge_kwargs(local_kwarg, default_kwarg):14 unmodified lines37 # Bypass if not a dictionary (e.g. timeout)38 if not hasattr(default_kwarg, 'items'):39 return local_kwarg40 41- try:42- dict(local_kwarg)43- except ValueError:44- raise ValueError('Unable to encode lists with elements that are not '45- '2-tuples.')41+ local_kwarg = to_key_val_list(local_kwarg)42 47- if hasattr(local_kwarg, 'items'):48- local_kwarg = list(local_kwarg.items())49-43 # Update new values.44 kwargs = default_kwarg.copy()45 kwargs.update(local_kwarg)46 24 unmodified lines71 prefetch=False,72 verify=True,73 cert=None):74 82- self.headers = headers or {}75+ self.headers = to_key_val_list(headers or [])76 self.auth = auth77 self.timeout = timeout85- self.proxies = proxies or {}78+ self.proxies = to_key_val_list(proxies or [])79 self.hooks = hooks or {}87- self.params = params or {}80+ self.params = to_key_val_list(params or [])81 self.config = config or {}82 self.prefetch = prefetch83 self.verify = verify84 self.cert = cert64 unmodified lines149 150 method = str(method).upper()151 152 # Default empty dicts for dict params.160- data = {} if data is None else data161- files = {} if files is None else files162- headers = {} if headers is None else headers163- params = {} if params is None else params153+ data = [] if data is None else data154+ files = [] if files is None else files155+ headers = [] if headers is None else headers156+ params = [] if params is None else params157 hooks = {} if hooks is None else hooks158 prefetch = self.prefetch or prefetch159 160 # use session's hooks as defaults1 unmodified line162 hooks.setdefault(key, cb)163 164 # Expand header values.165 if headers:173- for k, v in list(headers.items()) or {}:174- headers[k] = header_expand(v)166+ expanded = []167+ for k, v in to_key_val_list(headers):168+ expanded.append((k, header_expand(v)))169+ headers = expanded170 171 args = dict(172 method=method,173 url=url,5 unmodified lines179 auth=auth,180 hooks=hooks,181 timeout=timeout,182 allow_redirects=allow_redirects,188- proxies=proxies,183+ proxies=to_key_val_list(proxies),184 config=config,185 prefetch=prefetch,186 verify=verify,187 cert=cert,141 unmodified linesmodified:requests/utils.py+27 added
110 unmodified lines111 if name and name[0] != '<' and name[-1] != '>':112 return name113 114 115+def to_key_val_list(value):116+ """Take an object and test to see if it can be represented as a117+ dictionary. Unless it can not be represented as such, return a list of118+ tuples, e.g.,:119+120+ >>> to_key_val_list([('key', 'val')])121+ [('key', 'val')]122+ >>> to_key_val_list('string')123+ ValueError: ...124+ >>> to_key_val_list({'key': 'val'})125+ [('key', 'val')]126+ """127+ if value is None:128+ return None129+130+ try:131+ dict(value)132+ except ValueError:133+ raise ValueError('Unable to encode lists with elements that are not '134+ '2-tuples.')135+136+ if isinstance(value, dict) or hasattr(value, 'items'):137+ value = value.items()138+139+ return list(value)140+141+142 # From mitsuhiko/werkzeug (used with permission).143 def parse_list_header(value):144 """Parse lists as described by RFC 2068 Section 2.145 372 unmodified lines