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.
 
 
 
 

278 lines
9.6 KiB

  1. import os
  2. from collections import OrderedDict
  3. from django.apps import apps
  4. from django.conf import settings
  5. from django.contrib.staticfiles import utils
  6. from django.core.exceptions import ImproperlyConfigured
  7. from django.core.files.storage import (
  8. FileSystemStorage, Storage, default_storage,
  9. )
  10. from django.utils import lru_cache, six
  11. from django.utils._os import safe_join
  12. from django.utils.functional import LazyObject, empty
  13. from django.utils.module_loading import import_string
  14. # To keep track on which directories the finder has searched the static files.
  15. searched_locations = []
  16. class BaseFinder(object):
  17. """
  18. A base file finder to be used for custom staticfiles finder classes.
  19. """
  20. def find(self, path, all=False):
  21. """
  22. Given a relative file path this ought to find an
  23. absolute file path.
  24. If the ``all`` parameter is ``False`` (default) only
  25. the first found file path will be returned; if set
  26. to ``True`` a list of all found files paths is returned.
  27. """
  28. raise NotImplementedError('subclasses of BaseFinder must provide a find() method')
  29. def list(self, ignore_patterns):
  30. """
  31. Given an optional list of paths to ignore, this should return
  32. a two item iterable consisting of the relative path and storage
  33. instance.
  34. """
  35. raise NotImplementedError('subclasses of BaseFinder must provide a list() method')
  36. class FileSystemFinder(BaseFinder):
  37. """
  38. A static files finder that uses the ``STATICFILES_DIRS`` setting
  39. to locate files.
  40. """
  41. def __init__(self, app_names=None, *args, **kwargs):
  42. # List of locations with static files
  43. self.locations = []
  44. # Maps dir paths to an appropriate storage instance
  45. self.storages = OrderedDict()
  46. if not isinstance(settings.STATICFILES_DIRS, (list, tuple)):
  47. raise ImproperlyConfigured(
  48. "Your STATICFILES_DIRS setting is not a tuple or list; "
  49. "perhaps you forgot a trailing comma?")
  50. for root in settings.STATICFILES_DIRS:
  51. if isinstance(root, (list, tuple)):
  52. prefix, root = root
  53. else:
  54. prefix = ''
  55. if settings.STATIC_ROOT and os.path.abspath(settings.STATIC_ROOT) == os.path.abspath(root):
  56. raise ImproperlyConfigured(
  57. "The STATICFILES_DIRS setting should "
  58. "not contain the STATIC_ROOT setting")
  59. if (prefix, root) not in self.locations:
  60. self.locations.append((prefix, root))
  61. for prefix, root in self.locations:
  62. filesystem_storage = FileSystemStorage(location=root)
  63. filesystem_storage.prefix = prefix
  64. self.storages[root] = filesystem_storage
  65. super(FileSystemFinder, self).__init__(*args, **kwargs)
  66. def find(self, path, all=False):
  67. """
  68. Looks for files in the extra locations
  69. as defined in ``STATICFILES_DIRS``.
  70. """
  71. matches = []
  72. for prefix, root in self.locations:
  73. if root not in searched_locations:
  74. searched_locations.append(root)
  75. matched_path = self.find_location(root, path, prefix)
  76. if matched_path:
  77. if not all:
  78. return matched_path
  79. matches.append(matched_path)
  80. return matches
  81. def find_location(self, root, path, prefix=None):
  82. """
  83. Finds a requested static file in a location, returning the found
  84. absolute path (or ``None`` if no match).
  85. """
  86. if prefix:
  87. prefix = '%s%s' % (prefix, os.sep)
  88. if not path.startswith(prefix):
  89. return None
  90. path = path[len(prefix):]
  91. path = safe_join(root, path)
  92. if os.path.exists(path):
  93. return path
  94. def list(self, ignore_patterns):
  95. """
  96. List all files in all locations.
  97. """
  98. for prefix, root in self.locations:
  99. storage = self.storages[root]
  100. for path in utils.get_files(storage, ignore_patterns):
  101. yield path, storage
  102. class AppDirectoriesFinder(BaseFinder):
  103. """
  104. A static files finder that looks in the directory of each app as
  105. specified in the source_dir attribute.
  106. """
  107. storage_class = FileSystemStorage
  108. source_dir = 'static'
  109. def __init__(self, app_names=None, *args, **kwargs):
  110. # The list of apps that are handled
  111. self.apps = []
  112. # Mapping of app names to storage instances
  113. self.storages = OrderedDict()
  114. app_configs = apps.get_app_configs()
  115. if app_names:
  116. app_names = set(app_names)
  117. app_configs = [ac for ac in app_configs if ac.name in app_names]
  118. for app_config in app_configs:
  119. app_storage = self.storage_class(
  120. os.path.join(app_config.path, self.source_dir))
  121. if os.path.isdir(app_storage.location):
  122. self.storages[app_config.name] = app_storage
  123. if app_config.name not in self.apps:
  124. self.apps.append(app_config.name)
  125. super(AppDirectoriesFinder, self).__init__(*args, **kwargs)
  126. def list(self, ignore_patterns):
  127. """
  128. List all files in all app storages.
  129. """
  130. for storage in six.itervalues(self.storages):
  131. if storage.exists(''): # check if storage location exists
  132. for path in utils.get_files(storage, ignore_patterns):
  133. yield path, storage
  134. def find(self, path, all=False):
  135. """
  136. Looks for files in the app directories.
  137. """
  138. matches = []
  139. for app in self.apps:
  140. app_location = self.storages[app].location
  141. if app_location not in searched_locations:
  142. searched_locations.append(app_location)
  143. match = self.find_in_app(app, path)
  144. if match:
  145. if not all:
  146. return match
  147. matches.append(match)
  148. return matches
  149. def find_in_app(self, app, path):
  150. """
  151. Find a requested static file in an app's static locations.
  152. """
  153. storage = self.storages.get(app)
  154. if storage:
  155. # only try to find a file if the source dir actually exists
  156. if storage.exists(path):
  157. matched_path = storage.path(path)
  158. if matched_path:
  159. return matched_path
  160. class BaseStorageFinder(BaseFinder):
  161. """
  162. A base static files finder to be used to extended
  163. with an own storage class.
  164. """
  165. storage = None
  166. def __init__(self, storage=None, *args, **kwargs):
  167. if storage is not None:
  168. self.storage = storage
  169. if self.storage is None:
  170. raise ImproperlyConfigured("The staticfiles storage finder %r "
  171. "doesn't have a storage class "
  172. "assigned." % self.__class__)
  173. # Make sure we have an storage instance here.
  174. if not isinstance(self.storage, (Storage, LazyObject)):
  175. self.storage = self.storage()
  176. super(BaseStorageFinder, self).__init__(*args, **kwargs)
  177. def find(self, path, all=False):
  178. """
  179. Looks for files in the default file storage, if it's local.
  180. """
  181. try:
  182. self.storage.path('')
  183. except NotImplementedError:
  184. pass
  185. else:
  186. if self.storage.location not in searched_locations:
  187. searched_locations.append(self.storage.location)
  188. if self.storage.exists(path):
  189. match = self.storage.path(path)
  190. if all:
  191. match = [match]
  192. return match
  193. return []
  194. def list(self, ignore_patterns):
  195. """
  196. List all files of the storage.
  197. """
  198. for path in utils.get_files(self.storage, ignore_patterns):
  199. yield path, self.storage
  200. class DefaultStorageFinder(BaseStorageFinder):
  201. """
  202. A static files finder that uses the default storage backend.
  203. """
  204. storage = default_storage
  205. def __init__(self, *args, **kwargs):
  206. super(DefaultStorageFinder, self).__init__(*args, **kwargs)
  207. base_location = getattr(self.storage, 'base_location', empty)
  208. if not base_location:
  209. raise ImproperlyConfigured("The storage backend of the "
  210. "staticfiles finder %r doesn't have "
  211. "a valid location." % self.__class__)
  212. def find(path, all=False):
  213. """
  214. Find a static file with the given path using all enabled finders.
  215. If ``all`` is ``False`` (default), return the first matching
  216. absolute path (or ``None`` if no match). Otherwise return a list.
  217. """
  218. searched_locations[:] = []
  219. matches = []
  220. for finder in get_finders():
  221. result = finder.find(path, all=all)
  222. if not all and result:
  223. return result
  224. if not isinstance(result, (list, tuple)):
  225. result = [result]
  226. matches.extend(result)
  227. if matches:
  228. return matches
  229. # No match.
  230. return [] if all else None
  231. def get_finders():
  232. for finder_path in settings.STATICFILES_FINDERS:
  233. yield get_finder(finder_path)
  234. @lru_cache.lru_cache(maxsize=None)
  235. def get_finder(import_path):
  236. """
  237. Imports the staticfiles finder class described by import_path, where
  238. import_path is the full Python path to the class.
  239. """
  240. Finder = import_string(import_path)
  241. if not issubclass(Finder, BaseFinder):
  242. raise ImproperlyConfigured('Finder "%s" is not a subclass of "%s"' %
  243. (Finder, BaseFinder))
  244. return Finder()