diff options
Diffstat (limited to 'netlib/multidict.py')
-rw-r--r-- | netlib/multidict.py | 48 |
1 files changed, 34 insertions, 14 deletions
diff --git a/netlib/multidict.py b/netlib/multidict.py index 248acdec..dc0f3466 100644 --- a/netlib/multidict.py +++ b/netlib/multidict.py @@ -2,7 +2,6 @@ from __future__ import absolute_import, print_function, division from abc import ABCMeta, abstractmethod -from typing import Tuple, TypeVar try: from collections.abc import MutableMapping @@ -10,14 +9,13 @@ except ImportError: # pragma: no cover from collections import MutableMapping # Workaround for Python < 3.3 import six - -from .utils import Serializable +from netlib import basetypes @six.add_metaclass(ABCMeta) -class _MultiDict(MutableMapping, Serializable): +class _MultiDict(MutableMapping, basetypes.Serializable): def __repr__(self): - fields = tuple( + fields = ( repr(field) for field in self.fields ) @@ -172,6 +170,30 @@ class _MultiDict(MutableMapping, Serializable): else: return super(_MultiDict, self).items() + def clear(self, key): + """ + Removes all items with the specified key, and does not raise an + exception if the key does not exist. + """ + if key in self: + del self[key] + + def collect(self): + """ + Returns a list of (key, value) tuples, where values are either + singular if threre is only one matching item for a key, or a list + if there are more than one. The order of the keys matches the order + in the underlying fields list. + """ + coll = [] + for key in self: + values = self.get_all(key) + if len(values) == 1: + coll.append([key, values[0]]) + else: + coll.append([key, values]) + return coll + def to_dict(self): """ Get the MultiDict as a plain Python dict. @@ -191,12 +213,8 @@ class _MultiDict(MutableMapping, Serializable): } """ d = {} - for key in self: - values = self.get_all(key) - if len(values) == 1: - d[key] = values[0] - else: - d[key] = values + for k, v in self.collect(): + d[k] = v return d def get_state(self): @@ -207,13 +225,15 @@ class _MultiDict(MutableMapping, Serializable): @classmethod def from_state(cls, state): - return cls(tuple(x) for x in state) + return cls(state) class MultiDict(_MultiDict): - def __init__(self, fields=None): + def __init__(self, fields=()): super(MultiDict, self).__init__() - self.fields = tuple(fields) if fields else tuple() # type: Tuple[Tuple[bytes, bytes], ...] + self.fields = tuple( + tuple(i) for i in fields + ) @six.add_metaclass(ABCMeta) |