Hide keyboard shortcuts

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. 

3 

4See https://docs.djangoproject.com/en/stable/topics/files/#file-storage 

5 

6Usage 

7----- 

8 

9Specify the backend for the AJAX upload: 

10 

11.. code-block:: python 

12 

13 # views.py 

14 from superdjango.ajax.views import AjaxFileUploader 

15 from superdjango.storage.backends.ajax.default import DefaultAjaxStorage 

16 

17 ajax_uploader = AjaxFileUploader(DefaultAjaxStorage) 

18 

19""" 

20 

21# Imports 

22 

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 

29 

30# Exports 

31 

32__all__ = ( 

33 "DefaultAjaxStorage", 

34) 

35 

36# Constants 

37 

38UPLOAD_DIR = getattr(settings, "SUPERDJANGO_UPLOAD_DIR", "uploads") 

39 

40# Classes 

41 

42 

43class DefaultAjaxStorage(BaseAjaxStorage): 

44 """Use the storage defined by Django's ``DEFAULT_FILE_STORAGE`` setting. 

45 

46 See https://docs.djangoproject.com/en/stable/topics/files/#file-storage 

47 

48 """ 

49 

50 def __init__(self, **kwargs): 

51 super().__init__(**kwargs) 

52 

53 self._dest = None 

54 self._path = None 

55 

56 def setup(self, filename, *args, **kwargs): 

57 # join UPLOAD_DIR with filename. 

58 new_path = os.path.join(self._get_upload_dir(), filename) 

59 

60 # save empty file in default storage with path = new_path 

61 self.path = default_storage.save(new_path, ContentFile('')) 

62 

63 # create BufferedWriter for new file 

64 self._dest = default_storage.open(self.path, mode='wb') 

65 

66 def upload_chunk(self, chunk, *args, **kwargs): 

67 self._dest.write(chunk) 

68 

69 def upload_complete(self, request, filename, *args, **kwargs): 

70 self._dest.close() 

71 return {"path": self.path} 

72 

73 def _get_upload_dir(self): 

74 if callable(UPLOAD_DIR): 

75 return UPLOAD_DIR() 

76 

77 return datetime.datetime.now().strftime(UPLOAD_DIR)