Funktionierender Prototyp des Serious Games zur Vermittlung von Wissen zu Software-Engineering-Arbeitsmodellen.
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.

finders.py 11KB

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