Merge pull request #833 from sigmavirus24/fix_key_val_args
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Fixes #817.
authored by Kenneth Reitz · committed by Kenneth Reitz · parents f58013c, 8081d7b · Browse files · 5 files·+60 added−47 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
5 files+60 added−47 removed
- other:+60 added−47 removed
Provenance
- Commit
2ae7c5a- Tree
b6f0f5c- Author
Kenneth Reitz <me@kennethreitz.com>- Committer
Kenneth Reitz <me@kennethreitz.com>- Parent 1
f58013c- Parent 2
8081d7b
5 files changed+60 added−47 removed
modified:requests/compat.py+2 added
91 unmodified lines92 try:93 import cchardet as chardet94 except ImportError:95 from .packages import chardet96+ from .packages.urllib3.packages.ordered_dict import OrderedDict97 98 builtin_str = str99 bytes = str100 str = unicode8 unmodified lines109 from http import cookiejar as cookielib110 from http.cookies import Morsel111 from io import StringIO112 from .packages import chardet2 as chardet113+ from collections import OrderedDict114 115 builtin_str = str116 str = str117 bytes = bytes2 unmodified linesmodified:requests/models.py+1 added-1 removed
32 unmodified lines33 stream_decode_response_unicode, get_netrc_auth, get_environ_proxies,34 to_key_val_list, DEFAULT_CA_BUNDLE_PATH, parse_header_links, iter_slices)35 from .compat import (36 cookielib, urlparse, urlunparse, urljoin, urlsplit, urlencode, str, bytes,37- StringIO, is_py2, chardet, json, builtin_str, numeric_types)37+ StringIO, is_py2, chardet, json, builtin_str)38 39 REDIRECT_STATI = (codes.moved, codes.found, codes.other, codes.temporary_moved)40 CONTENT_CHUNK_SIZE = 10 * 102441 843 unmodified linesmodified:requests/sessions.py+18 added-29 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_expand, to_key_val_list18+from .utils import header_expand, from_key_val_list19 from .packages.urllib3.poolmanager import PoolManager20 21 22 def merge_kwargs(local_kwarg, default_kwarg):10 unmodified lines33 34 if local_kwarg is None:35 return default_kwarg36 37- kwargs = default_kwarg38- # If default_kwargs is a list rather than a dictionary attempt to convert39- # to dictionary. If the check fails, return local_kwargs.40- if isinstance(default_kwarg, list):41- try:42- kwargs = dict(kwargs)43- except ValueError:44- return local_kwarg45-37 # Bypass if not a dictionary (e.g. timeout)47- if not hasattr(kwargs, 'items'):38+ if not hasattr(default_kwarg, 'items'):39 return local_kwarg40 41+ default_kwarg = from_key_val_list(default_kwarg)50- local_kwarg = to_key_val_list(local_kwarg)42+ local_kwarg = from_key_val_list(local_kwarg)43 44 # Update new values.53- kwargs = kwargs.copy()45+ kwargs = default_kwarg.copy()46 kwargs.update(local_kwarg)47 48 # Remove keys that are set to None.57- for (k, v) in local_kwarg:49+ for (k, v) in local_kwarg.items():50 if v is None:51 del kwargs[k]52 53 return kwargs18 unmodified lines72 prefetch=True,73 verify=True,74 cert=None):75 84- #self.headers = to_key_val_list(headers or [])85- self.headers = headers or {}76+ self.headers = from_key_val_list(headers or [])77 self.auth = auth78 self.timeout = timeout88- self.proxies = to_key_val_list(proxies or [])89- self.hooks = hooks or {}90- self.params = to_key_val_list(params or [])91- self.config = config or {}79+ self.proxies = from_key_val_list(proxies or [])80+ self.hooks = from_key_val_list(hooks or {})81+ self.params = from_key_val_list(params or [])82+ self.config = from_key_val_list(config or {})83 self.prefetch = prefetch84 self.verify = verify85 self.cert = cert86 74 unmodified lines161 # Default empty dicts for dict params.162 data = [] if data is None else data163 files = [] if files is None else files164 headers = {} if headers is None else headers174- params = [] if params is None else params165+ params = {} if params is None else params166 hooks = {} if hooks is None else hooks167 prefetch = prefetch if prefetch is not None else self.prefetch168 169 # use session's hooks as defaults1 unmodified line171 hooks.setdefault(key, cb)172 173 # Expand header values.174 if headers:184- #e = [(k, header_expand(v)) for k, v in to_key_val_list(headers)]185- #headers = e186- for k, v in list(headers.items()) or {}:175+ for k, v in list(headers.items() or {}):176 headers[k] = header_expand(v)177 178 args = dict(179 method=method,180 url=url,181 data=data,193- params=params,194- headers=headers,182+ params=from_key_val_list(params),183+ headers=from_key_val_list(headers),184 cookies=cookies,185 files=files,186 auth=auth,198- hooks=hooks,187+ hooks=from_key_val_list(hooks),188 timeout=timeout,189 allow_redirects=allow_redirects,201- proxies=to_key_val_list(proxies),202- config=config,190+ proxies=from_key_val_list(proxies),191+ config=from_key_val_list(config),192 prefetch=prefetch,193 verify=verify,194 cert=cert,195 _poolmanager=self.poolmanager133 unmodified linesmodified:requests/structures.py+1 added
6 unmodified lines7 Data structures that power Requests.8 9 """10 11+12 class CaseInsensitiveDict(dict):13 """Case-insensitive Dictionary14 15 For example, ``headers['content-encoding']`` will return the52 unmodified linesmodified:requests/utils.py+38 added-17 removed
18 unmodified lines19 from netrc import netrc, NetrcParseError20 21 from . import __version__22 from .compat import parse_http_list as _parse_list_header23-from .compat import quote, urlparse, basestring, bytes, str23+from .compat import quote, urlparse, basestring, bytes, str, OrderedDict24 from .cookies import RequestsCookieJar, cookiejar_from_dict25 26 _hush_pyflakes = (RequestsCookieJar,)27 85 unmodified lines113 if name and name[0] != '<' and name[-1] != '>':114 return name115 116 117+def from_key_val_list(value):118+ """Take an object and test to see if it can be represented as a119+ dictionary. Unless it can not be represented as such, return an120+ OrderedDict, e.g.,121+122+ ::123+124+ >>> from_key_val_list([('key', 'val')])125+ OrderedDict([('key', 'val')])126+ >>> from_key_val_list('string')127+ ValueError: need more than 1 value to unpack128+ >>> from_key_val_list({'key': 'val'})129+ OrderedDict([('key', 'val')])130+ """131+ if value is None:132+ return None133+134+ if isinstance(value, (str, bytes, bool, int)):135+ raise ValueError('cannot encode objects that are not 2-tuples')136+137+ return OrderedDict(value)138+139+140 def to_key_val_list(value):141 """Take an object and test to see if it can be represented as a119- dictionary. Unless it can not be represented as such, return a list of120- tuples, e.g.,:142+ dictionary. If it can be, return a list of tuples, e.g.,143 122- >>> to_key_val_list([('key', 'val')])123- [('key', 'val')]124- >>> to_key_val_list('string')125- ValueError: ...126- >>> to_key_val_list({'key': 'val'})127- [('key', 'val')]144+ ::145+146+ >>> to_key_val_list([('key', 'val')])147+ [('key', 'val')]148+ >>> to_key_val_list({'key': 'val'})149+ [('key', 'val')]150+ >>> to_key_val_list('string')151+ ValueError: cannot encode objects that are not 2-tuples.152 """153 if value is None:154 return None155 132- try:133- dict(value)134- except ValueError:135- raise ValueError('Unable to encode lists with elements that are not '136- '2-tuples.')156+ if isinstance(value, (str, bytes, bool, int)):157+ raise ValueError('cannot encode objects that are not 2-tuples')158 138- if isinstance(value, dict) or hasattr(value, 'items'):159+ if isinstance(value, dict):160 value = value.items()161 162 return list(value)163 387 unmodified lines551 552 i.e. Link: <http:/.../front.jpeg>; rel=front; type="image/jpeg",<http://.../back.jpeg>; rel=back;type="image/jpeg"553 554 """534- 555+556 links = []557 558 replace_chars = " '\""559 11 unmodified lines571 try:572 key,value = param.split("=")573 except ValueError:574 break554- 575+576 link[key.strip(replace_chars)] = value.strip(replace_chars)577 578 links.append(link)579 1 unmodified line