Back to index

moin  1.9.0~rc2
Public Member Functions | Static Public Attributes
MoinMoin.support.werkzeug.datastructures.MultiDict Class Reference
Inheritance diagram for MoinMoin.support.werkzeug.datastructures.MultiDict:
Inheritance graph
[legend]
Collaboration diagram for MoinMoin.support.werkzeug.datastructures.MultiDict:
Collaboration graph
[legend]

List of all members.

Public Member Functions

def __init__
def __getitem__
def __setitem__
def getlist
def setlist
def setdefault
def setlistdefault
def items
def values
def listvalues
def iteritems
def iterlists
def itervalues
def iterlistvalues
def copy
def to_dict
def update
def pop
def popitem
def poplist
def popitemlist
def __repr__
def get

Static Public Attributes

 KeyError = None
 lists = dict.items

Detailed Description

A :class:`MultiDict` is a dictionary subclass customized to deal with
multiple values for the same key which is for example used by the parsing
functions in the wrappers.  This is necessary because some HTML form
elements pass multiple values for the same key.

:class:`MultiDict` implements all standard dictionary methods.
Internally, it saves all values for a key as a list, but the standard dict
access methods will only return the first value for a key. If you want to
gain access to the other values, too, you have to use the `list` methods as
explained below.

Basic Usage:

>>> d = MultiDict([('a', 'b'), ('a', 'c')])
>>> d
MultiDict([('a', 'b'), ('a', 'c')])
>>> d['a']
'b'
>>> d.getlist('a')
['b', 'c']
>>> 'a' in d
True

It behaves like a normal dict thus all dict functions will only return the
first value when multiple values for one key are found.

From Werkzeug 0.3 onwards, the `KeyError` raised by this class is also a
subclass of the :exc:`~exceptions.BadRequest` HTTP exception and will
render a page for a ``400 BAD REQUEST`` if catched in a catch-all for HTTP
exceptions.

A :class:`MultiDict` can be constructed from an iterable of
``(key, value)`` tuples, a dict, a :class:`MultiDict` or from Werkzeug 0.2
onwards some keyword parameters.

:param mapping: the initial value for the :class:`MultiDict`.  Either a
                regular dict, an iterable of ``(key, value)`` tuples
                or `None`.

Definition at line 210 of file datastructures.py.


Constructor & Destructor Documentation

Reimplemented in MoinMoin.support.werkzeug.datastructures.CombinedMultiDict.

Definition at line 256 of file datastructures.py.

00256 
00257     def __init__(self, mapping=None):
00258         if isinstance(mapping, MultiDict):
00259             dict.__init__(self, ((k, l[:]) for k, l in mapping.iterlists()))
00260         elif isinstance(mapping, dict):
00261             tmp = {}
00262             for key, value in mapping.iteritems():
00263                 if isinstance(value, (tuple, list)):
00264                     value = list(value)
00265                 else:
00266                     value = [value]
00267                 tmp[key] = value
00268             dict.__init__(self, tmp)
00269         else:
00270             tmp = {}
00271             for key, value in mapping or ():
00272                 tmp.setdefault(key, []).append(value)
00273             dict.__init__(self, tmp)


Member Function Documentation

Return the first data value for this key;
raises KeyError if not found.

:param key: The key to be looked up.
:raise KeyError: if the key does not exist.

Reimplemented in MoinMoin.support.werkzeug.datastructures.CombinedMultiDict.

Definition at line 274 of file datastructures.py.

00274 
00275     def __getitem__(self, key):
00276         """Return the first data value for this key;
00277         raises KeyError if not found.
00278 
00279         :param key: The key to be looked up.
00280         :raise KeyError: if the key does not exist.
00281         """
00282         if key in self:
00283             return dict.__getitem__(self, key)[0]
00284         raise self.KeyError(key)

Here is the caller graph for this function:

Reimplemented in MoinMoin.support.werkzeug.datastructures.CombinedMultiDict.

Definition at line 511 of file datastructures.py.

00511 
00512     def __repr__(self):
00513         return '%s(%r)' % (self.__class__.__name__, self.items(multi=True))
00514 

