storage.py 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543
  1. import json
  2. import os
  3. import posixpath
  4. import re
  5. from hashlib import md5
  6. from urllib.parse import unquote, urldefrag, urlsplit, urlunsplit
  7. from django.conf import STATICFILES_STORAGE_ALIAS, settings
  8. from django.contrib.staticfiles.utils import check_settings, matches_patterns
  9. from django.core.exceptions import ImproperlyConfigured
  10. from django.core.files.base import ContentFile
  11. from django.core.files.storage import FileSystemStorage, storages
  12. from django.utils.functional import LazyObject
  13. class StaticFilesStorage(FileSystemStorage):
  14. """
  15. Standard file system storage for static files.
  16. The defaults for ``location`` and ``base_url`` are
  17. ``STATIC_ROOT`` and ``STATIC_URL``.
  18. """
  19. def __init__(self, location=None, base_url=None, *args, **kwargs):
  20. if location is None:
  21. location = settings.STATIC_ROOT
  22. if base_url is None:
  23. base_url = settings.STATIC_URL
  24. check_settings(base_url)
  25. super().__init__(location, base_url, *args, **kwargs)
  26. # FileSystemStorage fallbacks to MEDIA_ROOT when location
  27. # is empty, so we restore the empty value.
  28. if not location:
  29. self.base_location = None
  30. self.location = None
  31. def path(self, name):
  32. if not self.location:
  33. raise ImproperlyConfigured(
  34. "You're using the staticfiles app "
  35. "without having set the STATIC_ROOT "
  36. "setting to a filesystem path."
  37. )
  38. return super().path(name)
  39. class HashedFilesMixin:
  40. default_template = """url("%(url)s")"""
  41. max_post_process_passes = 5
  42. support_js_module_import_aggregation = False
  43. _js_module_import_aggregation_patterns = (
  44. "*.js",
  45. (
  46. (
  47. (
  48. r"""(?P<matched>import(?s:(?P<import>[\s\{].*?))"""
  49. r"""\s*from\s*['"](?P<url>[\.\/].*?)["']\s*;)"""
  50. ),
  51. """import%(import)s from "%(url)s";""",
  52. ),
  53. (
  54. (
  55. r"""(?P<matched>export(?s:(?P<exports>[\s\{].*?))"""
  56. r"""\s*from\s*["'](?P<url>[\.\/].*?)["']\s*;)"""
  57. ),
  58. """export%(exports)s from "%(url)s";""",
  59. ),
  60. (
  61. r"""(?P<matched>import\s*['"](?P<url>[\.\/].*?)["']\s*;)""",
  62. """import"%(url)s";""",
  63. ),
  64. (
  65. r"""(?P<matched>import\(["'](?P<url>.*?)["']\))""",
  66. """import("%(url)s")""",
  67. ),
  68. ),
  69. )
  70. patterns = (
  71. (
  72. "*.css",
  73. (
  74. r"""(?P<matched>url\(['"]{0,1}\s*(?P<url>.*?)["']{0,1}\))""",
  75. (
  76. r"""(?P<matched>@import\s*["']\s*(?P<url>.*?)["'])""",
  77. """@import url("%(url)s")""",
  78. ),
  79. (
  80. (
  81. r"(?m)^(?P<matched>/\*#[ \t]"
  82. r"(?-i:sourceMappingURL)=(?P<url>.*)[ \t]*\*/)$"
  83. ),
  84. "/*# sourceMappingURL=%(url)s */",
  85. ),
  86. ),
  87. ),
  88. (
  89. "*.js",
  90. (
  91. (
  92. r"(?m)^(?P<matched>//# (?-i:sourceMappingURL)=(?P<url>.*))$",
  93. "//# sourceMappingURL=%(url)s",
  94. ),
  95. ),
  96. ),
  97. )
  98. keep_intermediate_files = True
  99. def __init__(self, *args, **kwargs):
  100. if self.support_js_module_import_aggregation:
  101. self.patterns += (self._js_module_import_aggregation_patterns,)
  102. super().__init__(*args, **kwargs)
  103. self._patterns = {}
  104. self.hashed_files = {}
  105. for extension, patterns in self.patterns:
  106. for pattern in patterns:
  107. if isinstance(pattern, (tuple, list)):
  108. pattern, template = pattern
  109. else:
  110. template = self.default_template
  111. compiled = re.compile(pattern, re.IGNORECASE)
  112. self._patterns.setdefault(extension, []).append((compiled, template))
  113. def file_hash(self, name, content=None):
  114. """
  115. Return a hash of the file with the given name and optional content.
  116. """
  117. if content is None:
  118. return None
  119. hasher = md5(usedforsecurity=False)
  120. for chunk in content.chunks():
  121. hasher.update(chunk)
  122. return hasher.hexdigest()[:12]
  123. def hashed_name(self, name, content=None, filename=None):
  124. # `filename` is the name of file to hash if `content` isn't given.
  125. # `name` is the base name to construct the new hashed filename from.
  126. parsed_name = urlsplit(unquote(name))
  127. clean_name = parsed_name.path.strip()
  128. filename = (filename and urlsplit(unquote(filename)).path.strip()) or clean_name
  129. opened = content is None
  130. if opened:
  131. if not self.exists(filename):
  132. raise ValueError(
  133. "The file '%s' could not be found with %r." % (filename, self)
  134. )
  135. try:
  136. content = self.open(filename)
  137. except OSError:
  138. # Handle directory paths and fragments
  139. return name
  140. try:
  141. file_hash = self.file_hash(clean_name, content)
  142. finally:
  143. if opened:
  144. content.close()
  145. path, filename = os.path.split(clean_name)
  146. root, ext = os.path.splitext(filename)
  147. file_hash = (".%s" % file_hash) if file_hash else ""
  148. hashed_name = os.path.join(path, "%s%s%s" % (root, file_hash, ext))
  149. unparsed_name = list(parsed_name)
  150. unparsed_name[2] = hashed_name
  151. # Special casing for a @font-face hack, like url(myfont.eot?#iefix")
  152. # http://www.fontspring.com/blog/the-new-bulletproof-font-face-syntax
  153. if "?#" in name and not unparsed_name[3]:
  154. unparsed_name[2] += "?"
  155. return urlunsplit(unparsed_name)
  156. def _url(self, hashed_name_func, name, force=False, hashed_files=None):
  157. """
  158. Return the non-hashed URL in DEBUG mode.
  159. """
  160. if settings.DEBUG and not force:
  161. hashed_name, fragment = name, ""
  162. else:
  163. clean_name, fragment = urldefrag(name)
  164. if urlsplit(clean_name).path.endswith("/"): # don't hash paths
  165. hashed_name = name
  166. else:
  167. args = (clean_name,)
  168. if hashed_files is not None:
  169. args += (hashed_files,)
  170. hashed_name = hashed_name_func(*args)
  171. final_url = super().url(hashed_name)
  172. # Special casing for a @font-face hack, like url(myfont.eot?#iefix")
  173. # http://www.fontspring.com/blog/the-new-bulletproof-font-face-syntax
  174. query_fragment = "?#" in name # [sic!]
  175. if fragment or query_fragment:
  176. urlparts = list(urlsplit(final_url))
  177. if fragment and not urlparts[4]:
  178. urlparts[4] = fragment
  179. if query_fragment and not urlparts[3]:
  180. urlparts[2] += "?"
  181. final_url = urlunsplit(urlparts)
  182. return unquote(final_url)
  183. def url(self, name, force=False):
  184. """
  185. Return the non-hashed URL in DEBUG mode.
  186. """
  187. return self._url(self.stored_name, name, force)
  188. def url_converter(self, name, hashed_files, template=None):
  189. """
  190. Return the custom URL converter for the given file name.
  191. """
  192. if template is None:
  193. template = self.default_template
  194. def converter(matchobj):
  195. """
  196. Convert the matched URL to a normalized and hashed URL.
  197. This requires figuring out which files the matched URL resolves
  198. to and calling the url() method of the storage.
  199. """
  200. matches = matchobj.groupdict()
  201. matched = matches["matched"]
  202. url = matches["url"]
  203. # Ignore absolute/protocol-relative and data-uri URLs.
  204. if re.match(r"^[a-z]+:", url):
  205. return matched
  206. # Ignore absolute URLs that don't point to a static file (dynamic
  207. # CSS / JS?). Note that STATIC_URL cannot be empty.
  208. if url.startswith("/") and not url.startswith(settings.STATIC_URL):
  209. return matched
  210. # Strip off the fragment so a path-like fragment won't interfere.
  211. url_path, fragment = urldefrag(url)
  212. # Ignore URLs without a path
  213. if not url_path:
  214. return matched
  215. if url_path.startswith("/"):
  216. # Otherwise the condition above would have returned prematurely.
  217. assert url_path.startswith(settings.STATIC_URL)
  218. target_name = url_path.removeprefix(settings.STATIC_URL)
  219. else:
  220. # We're using the posixpath module to mix paths and URLs conveniently.
  221. source_name = name if os.sep == "/" else name.replace(os.sep, "/")
  222. target_name = posixpath.join(posixpath.dirname(source_name), url_path)
  223. # Determine the hashed name of the target file with the storage backend.
  224. hashed_url = self._url(
  225. self._stored_name,
  226. unquote(target_name),
  227. force=True,
  228. hashed_files=hashed_files,
  229. )
  230. transformed_url = "/".join(
  231. url_path.split("/")[:-1] + hashed_url.split("/")[-1:]
  232. )
  233. # Restore the fragment that was stripped off earlier.
  234. if fragment:
  235. transformed_url += ("?#" if "?#" in url else "#") + fragment
  236. # Return the hashed version to the file
  237. matches["url"] = unquote(transformed_url)
  238. return template % matches
  239. return converter
  240. def post_process(self, paths, dry_run=False, **options):
  241. """
  242. Post process the given dictionary of files (called from collectstatic).
  243. Processing is actually two separate operations:
  244. 1. renaming files to include a hash of their content for cache-busting,
  245. and copying those files to the target storage.
  246. 2. adjusting files which contain references to other files so they
  247. refer to the cache-busting filenames.
  248. If either of these are performed on a file, then that file is considered
  249. post-processed.
  250. """
  251. # don't even dare to process the files if we're in dry run mode
  252. if dry_run:
  253. return
  254. # where to store the new paths
  255. hashed_files = {}
  256. # build a list of adjustable files
  257. adjustable_paths = [
  258. path for path in paths if matches_patterns(path, self._patterns)
  259. ]
  260. # Adjustable files to yield at end, keyed by the original path.
  261. processed_adjustable_paths = {}
  262. # Do a single pass first. Post-process all files once, yielding not
  263. # adjustable files and exceptions, and collecting adjustable files.
  264. for name, hashed_name, processed, _ in self._post_process(
  265. paths, adjustable_paths, hashed_files
  266. ):
  267. if name not in adjustable_paths or isinstance(processed, Exception):
  268. yield name, hashed_name, processed
  269. else:
  270. processed_adjustable_paths[name] = (name, hashed_name, processed)
  271. paths = {path: paths[path] for path in adjustable_paths}
  272. substitutions = False
  273. for i in range(self.max_post_process_passes):
  274. substitutions = False
  275. for name, hashed_name, processed, subst in self._post_process(
  276. paths, adjustable_paths, hashed_files
  277. ):
  278. # Overwrite since hashed_name may be newer.
  279. processed_adjustable_paths[name] = (name, hashed_name, processed)
  280. substitutions = substitutions or subst
  281. if not substitutions:
  282. break
  283. if substitutions:
  284. yield "All", None, RuntimeError("Max post-process passes exceeded.")
  285. # Store the processed paths
  286. self.hashed_files.update(hashed_files)
  287. # Yield adjustable files with final, hashed name.
  288. yield from processed_adjustable_paths.values()
  289. def _post_process(self, paths, adjustable_paths, hashed_files):
  290. # Sort the files by directory level
  291. def path_level(name):
  292. return len(name.split(os.sep))
  293. for name in sorted(paths, key=path_level, reverse=True):
  294. substitutions = True
  295. # use the original, local file, not the copied-but-unprocessed
  296. # file, which might be somewhere far away, like S3
  297. storage, path = paths[name]
  298. with storage.open(path) as original_file:
  299. cleaned_name = self.clean_name(name)
  300. hash_key = self.hash_key(cleaned_name)
  301. # generate the hash with the original content, even for
  302. # adjustable files.
  303. if hash_key not in hashed_files:
  304. hashed_name = self.hashed_name(name, original_file)
  305. else:
  306. hashed_name = hashed_files[hash_key]
  307. # then get the original's file content..
  308. if hasattr(original_file, "seek"):
  309. original_file.seek(0)
  310. hashed_file_exists = self.exists(hashed_name)
  311. processed = False
  312. # ..to apply each replacement pattern to the content
  313. if name in adjustable_paths:
  314. old_hashed_name = hashed_name
  315. try:
  316. content = original_file.read().decode("utf-8")
  317. except UnicodeDecodeError as exc:
  318. yield name, None, exc, False
  319. for extension, patterns in self._patterns.items():
  320. if matches_patterns(path, (extension,)):
  321. for pattern, template in patterns:
  322. converter = self.url_converter(
  323. name, hashed_files, template
  324. )
  325. try:
  326. content = pattern.sub(converter, content)
  327. except ValueError as exc:
  328. yield name, None, exc, False
  329. if hashed_file_exists:
  330. self.delete(hashed_name)
  331. # then save the processed result
  332. content_file = ContentFile(content.encode())
  333. if self.keep_intermediate_files:
  334. # Save intermediate file for reference
  335. self._save(hashed_name, content_file)
  336. hashed_name = self.hashed_name(name, content_file)
  337. if self.exists(hashed_name):
  338. self.delete(hashed_name)
  339. saved_name = self._save(hashed_name, content_file)
  340. hashed_name = self.clean_name(saved_name)
  341. # If the file hash stayed the same, this file didn't change
  342. if old_hashed_name == hashed_name:
  343. substitutions = False
  344. processed = True
  345. if not processed:
  346. # or handle the case in which neither processing nor
  347. # a change to the original file happened
  348. if not hashed_file_exists:
  349. processed = True
  350. saved_name = self._save(hashed_name, original_file)
  351. hashed_name = self.clean_name(saved_name)
  352. # and then set the cache accordingly
  353. hashed_files[hash_key] = hashed_name
  354. yield name, hashed_name, processed, substitutions
  355. def clean_name(self, name):
  356. return name.replace("\\", "/")
  357. def hash_key(self, name):
  358. return name
  359. def _stored_name(self, name, hashed_files):
  360. # Normalize the path to avoid multiple names for the same file like
  361. # ../foo/bar.css and ../foo/../foo/bar.css which normalize to the same
  362. # path.
  363. name = posixpath.normpath(name)
  364. cleaned_name = self.clean_name(name)
  365. hash_key = self.hash_key(cleaned_name)
  366. cache_name = hashed_files.get(hash_key)
  367. if cache_name is None:
  368. cache_name = self.clean_name(self.hashed_name(name))
  369. return cache_name
  370. def stored_name(self, name):
  371. cleaned_name = self.clean_name(name)
  372. hash_key = self.hash_key(cleaned_name)
  373. cache_name = self.hashed_files.get(hash_key)
  374. if cache_name:
  375. return cache_name
  376. # No cached name found, recalculate it from the files.
  377. intermediate_name = name
  378. for i in range(self.max_post_process_passes + 1):
  379. cache_name = self.clean_name(
  380. self.hashed_name(name, content=None, filename=intermediate_name)
  381. )
  382. if intermediate_name == cache_name:
  383. # Store the hashed name if there was a miss.
  384. self.hashed_files[hash_key] = cache_name
  385. return cache_name
  386. else:
  387. # Move on to the next intermediate file.
  388. intermediate_name = cache_name
  389. # If the cache name can't be determined after the max number of passes,
  390. # the intermediate files on disk may be corrupt; avoid an infinite loop.
  391. raise ValueError("The name '%s' could not be hashed with %r." % (name, self))
  392. class ManifestFilesMixin(HashedFilesMixin):
  393. manifest_version = "1.1" # the manifest format standard
  394. manifest_name = "staticfiles.json"
  395. manifest_strict = True
  396. keep_intermediate_files = False
  397. def __init__(self, *args, manifest_storage=None, **kwargs):
  398. super().__init__(*args, **kwargs)
  399. if manifest_storage is None:
  400. manifest_storage = self
  401. self.manifest_storage = manifest_storage
  402. self.hashed_files, self.manifest_hash = self.load_manifest()
  403. def read_manifest(self):
  404. try:
  405. with self.manifest_storage.open(self.manifest_name) as manifest:
  406. return manifest.read().decode()
  407. except FileNotFoundError:
  408. return None
  409. def load_manifest(self):
  410. content = self.read_manifest()
  411. if content is None:
  412. return {}, ""
  413. try:
  414. stored = json.loads(content)
  415. except json.JSONDecodeError:
  416. pass
  417. else:
  418. version = stored.get("version")
  419. if version in ("1.0", "1.1"):
  420. return stored.get("paths", {}), stored.get("hash", "")
  421. raise ValueError(
  422. "Couldn't load manifest '%s' (version %s)"
  423. % (self.manifest_name, self.manifest_version)
  424. )
  425. def post_process(self, *args, **kwargs):
  426. self.hashed_files = {}
  427. yield from super().post_process(*args, **kwargs)
  428. if not kwargs.get("dry_run"):
  429. self.save_manifest()
  430. def save_manifest(self):
  431. self.manifest_hash = self.file_hash(
  432. None, ContentFile(json.dumps(sorted(self.hashed_files.items())).encode())
  433. )
  434. payload = {
  435. "paths": self.hashed_files,
  436. "version": self.manifest_version,
  437. "hash": self.manifest_hash,
  438. }
  439. if self.manifest_storage.exists(self.manifest_name):
  440. self.manifest_storage.delete(self.manifest_name)
  441. contents = json.dumps(payload).encode()
  442. self.manifest_storage._save(self.manifest_name, ContentFile(contents))
  443. def stored_name(self, name):
  444. parsed_name = urlsplit(unquote(name))
  445. clean_name = parsed_name.path.strip()
  446. hash_key = self.hash_key(clean_name)
  447. cache_name = self.hashed_files.get(hash_key)
  448. if cache_name is None:
  449. if self.manifest_strict:
  450. raise ValueError(
  451. "Missing staticfiles manifest entry for '%s'" % clean_name
  452. )
  453. cache_name = self.clean_name(self.hashed_name(name))
  454. unparsed_name = list(parsed_name)
  455. unparsed_name[2] = cache_name
  456. # Special casing for a @font-face hack, like url(myfont.eot?#iefix")
  457. # http://www.fontspring.com/blog/the-new-bulletproof-font-face-syntax
  458. if "?#" in name and not unparsed_name[3]:
  459. unparsed_name[2] += "?"
  460. return urlunsplit(unparsed_name)
  461. class ManifestStaticFilesStorage(ManifestFilesMixin, StaticFilesStorage):
  462. """
  463. A static file system storage backend which also saves
  464. hashed copies of the files it saves.
  465. """
  466. pass
  467. class ConfiguredStorage(LazyObject):
  468. def _setup(self):
  469. self._wrapped = storages[STATICFILES_STORAGE_ALIAS]
  470. staticfiles_storage = ConfiguredStorage()