views.py 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287
  1. import datetime
  2. import decimal
  3. import logging
  4. import sys
  5. from django.core.exceptions import PermissionDenied, SuspiciousOperation
  6. from django.http import Http404, HttpResponse, JsonResponse
  7. from django.shortcuts import render
  8. from django.template import TemplateDoesNotExist
  9. from django.urls import get_resolver
  10. from django.views import View
  11. from django.views.debug import (
  12. ExceptionReporter, SafeExceptionReporterFilter, technical_500_response,
  13. )
  14. from django.views.decorators.debug import (
  15. sensitive_post_parameters, sensitive_variables,
  16. )
  17. def index_page(request):
  18. """Dummy index page"""
  19. return HttpResponse('<html><body>Dummy page</body></html>')
  20. def with_parameter(request, parameter):
  21. return HttpResponse('ok')
  22. def raises(request):
  23. # Make sure that a callable that raises an exception in the stack frame's
  24. # local vars won't hijack the technical 500 response (#15025).
  25. def callable():
  26. raise Exception
  27. try:
  28. raise Exception
  29. except Exception:
  30. return technical_500_response(request, *sys.exc_info())
  31. def raises500(request):
  32. # We need to inspect the HTML generated by the fancy 500 debug view but
  33. # the test client ignores it, so we send it explicitly.
  34. try:
  35. raise Exception
  36. except Exception:
  37. return technical_500_response(request, *sys.exc_info())
  38. def raises400(request):
  39. raise SuspiciousOperation
  40. def raises403(request):
  41. raise PermissionDenied("Insufficient Permissions")
  42. def raises404(request):
  43. resolver = get_resolver(None)
  44. resolver.resolve('/not-in-urls')
  45. def technical404(request):
  46. raise Http404("Testing technical 404.")
  47. class Http404View(View):
  48. def get(self, request):
  49. raise Http404("Testing class-based technical 404.")
  50. def template_exception(request):
  51. return render(request, 'debug/template_exception.html')
  52. def jsi18n(request):
  53. return render(request, 'jsi18n.html')
  54. def jsi18n_multi_catalogs(request):
  55. return render(request, 'jsi18n-multi-catalogs.html')
  56. def raises_template_does_not_exist(request, path='i_dont_exist.html'):
  57. # We need to inspect the HTML generated by the fancy 500 debug view but
  58. # the test client ignores it, so we send it explicitly.
  59. try:
  60. return render(request, path)
  61. except TemplateDoesNotExist:
  62. return technical_500_response(request, *sys.exc_info())
  63. def render_no_template(request):
  64. # If we do not specify a template, we need to make sure the debug
  65. # view doesn't blow up.
  66. return render(request, [], {})
  67. def send_log(request, exc_info):
  68. logger = logging.getLogger('django')
  69. # The default logging config has a logging filter to ensure admin emails are
  70. # only sent with DEBUG=False, but since someone might choose to remove that
  71. # filter, we still want to be able to test the behavior of error emails
  72. # with DEBUG=True. So we need to remove the filter temporarily.
  73. admin_email_handler = [
  74. h for h in logger.handlers
  75. if h.__class__.__name__ == "AdminEmailHandler"
  76. ][0]
  77. orig_filters = admin_email_handler.filters
  78. admin_email_handler.filters = []
  79. admin_email_handler.include_html = True
  80. logger.error(
  81. 'Internal Server Error: %s', request.path,
  82. exc_info=exc_info,
  83. extra={'status_code': 500, 'request': request},
  84. )
  85. admin_email_handler.filters = orig_filters
  86. def non_sensitive_view(request):
  87. # Do not just use plain strings for the variables' values in the code
  88. # so that the tests don't return false positives when the function's source
  89. # is displayed in the exception report.
  90. cooked_eggs = ''.join(['s', 'c', 'r', 'a', 'm', 'b', 'l', 'e', 'd']) # NOQA
  91. sauce = ''.join(['w', 'o', 'r', 'c', 'e', 's', 't', 'e', 'r', 's', 'h', 'i', 'r', 'e']) # NOQA
  92. try:
  93. raise Exception
  94. except Exception:
  95. exc_info = sys.exc_info()
  96. send_log(request, exc_info)
  97. return technical_500_response(request, *exc_info)
  98. @sensitive_variables('sauce')
  99. @sensitive_post_parameters('bacon-key', 'sausage-key')
  100. def sensitive_view(request):
  101. # Do not just use plain strings for the variables' values in the code
  102. # so that the tests don't return false positives when the function's source
  103. # is displayed in the exception report.
  104. cooked_eggs = ''.join(['s', 'c', 'r', 'a', 'm', 'b', 'l', 'e', 'd']) # NOQA
  105. sauce = ''.join(['w', 'o', 'r', 'c', 'e', 's', 't', 'e', 'r', 's', 'h', 'i', 'r', 'e']) # NOQA
  106. try:
  107. raise Exception
  108. except Exception:
  109. exc_info = sys.exc_info()
  110. send_log(request, exc_info)
  111. return technical_500_response(request, *exc_info)
  112. @sensitive_variables()
  113. @sensitive_post_parameters()
  114. def paranoid_view(request):
  115. # Do not just use plain strings for the variables' values in the code
  116. # so that the tests don't return false positives when the function's source
  117. # is displayed in the exception report.
  118. cooked_eggs = ''.join(['s', 'c', 'r', 'a', 'm', 'b', 'l', 'e', 'd']) # NOQA
  119. sauce = ''.join(['w', 'o', 'r', 'c', 'e', 's', 't', 'e', 'r', 's', 'h', 'i', 'r', 'e']) # NOQA
  120. try:
  121. raise Exception
  122. except Exception:
  123. exc_info = sys.exc_info()
  124. send_log(request, exc_info)
  125. return technical_500_response(request, *exc_info)
  126. def sensitive_args_function_caller(request):
  127. try:
  128. sensitive_args_function(''.join(['w', 'o', 'r', 'c', 'e', 's', 't', 'e', 'r', 's', 'h', 'i', 'r', 'e']))
  129. except Exception:
  130. exc_info = sys.exc_info()
  131. send_log(request, exc_info)
  132. return technical_500_response(request, *exc_info)
  133. @sensitive_variables('sauce')
  134. def sensitive_args_function(sauce):
  135. # Do not just use plain strings for the variables' values in the code
  136. # so that the tests don't return false positives when the function's source
  137. # is displayed in the exception report.
  138. cooked_eggs = ''.join(['s', 'c', 'r', 'a', 'm', 'b', 'l', 'e', 'd']) # NOQA
  139. raise Exception
  140. def sensitive_kwargs_function_caller(request):
  141. try:
  142. sensitive_kwargs_function(''.join(['w', 'o', 'r', 'c', 'e', 's', 't', 'e', 'r', 's', 'h', 'i', 'r', 'e']))
  143. except Exception:
  144. exc_info = sys.exc_info()
  145. send_log(request, exc_info)
  146. return technical_500_response(request, *exc_info)
  147. @sensitive_variables('sauce')
  148. def sensitive_kwargs_function(sauce=None):
  149. # Do not just use plain strings for the variables' values in the code
  150. # so that the tests don't return false positives when the function's source
  151. # is displayed in the exception report.
  152. cooked_eggs = ''.join(['s', 'c', 'r', 'a', 'm', 'b', 'l', 'e', 'd']) # NOQA
  153. raise Exception
  154. class UnsafeExceptionReporterFilter(SafeExceptionReporterFilter):
  155. """
  156. Ignores all the filtering done by its parent class.
  157. """
  158. def get_post_parameters(self, request):
  159. return request.POST
  160. def get_traceback_frame_variables(self, request, tb_frame):
  161. return tb_frame.f_locals.items()
  162. @sensitive_variables()
  163. @sensitive_post_parameters()
  164. def custom_exception_reporter_filter_view(request):
  165. # Do not just use plain strings for the variables' values in the code
  166. # so that the tests don't return false positives when the function's source
  167. # is displayed in the exception report.
  168. cooked_eggs = ''.join(['s', 'c', 'r', 'a', 'm', 'b', 'l', 'e', 'd']) # NOQA
  169. sauce = ''.join(['w', 'o', 'r', 'c', 'e', 's', 't', 'e', 'r', 's', 'h', 'i', 'r', 'e']) # NOQA
  170. request.exception_reporter_filter = UnsafeExceptionReporterFilter()
  171. try:
  172. raise Exception
  173. except Exception:
  174. exc_info = sys.exc_info()
  175. send_log(request, exc_info)
  176. return technical_500_response(request, *exc_info)
  177. class CustomExceptionReporter(ExceptionReporter):
  178. custom_traceback_text = 'custom traceback text'
  179. def get_traceback_html(self):
  180. return self.custom_traceback_text
  181. def custom_reporter_class_view(request):
  182. request.exception_reporter_class = CustomExceptionReporter
  183. try:
  184. raise Exception
  185. except Exception:
  186. exc_info = sys.exc_info()
  187. return technical_500_response(request, *exc_info)
  188. class Klass:
  189. @sensitive_variables('sauce')
  190. def method(self, request):
  191. # Do not just use plain strings for the variables' values in the code
  192. # so that the tests don't return false positives when the function's
  193. # source is displayed in the exception report.
  194. cooked_eggs = ''.join(['s', 'c', 'r', 'a', 'm', 'b', 'l', 'e', 'd']) # NOQA
  195. sauce = ''.join(['w', 'o', 'r', 'c', 'e', 's', 't', 'e', 'r', 's', 'h', 'i', 'r', 'e']) # NOQA
  196. try:
  197. raise Exception
  198. except Exception:
  199. exc_info = sys.exc_info()
  200. send_log(request, exc_info)
  201. return technical_500_response(request, *exc_info)
  202. def sensitive_method_view(request):
  203. return Klass().method(request)
  204. @sensitive_variables('sauce')
  205. @sensitive_post_parameters('bacon-key', 'sausage-key')
  206. def multivalue_dict_key_error(request):
  207. cooked_eggs = ''.join(['s', 'c', 'r', 'a', 'm', 'b', 'l', 'e', 'd']) # NOQA
  208. sauce = ''.join(['w', 'o', 'r', 'c', 'e', 's', 't', 'e', 'r', 's', 'h', 'i', 'r', 'e']) # NOQA
  209. try:
  210. request.POST['bar']
  211. except Exception:
  212. exc_info = sys.exc_info()
  213. send_log(request, exc_info)
  214. return technical_500_response(request, *exc_info)
  215. def json_response_view(request):
  216. return JsonResponse({
  217. 'a': [1, 2, 3],
  218. 'foo': {'bar': 'baz'},
  219. # Make sure datetime and Decimal objects would be serialized properly
  220. 'timestamp': datetime.datetime(2013, 5, 19, 20),
  221. 'value': decimal.Decimal('3.14'),
  222. })