Merge pull request #1343 from gazpachoking/#1321
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Refactor merge_kwargs
authored by Kenneth Reitz · committed by Kenneth Reitz · parents 8eb4243, 9811424 · Browse files · 3 files·+47 added−45 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+47 added−45 removed
- other:+47 added−45 removed
Provenance
- Commit
1621015- Tree
8b3a158- Author
Kenneth Reitz <me@kennethreitz.com>- Committer
Kenneth Reitz <me@kennethreitz.com>- Parent 1
8eb4243- Parent 2
9811424
3 files changed+47 added−45 removed
modified:requests/sessions.py+31 added-43 removed
7 unmodified lines8 requests (cookies, auth, proxies).9 10 """11 import os12+from collections import Mapping13 from datetime import datetime14 15 from .compat import cookielib, OrderedDict, urljoin, urlparse16 from .cookies import cookiejar_from_dict, extract_cookies_to_jar, RequestsCookieJar17 from .models import Request, PreparedRequest18 from .hooks import default_hooks, dispatch_hook18-from .utils import from_key_val_list, default_headers19+from .utils import to_key_val_list, default_headers20 from .exceptions import TooManyRedirects, InvalidSchema21+from .structures import CaseInsensitiveDict22 23 from .adapters import HTTPAdapter24 25 from .utils import requote_uri, get_environ_proxies, get_netrc_auth7 unmodified lines33 )34 DEFAULT_REDIRECT_LIMIT = 3035 36 35-def merge_kwargs(local_kwarg, default_kwarg):36- """Merges kwarg dictionaries.37-38- If a local key in the dictionary is set to None, it will be removed.37+def merge_setting(request_setting, session_setting, dict_class=OrderedDict):38 """39+ Determines appropriate setting for a given request, taking into account the40+ explicit setting on that request, and the setting in the session. If a41+ setting is a dictionary, they will be merged together using `dict_class`42+ """43 41- if default_kwarg is None:42- return local_kwarg44+ if session_setting is None:45+ return request_setting46 44- if isinstance(local_kwarg, str):45- return local_kwarg47+ if request_setting is None:48+ return session_setting49 47- if local_kwarg is None:48- return default_kwarg50+ # Bypass if not a dictionary (e.g. verify)51+ if not (52+ isinstance(session_setting, Mapping) and53+ isinstance(request_setting, Mapping)54+ ):55+ return request_setting56 50- # Bypass if not a dictionary (e.g. timeout)51- if not hasattr(default_kwarg, 'items'):52- return local_kwarg57+ merged_setting = dict_class(to_key_val_list(session_setting))58+ merged_setting.update(to_key_val_list(request_setting))59 54- default_kwarg = from_key_val_list(default_kwarg)55- local_kwarg = from_key_val_list(local_kwarg)56-57- # Update new values in a case-insensitive way58- def get_original_key(original_keys, new_key):59- """60- Finds the key from original_keys that case-insensitive matches new_key.61- """62- for original_key in original_keys:63- if key.lower() == original_key.lower():64- return original_key65- return new_key66-67- kwargs = default_kwarg.copy()68- original_keys = kwargs.keys()69- for key, value in local_kwarg.items():70- kwargs[get_original_key(original_keys, key)] = value71-60 # Remove keys that are set to None.73- for (k, v) in local_kwarg.items():61+ for (k, v) in request_setting.items():62 if v is None:75- del kwargs[k]63+ del merged_setting[k]64 77- return kwargs65+ return merged_setting66 67 68 class SessionRedirectMixin(object):69 def resolve_redirects(self, resp, req, stream=False, timeout=None,228 unmodified lines298 if not verify and verify is not False:299 verify = os.environ.get('CURL_CA_BUNDLE')300 301 # Merge all the kwargs.314- params = merge_kwargs(params, self.params)315- headers = merge_kwargs(headers, self.headers)316- auth = merge_kwargs(auth, self.auth)317- proxies = merge_kwargs(proxies, self.proxies)318- hooks = merge_kwargs(hooks, self.hooks)319- stream = merge_kwargs(stream, self.stream)320- verify = merge_kwargs(verify, self.verify)321- cert = merge_kwargs(cert, self.cert)302+ params = merge_setting(params, self.params)303+ headers = merge_setting(headers, self.headers, dict_class=CaseInsensitiveDict)304+ auth = merge_setting(auth, self.auth)305+ proxies = merge_setting(proxies, self.proxies)306+ hooks = merge_setting(hooks, self.hooks)307+ stream = merge_setting(stream, self.stream)308+ verify = merge_setting(verify, self.verify)309+ cert = merge_setting(cert, self.cert)310 311 # Create the Request.312 req = Request()313 req.method = method.upper()188 unmodified linesmodified:requests/utils.py+2 added-2 removed
9 unmodified lines10 """11 12 import cgi13 import codecs14+import collections15 import os16 import platform17 import re18 import sys18-import zlib19 from netrc import netrc, NetrcParseError20 21 from . import __version__22 from . import certs111 unmodified lines134 135 if isinstance(value, (str, bytes, bool, int)):136 raise ValueError('cannot encode objects that are not 2-tuples')137 138- if isinstance(value, dict):138+ if isinstance(value, collections.Mapping):139 value = value.items()140 141 return list(value)142 408 unmodified linesmodified:test_requests.py+14 added
519 unmodified lines520 s2.mount('https://', HTTPAdapter())521 self.assertTrue('http://' in s2.adapters)522 self.assertTrue('https://' in s2.adapters)523 524+ def test_header_remove_is_case_insensitive(self):525+ # From issue #1321526+ s = requests.Session()527+ s.headers['foo'] = 'bar'528+ r = s.get(httpbin('get'), headers={'FOO': None})529+ assert 'foo' not in r.request.headers530+531+ def test_params_are_merged_case_sensitive(self):532+ s = requests.Session()533+ s.params['foo'] = 'bar'534+ r = s.get(httpbin('get'), params={'FOO': 'bar'})535+ assert r.json()['args'] == {'foo': 'bar', 'FOO': 'bar'}536+537+538 def test_long_authinfo_in_url(self):539 url = 'http://{0}:{1}@{2}:9000/path?query#frag'.format(540 'E8A3BE87-9E3F-4620-8858-95478E385B5B',541 'EA770032-DA4D-4D84-8CE9-29C6D910BF1E',152 unmodified lines