Skip to content
Myr

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

4 files+226 added−27 removed

modified:requests/structures.py+62 added-25 removed
7 unmodified lines
89"""1011import os12import collections13from itertools import islice141516class IteratorProxy(object):
16 unmodified lines
33 def read(self, n):34 return "".join(islice(self.i, None, n))353636class CaseInsensitiveDict(dict):37 """Case-insensitive Dictionary37class CaseInsensitiveDict(collections.MutableMapping):38 """39 A case-insensitive ``dict``-like object.4041 Implements all methods and operations of42 ``collections.MutableMapping`` as well as dict's ``copy``. Also43 provides ``lower_items``.4445 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:5051 cid = CaseInsensitiveDict()52 cid['Accept'] = 'application/json'53 cid['aCCEPT'] == 'application/json' # True54 list(cid) == ['Accept'] # True5556 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.5942 @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.6348 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)7071 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)7576 def __getitem__(self, key):77 return self._store[key.lower()][1]7879 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()]8160 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())8463 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)8768 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 )9596 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())103104 # Copy is required105 def copy(self):106 return CaseInsensitiveDict(self._store.values())107108 def __repr__(self):109 return '%s(%r)' % (self.__class__.__name__, dict(self.items()))110111112class LookupDict(dict):113 """Dictionary lookup object."""114115 def __init__(self, name=None):
13 unmodified lines
modified:requests/utils.py+3 added-2 removed
21 unmodified lines
22from . import certs23from .compat import parse_http_list as _parse_list_header24from .compat import quote, urlparse, bytes, str, OrderedDict, urlunparse25from .cookies import RequestsCookieJar, cookiejar_from_dict26from .structures import CaseInsensitiveDict2728_hush_pyflakes = (RequestsCookieJar,)2930NETRC_FILES = ('.netrc', '_netrc')
418 unmodified lines
449 '%s/%s' % (p_system, p_release)])450451452def default_headers():452 return {453 return CaseInsensitiveDict({454 'User-Agent': default_user_agent(),455 'Accept-Encoding': ', '.join(('gzip', 'deflate', 'compress')),456 'Accept': '*/*'456 }457 })458459460def parse_header_links(value):461 """Return a dict of parsed link headers proxies.
89 unmodified lines
modified:AUTHORS.rst+1 added
122 unmodified lines
123- 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> @cdunklau
modified:test_requests.py+160 added
11 unmodified lines
12import requests13from requests.auth import HTTPDigestAuth14from requests.compat import str, cookielib15from requests.cookies import cookiejar_from_dict16from requests.structures import CaseInsensitiveDict1718try:19 import StringIO20except ImportError:
437 unmodified lines
458459 r = s.send(r.prepare())460 self.assertEqual(r.status_code, 200)461462 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 )476477478class TestCaseInsensitiveDict(unittest.TestCase):479480 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)485486 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)491492 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)497498 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'])503504 def test_len(self):505 cid = CaseInsensitiveDict({'a': 'a', 'b': 'b'})506 cid['A'] = 'a'507 self.assertEqual(len(cid), 2)508509 def test_getitem(self):510 cid = CaseInsensitiveDict({'Spam': 'blueval'})511 self.assertEqual(cid['spam'], 'blueval')512 self.assertEqual(cid['SPAM'], 'blueval')513514 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'])523524 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)530531 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)539540 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')548549 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')559560 def test_update_retains_unchanged(self):561 cid = CaseInsensitiveDict({'foo': 'foo', 'bar': 'bar'})562 cid.update({'foo': 'newfoo'})563 self.assertEquals(cid['bar'], 'bar')564565 def test_iter(self):566 cid = CaseInsensitiveDict({'Spam': 'spam', 'Eggs': 'eggs'})567 keys = frozenset(['Spam', 'Eggs'])568 self.assertEqual(frozenset(iter(cid)), keys)569570 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'})577578 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 )588589 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)597598 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)607608 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)619620621622if __name__ == '__main__':623 unittest.main()