Skip to content
Myr

Refactor merge_kwargs for clarity and to fix a few bugs

Before adoption: this commit came in with the history the project adopted, so no landing records it.

authored by Chase Sterling · committed by Chase Sterling · parent 8eb4243 · 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

3 files+47 added−45 removed

modified:requests/sessions.py+31 added-43 removed
7 unmodified lines
8requests (cookies, auth, proxies).910"""11import os12from collections import Mapping13from datetime import datetime1415from .compat import cookielib, OrderedDict, urljoin, urlparse16from .cookies import cookiejar_from_dict, extract_cookies_to_jar, RequestsCookieJar17from .models import Request, PreparedRequest18from .hooks import default_hooks, dispatch_hook18from .utils import from_key_val_list, default_headers19from .utils import to_key_val_list, default_headers20from .exceptions import TooManyRedirects, InvalidSchema21from .structures import CaseInsensitiveDict2223from .adapters import HTTPAdapter2425from .utils import requote_uri, get_environ_proxies, get_netrc_auth
7 unmodified lines
33)34DEFAULT_REDIRECT_LIMIT = 30353635def merge_kwargs(local_kwarg, default_kwarg):36 """Merges kwarg dictionaries.3738 If a local key in the dictionary is set to None, it will be removed.37def 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 """4341 if default_kwarg is None:42 return local_kwarg44 if session_setting is None:45 return request_setting4644 if isinstance(local_kwarg, str):45 return local_kwarg47 if request_setting is None:48 return session_setting4947 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_setting5650 # 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))5954 default_kwarg = from_key_val_list(default_kwarg)55 local_kwarg = from_key_val_list(local_kwarg)5657 # 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_key6667 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)] = value7160 # 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]6477 return kwargs65 return merged_setting666768class SessionRedirectMixin(object):69 def resolve_redirects(self, resp, req, stream=False, timeout=None,
228 unmodified lines
298 if not verify and verify is not False:299 verify = os.environ.get('CURL_CA_BUNDLE')300301 # 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)310311 # Create the Request.312 req = Request()313 req.method = method.upper()
188 unmodified lines
modified:requests/utils.py+2 added-2 removed
9 unmodified lines
10"""1112import cgi13import codecs14import collections15import os16import platform17import re18import sys18import zlib19from netrc import netrc, NetrcParseError2021from . import __version__22from . import certs
111 unmodified lines
134135 if isinstance(value, (str, bytes, bool, int)):136 raise ValueError('cannot encode objects that are not 2-tuples')137138 if isinstance(value, dict):138 if isinstance(value, collections.Mapping):139 value = value.items()140141 return list(value)142
408 unmodified lines
modified:test_requests.py+14 added
519 unmodified lines
520 s2.mount('https://', HTTPAdapter())521 self.assertTrue('http://' in s2.adapters)522 self.assertTrue('https://' in s2.adapters)523524 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.headers530531 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'}536537538 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