Code

Ticket #5956: unicode_http_headers.diff

File unicode_http_headers.diff, 2.0 KB (added by shanx, 6 years ago)

Patch for unicode support for response headers

Line 
1Index: django/http/__init__.py
2===================================================================
3--- django/http/__init__.py     (revision 6783)
4+++ django/http/__init__.py     (working copy)
5@@ -276,9 +276,15 @@
6         return '\n'.join(['%s: %s' % (key, value)
7             for key, value in self._headers.values()]) \
8             + '\n\n' + self.content
9+           
10+    def _encoded(self, val):
11+        if isinstance(val, unicode):
12+            return val.encode(self._charset)
13+        return val
14 
15     def __setitem__(self, header, value):
16-        self._headers[header.lower()] = (header, value)
17+        self._headers[header.lower()] = (self._encoded(header),
18+                                         self._encoded(value))
19 
20     def __delitem__(self, header):
21         try:
22Index: tests/regressiontests/httpwrappers/tests.py
23===================================================================
24--- tests/regressiontests/httpwrappers/tests.py (revision 6783)
25+++ tests/regressiontests/httpwrappers/tests.py (working copy)
26@@ -391,9 +391,40 @@
27 >>> q.getlist('foo')
28 [u'bar', u'\ufffd']
29 
30+######################################
31+# HttpResponse with Unicode headers  #
32+######################################
33+
34+>>> r = HttpResponse()
35+
36+If we insert a unicode value it will be converted to a string. This is done
37+because the handlers (WSGI/mod_python) expect binary data and will break on
38+non-ascii unicode.
39+
40+>>> r['value'] = u't\xebst value'
41+>>> type(r['value'])
42+<type 'str'>
43+
44+It uses the charset of the response for encoding it. By default it is utf-8.
45+
46+>>> type(r['value'].decode('utf8'))
47+<type 'unicode'>
48+
49+The response also converts unicode keys to strings.
50+
51+>>> r[u't\xebst'] = 'testing key'
52+>>> type(list(sorted(r.items()))[1][0])
53+<type 'str'>
54+
55+This only happens when you call items since the implementation uses a system
56+where the original key is used for normal dict lookups.
57+
58+>>> u't\xebst' in r
59+True
60+
61 """
62 
63-from django.http import QueryDict
64+from django.http import QueryDict, HttpResponse
65 
66 if __name__ == "__main__":
67     import doctest