Ticket #11739: 11739-3.diff

File 11739-3.diff, 1.7 KB (added by Claude Paroz, 12 years ago)

Wrap StringIO with utf-8 reader/writer

  • django/core/files/base.py

    diff --git a/django/core/files/base.py b/django/core/files/base.py
    index 48d0be4..db0e892 100644
    a b  
     1import codecs
    12import os
    23try:
    34    from cStringIO import StringIO
    class ContentFile(File):  
    124125    """
    125126    def __init__(self, content, name=None):
    126127        content = content or ''
    127         super(ContentFile, self).__init__(StringIO(content), name=name)
     128        if isinstance(content, unicode):
     129            buffer = StringIO(content.encode('utf-8'))
     130            codecinfo = codecs.lookup('utf8')
     131            file_wrapper = codecs.StreamReaderWriter(
     132                buffer, codecinfo.streamreader, codecinfo.streamwriter)
     133        else:
     134            file_wrapper = StringIO(content)
     135        super(ContentFile, self).__init__(file_wrapper, name=name)
    128136        self.size = len(content)
    129137
    130138    def __str__(self):
  • tests/regressiontests/file_storage/tests.py

    diff --git a/tests/regressiontests/file_storage/tests.py b/tests/regressiontests/file_storage/tests.py
    index d1ecbe6..576c1c3 100644
    a b class ContentFileTestCase(unittest.TestCase):  
    553553    def test_content_file_custome_name(self):
    554554        name = "I can have a name too!"
    555555        self.assertEqual(ContentFile("content", name=name).name, name)
     556
     557class ContentFileUnicodeBug(unittest.TestCase):
     558    """
     559    Tests that ContentFile instances can contain unicode (#11739)
     560    """
     561    def test_unicode(self):
     562        """
     563        ContentFile instances should be able to handle unicode.
     564        """
     565        snowman = u'☃'
     566        file = ContentFile(snowman)
     567        self.assertEqual(file.read(), snowman)
Back to Top