Added blob file copy hook
authorThierry Florac <thierry.florac@onf.fr>
Tue, 17 Mar 2015 17:12:22 +0100 (2015-03-17)
changeset 2 2cbea3d9e537
parent 1 36a56f22e80b
child 3 5ee5bf0d8c45
Added blob file copy hook
src/pyams_file/file.py
--- a/src/pyams_file/file.py	Mon Mar 02 15:26:52 2015 +0100
+++ b/src/pyams_file/file.py	Tue Mar 17 17:12:22 2015 +0100
@@ -9,25 +9,31 @@
 # WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
 # FOR A PARTICULAR PURPOSE.
 #
+from pyramid.events import subscriber
+from zope.lifecycleevent.interfaces import IObjectAddedEvent
 
 __docformat__ = 'restructuredtext'
 
 
 # import standard library
-from io import BytesIO
-from PIL import Image
 import os
+import shutil
 try:
     import magic
 except ImportError:
     magic = None
 
+from io import BytesIO
+from PIL import Image
+
 # import interfaces
-from pyams_file.interfaces import IFile, IImage, IVideo, IAudio, IFileInfo, FileModifiedEvent
+from pyams_file.interfaces import IFile, IImage, IVideo, IAudio, IFileInfo, FileModifiedEvent, IFileFieldContainer
+from zope.copy.interfaces import ICopyHook, ResumeCopy
 from zope.location.interfaces import IContained
 
 # import packages
 from persistent import Persistent
+from pyams_utils.adapter import adapter_config, ContextAdapter
 from pyams_utils.request import check_request
 from ZODB.blob import Blob
 from zope.container.contained import Contained
@@ -217,3 +223,25 @@
     else:
         factory = File
     return factory(data, content_type)
+
+
+@adapter_config(context=IFile, provides=ICopyHook)
+class BlobFileCopyHook(ContextAdapter):
+    """Blob file copy hook
+
+    Copied from z3c.blobfile package
+    """
+
+    def __call__(self, toplevel, register):
+        register(self._copy_blob)
+        raise ResumeCopy
+
+    def _copy_blob(self, translate):
+        if self.context._blob is not None:
+            target = translate(self.context)
+            target._blob = Blob()
+            fsrc = self.context._blob.open('r')
+            fdst = target._blob.open('w')
+            shutil.copyfileobj(fsrc, fdst)
+            fdst.close()
+            fsrc.close()