Header keys should be native strings.
Before adoption: this commit came in with the history the project adopted, so no landing records it.
This commit follows a discussion on IRC. For more information, see the Pull Request associated with it.
authored by Cory Benfield · committed by Cory Benfield · parent 9473f15 · Browse files · 3 files·+40 added−11 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+40 added−11 removed
- other:+40 added−11 removed
Provenance
- Commit
f577559- Tree
60feb4b- Author
Cory Benfield <lukasaoz@gmail.com>- Committer
Cory Benfield <lukasaoz@gmail.com>- Parent
9473f15
3 files changed+40 added−11 removed
modified:requests/models.py+2 added-2 removed
21 unmodified lines22 from .exceptions import HTTPError, RequestException, MissingSchema, InvalidURL23 from .utils import (24 guess_filename, get_auth_from_url, requote_uri,25 stream_decode_response_unicode, to_key_val_list, parse_header_links,26- iter_slices, guess_json_utf, super_len)26+ iter_slices, guess_json_utf, super_len, to_native_string)27 from .compat import (28 cookielib, urlunparse, urlsplit, urlencode, str, bytes, StringIO,29 is_py2, chardet, json, builtin_str, basestring)30 314 unmodified lines345 def prepare_headers(self, headers):346 """Prepares the given HTTP headers."""347 348 if headers:349- headers = dict((name.encode('ascii'), value) for name, value in headers.items())349+ headers = dict((to_native_string(name), value) for name, value in headers.items())350 self.headers = CaseInsensitiveDict(headers)351 else:352 self.headers = CaseInsensitiveDict()353 353 unmodified linesmodified:requests/utils.py+25 added-6 removed
19 unmodified lines20 21 from . import __version__22 from . import certs23 from .compat import parse_http_list as _parse_list_header24-from .compat import quote, urlparse, bytes, str, OrderedDict, urlunparse25-from .compat import getproxies, proxy_bypass24+from .compat import (quote, urlparse, bytes, str, OrderedDict, urlunparse,25+ is_py2, is_py3, builtin_str, getproxies, proxy_bypass)26 from .cookies import RequestsCookieJar, cookiejar_from_dict27 from .structures import CaseInsensitiveDict28 29 _hush_pyflakes = (RequestsCookieJar,)362 unmodified lines392 # First check whether no_proxy is defined. If it is, check that the URL393 # we're getting isn't in the no_proxy list.394 no_proxy = get_proxy('no_proxy')395 netloc = urlparse(url).netloc396- 396+397 if no_proxy:398 # We need to check whether we match here. We need to see if we match399 # the end of the netloc, both with and without the port.400 no_proxy = no_proxy.split(',')401- 401+402 for host in no_proxy:403 if netloc.endswith(host) or netloc.split(':')[0].endswith(host):404 # The URL does match something in no_proxy, so we don't want405 # to apply the proxies on this URL.406 return {}407- 407+408 # If the system proxy settings indicate that this URL should be bypassed,409 # don't proxy.410 if proxy_bypass(netloc):411 return {}1 unmodified line413 # If we get here, we either didn't have no_proxy set or we're not going414 # anywhere that no_proxy applies to, and the system settings don't require415 # bypassing the proxy for the current URL.416 return getproxies()417- 417 418+419 def default_user_agent():420 """Return a string representing the default user agent."""421 _implementation = platform.python_implementation()422 122 unmodified lines545 parsed = urlparse(url)546 return (parsed.username, parsed.password)547 else:548 return ('', '')549+550+551+def to_native_string(string, encoding='ascii'):552+ """553+ Given a string object, regardless of type, returns a representation of that554+ string in the native string type, encoding and decoding where necessary.555+ This assumes ASCII unless told otherwise.556+ """557+ out = None558+559+ if isinstance(string, builtin_str):560+ out = string561+ else:562+ if is_py2:563+ out = string.encode(encoding)564+ else:565+ out = string.decode(encoding)566+567+ return outmodified:test_requests.py+13 added-3 removed
197 unmodified lines198 # Make sure the cookie was sent199 assert r.json()['cookies']['foo'] == 'bar'200 # Make sure the session cj is still the custom one201 assert s.cookies is cj202- 202+203 def test_requests_in_history_are_not_overridden(self):204 resp = requests.get(httpbin('redirect/3'))205 urls = [r.url for r in resp.history]206 req_urls = [r.request.url for r in resp.history]207 self.assertEquals(urls, req_urls)208- 208+209 def test_user_agent_transfers(self):210 211 heads = {212 'User-agent': 'Mozilla/5.0 (github.com/kennethreitz/requests)'49 unmodified lines262 r = requests.get(url, auth=wrong_auth)263 self.assertEqual(r.status_code, 401)264 265 s = requests.session()266- 266+267 # Should use netrc and work.268 r = s.get(url)269 self.assertEqual(r.status_code, 200)270 368 unmodified lines639 )640 r = requests.Request('GET', url).prepare()641 self.assertEqual(r.url, url)642 643+ def test_header_keys_are_native(self):644+ headers = {u'unicode': 'blah', 'byte'.encode('ascii'): 'blah'}645+ r = requests.Request('GET', httpbin('get'), headers=headers)646+ p = r.prepare()647 648+ # This is testing that they are builtin strings. A bit weird, but there649+ # we go.650+ self.assertTrue('unicode' in p.headers.keys())651+ self.assertTrue('byte' in p.headers.keys())652+653+654 class TestCaseInsensitiveDict(unittest.TestCase):655 656 def test_mapping_init(self):657 cid = CaseInsensitiveDict({'Foo': 'foo','BAr': 'bar'})142 unmodified lines