import warnings
from six import BytesIO, text_type
from six.moves.urllib.parse import urlparse, parse_qsl
-from .util import CaseInsensitiveDict
+from .util import HeadersDict
class Request(object):
- """
- VCR's representation of a request.
- """
+ """Represent an HTTP request in vcrpy."""
def __init__(self, method, uri, body, headers):
self.method = method
'method': self.method,
'uri': self.uri,
'body': self.body,
- 'headers': dict(((k, [v]) for k, v in self.headers.items())),
+ 'headers': self.headers.serialize,
}
@classmethod
def _from_dict(cls, dct):
return Request(**dct)
-
-
-class HeadersDict(CaseInsensitiveDict):
- """
- There is a weird quirk in HTTP. You can send the same header twice. For
- this reason, headers are represented by a dict, with lists as the values.
- However, it appears that HTTPlib is completely incapable of sending the
- same header twice. This puts me in a weird position: I want to be able to
- accurately represent HTTP headers in cassettes, but I don't want the extra
- step of always having to do [0] in the general case, i.e.
- request.headers['key'][0]
-
- In addition, some servers sometimes send the same header more than once,
- and httplib *can* deal with this situation.
-
- Futhermore, I wanted to keep the request and response cassette format as
- similar as possible.
-
- For this reason, in cassettes I keep a dict with lists as keys, but once
- deserialized into VCR, I keep them as plain, naked dicts.
- """
-
- def __setitem__(self, key, value):
- if isinstance(value, (tuple, list)):
- value = value[0]
-
- # Preserve the case from the first time this key was set.
- old = self._store.get(key.lower())
- if old:
- key = old[0]
-
- super(HeadersDict, self).__setitem__(key, value)
import collections
import types
+import six
-# Shamelessly stolen from https://github.com/kennethreitz/requests/blob/master/requests/structures.py
-class CaseInsensitiveDict(collections.MutableMapping):
- """
- A case-insensitive ``dict``-like object.
- Implements all methods and operations of
- ``collections.MutableMapping`` as well as dict's ``copy``. Also
- provides ``lower_items``.
- All keys are expected to be strings. The structure remembers the
- case of the last key to be set, and ``iter(instance)``,
- ``keys()``, ``items()``, ``iterkeys()``, and ``iteritems()``
- will contain case-sensitive keys. However, querying and contains
- testing is case insensitive::
- cid = CaseInsensitiveDict()
- cid['Accept'] = 'application/json'
- cid['aCCEPT'] == 'application/json' # True
- list(cid) == ['Accept'] # True
- For example, ``headers['content-encoding']`` will return the
- value of a ``'Content-Encoding'`` response header, regardless
- of how the header name was originally stored.
- If the constructor, ``.update``, or equality comparison
- operations are given keys that have equal ``.lower()``s, the
- behavior is undefined.
- """
- def __init__(self, data=None, **kwargs):
- self._store = dict()
+
+class DictDecorator(collections.MutableMapping):
+
+ def __init__(self, data=None, store_type=dict):
+ self._store_type = store_type
+ self._store = self._store_type()
if data is None:
data = {}
- self.update(data, **kwargs)
+ self.update(data)
def __setitem__(self, key, value):
- # Use the lowercased key for lookups, but store the actual
- # key alongside the value.
- self._store[key.lower()] = (key, value)
+ self._store[key] = value
def __getitem__(self, key):
- return self._store[key.lower()][1]
+ return self._store[key]
def __delitem__(self, key):
- del self._store[key.lower()]
+ del self._store[key]
def __iter__(self):
- return (casedkey for casedkey, mappedvalue in self._store.values())
+ return iter(self._store)
def __len__(self):
return len(self._store)
- def lower_items(self):
- """Like iteritems(), but with all lowercase keys."""
- return (
- (lowerkey, keyval[1])
- for (lowerkey, keyval)
- in self._store.items()
- )
+ def __getattr__(self, attr):
+ return getattr(self._store, attr)
- def __eq__(self, other):
- if isinstance(other, collections.Mapping):
- other = CaseInsensitiveDict(other)
- else:
- return NotImplemented
- # Compare insensitively
- return dict(self.lower_items()) == dict(other.lower_items())
+ def __contains__(self, key):
+ return key in self._store
+
+ def setdefault(self, key, default=None):
+ return self._store.setdefault(key, default)
- # Copy is required
def copy(self):
- return CaseInsensitiveDict(self._store.values())
+ return type(self)(data=self._store, store_type=self._store_type)
+
+ @property
+ def underlying_store(self):
+ return (self._store.underlying_store
+ if hasattr(self._store, 'underlying_store')
+ else self._store)
+
+
+KVPair = collections.namedtuple('KVPair', ['key', 'value'])
+
+
+# Adapted from:
+# https://github.com/kennethreitz/requests/blob/master/requests/structures.py
+class CaseInsensitiveDict(DictDecorator):
+
+ def __setitem__(self, key, value):
+ # Use the lowercased key for lookups, but store the actual
+ # key alongside the value.
+ self._store[key.lower()] = KVPair(key, value)
+
+ def __getitem__(self, key):
+ return self._store[key.lower()]
+
+ def __delitem__(self, key):
+ del self._store[key.lower()]
+
+ def __len__(self):
+ return len(self._store)
+
+ def __contains__(self, key):
+ return key.lower() in self._store
def __repr__(self):
return str(dict(self.items()))
+
+class MultiValueDict(DictDecorator):
+
+ _no_set_iterables = six.string_types + (KVPair,)
+
+ def __setitem__(self, key, value):
+ if (not isinstance(value, self._no_set_iterables) and
+ isinstance(value, collections.Iterable)):
+ self._store[key] = collections.deque(value)
+ return
+ if key not in self._store:
+ self._store[key] = collections.deque()
+ self._store[key].appendleft(value)
+
+
+class HeadersDict(CaseInsensitiveDict):
+ """A dictionary object that is adapted to the specific case of
+ representing HTTP requests.
+
+ The HTTP spec has a strange quirk where it allows the submission
+ of a single header twice. For this reason, HeadersDict instances
+ map each case insensitive header string to a list of values that
+ were provided for that header. However, since httplib is incapable
+ of sending the same header twice, HeadersDict provides the
+ property `single_valued`, which returns a version of the headers
+ dict where each header key is mapped to the single value at index
+ 0 for that key in the HeadersDict store.
+ """
+
+ def __init__(self, data=None, store_type=None):
+ super(HeadersDict, self).__init__(data, store_type=MultiValueDict)
+
+ @property
+ def single_valued(self):
+ return dict(
+ key_value_pairs[0]
+ for key_value_pairs in self.values()
+ )
+
+ @property
+ def serialize(self):
+ return dict(
+ (lower_key, [(key, value) for key, value in value_pairs])
+ for lower_key, value_pairs in self.items()
+ )
+
+
def partition_dict(predicate, dictionary):
true_dict = {}
false_dict = {}
return res
return composed
+
def read_body(request):
if hasattr(request.body, 'read'):
return request.body.read()