Skip to content
Myr

structures.py

This file

Path

requests/structures.py

105 lines · 2.9 KiB · Python

Last changed by

Merge pull request #3429 from nateprewitt/docstring_cleanupKenneth Reitzbefore adoptionfb01456

History of this file

Take it

1# -*- coding: utf-8 -*-23"""4requests.structures5~~~~~~~~~~~~~~~~~~~67Data structures that power Requests.8"""910import collections1112from .compat import OrderedDict131415class CaseInsensitiveDict(collections.MutableMapping):16    """A case-insensitive ``dict``-like object.1718    Implements all methods and operations of19    ``collections.MutableMapping`` as well as dict's ``copy``. Also20    provides ``lower_items``.2122    All keys are expected to be strings. The structure remembers the23    case of the last key to be set, and ``iter(instance)``,24    ``keys()``, ``items()``, ``iterkeys()``, and ``iteritems()``25    will contain case-sensitive keys. However, querying and contains26    testing is case insensitive::2728        cid = CaseInsensitiveDict()29        cid['Accept'] = 'application/json'30        cid['aCCEPT'] == 'application/json'  # True31        list(cid) == ['Accept']  # True3233    For example, ``headers['content-encoding']`` will return the34    value of a ``'Content-Encoding'`` response header, regardless35    of how the header name was originally stored.3637    If the constructor, ``.update``, or equality comparison38    operations are given keys that have equal ``.lower()``s, the39    behavior is undefined.40    """4142    def __init__(self, data=None, **kwargs):43        self._store = OrderedDict()44        if data is None:45            data = {}46        self.update(data, **kwargs)4748    def __setitem__(self, key, value):49        # Use the lowercased key for lookups, but store the actual50        # key alongside the value.51        self._store[key.lower()] = (key, value)5253    def __getitem__(self, key):54        return self._store[key.lower()][1]5556    def __delitem__(self, key):57        del self._store[key.lower()]5859    def __iter__(self):60        return (casedkey for casedkey, mappedvalue in self._store.values())6162    def __len__(self):63        return len(self._store)6465    def lower_items(self):66        """Like iteritems(), but with all lowercase keys."""67        return (68            (lowerkey, keyval[1])69            for (lowerkey, keyval)70            in self._store.items()71        )7273    def __eq__(self, other):74        if isinstance(other, collections.Mapping):75            other = CaseInsensitiveDict(other)76        else:77            return NotImplemented78        # Compare insensitively79        return dict(self.lower_items()) == dict(other.lower_items())8081    # Copy is required82    def copy(self):83        return CaseInsensitiveDict(self._store.values())8485    def __repr__(self):86        return str(dict(self.items()))878889class LookupDict(dict):90    """Dictionary lookup object."""9192    def __init__(self, name=None):93        self.name = name94        super(LookupDict, self).__init__()9596    def __repr__(self):97        return '<lookup \'%s\'>' % (self.name)9899    def __getitem__(self, key):100        # We allow fall-through here, so values default to None101102        return self.__dict__.get(key, None)103104    def get(self, key, default=None):105        return self.__dict__.get(key, default)