2011-03-28 10:11:19 +08:00
|
|
|
import copy
|
2018-05-05 07:37:01 +08:00
|
|
|
from collections.abc import Mapping
|
2014-02-27 05:48:20 +08:00
|
|
|
|
2013-11-03 07:53:29 +08:00
|
|
|
|
2017-01-19 15:39:46 +08:00
|
|
|
class OrderedSet:
|
2013-05-10 19:52:04 +08:00
|
|
|
"""
|
|
|
|
A set which keeps the ordering of the inserted items.
|
|
|
|
"""
|
|
|
|
|
|
|
|
def __init__(self, iterable=None):
|
2019-02-05 19:22:08 +08:00
|
|
|
self.dict = dict.fromkeys(iterable or ())
|
2013-05-10 19:52:04 +08:00
|
|
|
|
|
|
|
def add(self, item):
|
|
|
|
self.dict[item] = None
|
|
|
|
|
|
|
|
def remove(self, item):
|
|
|
|
del self.dict[item]
|
|
|
|
|
|
|
|
def discard(self, item):
|
2017-09-07 20:16:21 +08:00
|
|
|
try:
|
2013-05-10 19:52:04 +08:00
|
|
|
self.remove(item)
|
2017-09-07 20:16:21 +08:00
|
|
|
except KeyError:
|
|
|
|
pass
|
2013-05-10 19:52:04 +08:00
|
|
|
|
|
|
|
def __iter__(self):
|
2017-05-28 07:08:46 +08:00
|
|
|
return iter(self.dict)
|
2013-05-10 19:52:04 +08:00
|
|
|
|
|
|
|
def __contains__(self, item):
|
|
|
|
return item in self.dict
|
|
|
|
|
2014-10-16 18:43:46 +08:00
|
|
|
def __bool__(self):
|
2013-05-10 19:52:04 +08:00
|
|
|
return bool(self.dict)
|
|
|
|
|
2015-07-10 02:00:36 +08:00
|
|
|
def __len__(self):
|
|
|
|
return len(self.dict)
|
|
|
|
|
2013-11-03 07:53:29 +08:00
|
|
|
|
2005-07-13 09:25:57 +08:00
|
|
|
class MultiValueDictKeyError(KeyError):
|
|
|
|
pass
|
|
|
|
|
2013-11-03 07:53:29 +08:00
|
|
|
|
2005-11-30 12:08:46 +08:00
|
|
|
class MultiValueDict(dict):
|
2005-07-13 09:25:57 +08:00
|
|
|
"""
|
2007-10-19 09:26:09 +08:00
|
|
|
A subclass of dictionary customized to handle multiple values for the
|
|
|
|
same key.
|
2005-07-13 09:25:57 +08:00
|
|
|
|
|
|
|
>>> d = MultiValueDict({'name': ['Adrian', 'Simon'], 'position': ['Developer']})
|
|
|
|
>>> d['name']
|
|
|
|
'Simon'
|
|
|
|
>>> d.getlist('name')
|
|
|
|
['Adrian', 'Simon']
|
2011-05-22 23:05:29 +08:00
|
|
|
>>> d.getlist('doesnotexist')
|
|
|
|
[]
|
|
|
|
>>> d.getlist('doesnotexist', ['Adrian', 'Simon'])
|
|
|
|
['Adrian', 'Simon']
|
2005-07-13 09:25:57 +08:00
|
|
|
>>> d.get('lastname', 'nonexistent')
|
|
|
|
'nonexistent'
|
|
|
|
>>> d.setlist('lastname', ['Holovaty', 'Willison'])
|
|
|
|
|
|
|
|
This class exists to solve the irritating problem raised by cgi.parse_qs,
|
|
|
|
which returns a list for every key, even though most Web forms submit
|
|
|
|
single name-value pairs.
|
|
|
|
"""
|
2005-11-30 12:08:46 +08:00
|
|
|
def __init__(self, key_to_list_mapping=()):
|
2017-01-21 21:13:44 +08:00
|
|
|
super().__init__(key_to_list_mapping)
|
2005-07-13 09:25:57 +08:00
|
|
|
|
2005-12-29 07:11:07 +08:00
|
|
|
def __repr__(self):
|
2017-01-21 21:13:44 +08:00
|
|
|
return "<%s: %s>" % (self.__class__.__name__, super().__repr__())
|
2005-12-29 07:11:07 +08:00
|
|
|
|
2005-07-13 09:25:57 +08:00
|
|
|
def __getitem__(self, key):
|
2005-11-30 12:08:46 +08:00
|
|
|
"""
|
2017-01-25 04:32:33 +08:00
|
|
|
Return the last data value for this key, or [] if it's an empty list;
|
|
|
|
raise KeyError if not found.
|
2005-11-30 12:08:46 +08:00
|
|
|
"""
|
|
|
|
try:
|
2017-01-21 21:13:44 +08:00
|
|
|
list_ = super().__getitem__(key)
|
2005-11-30 12:08:46 +08:00
|
|
|
except KeyError:
|
2017-04-12 00:44:52 +08:00
|
|
|
raise MultiValueDictKeyError(key)
|
2005-11-30 12:08:46 +08:00
|
|
|
try:
|
|
|
|
return list_[-1]
|
|
|
|
except IndexError:
|
|
|
|
return []
|
2005-07-13 09:25:57 +08:00
|
|
|
|
2006-03-29 01:31:04 +08:00
|
|
|
def __setitem__(self, key, value):
|
2017-01-21 21:13:44 +08:00
|
|
|
super().__setitem__(key, [value])
|
2006-03-29 01:31:04 +08:00
|
|
|
|
|
|
|
def __copy__(self):
|
2010-10-28 04:39:20 +08:00
|
|
|
return self.__class__([
|
|
|
|
(k, v[:])
|
|
|
|
for k, v in self.lists()
|
|
|
|
])
|
2006-03-29 01:31:04 +08:00
|
|
|
|
2017-04-07 21:13:57 +08:00
|
|
|
def __deepcopy__(self, memo):
|
2006-03-29 01:31:04 +08:00
|
|
|
result = self.__class__()
|
|
|
|
memo[id(self)] = result
|
|
|
|
for key, value in dict.items(self):
|
2007-10-19 09:26:09 +08:00
|
|
|
dict.__setitem__(result, copy.deepcopy(key, memo),
|
|
|
|
copy.deepcopy(value, memo))
|
2006-03-29 01:31:04 +08:00
|
|
|
return result
|
2009-12-12 14:00:59 +08:00
|
|
|
|
2009-03-31 13:14:13 +08:00
|
|
|
def __getstate__(self):
|
2018-02-27 01:23:31 +08:00
|
|
|
return {**self.__dict__, '_data': {k: self._getlist(k) for k in self}}
|
2009-12-12 14:00:59 +08:00
|
|
|
|
2009-03-31 13:14:13 +08:00
|
|
|
def __setstate__(self, obj_dict):
|
|
|
|
data = obj_dict.pop('_data', {})
|
|
|
|
for k, v in data.items():
|
|
|
|
self.setlist(k, v)
|
|
|
|
self.__dict__.update(obj_dict)
|
2009-12-12 14:00:59 +08:00
|
|
|
|
2005-11-30 12:08:46 +08:00
|
|
|
def get(self, key, default=None):
|
2007-11-26 02:14:18 +08:00
|
|
|
"""
|
2017-01-25 04:32:33 +08:00
|
|
|
Return the last data value for the passed key. If key doesn't exist
|
|
|
|
or value is an empty list, return `default`.
|
2007-11-26 02:14:18 +08:00
|
|
|
"""
|
2005-07-13 09:25:57 +08:00
|
|
|
try:
|
|
|
|
val = self[key]
|
2005-11-30 12:08:46 +08:00
|
|
|
except KeyError:
|
2005-07-13 09:25:57 +08:00
|
|
|
return default
|
|
|
|
if val == []:
|
|
|
|
return default
|
|
|
|
return val
|
|
|
|
|
2016-09-10 17:25:42 +08:00
|
|
|
def _getlist(self, key, default=None, force_list=False):
|
2007-11-26 02:14:18 +08:00
|
|
|
"""
|
2016-09-10 17:25:42 +08:00
|
|
|
Return a list of values for the key.
|
|
|
|
|
|
|
|
Used internally to manipulate values list. If force_list is True,
|
|
|
|
return a new copy of values.
|
2007-11-26 02:14:18 +08:00
|
|
|
"""
|
2005-07-13 09:25:57 +08:00
|
|
|
try:
|
2017-01-21 21:13:44 +08:00
|
|
|
values = super().__getitem__(key)
|
2005-07-13 09:25:57 +08:00
|
|
|
except KeyError:
|
2012-02-10 02:41:20 +08:00
|
|
|
if default is None:
|
|
|
|
return []
|
|
|
|
return default
|
2016-09-10 17:25:42 +08:00
|
|
|
else:
|
|
|
|
if force_list:
|
2016-12-10 04:31:52 +08:00
|
|
|
values = list(values) if values is not None else None
|
2016-09-10 17:25:42 +08:00
|
|
|
return values
|
|
|
|
|
|
|
|
def getlist(self, key, default=None):
|
|
|
|
"""
|
|
|
|
Return the list of values for the key. If key doesn't exist, return a
|
|
|
|
default value.
|
|
|
|
"""
|
|
|
|
return self._getlist(key, default, force_list=True)
|
2005-07-13 09:25:57 +08:00
|
|
|
|
|
|
|
def setlist(self, key, list_):
|
2017-01-21 21:13:44 +08:00
|
|
|
super().__setitem__(key, list_)
|
2005-07-13 09:25:57 +08:00
|
|
|
|
2005-11-30 12:08:46 +08:00
|
|
|
def setdefault(self, key, default=None):
|
|
|
|
if key not in self:
|
|
|
|
self[key] = default
|
2012-07-26 01:10:40 +08:00
|
|
|
# Do not return default here because __setitem__() may store
|
|
|
|
# another value -- QueryDict.__setitem__() does. Look it up.
|
2005-11-30 12:08:46 +08:00
|
|
|
return self[key]
|
2005-07-13 09:25:57 +08:00
|
|
|
|
2012-02-10 02:41:20 +08:00
|
|
|
def setlistdefault(self, key, default_list=None):
|
2005-11-30 12:08:46 +08:00
|
|
|
if key not in self:
|
2012-02-10 02:41:20 +08:00
|
|
|
if default_list is None:
|
|
|
|
default_list = []
|
2005-11-30 12:08:46 +08:00
|
|
|
self.setlist(key, default_list)
|
2012-07-26 01:10:40 +08:00
|
|
|
# Do not return default_list here because setlist() may store
|
|
|
|
# another value -- QueryDict.setlist() does. Look it up.
|
2016-09-10 17:25:42 +08:00
|
|
|
return self._getlist(key)
|
2005-11-30 12:08:46 +08:00
|
|
|
|
|
|
|
def appendlist(self, key, value):
|
2017-01-25 04:32:33 +08:00
|
|
|
"""Append an item to the internal list associated with key."""
|
2012-02-10 02:41:20 +08:00
|
|
|
self.setlistdefault(key).append(value)
|
2005-07-13 09:25:57 +08:00
|
|
|
|
2016-12-01 18:38:01 +08:00
|
|
|
def items(self):
|
2008-08-16 10:17:55 +08:00
|
|
|
"""
|
2017-01-25 04:32:33 +08:00
|
|
|
Yield (key, value) pairs, where value is the last item in the list
|
2008-08-16 10:17:55 +08:00
|
|
|
associated with the key.
|
|
|
|
"""
|
2012-07-25 15:12:59 +08:00
|
|
|
for key in self:
|
|
|
|
yield key, self[key]
|
2005-07-13 09:25:57 +08:00
|
|
|
|
2016-12-01 18:38:01 +08:00
|
|
|
def lists(self):
|
2017-01-25 04:32:33 +08:00
|
|
|
"""Yield (key, list) pairs."""
|
2017-01-21 21:13:44 +08:00
|
|
|
return iter(super().items())
|
2009-03-31 14:30:07 +08:00
|
|
|
|
2016-12-01 18:38:01 +08:00
|
|
|
def values(self):
|
2009-03-31 14:30:07 +08:00
|
|
|
"""Yield the last value on every key list."""
|
2012-07-25 15:12:59 +08:00
|
|
|
for key in self:
|
2009-03-31 14:30:07 +08:00
|
|
|
yield self[key]
|
2009-12-12 14:00:59 +08:00
|
|
|
|
2005-07-13 09:25:57 +08:00
|
|
|
def copy(self):
|
2017-01-25 04:32:33 +08:00
|
|
|
"""Return a shallow copy of this object."""
|
2011-03-28 10:11:19 +08:00
|
|
|
return copy.copy(self)
|
2005-07-13 09:25:57 +08:00
|
|
|
|
2006-09-01 05:51:19 +08:00
|
|
|
def update(self, *args, **kwargs):
|
2017-01-25 04:32:33 +08:00
|
|
|
"""Extend rather than replace existing key lists."""
|
2006-09-01 05:51:19 +08:00
|
|
|
if len(args) > 1:
|
2018-10-14 23:20:22 +08:00
|
|
|
raise TypeError("update expected at most 1 argument, got %d" % len(args))
|
2006-09-01 05:51:19 +08:00
|
|
|
if args:
|
|
|
|
other_dict = args[0]
|
|
|
|
if isinstance(other_dict, MultiValueDict):
|
|
|
|
for key, value_list in other_dict.lists():
|
2012-02-10 02:41:20 +08:00
|
|
|
self.setlistdefault(key).extend(value_list)
|
2006-09-01 05:51:19 +08:00
|
|
|
else:
|
|
|
|
try:
|
|
|
|
for key, value in other_dict.items():
|
2012-02-10 02:41:20 +08:00
|
|
|
self.setlistdefault(key).append(value)
|
2006-09-01 05:51:19 +08:00
|
|
|
except TypeError:
|
2010-01-11 02:36:20 +08:00
|
|
|
raise ValueError("MultiValueDict.update() takes either a MultiValueDict or dictionary")
|
2017-01-07 19:11:46 +08:00
|
|
|
for key, value in kwargs.items():
|
2012-02-10 02:41:20 +08:00
|
|
|
self.setlistdefault(key).append(value)
|
2005-11-30 12:08:46 +08:00
|
|
|
|
2011-06-17 00:34:55 +08:00
|
|
|
def dict(self):
|
2017-01-25 04:32:33 +08:00
|
|
|
"""Return current object as a dict with singular values."""
|
2014-12-07 05:00:09 +08:00
|
|
|
return {key: self[key] for key in self}
|
2011-06-17 00:34:55 +08:00
|
|
|
|
2007-08-12 20:02:08 +08:00
|
|
|
|
2008-07-01 23:10:51 +08:00
|
|
|
class ImmutableList(tuple):
|
2007-08-12 20:02:08 +08:00
|
|
|
"""
|
2008-07-01 23:10:51 +08:00
|
|
|
A tuple-like object that raises useful errors when it is asked to mutate.
|
|
|
|
|
|
|
|
Example::
|
|
|
|
|
|
|
|
>>> a = ImmutableList(range(5), warning="You cannot mutate this.")
|
|
|
|
>>> a[3] = '4'
|
|
|
|
Traceback (most recent call last):
|
|
|
|
...
|
|
|
|
AttributeError: You cannot mutate this.
|
2007-08-12 20:02:08 +08:00
|
|
|
"""
|
2008-07-01 23:10:51 +08:00
|
|
|
|
2017-02-02 00:41:56 +08:00
|
|
|
def __new__(cls, *args, warning='ImmutableList object is immutable.', **kwargs):
|
2008-07-01 23:10:51 +08:00
|
|
|
self = tuple.__new__(cls, *args, **kwargs)
|
|
|
|
self.warning = warning
|
|
|
|
return self
|
|
|
|
|
|
|
|
def complain(self, *wargs, **kwargs):
|
|
|
|
if isinstance(self.warning, Exception):
|
|
|
|
raise self.warning
|
|
|
|
else:
|
2010-01-11 02:36:20 +08:00
|
|
|
raise AttributeError(self.warning)
|
2008-07-01 23:10:51 +08:00
|
|
|
|
|
|
|
# All list mutation functions complain.
|
2013-10-22 21:31:43 +08:00
|
|
|
__delitem__ = complain
|
2008-07-01 23:10:51 +08:00
|
|
|
__delslice__ = complain
|
2013-10-22 21:31:43 +08:00
|
|
|
__iadd__ = complain
|
|
|
|
__imul__ = complain
|
|
|
|
__setitem__ = complain
|
2008-07-01 23:10:51 +08:00
|
|
|
__setslice__ = complain
|
2013-10-22 21:31:43 +08:00
|
|
|
append = complain
|
|
|
|
extend = complain
|
|
|
|
insert = complain
|
|
|
|
pop = complain
|
2013-10-23 18:09:29 +08:00
|
|
|
remove = complain
|
2013-10-22 21:31:43 +08:00
|
|
|
sort = complain
|
|
|
|
reverse = complain
|
2008-06-26 11:11:32 +08:00
|
|
|
|
2013-11-03 07:53:29 +08:00
|
|
|
|
2008-06-26 11:11:32 +08:00
|
|
|
class DictWrapper(dict):
|
|
|
|
"""
|
2017-01-25 04:32:33 +08:00
|
|
|
Wrap accesses to a dictionary so that certain values (those starting with
|
2008-06-26 11:11:32 +08:00
|
|
|
the specified prefix) are passed through a function before being returned.
|
|
|
|
The prefix is removed before looking up the real value.
|
|
|
|
|
|
|
|
Used by the SQL construction code to ensure that values are correctly
|
|
|
|
quoted before being used.
|
|
|
|
"""
|
|
|
|
def __init__(self, data, func, prefix):
|
2017-01-21 21:13:44 +08:00
|
|
|
super().__init__(data)
|
2008-06-26 11:11:32 +08:00
|
|
|
self.func = func
|
|
|
|
self.prefix = prefix
|
|
|
|
|
|
|
|
def __getitem__(self, key):
|
|
|
|
"""
|
2017-01-25 04:32:33 +08:00
|
|
|
Retrieve the real value after stripping the prefix string (if
|
2008-06-26 11:11:32 +08:00
|
|
|
present). If the prefix is present, pass the value through self.func
|
|
|
|
before returning, otherwise return the raw value.
|
|
|
|
"""
|
2018-01-12 22:05:16 +08:00
|
|
|
use_func = key.startswith(self.prefix)
|
|
|
|
if use_func:
|
2008-06-26 11:11:32 +08:00
|
|
|
key = key[len(self.prefix):]
|
2017-01-21 21:13:44 +08:00
|
|
|
value = super().__getitem__(key)
|
2008-06-26 11:11:32 +08:00
|
|
|
if use_func:
|
|
|
|
return self.func(value)
|
|
|
|
return value
|
2018-05-05 07:37:01 +08:00
|
|
|
|
|
|
|
|
|
|
|
def _destruct_iterable_mapping_values(data):
|
|
|
|
for i, elem in enumerate(data):
|
|
|
|
if len(elem) != 2:
|
|
|
|
raise ValueError(
|
|
|
|
'dictionary update sequence element #{} has '
|
|
|
|
'length {}; 2 is required.'.format(i, len(elem))
|
|
|
|
)
|
|
|
|
if not isinstance(elem[0], str):
|
|
|
|
raise ValueError('Element key %r invalid, only strings are allowed' % elem[0])
|
|
|
|
yield tuple(elem)
|
|
|
|
|
|
|
|
|
|
|
|
class CaseInsensitiveMapping(Mapping):
|
|
|
|
"""
|
|
|
|
Mapping allowing case-insensitive key lookups. Original case of keys is
|
|
|
|
preserved for iteration and string representation.
|
|
|
|
|
|
|
|
Example::
|
|
|
|
|
|
|
|
>>> ci_map = CaseInsensitiveMapping({'name': 'Jane'})
|
|
|
|
>>> ci_map['Name']
|
|
|
|
Jane
|
|
|
|
>>> ci_map['NAME']
|
|
|
|
Jane
|
|
|
|
>>> ci_map['name']
|
|
|
|
Jane
|
|
|
|
>>> ci_map # original case preserved
|
|
|
|
{'name': 'Jane'}
|
|
|
|
"""
|
|
|
|
|
|
|
|
def __init__(self, data):
|
|
|
|
if not isinstance(data, Mapping):
|
|
|
|
data = {k: v for k, v in _destruct_iterable_mapping_values(data)}
|
|
|
|
self._store = {k.lower(): (k, v) for k, v in data.items()}
|
|
|
|
|
|
|
|
def __getitem__(self, key):
|
|
|
|
return self._store[key.lower()][1]
|
|
|
|
|
|
|
|
def __len__(self):
|
|
|
|
return len(self._store)
|
|
|
|
|
|
|
|
def __eq__(self, other):
|
|
|
|
return isinstance(other, Mapping) and {
|
|
|
|
k.lower(): v for k, v in self.items()
|
|
|
|
} == {
|
|
|
|
k.lower(): v for k, v in other.items()
|
|
|
|
}
|
|
|
|
|
|
|
|
def __iter__(self):
|
|
|
|
return (original_key for original_key, value in self._store.values())
|
|
|
|
|
|
|
|
def __repr__(self):
|
|
|
|
return repr({key: value for key, value in self._store.values()})
|
|
|
|
|
|
|
|
def copy(self):
|
|
|
|
return self
|