views.py 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229
  1. import sys
  2. from django import forms
  3. from django.core.exceptions import PermissionDenied
  4. from django.core.urlresolvers import get_resolver
  5. from django.http import HttpResponse, HttpResponseRedirect
  6. from django.shortcuts import render_to_response, render
  7. from django.template import Context, RequestContext, TemplateDoesNotExist
  8. from django.views.debug import technical_500_response, SafeExceptionReporterFilter
  9. from django.views.decorators.debug import (sensitive_post_parameters,
  10. sensitive_variables)
  11. from django.utils.log import getLogger
  12. from regressiontests.views import BrokenException, except_args
  13. from models import Article
  14. def index_page(request):
  15. """Dummy index page"""
  16. return HttpResponse('<html><body>Dummy page</body></html>')
  17. def custom_create(request):
  18. """
  19. Calls create_object generic view with a custom form class.
  20. """
  21. class SlugChangingArticleForm(forms.ModelForm):
  22. """Custom form class to overwrite the slug."""
  23. class Meta:
  24. model = Article
  25. def save(self, *args, **kwargs):
  26. self.instance.slug = 'some-other-slug'
  27. return super(SlugChangingArticleForm, self).save(*args, **kwargs)
  28. from django.views.generic.create_update import create_object
  29. return create_object(request,
  30. post_save_redirect='/create_update/view/article/%(slug)s/',
  31. form_class=SlugChangingArticleForm)
  32. def raises(request):
  33. # Make sure that a callable that raises an exception in the stack frame's
  34. # local vars won't hijack the technical 500 response. See:
  35. # http://code.djangoproject.com/ticket/15025
  36. def callable():
  37. raise Exception
  38. try:
  39. raise Exception
  40. except Exception:
  41. return technical_500_response(request, *sys.exc_info())
  42. def raises404(request):
  43. resolver = get_resolver(None)
  44. resolver.resolve('')
  45. def raises403(request):
  46. raise PermissionDenied
  47. def redirect(request):
  48. """
  49. Forces an HTTP redirect.
  50. """
  51. return HttpResponseRedirect("target/")
  52. def view_exception(request, n):
  53. raise BrokenException(except_args[int(n)])
  54. def template_exception(request, n):
  55. return render_to_response('debug/template_exception.html',
  56. {'arg': except_args[int(n)]})
  57. # Some views to exercise the shortcuts
  58. def render_to_response_view(request):
  59. return render_to_response('debug/render_test.html', {
  60. 'foo': 'FOO',
  61. 'bar': 'BAR',
  62. })
  63. def render_to_response_view_with_request_context(request):
  64. return render_to_response('debug/render_test.html', {
  65. 'foo': 'FOO',
  66. 'bar': 'BAR',
  67. }, context_instance=RequestContext(request))
  68. def render_to_response_view_with_mimetype(request):
  69. return render_to_response('debug/render_test.html', {
  70. 'foo': 'FOO',
  71. 'bar': 'BAR',
  72. }, mimetype='application/x-rendertest')
  73. def render_view(request):
  74. return render(request, 'debug/render_test.html', {
  75. 'foo': 'FOO',
  76. 'bar': 'BAR',
  77. })
  78. def render_view_with_base_context(request):
  79. return render(request, 'debug/render_test.html', {
  80. 'foo': 'FOO',
  81. 'bar': 'BAR',
  82. }, context_instance=Context())
  83. def render_view_with_content_type(request):
  84. return render(request, 'debug/render_test.html', {
  85. 'foo': 'FOO',
  86. 'bar': 'BAR',
  87. }, content_type='application/x-rendertest')
  88. def render_view_with_status(request):
  89. return render(request, 'debug/render_test.html', {
  90. 'foo': 'FOO',
  91. 'bar': 'BAR',
  92. }, status=403)
  93. def render_view_with_current_app(request):
  94. return render(request, 'debug/render_test.html', {
  95. 'foo': 'FOO',
  96. 'bar': 'BAR',
  97. }, current_app="foobar_app")
  98. def render_view_with_current_app_conflict(request):
  99. # This should fail because we don't passing both a current_app and
  100. # context_instance:
  101. return render(request, 'debug/render_test.html', {
  102. 'foo': 'FOO',
  103. 'bar': 'BAR',
  104. }, current_app="foobar_app", context_instance=RequestContext(request))
  105. def raises_template_does_not_exist(request):
  106. # We need to inspect the HTML generated by the fancy 500 debug view but
  107. # the test client ignores it, so we send it explicitly.
  108. try:
  109. return render_to_response('i_dont_exist.html')
  110. except TemplateDoesNotExist:
  111. return technical_500_response(request, *sys.exc_info())
  112. def send_log(request, exc_info):
  113. logger = getLogger('django.request')
  114. # The default logging config has a logging filter to ensure admin emails are
  115. # only sent with DEBUG=False, but since someone might choose to remove that
  116. # filter, we still want to be able to test the behavior of error emails
  117. # with DEBUG=True. So we need to remove the filter temporarily.
  118. admin_email_handler = [
  119. h for h in logger.handlers
  120. if h.__class__.__name__ == "AdminEmailHandler"
  121. ][0]
  122. orig_filters = admin_email_handler.filters
  123. admin_email_handler.filters = []
  124. logger.error('Internal Server Error: %s' % request.path,
  125. exc_info=exc_info,
  126. extra={
  127. 'status_code': 500,
  128. 'request': request
  129. }
  130. )
  131. admin_email_handler.filters = orig_filters
  132. def non_sensitive_view(request):
  133. # Do not just use plain strings for the variables' values in the code
  134. # so that the tests don't return false positives when the function's source
  135. # is displayed in the exception report.
  136. cooked_eggs = ''.join(['s', 'c', 'r', 'a', 'm', 'b', 'l', 'e', 'd'])
  137. sauce = ''.join(['w', 'o', 'r', 'c', 'e', 's', 't', 'e', 'r', 's', 'h', 'i', 'r', 'e'])
  138. try:
  139. raise Exception
  140. except Exception:
  141. exc_info = sys.exc_info()
  142. send_log(request, exc_info)
  143. return technical_500_response(request, *exc_info)
  144. @sensitive_variables('sauce')
  145. @sensitive_post_parameters('bacon-key', 'sausage-key')
  146. def sensitive_view(request):
  147. # Do not just use plain strings for the variables' values in the code
  148. # so that the tests don't return false positives when the function's source
  149. # is displayed in the exception report.
  150. cooked_eggs = ''.join(['s', 'c', 'r', 'a', 'm', 'b', 'l', 'e', 'd'])
  151. sauce = ''.join(['w', 'o', 'r', 'c', 'e', 's', 't', 'e', 'r', 's', 'h', 'i', 'r', 'e'])
  152. try:
  153. raise Exception
  154. except Exception:
  155. exc_info = sys.exc_info()
  156. send_log(request, exc_info)
  157. return technical_500_response(request, *exc_info)
  158. @sensitive_variables()
  159. @sensitive_post_parameters()
  160. def paranoid_view(request):
  161. # Do not just use plain strings for the variables' values in the code
  162. # so that the tests don't return false positives when the function's source
  163. # is displayed in the exception report.
  164. cooked_eggs = ''.join(['s', 'c', 'r', 'a', 'm', 'b', 'l', 'e', 'd'])
  165. sauce = ''.join(['w', 'o', 'r', 'c', 'e', 's', 't', 'e', 'r', 's', 'h', 'i', 'r', 'e'])
  166. try:
  167. raise Exception
  168. except Exception:
  169. exc_info = sys.exc_info()
  170. send_log(request, exc_info)
  171. return technical_500_response(request, *exc_info)
  172. class UnsafeExceptionReporterFilter(SafeExceptionReporterFilter):
  173. """
  174. Ignores all the filtering done by its parent class.
  175. """
  176. def get_post_parameters(self, request):
  177. return request.POST
  178. def get_traceback_frame_variables(self, request, tb_frame):
  179. return tb_frame.f_locals.items()
  180. @sensitive_variables()
  181. @sensitive_post_parameters()
  182. def custom_exception_reporter_filter_view(request):
  183. # Do not just use plain strings for the variables' values in the code
  184. # so that the tests don't return false positives when the function's source
  185. # is displayed in the exception report.
  186. cooked_eggs = ''.join(['s', 'c', 'r', 'a', 'm', 'b', 'l', 'e', 'd'])
  187. sauce = ''.join(['w', 'o', 'r', 'c', 'e', 's', 't', 'e', 'r', 's', 'h', 'i', 'r', 'e'])
  188. request.exception_reporter_filter = UnsafeExceptionReporterFilter()
  189. try:
  190. raise Exception
  191. except Exception:
  192. exc_info = sys.exc_info()
  193. send_log(request, exc_info)
  194. return technical_500_response(request, *exc_info)