storage.py 17 KB

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