Debian Codegraph @

django_downloadview/views/path.py

raw
1 """:class:`PathDownloadView`."""
2
3 import os
4
5 from django.core.files import File
6
7 from django_downloadview.exceptions import FileNotFound
8 from django_downloadview.views.base import BaseDownloadView
9
10
11 class PathDownloadView(BaseDownloadView):
12 """Serve a file using filename."""
13
14 #: Server-side name (including path) of the file to serve.
15 #:
16 #: Filename is supposed to be an absolute filename of a file located on the
17 #: local filesystem.
18 path = None
19
20 #: Name of the URL argument that contains path.
21 path_url_kwarg = "path"
22
23 def get_path(self):
24 """Return actual path of the file to serve.
25
26 Default implementation simply returns view's :py:attr:`path`.
27
28 Override this method if you want custom implementation.
29 As an example, :py:attr:`path` could be relative and your custom
30 :py:meth:`get_path` implementation makes it absolute.
31
32 """
33 return self.kwargs.get(self.path_url_kwarg, self.path)
34
35 def get_file(self):
36 """Use path to return wrapper around file to serve."""
37 filename = self.get_path()
38 if not os.path.isfile(filename):
39 raise FileNotFound(f'File "{filename}" does not exists')
40 return File(open(filename, "rb"))