Merge pull request #1339 from cdunklau/case_insensitive_headers_cleanup
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Rewrite CaseInsensitiveDict to work correctly/sanely
authored by Kenneth Reitz · committed by Kenneth Reitz · parents f8f1db8, f7596c7 · Browse files · 4 files·+226 added−27 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
4 files+226 added−27 removed
- other:+226 added−27 removed
Provenance
- Commit
e6e9b55- Tree
3025696- Author
Kenneth Reitz <me@kennethreitz.com>- Committer
Kenneth Reitz <me@kennethreitz.com>- Parent 1
f8f1db8- Parent 2
f7596c7
4 files changed+226 added−27 removed
modified:requests/structures.py+62 added-25 removed
7 unmodified lines8 9 """10 11 import os12+import collections13 from itertools import islice14 15 16 class IteratorProxy(object):16 unmodified lines33 def read(self, n):34 return "".join(islice(self.i, None, n))35 36 36-class CaseInsensitiveDict(dict):37- """Case-insensitive Dictionary37+class CaseInsensitiveDict(collections.MutableMapping):38+ """39+ A case-insensitive ``dict``-like object.40 41+ Implements all methods and operations of42+ ``collections.MutableMapping`` as well as dict's ``copy``. Also43+ provides ``lower_items``.44+45+ All keys are expected to be strings. The structure remembers the46+ case of the last key to be set, and ``iter(instance)``,47+ ``keys()``, ``items()``, ``iterkeys()``, and ``iteritems()``48+ will contain case-sensitive keys. However, querying and contains49+ testing is case insensitive:50+51+ cid = CaseInsensitiveDict()52+ cid['Accept'] = 'application/json'53+ cid['aCCEPT'] == 'application/json' # True54+ list(cid) == ['Accept'] # True55+56 For example, ``headers['content-encoding']`` will return the40- value of a ``'Content-Encoding'`` response header."""57+ value of a ``'Content-Encoding'`` response header, regardless58+ of how the header name was originally stored.59 42- @property43- def lower_keys(self):44- if not hasattr(self, '_lower_keys') or not self._lower_keys:45- self._lower_keys = dict((k.lower(), k) for k in list(self.keys()))46- return self._lower_keys60+ If the constructor, ``.update``, or equality comparison61+ operations are given keys that have equal ``.lower()``s, the62+ behavior is undefined.63 48- def _clear_lower_keys(self):49- if hasattr(self, '_lower_keys'):50- self._lower_keys.clear()64+ """65+ def __init__(self, data=None, **kwargs):66+ self._store = dict()67+ if data is None:68+ data = {}69+ self.update(data, **kwargs)70 71 def __setitem__(self, key, value):53- dict.__setitem__(self, key, value)54- self._clear_lower_keys()72+ # Use the lowercased key for lookups, but store the actual73+ # key alongside the value.74+ self._store[key.lower()] = (key, value)75 76+ def __getitem__(self, key):77+ return self._store[key.lower()][1]78+79 def __delitem__(self, key):57- dict.__delitem__(self, self.lower_keys.get(key.lower(), key))58- self._lower_keys.clear()80+ del self._store[key.lower()]81 60- def __contains__(self, key):61- return key.lower() in self.lower_keys82+ def __iter__(self):83+ return (casedkey for casedkey, mappedvalue in self._store.values())84 63- def __getitem__(self, key):64- # We allow fall-through here, so values default to None65- if key in self:66- return dict.__getitem__(self, self.lower_keys[key.lower()])85+ def __len__(self):86+ return len(self._store)87 68- def get(self, key, default=None):69- if key in self:70- return self[key]88+ def lower_items(self):89+ """Like iteritems(), but with all lowercase keys."""90+ return (91+ (lowerkey, keyval[1])92+ for (lowerkey, keyval)93+ in self._store.items()94+ )95+96+ def __eq__(self, other):97+ if isinstance(other, collections.Mapping):98+ other = CaseInsensitiveDict(other)99 else:72- return default100+ return NotImplemented101+ # Compare insensitively102+ return dict(self.lower_items()) == dict(other.lower_items())103 104+ # Copy is required105+ def copy(self):106+ return CaseInsensitiveDict(self._store.values())107 108+ def __repr__(self):109+ return '%s(%r)' % (self.__class__.__name__, dict(self.items()))110+111+112 class LookupDict(dict):113 """Dictionary lookup object."""114 115 def __init__(self, name=None):13 unmodified linesmodified:requests/utils.py+3 added-2 removed
21 unmodified lines22 from . import certs23 from .compat import parse_http_list as _parse_list_header24 from .compat import quote, urlparse, bytes, str, OrderedDict, urlunparse25 from .cookies import RequestsCookieJar, cookiejar_from_dict26+from .structures import CaseInsensitiveDict27 28 _hush_pyflakes = (RequestsCookieJar,)29 30 NETRC_FILES = ('.netrc', '_netrc')418 unmodified lines449 '%s/%s' % (p_system, p_release)])450 451 452 def default_headers():452- return {453+ return CaseInsensitiveDict({454 'User-Agent': default_user_agent(),455 'Accept-Encoding': ', '.join(('gzip', 'deflate', 'compress')),456 'Accept': '*/*'456- }457+ })458 459 460 def parse_header_links(value):461 """Return a dict of parsed link headers proxies.89 unmodified linesmodified:AUTHORS.rst+1 added
122 unmodified lines123 - Denis Ryzhkov <denisr@denisr.com>124 - Wilfred Hughes <me@wilfred.me.uk> @dontYetKnow125 - Dmitry Medvinsky <me@dmedvinsky.name>126 - Bryce Boe <bbzbryce@gmail.com> @bboe127+- Colin Dunklau <colin.dunklau@gmail.com> @cdunklaumodified:test_requests.py+160 added
11 unmodified lines12 import requests13 from requests.auth import HTTPDigestAuth14 from requests.compat import str, cookielib15 from requests.cookies import cookiejar_from_dict16+from requests.structures import CaseInsensitiveDict17 18 try:19 import StringIO20 except ImportError:437 unmodified lines458 459 r = s.send(r.prepare())460 self.assertEqual(r.status_code, 200)461 462+ def test_fixes_1329(self):463+ s = requests.Session()464+ s.headers.update({'accept': 'application/json'})465+ r = s.get(httpbin('get'))466+ headers = r.request.headers467+ # ASCII encode because of key comparison changes in py3468+ self.assertEqual(469+ headers['accept'.encode('ascii')],470+ 'application/json'471+ )472+ self.assertEqual(473+ headers['Accept'.encode('ascii')],474+ 'application/json'475+ )476 477+478+class TestCaseInsensitiveDict(unittest.TestCase):479+480+ def test_mapping_init(self):481+ cid = CaseInsensitiveDict({'Foo': 'foo','BAr': 'bar'})482+ self.assertEqual(len(cid), 2)483+ self.assertTrue('foo' in cid)484+ self.assertTrue('bar' in cid)485+486+ def test_iterable_init(self):487+ cid = CaseInsensitiveDict([('Foo', 'foo'), ('BAr', 'bar')])488+ self.assertEqual(len(cid), 2)489+ self.assertTrue('foo' in cid)490+ self.assertTrue('bar' in cid)491+492+ def test_kwargs_init(self):493+ cid = CaseInsensitiveDict(FOO='foo', BAr='bar')494+ self.assertEqual(len(cid), 2)495+ self.assertTrue('foo' in cid)496+ self.assertTrue('bar' in cid)497+498+ def test_docstring_example(self):499+ cid = CaseInsensitiveDict()500+ cid['Accept'] = 'application/json'501+ self.assertEqual(cid['aCCEPT'], 'application/json')502+ self.assertEqual(list(cid), ['Accept'])503+504+ def test_len(self):505+ cid = CaseInsensitiveDict({'a': 'a', 'b': 'b'})506+ cid['A'] = 'a'507+ self.assertEqual(len(cid), 2)508+509+ def test_getitem(self):510+ cid = CaseInsensitiveDict({'Spam': 'blueval'})511+ self.assertEqual(cid['spam'], 'blueval')512+ self.assertEqual(cid['SPAM'], 'blueval')513+514+ def test_fixes_649(self):515+ cid = CaseInsensitiveDict()516+ cid['spam'] = 'oneval'517+ cid['Spam'] = 'twoval'518+ cid['sPAM'] = 'redval'519+ cid['SPAM'] = 'blueval'520+ self.assertEqual(cid['spam'], 'blueval')521+ self.assertEqual(cid['SPAM'], 'blueval')522+ self.assertEqual(list(cid.keys()), ['SPAM'])523+524+ def test_delitem(self):525+ cid = CaseInsensitiveDict()526+ cid['Spam'] = 'someval'527+ del cid['sPam']528+ self.assertFalse('spam' in cid)529+ self.assertEqual(len(cid), 0)530+531+ def test_contains(self):532+ cid = CaseInsensitiveDict()533+ cid['Spam'] = 'someval'534+ self.assertTrue('Spam' in cid)535+ self.assertTrue('spam' in cid)536+ self.assertTrue('SPAM' in cid)537+ self.assertTrue('sPam' in cid)538+ self.assertFalse('notspam' in cid)539+540+ def test_get(self):541+ cid = CaseInsensitiveDict()542+ cid['spam'] = 'oneval'543+ cid['SPAM'] = 'blueval'544+ self.assertEqual(cid.get('spam'), 'blueval')545+ self.assertEqual(cid.get('SPAM'), 'blueval')546+ self.assertEqual(cid.get('sPam'), 'blueval')547+ self.assertEqual(cid.get('notspam', 'default'), 'default')548+549+ def test_update(self):550+ cid = CaseInsensitiveDict()551+ cid['spam'] = 'blueval'552+ cid.update({'sPam': 'notblueval'})553+ self.assertEqual(cid['spam'], 'notblueval')554+ cid = CaseInsensitiveDict({'Foo': 'foo','BAr': 'bar'})555+ cid.update({'fOO': 'anotherfoo', 'bAR': 'anotherbar'})556+ self.assertEqual(len(cid), 2)557+ self.assertEqual(cid['foo'], 'anotherfoo')558+ self.assertEqual(cid['bar'], 'anotherbar')559+560+ def test_update_retains_unchanged(self):561+ cid = CaseInsensitiveDict({'foo': 'foo', 'bar': 'bar'})562+ cid.update({'foo': 'newfoo'})563+ self.assertEquals(cid['bar'], 'bar')564+565+ def test_iter(self):566+ cid = CaseInsensitiveDict({'Spam': 'spam', 'Eggs': 'eggs'})567+ keys = frozenset(['Spam', 'Eggs'])568+ self.assertEqual(frozenset(iter(cid)), keys)569+570+ def test_equality(self):571+ cid = CaseInsensitiveDict({'SPAM': 'blueval', 'Eggs': 'redval'})572+ othercid = CaseInsensitiveDict({'spam': 'blueval', 'eggs': 'redval'})573+ self.assertEqual(cid, othercid)574+ del othercid['spam']575+ self.assertNotEqual(cid, othercid)576+ self.assertEqual(cid, {'spam': 'blueval', 'eggs': 'redval'})577+578+ def test_setdefault(self):579+ cid = CaseInsensitiveDict({'Spam': 'blueval'})580+ self.assertEqual(581+ cid.setdefault('spam', 'notblueval'),582+ 'blueval'583+ )584+ self.assertEqual(585+ cid.setdefault('notspam', 'notblueval'),586+ 'notblueval'587+ )588+589+ def test_lower_items(self):590+ cid = CaseInsensitiveDict({591+ 'Accept': 'application/json',592+ 'user-Agent': 'requests',593+ })594+ keyset = frozenset(lowerkey for lowerkey, v in cid.lower_items())595+ lowerkeyset = frozenset(['accept', 'user-agent'])596+ self.assertEqual(keyset, lowerkeyset)597+598+ def test_preserve_key_case(self):599+ cid = CaseInsensitiveDict({600+ 'Accept': 'application/json',601+ 'user-Agent': 'requests',602+ })603+ keyset = frozenset(['Accept', 'user-Agent'])604+ self.assertEqual(frozenset(i[0] for i in cid.items()), keyset)605+ self.assertEqual(frozenset(cid.keys()), keyset)606+ self.assertEqual(frozenset(cid), keyset)607+608+ def test_preserve_last_key_case(self):609+ cid = CaseInsensitiveDict({610+ 'Accept': 'application/json',611+ 'user-Agent': 'requests',612+ })613+ cid.update({'ACCEPT': 'application/json'})614+ cid['USER-AGENT'] = 'requests'615+ keyset = frozenset(['ACCEPT', 'USER-AGENT'])616+ self.assertEqual(frozenset(i[0] for i in cid.items()), keyset)617+ self.assertEqual(frozenset(cid.keys()), keyset)618+ self.assertEqual(frozenset(cid), keyset)619+620+621+622 if __name__ == '__main__':623 unittest.main()