Skip to content
Myr

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

3 files+45 added−42 removed

modified:requests/models.py+4 added-23 removed
27 unmodified lines
28 URLRequired, SSLError, MissingSchema, InvalidSchema, InvalidURL)29from .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)33from .compat import (34 cookielib, urlparse, urlunparse, urljoin, urlsplit, urlencode, str, bytes,35 StringIO, is_py2, chardet, json, builtin_str)36
279 unmodified lines
316 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.')325326 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 lines
331332 if (not files) or isinstance(self.data, str):333 return None334342 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)337348 try:349 dict(files)350 except ValueError:351 raise ValueError('Unable to encode lists with elements that '352 'are not 2-tuples.')353354 if isinstance(files, dict):355 files = files.items()356338 for (k, v) in files:339 # support for explicit filename340 if isinstance(v, (tuple, list)):341 fn, fp = v
497 unmodified lines
modified:requests/sessions.py+14 added-19 removed
13 unmodified lines
14from .cookies import cookiejar_from_dict, remove_cookie_by_name15from .defaults import defaults16from .models import Request17from .hooks import dispatch_hook18from .utils import header_expand18from .utils import header_expand, to_key_val_list19from .packages.urllib3.poolmanager import PoolManager202122def merge_kwargs(local_kwarg, default_kwarg):
14 unmodified lines
37 # Bypass if not a dictionary (e.g. timeout)38 if not hasattr(default_kwarg, 'items'):39 return local_kwarg4041 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)4247 if hasattr(local_kwarg, 'items'):48 local_kwarg = list(local_kwarg.items())4943 # Update new values.44 kwargs = default_kwarg.copy()45 kwargs.update(local_kwarg)46
24 unmodified lines
71 prefetch=False,72 verify=True,73 cert=None):7482 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 = cert
64 unmodified lines
149150 method = str(method).upper()151152 # 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 prefetch159160 # use session's hooks as defaults
1 unmodified line
162 hooks.setdefault(key, cb)163164 # 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 = expanded170171 args = dict(172 method=method,173 url=url,
5 unmodified lines
179 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 lines
modified:requests/utils.py+27 added
110 unmodified lines
111 if name and name[0] != '<' and name[-1] != '>':112 return name113114115def 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.,:119120 >>> 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 None129130 try:131 dict(value)132 except ValueError:133 raise ValueError('Unable to encode lists with elements that are not '134 '2-tuples.')135136 if isinstance(value, dict) or hasattr(value, 'items'):137 value = value.items()138139 return list(value)140141142# From mitsuhiko/werkzeug (used with permission).143def parse_list_header(value):144 """Parse lists as described by RFC 2068 Section 2.145
372 unmodified lines