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"""
2Use the storage defined by Django's ``DEFAULT_FILE_STORAGE`` setting.
4See https://docs.djangoproject.com/en/stable/topics/files/#file-storage
6Usage
7-----
9Specify the backend for the AJAX upload:
11.. code-block:: python
13 # views.py
14 from superdjango.ajax.views import AjaxFileUploader
15 from superdjango.storage.backends.ajax.default import DefaultAjaxStorage
17 ajax_uploader = AjaxFileUploader(DefaultAjaxStorage)
19"""
21# Imports
23import datetime
24from django.conf import settings
25from django.core.files.storage import default_storage
26from django.core.files.base import ContentFile
27import os
28from .base import BaseAjaxStorage
30# Exports
32__all__ = (
33 "DefaultAjaxStorage",
34)
36# Constants
38UPLOAD_DIR = getattr(settings, "SUPERDJANGO_UPLOAD_DIR", "uploads")
40# Classes
43class DefaultAjaxStorage(BaseAjaxStorage):
44 """Use the storage defined by Django's ``DEFAULT_FILE_STORAGE`` setting.
46 See https://docs.djangoproject.com/en/stable/topics/files/#file-storage
48 """
50 def __init__(self, **kwargs):
51 super().__init__(**kwargs)
53 self._dest = None
54 self._path = None
56 def setup(self, filename, *args, **kwargs):
57 # join UPLOAD_DIR with filename.
58 new_path = os.path.join(self._get_upload_dir(), filename)
60 # save empty file in default storage with path = new_path
61 self.path = default_storage.save(new_path, ContentFile(''))
63 # create BufferedWriter for new file
64 self._dest = default_storage.open(self.path, mode='wb')
66 def upload_chunk(self, chunk, *args, **kwargs):
67 self._dest.write(chunk)
69 def upload_complete(self, request, filename, *args, **kwargs):
70 self._dest.close()
71 return {"path": self.path}
73 def _get_upload_dir(self):
74 if callable(UPLOAD_DIR):
75 return UPLOAD_DIR()
77 return datetime.datetime.now().strftime(UPLOAD_DIR)