Hot-keys on this page
r m x p toggle line displays
j k next/prev highlighted chunk
0 (zero) top of page
1 (one) first highlighted chunk
1# Imports
3from django.conf import settings
4from io import FileIO, BufferedWriter
5import os
6from superdjango.storage.utils import get_unique_file_name
7from .base import BaseAjaxStorage
9# Exports
11__all__ = (
12 "LocalAjaxStorage",
13 "OverwriteLocalAjaxStorage",
14)
16# Constants
18UPLOAD_DIR = getattr(settings, "SUPERDJANGO_UPLOAD_DIR", "uploads")
20# Classes
23class LocalAjaxStorage(BaseAjaxStorage):
24 """Store files uploaded via AJAX to the local file system."""
26 def __init__(self, **kwargs):
27 super().__init__(**kwargs)
29 self._dest = None
30 self._path = None
32 def setup(self, filename, *args, **kwargs):
33 self._path = os.path.join(settings.MEDIA_ROOT, UPLOAD_DIR, filename)
34 try:
35 os.makedirs(os.path.realpath(os.path.dirname(self._path)))
36 except (FileExistsError, OSError):
37 pass
39 self._dest = BufferedWriter(FileIO(self._path, "w"))
41 def upload_chunk(self, chunk, *args, **kwargs):
42 self._dest.write(chunk)
44 def upload_complete(self, request, filename, *args, **kwargs):
45 path = settings.MEDIA_URL + UPLOAD_DIR + "/" + filename
46 self._dest.close()
47 return {"path": path}
49 def update_filename(self, request, filename, *args, **kwargs):
50 """Get the name of the file being uploaded, ensuring that the file does not exist. If a file of the same name
51 *does* exist, create a new file name to prevent overwriting.
53 :rtype: str
54 :returns: The name of the file.
56 """
57 return get_unique_file_name(filename)
59 @property
60 def path(self):
61 """
62 Return a path of file uploaded
63 """
64 return self._path
67class OverwriteLocalAjaxStorage(LocalAjaxStorage):
68 """Extends the local storage to simply overwrite files that already exist."""
70 def update_filename(self, request, filename, *args, **kwargs):
71 """Return the file name as is."""
72 return filename