Here is the call graph for this function:

Set an item as list.

Definition at line 285 of file datastructures.py.

00285 
00286     def __setitem__(self, key, value):
00287         """Set an item as list."""
00288         dict.__setitem__(self, key, [value])

Here is the caller graph for this function:

Return a shallow copy of this object.

Reimplemented in MoinMoin.support.werkzeug.datastructures.ImmutableMultiDict, and MoinMoin.support.werkzeug.datastructures.CombinedMultiDict.

Definition at line 435 of file datastructures.py.

00435 
00436     def copy(self):
00437         """Return a shallow copy of this object."""
00438         return self.__class__(self)

Here is the caller graph for this function:

def MoinMoin.support.werkzeug.datastructures.TypeConversionDict.get (   self,
  key,
  default = None,
  type = None 
) [inherited]
Return the default value if the requested data doesn't exist.
If `type` is provided and is a callable it should convert the value,
return it or raise a :exc:`ValueError` if that is not possible.  In
this case the function will return the default as if the value was not
found:

>>> d = TypeConversionDict(foo='42', bar='blub')
>>> d.get('foo', type=int)
42
>>> d.get('bar', -1, type=int)
-1

:param key: The key to be looked up.
:param default: The default value to be returned if the key can't
        be looked up.  If not further specified `None` is
        returned.
:param type: A callable that is used to cast the value in the
     :class:`MultiDict`.  If a :exc:`ValueError` is raised
     by this callable the default value is returned.

Reimplemented in MoinMoin.support.werkzeug.datastructures.CombinedMultiDict.

Definition at line 162 of file datastructures.py.

00162 
00163     def get(self, key, default=None, type=None):
00164         """Return the default value if the requested data doesn't exist.
00165         If `type` is provided and is a callable it should convert the value,
00166         return it or raise a :exc:`ValueError` if that is not possible.  In
00167         this case the function will return the default as if the value was not
00168         found:
00169 
00170         >>> d = TypeConversionDict(foo='42', bar='blub')
00171         >>> d.get('foo', type=int)
00172         42
00173         >>> d.get('bar', -1, type=int)
00174         -1
00175 
00176         :param key: The key to be looked up.
00177         :param default: The default value to be returned if the key can't
00178                         be looked up.  If not further specified `None` is
00179                         returned.
00180         :param type: A callable that is used to cast the value in the
00181                      :class:`MultiDict`.  If a :exc:`ValueError` is raised
00182                      by this callable the default value is returned.
00183         """
00184         try:
00185             rv = self[key]
00186             if type is not None:
00187                 rv = type(rv)
00188         except (KeyError, ValueError):
00189             rv = default
00190         return rv
00191 

Here is the caller graph for this function:

def MoinMoin.support.werkzeug.datastructures.MultiDict.getlist (   self,
  key,
  type = None 
)
Return the list of items for a given key. If that key is not in the
`MultiDict`, the return value will be an empty list.  Just as `get`
`getlist` accepts a `type` parameter.  All items will be converted
with the callable defined there.

:param key: The key to be looked up.
:param type: A callable that is used to cast the value in the
     :class:`MultiDict`.  If a :exc:`ValueError` is raised
     by this callable the value will be removed from the list.
:return: a :class:`list` of all the values for the key.

Reimplemented in MoinMoin.support.werkzeug.datastructures.CombinedMultiDict.

Definition at line 289 of file datastructures.py.

00289 
00290     def getlist(self, key, type=None):
00291         """Return the list of items for a given key. If that key is not in the
00292         `MultiDict`, the return value will be an empty list.  Just as `get`
00293         `getlist` accepts a `type` parameter.  All items will be converted
00294         with the callable defined there.
00295 
00296         :param key: The key to be looked up.
00297         :param type: A callable that is used to cast the value in the
00298                      :class:`MultiDict`.  If a :exc:`ValueError` is raised
00299                      by this callable the value will be removed from the list.
00300         :return: a :class:`list` of all the values for the key.
00301         """
00302         try:
00303             rv = dict.__getitem__(self, key)
00304         except KeyError:
00305             return []
00306         if type is None:
00307             return list(rv)
00308         result = []
00309         for item in rv:
00310             try:
00311                 result.append(type(item))
00312             except ValueError:
00313                 pass
00314         return result

