Back to index

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

List of all members.

Public Member Functions

def __init__
def linked
def __getitem__
def __eq__
def __ne__
def get
def getlist
def get_all
def iteritems
def iterkeys
def itervalues
def keys
def values
def items
def extend
def __delitem__
def remove
def pop
def popitem
def __contains__
def __iter__
def __len__
def add
def add_header
def clear
def set
def setdefault
def __setitem__
def to_list
def copy
def __copy__
def __str__
def __repr__

Static Public Attributes

 KeyError = None
 has_key = __contains__

Private Attributes

 _list

Detailed Description

An object that stores some headers.  It has a dict-like interface
but is ordered and can store the same keys multiple times.

This data structure is useful if you want a nicer way to handle WSGI
headers which are stored as tuples in a list.

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

Headers is mostly compatible with the Python :class:`wsgiref.headers.Headers`
class, with the exception of `__getitem__`.  :mod:`wsgiref` will return
`None` for ``headers['missing']``, whereas :class:`Headers` will raise
a :class:`KeyError`.

To create a new :class:`Headers` object pass it a list or dict of headers
which are used as default values.  This does not reuse the list passed
to the constructor for internal usage.  To create a :class:`Headers`
object that uses as internal storage the list or list-like object you
can use the :meth:`linked` class method.

:param defaults: The list of default values for the :class:`Headers`.

Definition at line 515 of file datastructures.py.


Constructor & Destructor Documentation

def MoinMoin.support.werkzeug.datastructures.Headers.__init__ (   self,
  defaults = None,
  _list = None 
)

Definition at line 546 of file datastructures.py.

00546 
00547     def __init__(self, defaults=None, _list=None):
00548         if _list is None:
00549             _list = []
00550         self._list = _list
00551         if defaults is not None:
00552             self.extend(defaults)


Member Function Documentation

Check if a key is present.

Definition at line 735 of file datastructures.py.

00735 
00736     def __contains__(self, key):
00737         """Check if a key is present."""
00738         try:
00739             self.__getitem__(key, _index_operation=False)
00740         except KeyError:
00741             return False
00742         return True

Here is the call graph for this function:

Definition at line 842 of file datastructures.py.

00842 
00843     def __copy__(self):
00844         return self.copy()

Here is the call graph for this function:

def MoinMoin.support.werkzeug.datastructures.Headers.__delitem__ (   self,
  key,
  _index_operation = True 
)

Definition at line 691 of file datastructures.py.

00691 
00692     def __delitem__(self, key, _index_operation=True):
00693         if _index_operation and isinstance(key, (int, long, slice)):
00694             del self._list[key]
00695             return
00696         key = key.lower()
00697         new = []
00698         for k, v in self._list:
00699             if k.lower() != key:
00700                 new.append((k, v))
00701         self._list[:] = new

Here is the caller graph for this function:

Reimplemented in MoinMoin.support.werkzeug.datastructures.EnvironHeaders.

Definition at line 581 of file datastructures.py.

00581 
00582     def __eq__(self, other):
00583         return other.__class__ is self.__class__ and \
00584                set(other._list) == set(self._list)

Here is the call graph for this function:

Here is the caller graph for this function:

def MoinMoin.support.werkzeug.datastructures.Headers.__getitem__ (   self,
  key,
  _index_operation = True 
)

Reimplemented in MoinMoin.support.werkzeug.datastructures.EnvironHeaders.

Definition at line 569 of file datastructures.py.

00569 
00570     def __getitem__(self, key, _index_operation=True):
00571         if _index_operation:
00572             if isinstance(key, (int, long)):
00573                 return self._list[key]
00574             elif isinstance(key, slice):
00575                 return self.__class__(self._list[key])
00576         ikey = key.lower()
00577         for k, v in self._list:
00578             if k.lower() == ikey:
00579                 return v
00580         raise self.KeyError(key)

Here is the caller graph for this function:

Yield ``(key, value)`` tuples.

Reimplemented in MoinMoin.support.werkzeug.datastructures.EnvironHeaders.

Definition at line 745 of file datastructures.py.

00745 
00746     def __iter__(self):
00747         """Yield ``(key, value)`` tuples."""
00748         return iter(self._list)

Definition at line 749 of file datastructures.py.

00749 
00750     def __len__(self):
00751         return len(self._list)

Definition at line 585 of file datastructures.py.

00585 
00586     def __ne__(self, other):
00587         return not self.__eq__(other)

Here is the call graph for this function:

Definition at line 853 of file datastructures.py.

00853 
00854     def __repr__(self):
00855         return '%s(%r)' % (
00856             self.__class__.__name__,
00857             list(self)
00858         )
00859 

Like :meth:`set` but also supports index/slice based setting.

Definition at line 817 of file datastructures.py.

