[Web-SIG] Re: Pending modifications to PEP 333

Denis S. Otkidach ods at strana.ru
Mon Aug 30 11:06:49 CEST 2004

On Sun, 29 Aug 2004 22:38:57 -0500
Ian Bicking <ianb at colorstudy.com> wrote:

> > * Make the 'headers' object an 'email.Message' (well, there's been some 
> > feedback, but I think I addressed the concerns, and there was no 
> > feedback since)
> I'm -0 on email.Message.

Below is a class we use for headers in our framework for several years.
I guess it's more comfortable than list of tuples or email.Message.
Anyway, we have to fix only "must have" interface, but not all useful

class Headers:
    '''Dictionary-like object of HTTP headers with case insensitive key lookup
    and add() method. The order of headers is preserved.'''

    def __init__(self, data={}):
        self._headers =  []
        self._headers_map = {}
        if data:
            if isinstance(data, dict):
                # From dictionary
                for key, value in data.iteritems():
                    self.add(key, value)
                # from any sequence of pairs
                for key, value in data:
                    self.add(key, value)
            # XXX Here can be initialization from other types: string, file.

    def __iter__(self):
        return iter(self._headers)

    def __len__(self):
        return len(self._headers)

    def keys(self):
        return self._headers_map.keys()

    def has_key(self, key):
        return self._headers_map.has_key(key)

    def add(self, key, value):
        self._headers.append((key, value))
        self._headers_map.setdefault(key.lower(), []).append(value)

    def __getitem__(self, key):
        '''Get header. If there are several header with the same key, their
        values are joined.'''
        # RFC 2616, 4.2 Message Headers
        return ', '.join(self._headers_map[key.lower()])

    def __setitem__(self, key, value):
        '''Replace headers with the same key.'''
        del self[key]
        self.add(key, value)

    def __delitem__(self, key):
        '''Delete all headers with this key. Never fail.'''
        key = key.lower()
        if self._headers_map.has_key(key):
            del self._headers_map[key]
            self._headers = [(k, v) for (k, v) in self._headers
                                    if k.lower()!=key]

    def __str__(self):
        return '\r\n'.join(['%s: %s' % h for h in self._headers])+'\r\n'

Denis S. Otkidach
http://www.python.ru/      [ru]

More information about the Web-SIG mailing list