Here is the caller graph for this function:

def MoinMoin.support.werkzeug.datastructures.MultiDict.items (   self,
  multi = False 
)
Return a list of ``(key, value)`` pairs.

:param multi: If set to `True` the list returned will have a
      pair for each value of each key.  Ohterwise it
      will only contain pairs for the first value of
      each key.

:return: a :class:`list`

Reimplemented in MoinMoin.support.werkzeug.datastructures.CombinedMultiDict.

Definition at line 371 of file datastructures.py.

00371 
00372     def items(self, multi=False):
00373         """Return a list of ``(key, value)`` pairs.
00374 
00375         :param multi: If set to `True` the list returned will have a
00376                       pair for each value of each key.  Ohterwise it
00377                       will only contain pairs for the first value of
00378                       each key.
00379 
00380         :return: a :class:`list`
00381         """
00382         return list(self.iteritems(multi))

Here is the call graph for this function:

Here is the caller graph for this function:

Like :meth:`items` but returns an iterator.

Reimplemented in MoinMoin.support.werkzeug.datastructures.CombinedMultiDict.

Definition at line 408 of file datastructures.py.

00408 
00409     def iteritems(self, multi=False):
00410         """Like :meth:`items` but returns an iterator."""
00411         for key, values in dict.iteritems(self):
00412             if multi:
00413                 for value in values:
00414                     yield key, value
00415             else:
00416                 yield key, values[0]

Here is the caller graph for this function:

Return a list of all values associated with a key.

:return: a class:`list`

Reimplemented in MoinMoin.support.werkzeug.datastructures.CombinedMultiDict.

Definition at line 417 of file datastructures.py.

00417 
00418     def iterlists(self):
00419         """Return a list of all values associated with a key.
00420 
00421         :return: a class:`list`
00422         """
00423         for key, values in dict.iteritems(self):
00424             yield key, list(values)

Here is the caller graph for this function:

like :meth:`listvalues` but returns an iterator.

Reimplemented in MoinMoin.support.werkzeug.datastructures.CombinedMultiDict.

Definition at line 430 of file datastructures.py.

00430 
00431     def iterlistvalues(self):
00432         """like :meth:`listvalues` but returns an iterator."""
00433         for values in dict.itervalues(self):
00434             yield list(values)

Here is the caller graph for this function:

Like :meth:`values` but returns an iterator.

Reimplemented in MoinMoin.support.werkzeug.datastructures.CombinedMultiDict.

Definition at line 425 of file datastructures.py.

00425 
00426     def itervalues(self):
00427         """Like :meth:`values` but returns an iterator."""
00428         for values in dict.itervalues(self):
00429             yield values[0]

Here is the caller graph for this function:

Return a list of all values associated with a key.  Zipping
:meth:`keys` and this is the same as calling :meth:`lists`:

>>> d = MultiDict({"foo": [1, 2, 3]})
>>> zip(d.keys(), d.listvalues()) == d.lists()
True

:return: a :class:`list`

Reimplemented in MoinMoin.support.werkzeug.datastructures.CombinedMultiDict.

Definition at line 396 of file datastructures.py.

00396 
00397     def listvalues(self):
00398         """Return a list of all values associated with a key.  Zipping
00399         :meth:`keys` and this is the same as calling :meth:`lists`:
00400 
00401         >>> d = MultiDict({"foo": [1, 2, 3]})
00402         >>> zip(d.keys(), d.listvalues()) == d.lists()
00403         True
00404 
00405         :return: a :class:`list`
00406         """
00407         return list(self.iterlistvalues())

Here is the call graph for this function:

def MoinMoin.support.werkzeug.datastructures.MultiDict.pop (   self,
  key,
  default = _missing 
)
Pop the first item for a list on the dict.  Afterwards the
key is removed from the dict, so additional values are discarded:

