David Larlet avatar David Larlet committed 91745b6

Symlink: refs #6. It allows you to symlink a file when it's identical to the original file and to copy the file if it's modified. Thanks Wim Leers.

Comments (0)

Files changed (2)

     * Chris McCormick (S3 with Boto)
     * Ivanov E. (Database)
     * Ariel Núñez (packaging)
+    * Wim Leers (SymlinkOrCopy + patches)
 
 Extra thanks to Marty for adding this in Django, 
 you can buy his very interesting book (Pro Django).

backends/symlinkorcopy.py

+import os
+import os.path
+
+from django.conf import settings
+from django.core.files.storage import FileSystemStorage
+
+
+class SymlinkOrCopyStorage(FileSystemStorage):
+    """Stores symlinks to files instead of actual files whenever possible
+    
+    When a file that's being saved is currently stored in the symlinkWithin
+    directory, then symlink the file. Otherwise, copy the file.
+    """
+    def __init__(self, location=settings.MEDIA_ROOT, base_url=settings.MEDIA_URL, 
+            symlink_within=None):
+        super(FileSystemStorage, self).__init__(location, base_url)
+        self.symlink_within = symlink_within.split(":")
+
+    def _save(self, name, content):
+        full_path_dst = self.path(name)
+
+        directory = os.path.dirname(full_path_dst)
+        if not os.path.exists(directory):
+            os.makedirs(directory)
+        elif not os.path.isdir(directory):
+            raise IOError("%s exists and is not a directory." % directory)
+
+        full_path_src = os.path.abspath(content.name)
+
+        symlinked = False
+        # Only symlink if the current platform supports it.
+        if getattr(os, "symlink", False):
+            for path in self.symlink_within:
+                if full_path_src.startswith(path):
+                    os.symlink(full_path_src, full_path_dst)
+                    symlinked = True
+                    break
+
+        if not symlinked:
+            super(FileSystemStorage, self)._save(name, content)
+
+        return name
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.