PYTHON   94

shortcuts

Guest on 1st May 2022 12:09:05 AM

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

Raw Paste


Login or Register to edit or fork this paste. It's free.