>>> d = MultiDict({"foo": [1, 2, 3]})
>>> d.pop("foo")
1
>>> "foo" in d
False

:param key: the key to pop.
:param default: if provided the value to return if the key was
        not in the dictionary.

Definition at line 465 of file datastructures.py.

00465 
00466     def pop(self, key, default=_missing):
00467         """Pop the first item for a list on the dict.  Afterwards the
00468         key is removed from the dict, so additional values are discarded:
00469 
00470         >>> d = MultiDict({"foo": [1, 2, 3]})
00471         >>> d.pop("foo")
00472         1
00473         >>> "foo" in d
00474         False
00475 
00476         :param key: the key to pop.
00477         :param default: if provided the value to return if the key was
00478                         not in the dictionary.
00479         """
00480         if default is not _missing:
00481             return dict.pop(self, key, default)
00482         try:
00483             return dict.pop(self, key)[0]
00484         except KeyError, e:
00485             raise self.KeyError(str(e))

Here is the caller graph for this function:

Pop an item from the dict.

Definition at line 486 of file datastructures.py.

00486 
00487     def popitem(self):
00488         """Pop an item from the dict."""
00489         try:
00490             item = dict.popitem(self)
00491             return (item[0], item[1][0])
00492         except KeyError, e:
00493             raise self.KeyError(str(e))

Pop a ``(key, list)`` tuple from the dict.

Definition at line 504 of file datastructures.py.

00504 
00505     def popitemlist(self):
00506         """Pop a ``(key, list)`` tuple from the dict."""
00507         try:
00508             return dict.popitem(self)
00509         except KeyError, e:
00510             raise self.KeyError(str(e))

Pop the list for a key from the dict.  If the key is not in the dict
an empty list is returned.

.. versionchanged:: 0.5
   If the key does no longer exist a list is returned instead of
   raising an error.

Definition at line 494 of file datastructures.py.

00494 
00495     def poplist(self, key):
00496         """Pop the list for a key from the dict.  If the key is not in the dict
00497         an empty list is returned.
00498 
00499         .. versionchanged:: 0.5
00500            If the key does no longer exist a list is returned instead of
00501            raising an error.
00502         """
00503         return dict.pop(self, key, [])

def MoinMoin.support.werkzeug.datastructures.MultiDict.setdefault (   self,
  key,
  default = None 
)
Returns the value for the key if it is in the dict, otherwise it
returns `default` and sets that value for `key`.

:param key: The key to be looked up.
:param default: The default value to be returned if the key is not
        in the dict.  If not further specified it's `None`.

Definition at line 333 of file datastructures.py.

00333 
00334     def setdefault(self, key, default=None):
00335         """Returns the value for the key if it is in the dict, otherwise it
00336         returns `default` and sets that value for `key`.
00337 
00338         :param key: The key to be looked up.
00339         :param default: The default value to be returned if the key is not
00340                         in the dict.  If not further specified it's `None`.
00341         """
00342         if key not in self:
00343             self[key] = default
00344         else:
00345             default = self[key]
00346         return default

def MoinMoin.support.werkzeug.datastructures.MultiDict.setlist (   self,
  key,
  new_list 
)
Remove the old values for a key and add new ones.  Note that the list
you pass the values in will be shallow-copied before it is inserted in
the dictionary.

>>> d = MultiDict()
>>> d.setlist('foo', ['1', '2'])
>>> d['foo']
'1'
>>> d.getlist('foo')
['1', '2']

:param key: The key for which the values are set.
:param new_list: An iterable with the new values for the key.  Old values
         are removed first.

Definition at line 315 of file datastructures.py.

00315 
00316     def setlist(self, key, new_list):
00317         """Remove the old values for a key and add new ones.  Note that the list
00318         you pass the values in will be shallow-copied before it is inserted in
00319         the dictionary.
00320 
00321         >>> d = MultiDict()
00322         >>> d.setlist('foo', ['1', '2'])
00323         >>> d['foo']
00324         '1'
00325         >>> d.getlist('foo')
00326         ['1', '2']
00327 
00328         :param key: The key for which the values are set.
00329         :param new_list: An iterable with the new values for the key.  Old values
00330                          are removed first.
00331         """
00332         dict.__setitem__(self, key, list(new_list))

