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# Imports 

2 

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 

8 

9# Exports 

10 

11__all__ = ( 

12 "LocalAjaxStorage", 

13 "OverwriteLocalAjaxStorage", 

14) 

15 

16# Constants 

17 

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

19 

20# Classes 

21 

22 

23class LocalAjaxStorage(BaseAjaxStorage): 

24 """Store files uploaded via AJAX to the local file system.""" 

25 

26 def __init__(self, **kwargs): 

27 super().__init__(**kwargs) 

28 

29 self._dest = None 

30 self._path = None 

31 

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 

38 

39 self._dest = BufferedWriter(FileIO(self._path, "w")) 

40 

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

42 self._dest.write(chunk) 

43 

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} 

48 

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. 

52 

53 :rtype: str 

54 :returns: The name of the file. 

55 

56 """ 

57 return get_unique_file_name(filename) 

58 

59 @property 

60 def path(self): 

61 """ 

62 Return a path of file uploaded 

63 """ 

64 return self._path 

65 

66 

67class OverwriteLocalAjaxStorage(LocalAjaxStorage): 

68 """Extends the local storage to simply overwrite files that already exist.""" 

69 

70 def update_filename(self, request, filename, *args, **kwargs): 

71 """Return the file name as is.""" 

72 return filename