Skip to content

storage

A module that handle overriding files names.

Classes
  • OverwriteStorage: A class that handle overriding files names

OverwriteStorage

Bases: FileSystemStorage

Overrides the default storage system to allow overwriting of existing files.

This class inherits from Django's FileSystemStorage class and overrides the get_available_name method to check if a file with the same name already exists. If so, it deletes the old file before returning the name, allowing the new file to overwrite the old one.

Methods
  • get_available_name(name, max_length): A method to get file name and override it
Source code in backend/api/files/storage.py
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
class OverwriteStorage(FileSystemStorage):
    """Overrides the default storage system to allow overwriting of existing files.

    This class inherits from Django's FileSystemStorage class and overrides the `get_available_name`
    method to check if a file with the same name already exists. If so, it deletes the old file before
    returning the name, allowing the new file to overwrite the old one.

    Methods:
        - `get_available_name(name, max_length)`: A method to get file name and override it
    """

    def get_available_name(self, name: str, max_length: int = None) -> str:
        """Return a filename that's available for new content to be written to.

        If the file already exists, it is deleted to allow overwriting.

        Args:
            name: The desired filename.
            max_length: The maximum length of the filename. Defaults to None.

        Returns:
            The new filename that's available for use.
        """
        if self.exists(name):
            os.remove(os.path.join(settings.MEDIA_ROOT, name))
        return name

get_available_name(name, max_length=None)

Return a filename that's available for new content to be written to.

If the file already exists, it is deleted to allow overwriting.

Parameters:

Name Type Description Default
name str

The desired filename.

required
max_length int

The maximum length of the filename. Defaults to None.

None

Returns:

Type Description
str

The new filename that's available for use.

Source code in backend/api/files/storage.py
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
def get_available_name(self, name: str, max_length: int = None) -> str:
    """Return a filename that's available for new content to be written to.

    If the file already exists, it is deleted to allow overwriting.

    Args:
        name: The desired filename.
        max_length: The maximum length of the filename. Defaults to None.

    Returns:
        The new filename that's available for use.
    """
    if self.exists(name):
        os.remove(os.path.join(settings.MEDIA_ROOT, name))
    return name