Debian Codegraph @

django_downloadview/response.py

raw
1 """:py:class:`django.http.HttpResponse` subclasses."""
2
3 import mimetypes
4 import os
5 import re
6 import unicodedata
7 from urllib.parse import quote
8
9 from django.conf import settings
10 from django.http import HttpResponse, StreamingHttpResponse
11 from django.utils.encoding import force_str
12
13
14 def encode_basename_ascii(value):
15 """Return US-ASCII encoded ``value`` for Content-Disposition header.
16
17 >>> print(encode_basename_ascii(u'éà'))
18 ea
19
20 Spaces are converted to underscores.
21
22 >>> print(encode_basename_ascii(' '))
23 _
24
25 Of course, ASCII values are not modified.
26
27 >>> print(encode_basename_ascii('ea'))
28 ea
29 >>> print(encode_basename_ascii(b'ea'))
30 ea
31
32 """
33 if isinstance(value, bytes):
34 value = value.decode("utf-8")
35 ascii_basename = str(value)
36 ascii_basename = unicodedata.normalize("NFKD", ascii_basename)
37 ascii_basename = ascii_basename.encode("ascii", "ignore")
38 ascii_basename = ascii_basename.decode("ascii")
39 ascii_basename = re.sub(r"[\s]", "_", ascii_basename)
40 return ascii_basename
41
42
43 def encode_basename_utf8(value):
44 """Return UTF-8 encoded ``value`` for use in Content-Disposition header.
45
46 >>> print(encode_basename_utf8(u' .txt'))
47 %20.txt
48
49 >>> print(encode_basename_utf8(u'éà'))
50 %C3%A9%C3%A0
51
52 """
53 return quote(force_str(value))
54
55
56 def content_disposition(filename):
57 """Return value of ``Content-Disposition`` header with 'attachment'.
58
59 >>> print(content_disposition('demo.txt'))
60 attachment; filename="demo.txt"
61
62 If filename is empty, only "attachment" is returned.
63
64 >>> print(content_disposition(''))
65 attachment
66
67 If filename contains non US-ASCII characters, the returned value contains
68 UTF-8 encoded filename and US-ASCII fallback.
69
70 >>> print(content_disposition(u'é.txt'))
71 attachment; filename="e.txt"; filename*=UTF-8''%C3%A9.txt
72
73 """
74 if not filename:
75 return "attachment"
76 # ASCII filenames are quoted and must ensure escape sequences
77 # in the filename won't break out of the quoted header value
78 # which can permit a reflected file download attack. The UTF-8
79 # version is immune because it's not quoted.
80 ascii_filename = (
81 encode_basename_ascii(filename).replace("\\", "\\\\").replace('"', r"\"")
82 )
83 utf8_filename = encode_basename_utf8(filename)
84 if ascii_filename == utf8_filename: # ASCII only.
85 return f'attachment; filename="{ascii_filename}"'
86 else:
87 return (
88 f'attachment; filename="{ascii_filename}"; '
89 f"filename*=UTF-8''{utf8_filename}"
90 )
91
92
93 class DownloadResponse(StreamingHttpResponse):
94 """File download response (Django serves file, client downloads it).
95
96 This is a specialization of :class:`django.http.StreamingHttpResponse`
97 where :attr:`~django.http.StreamingHttpResponse.streaming_content` is a
98 file wrapper.
99
100 Constructor differs a bit from :class:`~django.http.response.HttpResponse`.
101
102 Here are some highlights to understand internal mechanisms and motivations:
103
104 * Let's start by quoting :pep:`3333` (WSGI specification):
105
106 For large files, or for specialized uses of HTTP streaming,
107 applications will usually return an iterator (often a
108 generator-iterator) that produces the output in a block-by-block
109 fashion.
110
111 * Django WSGI handler (application implementation) returns response object
112 (see :mod:`django.core.handlers.wsgi`).
113
114 * :class:`django.http.HttpResponse` and subclasses are iterators.
115
116 * In :class:`~django.http.StreamingHttpResponse`, the
117 :meth:`~container.__iter__` implementation proxies to
118 :attr:`~django.http.StreamingHttpResponse.streaming_content`.
119
120 * In :class:`DownloadResponse` and subclasses, :attr:`streaming_content`
121 is a :doc:`file wrapper </files>`. File wrapper is itself an iterator
122 over actual file content, and it also encapsulates access to file
123 attributes (size, name, ...).
124
125 """
126
127 def __init__(
128 self,
129 file_instance,
130 attachment=True,
131 basename=None,
132 status=200,
133 content_type=None,
134 file_mimetype=None,
135 file_encoding=None,
136 ):
137 """Constructor.
138
139 :param content_type: Value for ``Content-Type`` header.
140 If ``None``, then mime-type and encoding will be
141 populated by the response (default implementation
142 uses :mod:`mimetypes`, based on file name).
143
144 """
145 #: A :doc:`file wrapper instance </files>`, such as
146 #: :class:`~django.core.files.base.File`.
147 self.file = file_instance
148 super().__init__(
149 streaming_content=self.file, status=status, content_type=content_type
150 )
151
152 #: Client-side name of the file to stream.
153 #: Only used if ``attachment`` is ``True``.
154 #: Affects ``Content-Disposition`` header.
155 self.basename = basename
156
157 #: Whether to return the file as attachment or not.
158 #: Affects ``Content-Disposition`` header.
159 self.attachment = attachment
160 if not content_type:
161 del self["Content-Type"] # Will be set later.
162
163 #: Value for file's mimetype.
164 #: If ``None`` (the default), then the file's mimetype will be guessed
165 #: via Python's :mod:`mimetypes`. See :meth:`get_mime_type`.
166 self.file_mimetype = file_mimetype
167
168 #: Value for file's encoding. If ``None`` (the default), then the
169 #: file's encoding will be guessed via Python's :mod:`mimetypes`. See
170 #: :meth:`get_encoding`.
171 self.file_encoding = file_encoding
172
173 # Apply default headers.
174 for header, value in self.default_headers.items():
175 if header not in self:
176 self[header] = value # Does self support setdefault?
177
178 @property
179 def default_headers(self):
180 """Return dictionary of automatically-computed headers.
181
182 Uses an internal ``_default_headers`` cache.
183 Default values are computed if only cache hasn't been set.
184
185 ``Content-Disposition`` header is encoded according to `RFC 5987
186 <http://tools.ietf.org/html/rfc5987>`_. See also
187 http://stackoverflow.com/questions/93551/.
188
189 """
190 try:
191 return self._default_headers
192 except AttributeError:
193 headers = {}
194 headers["Content-Type"] = self.get_content_type()
195 try:
196 headers["Content-Length"] = self.file.size
197 except (AttributeError, NotImplementedError):
198 pass # Generated files.
199 if self.attachment:
200 basename = self.get_basename()
201 headers["Content-Disposition"] = content_disposition(basename)
202 self._default_headers = headers
203 return self._default_headers
204
205 def get_basename(self):
206 """Return basename."""
207 if self.basename:
208 return self.basename
209 else:
210 return os.path.basename(self.file.name)
211
212 def get_content_type(self):
213 """Return a suitable "Content-Type" header for ``self.file``."""
214 try:
215 return self.file.content_type
216 except AttributeError:
217 return f"{self.get_mime_type()}; charset={self.get_charset()}"
218
219 def get_mime_type(self):
220 """Return mime-type of the file."""
221 if self.file_mimetype is not None:
222 return self.file_mimetype
223 default_mime_type = "application/octet-stream"
224 basename = self.get_basename()
225 mime_type, encoding = mimetypes.guess_type(basename)
226 return mime_type or default_mime_type
227
228 def get_encoding(self):
229 """Return encoding of the file to serve."""
230 if self.file_encoding is not None:
231 return self.file_encoding
232 basename = self.get_basename()
233 mime_type, encoding = mimetypes.guess_type(basename)
234 return encoding
235
236 def get_charset(self):
237 """Return the charset of the file to serve."""
238 return settings.DEFAULT_CHARSET
239
240
241 class ProxiedDownloadResponse(HttpResponse):
242 """Base class for internal redirect download responses.
243
244 This base class makes it possible to identify several types of specific
245 responses such as
246 :py:class:`~django_downloadview.nginx.response.XAccelRedirectResponse`.
247
248 """