def MoinMoin.support.werkzeug.datastructures.MultiDict.setlistdefault (   self,
  key,
  default_list = None 
)
Like `setdefault` but sets multiple values.  The list returned
is not a copy, but the list that is actually used internally.  This
means that you can put new values into the dict by appending items
to the list:

>>> d = MultiDict({"foo": 1})
>>> d.setlistdefault("foo").extend([2, 3])
>>> d.getlist("foo")
[1, 2, 3]

:param key: The key to be looked up.
:param default: An iterable of default values.  It is either copied
        (in case it was a list) or converted into a list
        before returned.
:return: a :class:`list`

Definition at line 347 of file datastructures.py.

00347 
00348     def setlistdefault(self, key, default_list=None):
00349         """Like `setdefault` but sets multiple values.  The list returned
00350         is not a copy, but the list that is actually used internally.  This
00351         means that you can put new values into the dict by appending items
00352         to the list:
00353 
00354         >>> d = MultiDict({"foo": 1})
00355         >>> d.setlistdefault("foo").extend([2, 3])
00356         >>> d.getlist("foo")
00357         [1, 2, 3]
00358 
00359         :param key: The key to be looked up.
00360         :param default: An iterable of default values.  It is either copied
00361                         (in case it was a list) or converted into a list
00362                         before returned.
00363         :return: a :class:`list`
00364         """
00365         if key not in self:
00366             default_list = list(default_list or ())
00367             dict.__setitem__(self, key, default_list)
00368         else:
00369             default_list = dict.__getitem__(self, key)
00370         return default_list

Here is the caller graph for this function:

Return the contents as regular dict.  If `flat` is `True` the
returned dict will only have the first item present, if `flat` is
`False` all values will be returned as lists.

:param flat: If set to `False` the dict returned will have lists
     with all the values in it.  Otherwise it will only
     contain the first value for each key.
:return: a :class:`dict`

Reimplemented in MoinMoin.support.werkzeug.datastructures.CombinedMultiDict.

Definition at line 439 of file datastructures.py.

00439 
00440     def to_dict(self, flat=True):
00441         """Return the contents as regular dict.  If `flat` is `True` the
00442         returned dict will only have the first item present, if `flat` is
00443         `False` all values will be returned as lists.
00444 
00445         :param flat: If set to `False` the dict returned will have lists
00446                      with all the values in it.  Otherwise it will only
00447                      contain the first value for each key.
00448         :return: a :class:`dict`
00449         """
00450         if flat:
00451             return dict(self.iteritems())
00452         return dict(self)

Here is the call graph for this function:

update() extends rather than replaces existing key lists.

Definition at line 453 of file datastructures.py.

00453 
00454     def update(self, other_dict):
00455         """update() extends rather than replaces existing key lists."""
00456         if isinstance(other_dict, MultiDict):
00457             for key, value_list in other_dict.iterlists():
00458                 self.setlistdefault(key, []).extend(value_list)
00459         elif isinstance(other_dict, dict):
00460             for key, value in other_dict.items():
00461                 self.setlistdefault(key, []).append(value)
00462         else:
00463             for key, value in other_dict:
00464                 self.setlistdefault(key, []).append(value)

Here is the call graph for this function:

Here is the caller graph for this function:

Returns a list of the first value on every key's value list.

:return: a :class:`list`.

Reimplemented in MoinMoin.support.werkzeug.datastructures.CombinedMultiDict.

Definition at line 389 of file datastructures.py.

00389 
00390     def values(self):
00391         """Returns a list of the first value on every key's value list.
00392 
00393         :return: a :class:`list`.
00394         """
00395         return [self[key] for key in self.iterkeys()]

Here is the call graph for this function:

Here is the caller graph for this function:


Member Data Documentation

Definition at line 254 of file datastructures.py.

Definition at line 387 of file datastructures.py.


The documentation for this class was generated from the following file: