Tiago Cogumbreiro

O Irrepupável

Back to top

Saturday, March 29, 2008

Django and Unicode

I have made this patch against Django SVN r7379, please have a look at it:

--- /usr/lib/python2.5/site-packages/django/http/__init__.py    2008-03-29 22:24:02.000000000 +0000
+++ __init__.py 2008-03-29 22:23:03.000000000 +0000
@@ -360,10 +360,8 @@
         return self
 
     def next(self):
-        chunk = self._iterator.next()
-        if isinstance(chunk, unicode):
-            chunk = chunk.encode(self._charset)
-        return str(chunk)
+        chunk = unicode(self._iterator.next())
+        return chunk.encode(self._charset)
 
     def close(self):
         if hasattr(self._container, 'close'):

Before the patch, a chunk (the reply that will be sent by the HTTP server to the client) is encoded with the charset defined in our project (self._charset) only if it is an unicode object, otherwise, it will happily convert to a string using the system's encoding (by using the function str), which was resulting in a UnicodeEncodeError exception that would break Django.

If you want to make sure that the reply you are sending, through your HTTPResponse, is encoded into a string using the project's encoding, then convert it first into a unicode object. If my patch is accepted, though, this will be done automatically for you.

Oh, by the way, I am enjoying Django. I am using it to create REST web-services. It is being an enjoying and out-of-your-face experience.

0 comments: