Development of an internal social media platform with personalised dashboards for students
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

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