[views] Move zipview to a more general download.py file
authorVincent Michel <vincent.michel@logilab.fr>
Mon, 15 Jul 2013 16:08:20 +0200
changeset 280 04047bb24ad8
parent 279 9eb199a02da8
child 281 77fce4bb1856
[views] Move zipview to a more general download.py file
views/download.py
views/zipview.py
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/views/download.py	Mon Jul 15 16:08:20 2013 +0200
@@ -0,0 +1,127 @@
+# -*- coding: utf-8 -*-
+# copyright 2013 LOGILAB S.A. (Paris, FRANCE), all rights reserved.
+# copyright 2013 CEA (Saclay, FRANCE), all rights reserved.
+# contact http://www.logilab.fr -- mailto:contact@logilab.fr
+#
+# This program is free software: you can redistribute it and/or modify it under
+# the terms of the GNU Lesser General Public License as published by the Free
+# Software Foundation, either version 2.1 of the License, or (at your option)
+# any later version.
+#
+# This program is distributed in the hope that it will be useful, but WITHOUT
+# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
+# FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
+# details.
+#
+# You should have received a copy of the GNU Lesser General Public License along
+# with this program. If not, see <http://www.gnu.org/licenses/>.
+
+import os
+import os.path as osp
+import tempfile
+from contextlib import closing
+from zipfile import ZipFile, ZIP_DEFLATED
+
+from cubicweb.predicates import is_instance, authenticated_user, anonymous_user
+from cubicweb.view import EntityView
+
+
+###############################################################################
+### UTILITY FUNCTIONS #########################################################
+###############################################################################
+def zipfiles(filepaths):
+    """generates a zip archive from `filepaths`
+
+    :param filepaths: is a dictionary mapping basename (as it will appear in the
+                      archive) to corresponding absolute filepath (where it must
+                      read from on the filesystem)
+
+    :return: a couple fileobj, filepath where `fileobj` is a standard python
+             open file objet on the generated archive, and `filepath` is an
+             absolute file path to this archive on the filesystem
+    """
+    fd, archive_filepath = tempfile.mkstemp()
+    try:
+        noext_archivename = osp.splitext(DataZipAbstractView.archive_name)[0]
+        with closing(ZipFile(archive_filepath, "w", ZIP_DEFLATED)) as zip:
+            for filename, subj, filepath in filepaths:
+                zip.write(filepath, '%s/%s/%s' % (noext_archivename, subj, filename))
+        fileobj = os.fdopen(fd)
+        fileobj.seek(0)
+        return fileobj, archive_filepath
+    except:
+        os.close(fd)
+        os.unlink(archive_filepath)
+        raise
+
+
+###############################################################################
+### ZIP VIEWS #################################################################
+###############################################################################
+class DataZipAbstractView(EntityView):
+    """Abstract base class for the zip view"""
+    __abstract__ = True
+    __regid__ = 'data-zip'
+    __select__ = EntityView.__select__ & is_instance('Scan', 'GenomicMeasure')
+    templatable = False
+    binary = True
+    archive_name = 'brainomics_data.zip'
+
+    def set_request_content_type(self):
+        self._cw.set_content_type('application/zip', filename=self.archive_name)
+
+class DataZipAuthenticatedView(DataZipAbstractView):
+    __select__ = DataZipAbstractView.__select__ & authenticated_user()
+
+    def call(self):
+        if not self.cw_rset:
+            return
+        filepaths = set()
+        for entity in self.cw_rset.entities():
+            if entity.__regid__ == 'GenomicMeasure':
+                for ext in ('.bim', '.bed', '.fam'):
+                    filepaths.add((osp.basename(entity.filepath)+ext,
+                                   entity.concerns[0].identifier,
+                                   entity.full_filepath+ext))
+            else:
+                filename = entity.type+'_'+entity.filepath.split('/')[-1]
+                filename = filename.replace(' ', '_')
+                filepaths.add((filename, entity.concerns[0].identifier, entity.full_filepath))
+            for external_resource in entity.external_resources:
+                filepaths.add((osp.basename(external_resource.filepath),
+                               entity.concerns[0].identifier,
+                               external_resource.full_filepath))
+        fileobj, archive_filepath = zipfiles(list(filepaths))
+        try:
+            self.w(fileobj.read())
+        finally:
+            fileobj.close()
+            os.unlink(archive_filepath)
+
+
+class DataZipAnonymousView(DataZipAbstractView):
+    __select__ = DataZipAbstractView.__select__ & anonymous_user()
+    binary = False
+    templatable = True
+
+    def call(self):
+        ahref_login = u'<a href="%s">%s</a>' % (self._cw.build_url('login'),
+                                                self._cw._('sign in'))
+        ahref_register = u'<a href="%s">%s</a>' % (self._cw.build_url('register'),
+                                                   self._cw._('sign up'))
+        msg = self._cw._('Please %(login)s or %(register)s before downloading the archive.'
+                          % {'login': ahref_login, 'register': ahref_register})
+        self.w(u'<h2>%s</h2>' % msg)
+
+
+###############################################################################
+### REGISTRATION CALLBACK #####################################################
+###############################################################################
+def registration_callback(vreg):
+    vreg.register_all(globals().values(), __name__, (DataZipAnonymousView,))
+    if not vreg.config['allow-anon-download']:
+        # Register the anon view if do not allow anon download
+        vreg.register(DataZipAnonymousView)
+    else:
+        # Change the selector of DataZipAuthenticatedView
+        DataZipAuthenticatedView.__select__ = DataZipAbstractView.__select__
--- a/views/zipview.py	Wed Jul 17 11:50:11 2013 +0200
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,127 +0,0 @@
-# -*- coding: utf-8 -*-
-# copyright 2013 LOGILAB S.A. (Paris, FRANCE), all rights reserved.
-# copyright 2013 CEA (Saclay, FRANCE), all rights reserved.
-# contact http://www.logilab.fr -- mailto:contact@logilab.fr
-#
-# This program is free software: you can redistribute it and/or modify it under
-# the terms of the GNU Lesser General Public License as published by the Free
-# Software Foundation, either version 2.1 of the License, or (at your option)
-# any later version.
-#
-# This program is distributed in the hope that it will be useful, but WITHOUT
-# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
-# FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
-# details.
-#
-# You should have received a copy of the GNU Lesser General Public License along
-# with this program. If not, see <http://www.gnu.org/licenses/>.
-
-import os
-import os.path as osp
-import tempfile
-from contextlib import closing
-from zipfile import ZipFile, ZIP_DEFLATED
-
-from cubicweb.predicates import is_instance, authenticated_user, anonymous_user
-from cubicweb.view import EntityView
-
-
-###############################################################################
-### UTILITY FUNCTIONS #########################################################
-###############################################################################
-def zipfiles(filepaths):
-    """generates a zip archive from `filepaths`
-
-    :param filepaths: is a dictionary mapping basename (as it will appear in the
-                      archive) to corresponding absolute filepath (where it must
-                      read from on the filesystem)
-
-    :return: a couple fileobj, filepath where `fileobj` is a standard python
-             open file objet on the generated archive, and `filepath` is an
-             absolute file path to this archive on the filesystem
-    """
-    fd, archive_filepath = tempfile.mkstemp()
-    try:
-        noext_archivename = osp.splitext(DataZipAbstractView.archive_name)[0]
-        with closing(ZipFile(archive_filepath, "w", ZIP_DEFLATED)) as zip:
-            for filename, subj, filepath in filepaths:
-                zip.write(filepath, '%s/%s/%s' % (noext_archivename, subj, filename))
-        fileobj = os.fdopen(fd)
-        fileobj.seek(0)
-        return fileobj, archive_filepath
-    except:
-        os.close(fd)
-        os.unlink(archive_filepath)
-        raise
-
-
-###############################################################################
-### ZIP VIEWS #################################################################
-###############################################################################
-class DataZipAbstractView(EntityView):
-    """Abstract base class for the zip view"""
-    __abstract__ = True
-    __regid__ = 'data-zip'
-    __select__ = EntityView.__select__ & is_instance('Scan', 'GenomicMeasure')
-    templatable = False
-    binary = True
-    archive_name = 'brainomics_data.zip'
-
-    def set_request_content_type(self):
-        self._cw.set_content_type('application/zip', filename=self.archive_name)
-
-class DataZipAuthenticatedView(DataZipAbstractView):
-    __select__ = DataZipAbstractView.__select__ & authenticated_user()
-
-    def call(self):
-        if not self.cw_rset:
-            return
-        filepaths = set()
-        for entity in self.cw_rset.entities():
-            if entity.__regid__ == 'GenomicMeasure':
-                for ext in ('.bim', '.bed', '.fam'):
-                    filepaths.add((osp.basename(entity.filepath)+ext,
-                                   entity.concerns[0].identifier,
-                                   entity.full_filepath+ext))
-            else:
-                filename = entity.type+'_'+entity.filepath.split('/')[-1]
-                filename = filename.replace(' ', '_')
-                filepaths.add((filename, entity.concerns[0].identifier, entity.full_filepath))
-            for external_resource in entity.external_resources:
-                filepaths.add((osp.basename(external_resource.filepath),
-                               entity.concerns[0].identifier,
-                               external_resource.full_filepath))
-        fileobj, archive_filepath = zipfiles(list(filepaths))
-        try:
-            self.w(fileobj.read())
-        finally:
-            fileobj.close()
-            os.unlink(archive_filepath)
-
-
-class DataZipAnonymousView(DataZipAbstractView):
-    __select__ = DataZipAbstractView.__select__ & anonymous_user()
-    binary = False
-    templatable = True
-
-    def call(self):
-        ahref_login = u'<a href="%s">%s</a>' % (self._cw.build_url('login'),
-                                                self._cw._('sign in'))
-        ahref_register = u'<a href="%s">%s</a>' % (self._cw.build_url('register'),
-                                                   self._cw._('sign up'))
-        msg = self._cw._('Please %(login)s or %(register)s before downloading the archive.'
-                          % {'login': ahref_login, 'register': ahref_register})
-        self.w(u'<h2>%s</h2>' % msg)
-
-
-###############################################################################
-### REGISTRATION CALLBACK #####################################################
-###############################################################################
-def registration_callback(vreg):
-    vreg.register_all(globals().values(), __name__, (DataZipAnonymousView,))
-    if not vreg.config['allow-anon-download']:
-        # Register the anon view if do not allow anon download
-        vreg.register(DataZipAnonymousView)
-    else:
-        # Change the selector of DataZipAuthenticatedView
-        DataZipAuthenticatedView.__select__ = DataZipAbstractView.__select__