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.

shortcuts.py 4.9KB

1 year ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155
  1. """
  2. This module collects helper functions and classes that "span" multiple levels
  3. of MVC. In other words, these functions/classes introduce controlled coupling
  4. for convenience's sake.
  5. """
  6. from django.http import (
  7. Http404,
  8. HttpResponse,
  9. HttpResponsePermanentRedirect,
  10. HttpResponseRedirect,
  11. )
  12. from django.template import loader
  13. from django.urls import NoReverseMatch, reverse
  14. from django.utils.functional import Promise
  15. def render(
  16. request, template_name, context=None, content_type=None, status=None, using=None
  17. ):
  18. """
  19. Return an HttpResponse whose content is filled with the result of calling
  20. django.template.loader.render_to_string() with the passed arguments.
  21. """
  22. content = loader.render_to_string(template_name, context, request, using=using)
  23. return HttpResponse(content, content_type, status)
  24. def redirect(to, *args, permanent=False, **kwargs):
  25. """
  26. Return an HttpResponseRedirect to the appropriate URL for the arguments
  27. passed.
  28. The arguments could be:
  29. * A model: the model's `get_absolute_url()` function will be called.
  30. * A view name, possibly with arguments: `urls.reverse()` will be used
  31. to reverse-resolve the name.
  32. * A URL, which will be used as-is for the redirect location.
  33. Issues a temporary redirect by default; pass permanent=True to issue a
  34. permanent redirect.
  35. """
  36. redirect_class = (
  37. HttpResponsePermanentRedirect if permanent else HttpResponseRedirect
  38. )
  39. return redirect_class(resolve_url(to, *args, **kwargs))
  40. def _get_queryset(klass):
  41. """
  42. Return a QuerySet or a Manager.
  43. Duck typing in action: any class with a `get()` method (for
  44. get_object_or_404) or a `filter()` method (for get_list_or_404) might do
  45. the job.
  46. """
  47. # If it is a model class or anything else with ._default_manager
  48. if hasattr(klass, "_default_manager"):
  49. return klass._default_manager.all()
  50. return klass
  51. def get_object_or_404(klass, *args, **kwargs):
  52. """
  53. Use get() to return an object, or raise an Http404 exception if the object
  54. does not exist.
  55. klass may be a Model, Manager, or QuerySet object. All other passed
  56. arguments and keyword arguments are used in the get() query.
  57. Like with QuerySet.get(), MultipleObjectsReturned is raised if more than
  58. one object is found.
  59. """
  60. queryset = _get_queryset(klass)
  61. if not hasattr(queryset, "get"):
  62. klass__name = (
  63. klass.__name__ if isinstance(klass, type) else klass.__class__.__name__
  64. )
  65. raise ValueError(
  66. "First argument to get_object_or_404() must be a Model, Manager, "
  67. "or QuerySet, not '%s'." % klass__name
  68. )
  69. try:
  70. return queryset.get(*args, **kwargs)
  71. except queryset.model.DoesNotExist:
  72. raise Http404(
  73. "No %s matches the given query." % queryset.model._meta.object_name
  74. )
  75. def get_list_or_404(klass, *args, **kwargs):
  76. """
  77. Use filter() to return a list of objects, or raise an Http404 exception if
  78. the list is empty.
  79. klass may be a Model, Manager, or QuerySet object. All other passed
  80. arguments and keyword arguments are used in the filter() query.
  81. """
  82. queryset = _get_queryset(klass)
  83. if not hasattr(queryset, "filter"):
  84. klass__name = (
  85. klass.__name__ if isinstance(klass, type) else klass.__class__.__name__
  86. )
  87. raise ValueError(
  88. "First argument to get_list_or_404() must be a Model, Manager, or "
  89. "QuerySet, not '%s'." % klass__name
  90. )
  91. obj_list = list(queryset.filter(*args, **kwargs))
  92. if not obj_list:
  93. raise Http404(
  94. "No %s matches the given query." % queryset.model._meta.object_name
  95. )
  96. return obj_list
  97. def resolve_url(to, *args, **kwargs):
  98. """
  99. Return a URL appropriate for the arguments passed.
  100. The arguments could be:
  101. * A model: the model's `get_absolute_url()` function will be called.
  102. * A view name, possibly with arguments: `urls.reverse()` will be used
  103. to reverse-resolve the name.
  104. * A URL, which will be returned as-is.
  105. """
  106. # If it's a model, use get_absolute_url()
  107. if hasattr(to, "get_absolute_url"):
  108. return to.get_absolute_url()
  109. if isinstance(to, Promise):
  110. # Expand the lazy instance, as it can cause issues when it is passed
  111. # further to some Python functions like urlparse.
  112. to = str(to)
  113. # Handle relative URLs
  114. if isinstance(to, str) and to.startswith(("./", "../")):
  115. return to
  116. # Next try a reverse URL resolution.
  117. try:
  118. return reverse(to, args=args, kwargs=kwargs)
  119. except NoReverseMatch:
  120. # If this is a callable, re-raise.
  121. if callable(to):
  122. raise
  123. # If this doesn't "feel" like a URL, re-raise.
  124. if "/" not in to and "." not in to:
  125. raise
  126. # Finally, fall back and assume it's a URL
  127. return to