Debian Codegraph @

src/whitenoise/middleware.py

raw
1 from __future__ import annotations
2
3 import os
4 from posixpath import basename
5 from urllib.parse import urlparse
6
7 from django.conf import settings
8 from django.contrib.staticfiles import finders
9 from django.contrib.staticfiles.storage import staticfiles_storage
10 from django.http import FileResponse
11
12 from whitenoise.base import WhiteNoise
13 from whitenoise.string_utils import ensure_leading_trailing_slash
14
15 __all__ = ["WhiteNoiseMiddleware"]
16
17
18 class WhiteNoiseFileResponse(FileResponse):
19 """
20 Wrap Django's FileResponse to prevent setting any default headers. For the
21 most part these just duplicate work already done by WhiteNoise but in some
22 cases (e.g. the content-disposition header introduced in Django 3.0) they
23 are actively harmful.
24 """
25
26 def set_headers(self, *args, **kwargs):
27 pass
28
29
30 class WhiteNoiseMiddleware(WhiteNoise):
31 """
32 Wrap WhiteNoise to allow it to function as Django middleware, rather
33 than WSGI middleware.
34 """
35
36 def __init__(self, get_response=None, settings=settings):
37 self.get_response = get_response
38
39 try:
40 autorefresh: bool = settings.WHITENOISE_AUTOREFRESH
41 except AttributeError:
42 autorefresh = settings.DEBUG
43 try:
44 max_age = settings.WHITENOISE_MAX_AGE
45 except AttributeError:
46 if settings.DEBUG:
47 max_age = 0
48 else:
49 max_age = 60
50 try:
51 allow_all_origins = settings.WHITENOISE_ALLOW_ALL_ORIGINS
52 except AttributeError:
53 allow_all_origins = True
54 try:
55 charset = settings.WHITENOISE_CHARSET
56 except AttributeError:
57 charset = "utf-8"
58 try:
59 mimetypes = settings.WHITENOISE_MIMETYPES
60 except AttributeError:
61 mimetypes = None
62 try:
63 add_headers_function = settings.WHITENOISE_ADD_HEADERS_FUNCTION
64 except AttributeError:
65 add_headers_function = None
66 try:
67 index_file = settings.WHITENOISE_INDEX_FILE
68 except AttributeError:
69 index_file = None
70 try:
71 immutable_file_test = settings.WHITENOISE_IMMUTABLE_FILE_TEST
72 except AttributeError:
73 immutable_file_test = None
74
75 super().__init__(
76 application=None,
77 autorefresh=autorefresh,
78 max_age=max_age,
79 allow_all_origins=allow_all_origins,
80 charset=charset,
81 mimetypes=mimetypes,
82 add_headers_function=add_headers_function,
83 index_file=index_file,
84 immutable_file_test=immutable_file_test,
85 )
86
87 try:
88 self.use_finders = settings.WHITENOISE_USE_FINDERS
89 except AttributeError:
90 self.use_finders = settings.DEBUG
91
92 try:
93 self.static_prefix = settings.WHITENOISE_STATIC_PREFIX
94 except AttributeError:
95 self.static_prefix = urlparse(settings.STATIC_URL or "").path
96 if settings.FORCE_SCRIPT_NAME:
97 script_name = settings.FORCE_SCRIPT_NAME.rstrip("/")
98 if self.static_prefix.startswith(script_name):
99 self.static_prefix = self.static_prefix[len(script_name) :]
100 self.static_prefix = ensure_leading_trailing_slash(self.static_prefix)
101
102 self.static_root = settings.STATIC_ROOT
103 if self.static_root:
104 self.add_files(self.static_root, prefix=self.static_prefix)
105
106 try:
107 root = settings.WHITENOISE_ROOT
108 except AttributeError:
109 root = None
110 if root:
111 self.add_files(root)
112
113 if self.use_finders and not self.autorefresh:
114 self.add_files_from_finders()
115
116 def __call__(self, request):
117 if self.autorefresh:
118 static_file = self.find_file(request.path_info)
119 else:
120 static_file = self.files.get(request.path_info)
121 if static_file is not None:
122 return self.serve(static_file, request)
123 return self.get_response(request)
124
125 @staticmethod
126 def serve(static_file, request):
127 response = static_file.get_response(request.method, request.META)
128 status = int(response.status)
129 http_response = WhiteNoiseFileResponse(response.file or (), status=status)
130 # Remove default content-type
131 del http_response["content-type"]
132 for key, value in response.headers:
133 http_response[key] = value
134 return http_response
135
136 def add_files_from_finders(self):
137 files = {}
138 for finder in finders.get_finders():
139 for path, storage in finder.list(None):
140 prefix = (getattr(storage, "prefix", None) or "").strip("/")
141 url = "".join(
142 (
143 self.static_prefix,
144 prefix,
145 "/" if prefix else "",
146 path.replace("\\", "/"),
147 )
148 )
149 # Use setdefault as only first matching file should be used
150 files.setdefault(url, storage.path(path))
151 stat_cache = {path: os.stat(path) for path in files.values()}
152 for url, path in files.items():
153 self.add_file_to_dictionary(url, path, stat_cache=stat_cache)
154
155 def candidate_paths_for_url(self, url):
156 if self.use_finders and url.startswith(self.static_prefix):
157 path = finders.find(url[len(self.static_prefix) :])
158 if path:
159 yield path
160 paths = super().candidate_paths_for_url(url)
161 for path in paths:
162 yield path
163
164 def immutable_file_test(self, path, url):
165 """
166 Determine whether given URL represents an immutable file (i.e. a
167 file with a hash of its contents as part of its name) which can
168 therefore be cached forever
169 """
170 if not url.startswith(self.static_prefix):
171 return False
172 name = url[len(self.static_prefix) :]
173 name_without_hash = self.get_name_without_hash(name)
174 if name == name_without_hash:
175 return False
176 static_url = self.get_static_url(name_without_hash)
177 # If the static_url function maps the name without hash
178 # back to the original name, then we know we've got a
179 # versioned filename
180 if static_url and basename(static_url) == basename(url):
181 return True
182 return False
183
184 def get_name_without_hash(self, filename):
185 """
186 Removes the version hash from a filename e.g, transforms
187 'css/application.f3ea4bcc2.css' into 'css/application.css'
188
189 Note: this is specific to the naming scheme used by Django's
190 CachedStaticFilesStorage. You may have to override this if
191 you are using a different static files versioning system
192 """
193 name_with_hash, ext = os.path.splitext(filename)
194 name = os.path.splitext(name_with_hash)[0]
195 return name + ext
196
197 def get_static_url(self, name):
198 try:
199 return staticfiles_storage.url(name)
200 except ValueError:
201 return None