views.py 7.3 KB

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