Code

Ticket #1569: 1569.unicode.trunk.diff

File 1569.unicode.trunk.diff, 2.2 KB (added by Maniac <Maniac@…>, 8 years ago)

Unicode-aware iterator (trunk)

Line 
1Index: django/utils/httpwrappers.py
2===================================================================
3--- django/utils/httpwrappers.py        (revision 2671)
4+++ django/utils/httpwrappers.py        (working copy)
5@@ -151,10 +151,10 @@
6         if not mimetype:
7             mimetype = "%s; charset=%s" % (settings.DEFAULT_CONTENT_TYPE, settings.DEFAULT_CHARSET)
8         if hasattr(content, '__iter__'):
9-            self.iterator = content
10+            self._iterator = content
11             self._is_string = False
12         else:
13-            self.iterator = [content]
14+            self._iterator = [content]
15             self._is_string = True
16         self.headers = {'Content-Type': mimetype}
17         self.cookies = SimpleCookie()
18@@ -200,23 +200,32 @@
19             pass
20 
21     def _get_content(self):
22-        content = ''.join(self.iterator)
23+        content = ''.join(self._iterator)
24         if isinstance(content, unicode):
25             content = content.encode(self._charset)
26         return content
27 
28     def _set_content(self, value):
29-        self.iterator = [value]
30+        self._iterator = [value]
31         self._is_string = True
32 
33     content = property(_get_content, _set_content)
34 
35+    def _get_iterator(self):
36+        "Output iterator. Converts data into client charset if necessary."
37+        for chunk in self._iterator:
38+            if isinstance(chunk, unicode):
39+                chunk = chunk.encode(self._charset)
40+            yield chunk
41+
42+    iterator = property(_get_iterator)
43+
44     # The remaining methods partially implement the file-like object interface.
45     # See http://docs.python.org/lib/bltin-file-objects.html
46     def write(self, content):
47         if not self._is_string:
48             raise Exception, "This %s instance is not writable" % self.__class__
49-        self.iterator.append(content)
50+        self._iterator.append(content)
51 
52     def flush(self):
53         pass
54@@ -224,7 +233,7 @@
55     def tell(self):
56         if not self._is_string:
57             raise Exception, "This %s instance cannot tell its position" % self.__class__
58-        return sum([len(chunk) for chunk in self.iterator])
59+        return sum([len(chunk) for chunk in self._iterator])
60 
61 class HttpResponseRedirect(HttpResponse):
62     def __init__(self, redirect_to):