PageRenderTime 50ms CodeModel.GetById 16ms RepoModel.GetById 0ms app.codeStats 0ms

/lib/django-1.5/django/shortcuts/__init__.py

https://github.com/theosp/google_appengine
Python | 161 lines | 160 code | 0 blank | 1 comment | 1 complexity | 0293616f885d5598cf03825b4fa422a3 MD5 | raw file
  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. import warnings
  7. from django.template import loader, RequestContext
  8. from django.http import HttpResponse, Http404
  9. from django.http import HttpResponseRedirect, HttpResponsePermanentRedirect
  10. from django.db.models.base import ModelBase
  11. from django.db.models.manager import Manager
  12. from django.db.models.query import QuerySet
  13. from django.core import urlresolvers
  14. def render_to_response(*args, **kwargs):
  15. """
  16. Returns a HttpResponse whose content is filled with the result of calling
  17. django.template.loader.render_to_string() with the passed arguments.
  18. """
  19. httpresponse_kwargs = {'content_type': kwargs.pop('content_type', None)}
  20. mimetype = kwargs.pop('mimetype', None)
  21. if mimetype:
  22. warnings.warn("The mimetype keyword argument is deprecated, use "
  23. "content_type instead", PendingDeprecationWarning, stacklevel=2)
  24. httpresponse_kwargs['content_type'] = mimetype
  25. return HttpResponse(loader.render_to_string(*args, **kwargs), **httpresponse_kwargs)
  26. def render(request, *args, **kwargs):
  27. """
  28. Returns a HttpResponse whose content is filled with the result of calling
  29. django.template.loader.render_to_string() with the passed arguments.
  30. Uses a RequestContext by default.
  31. """
  32. httpresponse_kwargs = {
  33. 'content_type': kwargs.pop('content_type', None),
  34. 'status': kwargs.pop('status', None),
  35. }
  36. if 'context_instance' in kwargs:
  37. context_instance = kwargs.pop('context_instance')
  38. if kwargs.get('current_app', None):
  39. raise ValueError('If you provide a context_instance you must '
  40. 'set its current_app before calling render()')
  41. else:
  42. current_app = kwargs.pop('current_app', None)
  43. context_instance = RequestContext(request, current_app=current_app)
  44. kwargs['context_instance'] = context_instance
  45. return HttpResponse(loader.render_to_string(*args, **kwargs),
  46. **httpresponse_kwargs)
  47. def redirect(to, *args, **kwargs):
  48. """
  49. Returns an HttpResponseRedirect to the apropriate URL for the arguments
  50. passed.
  51. The arguments could be:
  52. * A model: the model's `get_absolute_url()` function will be called.
  53. * A view name, possibly with arguments: `urlresolvers.reverse()` will
  54. be used to reverse-resolve the name.
  55. * A URL, which will be used as-is for the redirect location.
  56. By default issues a temporary redirect; pass permanent=True to issue a
  57. permanent redirect
  58. """
  59. if kwargs.pop('permanent', False):
  60. redirect_class = HttpResponsePermanentRedirect
  61. else:
  62. redirect_class = HttpResponseRedirect
  63. return redirect_class(resolve_url(to, *args, **kwargs))
  64. def _get_queryset(klass):
  65. """
  66. Returns a QuerySet from a Model, Manager, or QuerySet. Created to make
  67. get_object_or_404 and get_list_or_404 more DRY.
  68. Raises a ValueError if klass is not a Model, Manager, or QuerySet.
  69. """
  70. if isinstance(klass, QuerySet):
  71. return klass
  72. elif isinstance(klass, Manager):
  73. manager = klass
  74. elif isinstance(klass, ModelBase):
  75. manager = klass._default_manager
  76. else:
  77. klass__name = klass.__name__ if isinstance(klass, type) \
  78. else klass.__class__.__name__
  79. raise ValueError("Object is of type '%s', but must be a Django Model, "
  80. "Manager, or QuerySet" % klass__name)
  81. return manager.all()
  82. def get_object_or_404(klass, *args, **kwargs):
  83. """
  84. Uses get() to return an object, or raises a Http404 exception if the object
  85. does not exist.
  86. klass may be a Model, Manager, or QuerySet object. All other passed
  87. arguments and keyword arguments are used in the get() query.
  88. Note: Like with get(), an MultipleObjectsReturned will be raised if more than one
  89. object is found.
  90. """
  91. queryset = _get_queryset(klass)
  92. try:
  93. return queryset.get(*args, **kwargs)
  94. except queryset.model.DoesNotExist:
  95. raise Http404('No %s matches the given query.' % queryset.model._meta.object_name)
  96. def get_list_or_404(klass, *args, **kwargs):
  97. """
  98. Uses filter() to return a list of objects, or raise a Http404 exception if
  99. the list is empty.
  100. klass may be a Model, Manager, or QuerySet object. All other passed
  101. arguments and keyword arguments are used in the filter() query.
  102. """
  103. queryset = _get_queryset(klass)
  104. obj_list = list(queryset.filter(*args, **kwargs))
  105. if not obj_list:
  106. raise Http404('No %s matches the given query.' % queryset.model._meta.object_name)
  107. return obj_list
  108. def resolve_url(to, *args, **kwargs):
  109. """
  110. Return a URL appropriate for the arguments passed.
  111. The arguments could be:
  112. * A model: the model's `get_absolute_url()` function will be called.
  113. * A view name, possibly with arguments: `urlresolvers.reverse()` will
  114. be used to reverse-resolve the name.
  115. * A URL, which will be returned as-is.
  116. """
  117. # If it's a model, use get_absolute_url()
  118. if hasattr(to, 'get_absolute_url'):
  119. return to.get_absolute_url()
  120. # Next try a reverse URL resolution.
  121. try:
  122. return urlresolvers.reverse(to, args=args, kwargs=kwargs)
  123. except urlresolvers.NoReverseMatch:
  124. # If this is a callable, re-raise.
  125. if callable(to):
  126. raise
  127. # If this doesn't "feel" like a URL, re-raise.
  128. if '/' not in to and '.' not in to:
  129. raise
  130. # Finally, fall back and assume it's a URL
  131. return to