Ticket #5956: unicode_http_headers.diff

File unicode_http_headers.diff, 2.0 KB (added by Remco Wendt, 16 years ago)

Patch for unicode support for response headers

  • django/http/__init__.py

     
    276276        return '\n'.join(['%s: %s' % (key, value)
    277277            for key, value in self._headers.values()]) \
    278278            + '\n\n' + self.content
     279           
     280    def _encoded(self, val):
     281        if isinstance(val, unicode):
     282            return val.encode(self._charset)
     283        return val
    279284
    280285    def __setitem__(self, header, value):
    281         self._headers[header.lower()] = (header, value)
     286        self._headers[header.lower()] = (self._encoded(header),
     287                                         self._encoded(value))
    282288
    283289    def __delitem__(self, header):
    284290        try:
  • tests/regressiontests/httpwrappers/tests.py

     
    391391>>> q.getlist('foo')
    392392[u'bar', u'\ufffd']
    393393
     394######################################
     395# HttpResponse with Unicode headers  #
     396######################################
     397
     398>>> r = HttpResponse()
     399
     400If we insert a unicode value it will be converted to a string. This is done
     401because the handlers (WSGI/mod_python) expect binary data and will break on
     402non-ascii unicode.
     403
     404>>> r['value'] = u't\xebst value'
     405>>> type(r['value'])
     406<type 'str'>
     407
     408It uses the charset of the response for encoding it. By default it is utf-8.
     409
     410>>> type(r['value'].decode('utf8'))
     411<type 'unicode'>
     412
     413The response also converts unicode keys to strings.
     414
     415>>> r[u't\xebst'] = 'testing key'
     416>>> type(list(sorted(r.items()))[1][0])
     417<type 'str'>
     418
     419This only happens when you call items since the implementation uses a system
     420where the original key is used for normal dict lookups.
     421
     422>>> u't\xebst' in r
     423True
     424
    394425"""
    395426
    396 from django.http import QueryDict
     427from django.http import QueryDict, HttpResponse
    397428
    398429if __name__ == "__main__":
    399430    import doctest
Back to Top