views.py 9.3 KB

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