[web/views] Port csvexport views to py3k
authorRémi Cardona <remi.cardona@logilab.fr>
Wed, 16 Sep 2015 17:07:26 +0200
changeset 10695 321b99973b69
parent 10694 7ece2df9cc5c
child 10696 4ba4be5553cf
[web/views] Port csvexport views to py3k There are a few hoops to jump through since python 3's csv module _is_ unicode aware.
uilib.py
web/test/unittest_views_csv.py
web/views/csvexport.py
--- a/uilib.py	Tue Sep 22 14:18:14 2015 +0200
+++ b/uilib.py	Wed Sep 16 17:07:26 2015 +0200
@@ -531,7 +531,9 @@
 # csv files / unicode support #################################################
 
 class UnicodeCSVWriter:
-    """proxies calls to csv.writer.writerow to be able to deal with unicode"""
+    """proxies calls to csv.writer.writerow to be able to deal with unicode
+
+    Under Python 3, this code no longer encodes anything."""
 
     def __init__(self, wfunc, encoding, **kwargs):
         self.writer = csv.writer(self, **kwargs)
@@ -542,6 +544,9 @@
         self.wfunc(data)
 
     def writerow(self, row):
+        if PY3:
+            self.writer.writerow(row)
+            return
         csvrow = []
         for elt in row:
             if isinstance(elt, text_type):
--- a/web/test/unittest_views_csv.py	Tue Sep 22 14:18:14 2015 +0200
+++ b/web/test/unittest_views_csv.py	Wed Sep 16 17:07:26 2015 +0200
@@ -30,7 +30,7 @@
             self.assertEqual(req.headers_out.getRawHeaders('content-type'),
                              ['text/comma-separated-values;charset=UTF-8'])
             expected_data = "String;COUNT(CWUser)\nguests;1\nmanagers;1"
-            self.assertMultiLineEqual(expected_data, data)
+            self.assertMultiLineEqual(expected_data, data.decode('utf-8'))
 
     def test_csvexport_on_empty_rset(self):
         """Should return the CSV header.
@@ -42,7 +42,7 @@
             self.assertEqual(req.headers_out.getRawHeaders('content-type'),
                              ['text/comma-separated-values;charset=UTF-8'])
             expected_data = "String;COUNT(CWUser)"
-            self.assertMultiLineEqual(expected_data, data)
+            self.assertMultiLineEqual(expected_data, data.decode('utf-8'))
 
 
 if __name__ == '__main__':
--- a/web/views/csvexport.py	Tue Sep 22 14:18:14 2015 +0200
+++ b/web/views/csvexport.py	Wed Sep 16 17:07:26 2015 +0200
@@ -20,6 +20,7 @@
 __docformat__ = "restructuredtext en"
 from cubicweb import _
 
+from six import PY2
 from six.moves import range
 
 from cubicweb.schema import display_name
@@ -31,7 +32,7 @@
     """mixin class for CSV views"""
     templatable = False
     content_type = "text/comma-separated-values"
-    binary = True # avoid unicode assertion
+    binary = PY2 # python csv module is unicode aware in py3k
     csv_params = {'dialect': 'excel',
                   'quotechar': '"',
                   'delimiter': ';',