00817 
00818     def __setitem__(self, key, value):
00819         """Like :meth:`set` but also supports index/slice based setting."""
00820         if isinstance(key, (slice, int, long)):
00821             self._list[key] = value
00822         else:
00823             self.set(key, value)

Here is the call graph for this function:

Here is the caller graph for this function:

def MoinMoin.support.werkzeug.datastructures.Headers.__str__ (   self,
  charset = 'utf-8' 
)
Returns formatted headers suitable for HTTP transmission.

Definition at line 845 of file datastructures.py.

00845 
00846     def __str__(self, charset='utf-8'):
00847         """Returns formatted headers suitable for HTTP transmission."""
00848         strs = []
00849         for key, value in self.to_list(charset):
00850             strs.append('%s: %s' % (key, value))
00851         strs.append('\r\n')
00852         return '\r\n'.join(strs)

Here is the call graph for this function:

def MoinMoin.support.werkzeug.datastructures.Headers.add (   self,
  _key,
  _value,
  kw 
)
Add a new header tuple to the list.

Keyword arguments can specify additional parameters for the header
value, with underscores converted to dashes::

>>> d = Headers()
>>> d.add('Content-Type', 'text/plain')
>>> d.add('Content-Disposition', 'attachment', filename='foo.png')

The keyword argument dumping uses :func:`dump_options_header`
behind the scenes.

.. versionadded:: 0.4.1
    keyword arguments were added for :mod:`wsgiref` compatibility.

Definition at line 752 of file datastructures.py.

00752 
00753     def add(self, _key, _value, **kw):
00754         """Add a new header tuple to the list.
00755 
00756         Keyword arguments can specify additional parameters for the header
00757         value, with underscores converted to dashes::
00758 
00759         >>> d = Headers()
00760         >>> d.add('Content-Type', 'text/plain')
00761         >>> d.add('Content-Disposition', 'attachment', filename='foo.png')
00762 
00763         The keyword argument dumping uses :func:`dump_options_header`
00764         behind the scenes.
00765 
00766         .. versionadded:: 0.4.1
00767             keyword arguments were added for :mod:`wsgiref` compatibility.
00768         """
00769         if kw:
00770             _value = dump_options_header(_value, dict((k.replace('_', '-'), v)
00771                                                       for k, v in kw.items()))
00772         self._list.append((_key, _value))

Here is the call graph for this function:

Here is the caller graph for this function:

def MoinMoin.support.werkzeug.datastructures.Headers.add_header (   self,
  _key,
  _value,
  _kw 
)
Add a new header tuple to the list.

An alias for :meth:`add` for compatibility with the :mod:`wsgiref`
:meth:`~wsgiref.headers.Headers.add_header` method.

Definition at line 773 of file datastructures.py.

00773 
00774     def add_header(self, _key, _value, **_kw):
00775         """Add a new header tuple to the list.
00776 
00777         An alias for :meth:`add` for compatibility with the :mod:`wsgiref`
00778         :meth:`~wsgiref.headers.Headers.add_header` method.
00779         """
00780         self.add(_key, _value, **_kw)

Here is the call graph for this function:

Clears all headers.

Definition at line 781 of file datastructures.py.

00781 
00782     def clear(self):
00783         """Clears all headers."""
00784         del self._list[:]

Reimplemented in MoinMoin.support.werkzeug.datastructures.EnvironHeaders.

Definition at line 839 of file datastructures.py.

00839 
00840     def copy(self):
00841         return self.__class__(self._list)

Here is the caller graph for this function:

Extend the headers with a dict or an iterable yielding keys and
values.

Definition at line 676 of file datastructures.py.

00676 
00677     def extend(self, iterable):
00678         """Extend the headers with a dict or an iterable yielding keys and
00679         values.
00680         """
00681         if isinstance(iterable, dict):
00682             for key, value in iterable.iteritems():
00683                 if isinstance(value, (tuple, list)):
00684                     for v in value:
00685                         self.add(key, v)
00686                 else:
00687                     self.add(key, value)
00688         else:
00689             for key, value in iterable:
00690                 self.add(key, value)

Here is the call graph for this function:

def MoinMoin.support.werkzeug.datastructures.Headers.get (   self,
  key,
  default = None,
  type = None 
)
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 = Headers([('Content-Length', '42')])
>>> d.get('Content-Length', type=int)
42

If a headers object is bound you must not add unicode strings
because no encoding takes place.

: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:`Headers`.  If a :exc:`ValueError` is raised
     by this callable the default value is returned.

Definition at line 588 of file datastructures.py.

00588 
00589     def get(self, key, default=None, type=None):
00590         """Return the default value if the requested data doesn't exist.
00591         If `type` is provided and is a callable it should convert the value,
00592         return it or raise a :exc:`ValueError` if that is not possible.  In
00593         this case the function will return the default as if the value was not
00594         found:
00595 
00596         >>> d = Headers([('Content-Length', '42')])
00597         >>> d.get('Content-Length', type=int)
00598         42
00599 
00600         If a headers object is bound you must not add unicode strings
00601         because no encoding takes place.
00602 
00603         :param key: The key to be looked up.
00604         :param default: The default value to be returned if the key can't
00605                         be looked up.  If not further specified `None` is
00606                         returned.
00607         :param type: A callable that is used to cast the value in the
00608                      :class:`Headers`.  If a :exc:`ValueError` is raised
00609                      by this callable the default value is returned.
00610         """
00611         try:
00612             rv = self.__getitem__(key, _index_operation=False)
00613         except KeyError:
00614             return default
00615         if type is None:
00616             return rv
00617         try:
00618             return type(rv)
00619         except ValueError:
00620             return default

Here is the call graph for this function:

Here is the caller graph for this function:

Return a list of all the values for the named field.

This method is compatible with the :mod:`wsgiref`
:meth:`~wsgiref.headers.Headers.get_all` method.

Definition at line 645 of file datastructures.py.

00645 
00646     def get_all(self, name):
00647         """Return a list of all the values for the named field.
00648 
00649         This method is compatible with the :mod:`wsgiref`
00650         :meth:`~wsgiref.headers.Headers.get_all` method.
00651         """
00652         return self.getlist(name)

Here is the call graph for this function:

def MoinMoin.support.werkzeug.datastructures.Headers.getlist (   self,
  key,
  type = None 
)
Return the list of items for a given key. If that key is not in the
:class:`Headers`, the return value will be an empty list.  Just as
:meth:`get` :meth:`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:`Headers`.  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.

Definition at line 621 of file datastructures.py.

00621 
00622     def getlist(self, key, type=None):
00623         """Return the list of items for a given key. If that key is not in the
00624         :class:`Headers`, the return value will be an empty list.  Just as
00625         :meth:`get` :meth:`getlist` accepts a `type` parameter.  All items will
00626         be converted with the callable defined there.
00627 
00628         :param key: The key to be looked up.
00629         :param type: A callable that is used to cast the value in the
00630                      :class:`Headers`.  If a :exc:`ValueError` is raised
00631                      by this callable the value will be removed from the list.
00632         :return: a :class:`list` of all the values for the key.
00633         """
00634         ikey = key.lower()
00635         result = []
00636         for k, v in self:
00637             if k.lower() == ikey:
00638                 if type is not None:
00639                     try:
00640                         v = type(v)
00641                     except ValueError:
00642                         continue
00643                 result.append(v)
00644         return result

Here is the caller graph for this function:

def MoinMoin.support.werkzeug.datastructures.Headers.items (   self,
  lower = False 
)

Definition at line 673 of file datastructures.py.

00673 
00674     def items(self, lower=False):
00675         return list(self.iteritems(lower))

Here is the call graph for this function:

Here is the caller graph for this function:

Definition at line 653 of file datastructures.py.

00653 
00654     def iteritems(self, lower=False):
00655         for key, value in self:
00656             if lower:
00657                 key = key.lower()
00658             yield key, value

Here is the caller graph for this function:

def MoinMoin.support.werkzeug.datastructures.Headers.iterkeys (   self,
  lower = False 
)

Definition at line 659 of file datastructures.py.

00659 
00660     def iterkeys(self, lower=False):
00661         for key, _ in self.iteritems(lower):
00662             yield key

Here is the call graph for this function:

Here is the caller graph for this function:

Definition at line 663 of file datastructures.py.

00663 
00664     def itervalues(self):
00665         for _, value in self.iteritems():
00666             yield value

Here is the call graph for this function:

Here is the caller graph for this function:

def MoinMoin.support.werkzeug.datastructures.Headers.keys (   self,
  lower = False 
)

Definition at line 667 of file datastructures.py.

00667 
00668     def keys(self, lower=False):
00669         return list(self.iterkeys(lower))

Here is the call graph for this function:

Here is the caller graph for this function:

Create a new :class:`Headers` object that uses the list of headers
passed as internal storage:

>>> headerlist = [('Content-Length', '40')]
>>> headers = Headers.linked(headerlist)
>>> headers.add('Content-Type', 'text/html')
>>> headerlist
[('Content-Length', '40'), ('Content-Type', 'text/html')]

:param headerlist: The list of headers the class is linked to.
:return: new linked :class:`Headers` object.

Reimplemented in MoinMoin.support.werkzeug.datastructures.EnvironHeaders.

Definition at line 554 of file datastructures.py.

00554 
00555     def linked(cls, headerlist):
00556         """Create a new :class:`Headers` object that uses the list of headers
00557         passed as internal storage:
00558 
00559         >>> headerlist = [('Content-Length', '40')]
00560         >>> headers = Headers.linked(headerlist)
00561         >>> headers.add('Content-Type', 'text/html')
00562         >>> headerlist
00563         [('Content-Length', '40'), ('Content-Type', 'text/html')]
00564 
00565         :param headerlist: The list of headers the class is linked to.
00566         :return: new linked :class:`Headers` object.
00567         """
00568         return cls(_list=headerlist)

def MoinMoin.support.werkzeug.datastructures.Headers.pop (   self,
  key = None,
  default = _missing 
)
Removes and returns a key or index.

:param key: The key to be popped.  If this is an integer the item at
    that position is removed, if it's a string the value for
    that key is.  If the key is omitted or `None` the last
    item is removed.
:return: an item.

Definition at line 709 of file datastructures.py.

00709 
00710     def pop(self, key=None, default=_missing):
00711         """Removes and returns a key or index.
00712 
00713         :param key: The key to be popped.  If this is an integer the item at
00714                     that position is removed, if it's a string the value for
00715                     that key is.  If the key is omitted or `None` the last
00716                     item is removed.
00717         :return: an item.
00718         """
00719         if key is None:
00720             return self._list.pop()
00721         if isinstance(key, (int, long)):
00722             return self._list.pop(key)
00723         try:
00724             rv = self[key]
00725             self.remove(key)
00726         except KeyError:
00727             if default is not _missing:
00728                 return default
00729             raise
00730         return rv

Here is the call graph for this function:

Here is the caller graph for this function:

Removes a key or index and returns a (key, value) item.

Definition at line 731 of file datastructures.py.

00731 
00732     def popitem(self):
00733         """Removes a key or index and returns a (key, value) item."""
00734         return self.pop()

Here is the call graph for this function:

Remove a key.

:param key: The key to be removed.

Definition at line 702 of file datastructures.py.

00702 
00703     def remove(self, key):
00704         """Remove a key.
00705 
00706         :param key: The key to be removed.
00707         """
00708         return self.__delitem__(key, _index_operation=False)

Here is the call graph for this function:

Here is the caller graph for this function:

def MoinMoin.support.werkzeug.datastructures.Headers.set (   self,
  key,
  value 
)
Remove all header tuples for `key` and add a new one.  The newly
added key either appears at the end of the list if there was no
entry or replaces the first one.

:param key: The key to be inserted.
:param value: The value to be inserted.

Definition at line 785 of file datastructures.py.

00785 
00786     def set(self, key, value):
00787         """Remove all header tuples for `key` and add a new one.  The newly
00788         added key either appears at the end of the list if there was no
00789         entry or replaces the first one.
00790 
00791         :param key: The key to be inserted.
00792         :param value: The value to be inserted.
00793         """
00794         lc_key = key.lower()
00795         for idx, (old_key, old_value) in enumerate(self._list):
00796             if old_key.lower() == lc_key:
00797                 # replace first ocurrence
00798                 self._list[idx] = (key, value)
00799                 break
00800         else:
00801             return self.add(key, value)
00802         self._list[idx + 1:] = [(k, v) for k, v in self._list[idx + 1:]
00803                                 if k.lower() != lc_key]

Here is the call graph for this function:

Here is the caller graph for this function:

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 804 of file datastructures.py.

00804 
00805     def setdefault(self, key, value):
00806         """Returns the value for the key if it is in the dict, otherwise it
00807         returns `default` and sets that value for `key`.
00808 
00809         :param key: The key to be looked up.
00810         :param default: The default value to be returned if the key is not
00811                         in the dict.  If not further specified it's `None`.
00812         """
00813         if key in self:
00814             return self[key]
00815         self.set(key, value)
00816         return value

Here is the call graph for this function:

def MoinMoin.support.werkzeug.datastructures.Headers.to_list (   self,
  charset = 'utf-8' 
)
Convert the headers into a list and converts the unicode header
items to the specified charset.

:return: list

Definition at line 824 of file datastructures.py.

00824 
00825     def to_list(self, charset='utf-8'):
00826         """Convert the headers into a list and converts the unicode header
00827         items to the specified charset.
00828 
00829         :return: list
00830         """
00831         result = []
00832         for k, v in self:
00833             if isinstance(v, unicode):
00834                 v = v.encode(charset)
00835             else:
00836                 v = str(v)
00837             result.append((k, v))
00838         return result

Here is the caller graph for this function:

Definition at line 670 of file datastructures.py.

00670 
00671     def values(self):
00672         return list(self.itervalues())

Here is the call graph for this function:

Here is the caller graph for this function:


Member Data Documentation

Definition at line 549 of file datastructures.py.

Definition at line 743 of file datastructures.py.

Definition at line 544 of file datastructures.py.


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