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.

1 year ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498
  1. import inspect
  2. from importlib import import_module
  3. from inspect import cleandoc
  4. from pathlib import Path
  5. from django.apps import apps
  6. from django.contrib import admin
  7. from django.contrib.admin.views.decorators import staff_member_required
  8. from django.contrib.admindocs import utils
  9. from django.contrib.admindocs.utils import (
  10. remove_non_capturing_groups,
  11. replace_metacharacters,
  12. replace_named_groups,
  13. replace_unnamed_groups,
  14. )
  15. from django.core.exceptions import ImproperlyConfigured, ViewDoesNotExist
  16. from django.db import models
  17. from django.http import Http404
  18. from django.template.engine import Engine
  19. from django.urls import get_mod_func, get_resolver, get_urlconf
  20. from django.utils._os import safe_join
  21. from django.utils.decorators import method_decorator
  22. from django.utils.functional import cached_property
  23. from django.utils.inspect import (
  24. func_accepts_kwargs,
  25. func_accepts_var_args,
  26. get_func_full_args,
  27. method_has_no_args,
  28. )
  29. from django.utils.translation import gettext as _
  30. from django.views.generic import TemplateView
  31. from .utils import get_view_name
  32. # Exclude methods starting with these strings from documentation
  33. MODEL_METHODS_EXCLUDE = ("_", "add_", "delete", "save", "set_")
  34. class BaseAdminDocsView(TemplateView):
  35. """
  36. Base view for admindocs views.
  37. """
  38. @method_decorator(staff_member_required)
  39. def dispatch(self, request, *args, **kwargs):
  40. if not utils.docutils_is_available:
  41. # Display an error message for people without docutils
  42. self.template_name = "admin_doc/missing_docutils.html"
  43. return self.render_to_response(admin.site.each_context(request))
  44. return super().dispatch(request, *args, **kwargs)
  45. def get_context_data(self, **kwargs):
  46. return super().get_context_data(
  47. **{
  48. **kwargs,
  49. **admin.site.each_context(self.request),
  50. }
  51. )
  52. class BookmarkletsView(BaseAdminDocsView):
  53. template_name = "admin_doc/bookmarklets.html"
  54. class TemplateTagIndexView(BaseAdminDocsView):
  55. template_name = "admin_doc/template_tag_index.html"
  56. def get_context_data(self, **kwargs):
  57. tags = []
  58. try:
  59. engine = Engine.get_default()
  60. except ImproperlyConfigured:
  61. # Non-trivial TEMPLATES settings aren't supported (#24125).
  62. pass
  63. else:
  64. app_libs = sorted(engine.template_libraries.items())
  65. builtin_libs = [("", lib) for lib in engine.template_builtins]
  66. for module_name, library in builtin_libs + app_libs:
  67. for tag_name, tag_func in library.tags.items():
  68. title, body, metadata = utils.parse_docstring(tag_func.__doc__)
  69. title = title and utils.parse_rst(
  70. title, "tag", _("tag:") + tag_name
  71. )
  72. body = body and utils.parse_rst(body, "tag", _("tag:") + tag_name)
  73. for key in metadata:
  74. metadata[key] = utils.parse_rst(
  75. metadata[key], "tag", _("tag:") + tag_name
  76. )
  77. tag_library = module_name.split(".")[-1]
  78. tags.append(
  79. {
  80. "name": tag_name,
  81. "title": title,
  82. "body": body,
  83. "meta": metadata,
  84. "library": tag_library,
  85. }
  86. )
  87. return super().get_context_data(**{**kwargs, "tags": tags})
  88. class TemplateFilterIndexView(BaseAdminDocsView):
  89. template_name = "admin_doc/template_filter_index.html"
  90. def get_context_data(self, **kwargs):
  91. filters = []
  92. try:
  93. engine = Engine.get_default()
  94. except ImproperlyConfigured:
  95. # Non-trivial TEMPLATES settings aren't supported (#24125).
  96. pass
  97. else:
  98. app_libs = sorted(engine.template_libraries.items())
  99. builtin_libs = [("", lib) for lib in engine.template_builtins]
  100. for module_name, library in builtin_libs + app_libs:
  101. for filter_name, filter_func in library.filters.items():
  102. title, body, metadata = utils.parse_docstring(filter_func.__doc__)
  103. title = title and utils.parse_rst(
  104. title, "filter", _("filter:") + filter_name
  105. )
  106. body = body and utils.parse_rst(
  107. body, "filter", _("filter:") + filter_name
  108. )
  109. for key in metadata:
  110. metadata[key] = utils.parse_rst(
  111. metadata[key], "filter", _("filter:") + filter_name
  112. )
  113. tag_library = module_name.split(".")[-1]
  114. filters.append(
  115. {
  116. "name": filter_name,
  117. "title": title,
  118. "body": body,
  119. "meta": metadata,
  120. "library": tag_library,
  121. }
  122. )
  123. return super().get_context_data(**{**kwargs, "filters": filters})
  124. class ViewIndexView(BaseAdminDocsView):
  125. template_name = "admin_doc/view_index.html"
  126. def get_context_data(self, **kwargs):
  127. views = []
  128. url_resolver = get_resolver(get_urlconf())
  129. try:
  130. view_functions = extract_views_from_urlpatterns(url_resolver.url_patterns)
  131. except ImproperlyConfigured:
  132. view_functions = []
  133. for func, regex, namespace, name in view_functions:
  134. views.append(
  135. {
  136. "full_name": get_view_name(func),
  137. "url": simplify_regex(regex),
  138. "url_name": ":".join((namespace or []) + (name and [name] or [])),
  139. "namespace": ":".join(namespace or []),
  140. "name": name,
  141. }
  142. )
  143. return super().get_context_data(**{**kwargs, "views": views})
  144. class ViewDetailView(BaseAdminDocsView):
  145. template_name = "admin_doc/view_detail.html"
  146. @staticmethod
  147. def _get_view_func(view):
  148. urlconf = get_urlconf()
  149. if get_resolver(urlconf)._is_callback(view):
  150. mod, func = get_mod_func(view)
  151. try:
  152. # Separate the module and function, e.g.
  153. # 'mymodule.views.myview' -> 'mymodule.views', 'myview').
  154. return getattr(import_module(mod), func)
  155. except ImportError:
  156. # Import may fail because view contains a class name, e.g.
  157. # 'mymodule.views.ViewContainer.my_view', so mod takes the form
  158. # 'mymodule.views.ViewContainer'. Parse it again to separate
  159. # the module and class.
  160. mod, klass = get_mod_func(mod)
  161. return getattr(getattr(import_module(mod), klass), func)
  162. def get_context_data(self, **kwargs):
  163. view = self.kwargs["view"]
  164. view_func = self._get_view_func(view)
  165. if view_func is None:
  166. raise Http404
  167. title, body, metadata = utils.parse_docstring(view_func.__doc__)
  168. title = title and utils.parse_rst(title, "view", _("view:") + view)
  169. body = body and utils.parse_rst(body, "view", _("view:") + view)
  170. for key in metadata:
  171. metadata[key] = utils.parse_rst(metadata[key], "model", _("view:") + view)
  172. return super().get_context_data(
  173. **{
  174. **kwargs,
  175. "name": view,
  176. "summary": title,
  177. "body": body,
  178. "meta": metadata,
  179. }
  180. )
  181. class ModelIndexView(BaseAdminDocsView):
  182. template_name = "admin_doc/model_index.html"
  183. def get_context_data(self, **kwargs):
  184. m_list = [m._meta for m in apps.get_models()]
  185. return super().get_context_data(**{**kwargs, "models": m_list})
  186. class ModelDetailView(BaseAdminDocsView):
  187. template_name = "admin_doc/model_detail.html"
  188. def get_context_data(self, **kwargs):
  189. model_name = self.kwargs["model_name"]
  190. # Get the model class.
  191. try:
  192. app_config = apps.get_app_config(self.kwargs["app_label"])
  193. except LookupError:
  194. raise Http404(_("App %(app_label)r not found") % self.kwargs)
  195. try:
  196. model = app_config.get_model(model_name)
  197. except LookupError:
  198. raise Http404(
  199. _("Model %(model_name)r not found in app %(app_label)r") % self.kwargs
  200. )
  201. opts = model._meta
  202. title, body, metadata = utils.parse_docstring(model.__doc__)
  203. title = title and utils.parse_rst(title, "model", _("model:") + model_name)
  204. body = body and utils.parse_rst(body, "model", _("model:") + model_name)
  205. # Gather fields/field descriptions.
  206. fields = []
  207. for field in opts.fields:
  208. # ForeignKey is a special case since the field will actually be a
  209. # descriptor that returns the other object
  210. if isinstance(field, models.ForeignKey):
  211. data_type = field.remote_field.model.__name__
  212. app_label = field.remote_field.model._meta.app_label
  213. verbose = utils.parse_rst(
  214. (
  215. _("the related `%(app_label)s.%(data_type)s` object")
  216. % {
  217. "app_label": app_label,
  218. "data_type": data_type,
  219. }
  220. ),
  221. "model",
  222. _("model:") + data_type,
  223. )
  224. else:
  225. data_type = get_readable_field_data_type(field)
  226. verbose = field.verbose_name
  227. fields.append(
  228. {
  229. "name": field.name,
  230. "data_type": data_type,
  231. "verbose": verbose or "",
  232. "help_text": field.help_text,
  233. }
  234. )
  235. # Gather many-to-many fields.
  236. for field in opts.many_to_many:
  237. data_type = field.remote_field.model.__name__
  238. app_label = field.remote_field.model._meta.app_label
  239. verbose = _("related `%(app_label)s.%(object_name)s` objects") % {
  240. "app_label": app_label,
  241. "object_name": data_type,
  242. }
  243. fields.append(
  244. {
  245. "name": "%s.all" % field.name,
  246. "data_type": "List",
  247. "verbose": utils.parse_rst(
  248. _("all %s") % verbose, "model", _("model:") + opts.model_name
  249. ),
  250. }
  251. )
  252. fields.append(
  253. {
  254. "name": "%s.count" % field.name,
  255. "data_type": "Integer",
  256. "verbose": utils.parse_rst(
  257. _("number of %s") % verbose,
  258. "model",
  259. _("model:") + opts.model_name,
  260. ),
  261. }
  262. )
  263. methods = []
  264. # Gather model methods.
  265. for func_name, func in model.__dict__.items():
  266. if inspect.isfunction(func) or isinstance(
  267. func, (cached_property, property)
  268. ):
  269. try:
  270. for exclude in MODEL_METHODS_EXCLUDE:
  271. if func_name.startswith(exclude):
  272. raise StopIteration
  273. except StopIteration:
  274. continue
  275. verbose = func.__doc__
  276. verbose = verbose and (
  277. utils.parse_rst(
  278. cleandoc(verbose), "model", _("model:") + opts.model_name
  279. )
  280. )
  281. # Show properties, cached_properties, and methods without
  282. # arguments as fields. Otherwise, show as a 'method with
  283. # arguments'.
  284. if isinstance(func, (cached_property, property)):
  285. fields.append(
  286. {
  287. "name": func_name,
  288. "data_type": get_return_data_type(func_name),
  289. "verbose": verbose or "",
  290. }
  291. )
  292. elif (
  293. method_has_no_args(func)
  294. and not func_accepts_kwargs(func)
  295. and not func_accepts_var_args(func)
  296. ):
  297. fields.append(
  298. {
  299. "name": func_name,
  300. "data_type": get_return_data_type(func_name),
  301. "verbose": verbose or "",
  302. }
  303. )
  304. else:
  305. arguments = get_func_full_args(func)
  306. # Join arguments with ', ' and in case of default value,
  307. # join it with '='. Use repr() so that strings will be
  308. # correctly displayed.
  309. print_arguments = ", ".join(
  310. [
  311. "=".join([arg_el[0], *map(repr, arg_el[1:])])
  312. for arg_el in arguments
  313. ]
  314. )
  315. methods.append(
  316. {
  317. "name": func_name,
  318. "arguments": print_arguments,
  319. "verbose": verbose or "",
  320. }
  321. )
  322. # Gather related objects
  323. for rel in opts.related_objects:
  324. verbose = _("related `%(app_label)s.%(object_name)s` objects") % {
  325. "app_label": rel.related_model._meta.app_label,
  326. "object_name": rel.related_model._meta.object_name,
  327. }
  328. accessor = rel.get_accessor_name()
  329. fields.append(
  330. {
  331. "name": "%s.all" % accessor,
  332. "data_type": "List",
  333. "verbose": utils.parse_rst(
  334. _("all %s") % verbose, "model", _("model:") + opts.model_name
  335. ),
  336. }
  337. )
  338. fields.append(
  339. {
  340. "name": "%s.count" % accessor,
  341. "data_type": "Integer",
  342. "verbose": utils.parse_rst(
  343. _("number of %s") % verbose,
  344. "model",
  345. _("model:") + opts.model_name,
  346. ),
  347. }
  348. )
  349. return super().get_context_data(
  350. **{
  351. **kwargs,
  352. "name": opts.label,
  353. "summary": title,
  354. "description": body,
  355. "fields": fields,
  356. "methods": methods,
  357. }
  358. )
  359. class TemplateDetailView(BaseAdminDocsView):
  360. template_name = "admin_doc/template_detail.html"
  361. def get_context_data(self, **kwargs):
  362. template = self.kwargs["template"]
  363. templates = []
  364. try:
  365. default_engine = Engine.get_default()
  366. except ImproperlyConfigured:
  367. # Non-trivial TEMPLATES settings aren't supported (#24125).
  368. pass
  369. else:
  370. # This doesn't account for template loaders (#24128).
  371. for index, directory in enumerate(default_engine.dirs):
  372. template_file = Path(safe_join(directory, template))
  373. if template_file.exists():
  374. template_contents = template_file.read_text()
  375. else:
  376. template_contents = ""
  377. templates.append(
  378. {
  379. "file": template_file,
  380. "exists": template_file.exists(),
  381. "contents": template_contents,
  382. "order": index,
  383. }
  384. )
  385. return super().get_context_data(
  386. **{
  387. **kwargs,
  388. "name": template,
  389. "templates": templates,
  390. }
  391. )
  392. ####################
  393. # Helper functions #
  394. ####################
  395. def get_return_data_type(func_name):
  396. """Return a somewhat-helpful data type given a function name"""
  397. if func_name.startswith("get_"):
  398. if func_name.endswith("_list"):
  399. return "List"
  400. elif func_name.endswith("_count"):
  401. return "Integer"
  402. return ""
  403. def get_readable_field_data_type(field):
  404. """
  405. Return the description for a given field type, if it exists. Fields'
  406. descriptions can contain format strings, which will be interpolated with
  407. the values of field.__dict__ before being output.
  408. """
  409. return field.description % field.__dict__
  410. def extract_views_from_urlpatterns(urlpatterns, base="", namespace=None):
  411. """
  412. Return a list of views from a list of urlpatterns.
  413. Each object in the returned list is a four-tuple:
  414. (view_func, regex, namespace, name)
  415. """
  416. views = []
  417. for p in urlpatterns:
  418. if hasattr(p, "url_patterns"):
  419. try:
  420. patterns = p.url_patterns
  421. except ImportError:
  422. continue
  423. views.extend(
  424. extract_views_from_urlpatterns(
  425. patterns,
  426. base + str(p.pattern),
  427. (namespace or []) + (p.namespace and [p.namespace] or []),
  428. )
  429. )
  430. elif hasattr(p, "callback"):
  431. try:
  432. views.append((p.callback, base + str(p.pattern), namespace, p.name))
  433. except ViewDoesNotExist:
  434. continue
  435. else:
  436. raise TypeError(_("%s does not appear to be a urlpattern object") % p)
  437. return views
  438. def simplify_regex(pattern):
  439. r"""
  440. Clean up urlpattern regexes into something more readable by humans. For
  441. example, turn "^(?P<sport_slug>\w+)/athletes/(?P<athlete_slug>\w+)/$"
  442. into "/<sport_slug>/athletes/<athlete_slug>/".
  443. """
  444. pattern = remove_non_capturing_groups(pattern)
  445. pattern = replace_named_groups(pattern)
  446. pattern = replace_unnamed_groups(pattern)
  447. pattern = replace_metacharacters(pattern)
  448. if not pattern.startswith("/"):
  449. pattern = "/" + pattern
  450. return pattern