a base storage class providing some default behaviors that all other storage systems can inherit or override as necessary the following methods represent a public interface to private methods these shouldn t be overridden by subclasses unless absolutely necessary retrieve the specified file from storage return self openname mode def saveself name content maxlengthnone get the proper name for the file as it will actually be saved if name is none name content name if not hasattrcontent chunks content filecontent name name self getavailablenamename maxlengthmaxlength name self savename content ensure that the name returned from the storage system is still valid validatefilenamename allowrelativepathtrue return name these methods are part of the public api with default implementations def getvalidnameself name return getvalidfilenamename def getalternativenameself fileroot fileext return sss fileroot getrandomstring7 fileext def getavailablenameself name maxlengthnone name strname replace dirname filename os path splitname if in pathlib purepathdirname parts raise suspiciousfileoperation detected path traversal attempt in s dirname validatefilenamefilename fileroot fileext os path splitextfilename if the filename already exists generate an alternative filename until it doesn t exist truncate original name if required so the new filename does not exceed the maxlength while self existsname or maxlength and lenname maxlength fileext includes the dot name os path join dirname self getalternativenamefileroot fileext if maxlength is none continue truncate fileroot if maxlength exceeded truncation lenname maxlength if truncation 0 fileroot fileroot truncation entire fileroot was truncated in attempt to find an available filename if not fileroot raise suspiciousfileoperation storage can not find an available filename for s please make sure that the corresponding file field allows sufficient maxlength name name os path join dirname self getalternativenamefileroot fileext return name def generatefilenameself filename filename strfilename replace filename may include a path as returned by filefield uploadto dirname filename os path splitfilename if in pathlib purepathdirname parts raise suspiciousfileoperation detected path traversal attempt in s dirname return os path normpathos path joindirname self getvalidnamefilename def pathself name raise notimplementederrorthis backend doesn t support absolute paths the following methods form the public api for storage systems but with no default implementations subclasses must implement all of these def deleteself name raise notimplementederror subclasses of storage must provide a delete method def existsself name raise notimplementederror subclasses of storage must provide an exists method def listdirself path raise notimplementederror subclasses of storage must provide a listdir method def sizeself name raise notimplementederrorsubclasses of storage must provide a size method def urlself name raise notimplementederrorsubclasses of storage must provide a url method def getaccessedtimeself name raise notimplementederror subclasses of storage must provide a getaccessedtime method def getcreatedtimeself name raise notimplementederror subclasses of storage must provide a getcreatedtime method def getmodifiedtimeself name raise notimplementederror subclasses of storage must provide a getmodifiedtime method a base storage class providing some default behaviors that all other storage systems can inherit or override as necessary the following methods represent a public interface to private methods these shouldn t be overridden by subclasses unless absolutely necessary retrieve the specified file from storage save new content to the file specified by name the content should be a proper file object or any python file like object ready to be read from the beginning get the proper name for the file as it will actually be saved ensure that the name returned from the storage system is still valid these methods are part of the public api with default implementations return a filename based on the provided filename that s suitable for use in the target storage system return an alternative filename by adding an underscore and a random 7 character alphanumeric string before the file extension if one exists to the filename return a filename that s free on the target storage system and available for new content to be written to if the filename already exists generate an alternative filename until it doesn t exist truncate original name if required so the new filename does not exceed the max_length file_ext includes the dot truncate file_root if max_length exceeded entire file_root was truncated in attempt to find an available filename validate the filename by calling get_valid_name and return a filename to be passed to the save method filename may include a path as returned by filefield upload_to return a local filesystem path where the file can be retrieved using python s built in open function storage systems that can t be accessed using open should not implement this method the following methods form the public api for storage systems but with no default implementations subclasses must implement all of these delete the specified file from the storage system return true if a file referenced by the given name already exists in the storage system or false if the name is available for a new file list the contents of the specified path return a 2 tuple of lists the first item being directories the second item being files return the total size in bytes of the file specified by name return an absolute url where the file s contents can be accessed directly by a web browser return the last accessed time as a datetime of the file specified by name the datetime will be timezone aware if use_tz true return the creation time as a datetime of the file specified by name the datetime will be timezone aware if use_tz true return the last modified time as a datetime of the file specified by name the datetime will be timezone aware if use_tz true
import os
import pathlib

from django.core.exceptions import SuspiciousFileOperation
from django.core.files import File
from django.core.files.utils import validate_file_name
from django.utils.crypto import get_random_string
from django.utils.text import get_valid_filename


class Storage:
    

    
    

    def open(self, name, mode="rb"):
        
        return self._open(name, mode)

    def save(self, name, content, max_length=None):
        
        
        if name is None:
            name = content.name

        if not hasattr(content, "chunks"):
            content = File(content, name)

        name = self.get_available_name(name, max_length=max_length)
        name = self._save(name, content)
        
        validate_file_name(name, allow_relative_path=True)
        return name

    

    def get_valid_name(self, name):
        
        return get_valid_filename(name)

    def get_alternative_name(self, file_root, file_ext):
        
        return "%s_%s%s" % (file_root, get_random_string(7), file_ext)

    def get_available_name(self, name, max_length=None):
        
        name = str(name).replace("\\", "/")
        dir_name, file_name = os.path.split(name)
        if ".." in pathlib.PurePath(dir_name).parts:
            raise SuspiciousFileOperation(
                "Detected path traversal attempt in '%s'" % dir_name
            )
        validate_file_name(file_name)
        file_root, file_ext = os.path.splitext(file_name)
        
        
        
        
        while self.exists(name) or (max_length and len(name) > max_length):
            
            name = os.path.join(
                dir_name, self.get_alternative_name(file_root, file_ext)
            )
            if max_length is None:
                continue
            
            truncation = len(name) - max_length
            if truncation > 0:
                file_root = file_root[:-truncation]
                
                
                if not file_root:
                    raise SuspiciousFileOperation(
                        'Storage can not find an available filename for "%s". '
                        "Please make sure that the corresponding file field "
                        'allows sufficient "max_length".' % name
                    )
                name = os.path.join(
                    dir_name, self.get_alternative_name(file_root, file_ext)
                )
        return name

    def generate_filename(self, filename):
        
        filename = str(filename).replace("\\", "/")
        
        dirname, filename = os.path.split(filename)
        if ".." in pathlib.PurePath(dirname).parts:
            raise SuspiciousFileOperation(
                "Detected path traversal attempt in '%s'" % dirname
            )
        return os.path.normpath(os.path.join(dirname, self.get_valid_name(filename)))

    def path(self, name):
        
        raise NotImplementedError("This backend doesn't support absolute paths.")

    
    

    def delete(self, name):
        
        raise NotImplementedError(
            "subclasses of Storage must provide a delete() method"
        )

    def exists(self, name):
        
        raise NotImplementedError(
            "subclasses of Storage must provide an exists() method"
        )

    def listdir(self, path):
        
        raise NotImplementedError(
            "subclasses of Storage must provide a listdir() method"
        )

    def size(self, name):
        
        raise NotImplementedError("subclasses of Storage must provide a size() method")

    def url(self, name):
        
        raise NotImplementedError("subclasses of Storage must provide a url() method")

    def get_accessed_time(self, name):
        
        raise NotImplementedError(
            "subclasses of Storage must provide a get_accessed_time() method"
        )

    def get_created_time(self, name):
        
        raise NotImplementedError(
            "subclasses of Storage must provide a get_created_time() method"
        )

    def get_modified_time(self, name):
        
        raise NotImplementedError(
            "subclasses of Storage must provide a get_modified_time() method"
        )