[Web-SIG] Multiple message-header fields handling

Alex Botero-Lowry alex at puddlejumper.foxybanana.com
Tue Oct 2 21:50:21 CEST 2007

On Tue, Oct 02, 2007 at 09:30:46PM +0200, Manlio Perillo wrote:
> The HTTP 1.1 protocol (section 4.2) says that:
> """Multiple message-header fields with the same field-name MAY be 
> present in a message if and only if the entire field-value for that 
> header field is defined as a comma-separated list [i.e., #(values)]."""
> This can happen, as an example, with the Cookie header.
> My question is: how should this be handled in WSGI?
> As an example Nginx stores all the headers in a associative array, 
> where, of course, only the "last seen" headers appears.
> However common multiple message-headers are stored in the request struct.
Initially I used such a solution (cookies was a special property in the response
object), but I ended up just throwing together a custom dict that looks like:

class ResponseHeaders(dict):
        def __setitem__(self, item, val):
                if item in self:
                        iv = self[item]
                        if isinstance(iv, list):
                                iv = [iv, val]
                        dict.__setitem__(self, item, iv)
                        dict.__setitem__(self, item, val)

        def replace(self, key, val):
                dict.__setitem__(self, key, val)

        def items(self):
                ret = []
                for k,v in dict.items(self):
                        if isinstance(v, list):
                                ret.extend([ (k, a) for a in v ])
                                ret.append((k, v))
                return ret

        def iteritems(self):
                return iter(self.items())

It's really intended for passing the headers on to start_response, and for
getting the headers into it, rather then for reading from it, which is fine
99% of the time. I recently had to add replace since i had a situation where
I needed to overwrite a preset header, but other than that it serves me well.


More information about the Web-SIG mailing list