You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

storage.py 19KB

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