views.py 5.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160
  1. import json
  2. from django.conf import settings
  3. from django.contrib.auth.decorators import login_required
  4. from django.core.serializers.json import DjangoJSONEncoder
  5. from django.http import HttpResponse, HttpResponseRedirect, JsonResponse
  6. from django.shortcuts import render, render_to_response
  7. from django.template.loader import render_to_string
  8. from django.test import Client
  9. from django.test.client import CONTENT_TYPE_RE
  10. from django.test.utils import setup_test_environment
  11. from django.utils.six.moves.urllib.parse import urlencode
  12. class CustomTestException(Exception):
  13. pass
  14. def no_template_view(request):
  15. "A simple view that expects a GET request, and returns a rendered template"
  16. return HttpResponse("No template used. Sample content: twice once twice. Content ends.")
  17. def staff_only_view(request):
  18. "A view that can only be visited by staff. Non staff members get an exception"
  19. if request.user.is_staff:
  20. return HttpResponse('')
  21. else:
  22. raise CustomTestException()
  23. def get_view(request):
  24. "A simple login protected view"
  25. return HttpResponse("Hello world")
  26. get_view = login_required(get_view)
  27. def request_data(request, template='base.html', data='sausage'):
  28. "A simple view that returns the request data in the context"
  29. return render_to_response(template, {
  30. 'get-foo': request.GET.get('foo'),
  31. 'get-bar': request.GET.get('bar'),
  32. 'post-foo': request.POST.get('foo'),
  33. 'post-bar': request.POST.get('bar'),
  34. 'data': data,
  35. })
  36. def view_with_argument(request, name):
  37. """A view that takes a string argument
  38. The purpose of this view is to check that if a space is provided in
  39. the argument, the test framework unescapes the %20 before passing
  40. the value to the view.
  41. """
  42. if name == 'Arthur Dent':
  43. return HttpResponse('Hi, Arthur')
  44. else:
  45. return HttpResponse('Howdy, %s' % name)
  46. def nested_view(request):
  47. """
  48. A view that uses test client to call another view.
  49. """
  50. setup_test_environment()
  51. c = Client()
  52. c.get("/no_template_view/")
  53. return render_to_response('base.html', {'nested': 'yes'})
  54. def login_protected_redirect_view(request):
  55. "A view that redirects all requests to the GET view"
  56. return HttpResponseRedirect('/get_view/')
  57. login_protected_redirect_view = login_required(login_protected_redirect_view)
  58. def redirect_to_self_with_changing_query_view(request):
  59. query = request.GET.copy()
  60. query['counter'] += '0'
  61. return HttpResponseRedirect('/redirect_to_self_with_changing_query_view/?%s' % urlencode(query))
  62. def set_session_view(request):
  63. "A view that sets a session variable"
  64. request.session['session_var'] = 'YES'
  65. return HttpResponse('set_session')
  66. def check_session_view(request):
  67. "A view that reads a session variable"
  68. return HttpResponse(request.session.get('session_var', 'NO'))
  69. def request_methods_view(request):
  70. "A view that responds with the request method"
  71. return HttpResponse('request method: %s' % request.method)
  72. def return_unicode(request):
  73. return render_to_response('unicode.html')
  74. def return_undecodable_binary(request):
  75. return HttpResponse(
  76. b'%PDF-1.4\r\n%\x93\x8c\x8b\x9e ReportLab Generated PDF document http://www.reportlab.com'
  77. )
  78. def return_json_response(request):
  79. return JsonResponse({'key': 'value'})
  80. def return_json_file(request):
  81. "A view that parses and returns a JSON string as a file."
  82. match = CONTENT_TYPE_RE.match(request.META['CONTENT_TYPE'])
  83. if match:
  84. charset = match.group(1)
  85. else:
  86. charset = settings.DEFAULT_CHARSET
  87. # This just checks that the uploaded data is JSON
  88. obj_dict = json.loads(request.body.decode(charset))
  89. obj_json = json.dumps(obj_dict, cls=DjangoJSONEncoder, ensure_ascii=False)
  90. response = HttpResponse(obj_json.encode(charset), status=200,
  91. content_type='application/json; charset=%s' % charset)
  92. response['Content-Disposition'] = 'attachment; filename=testfile.json'
  93. return response
  94. def check_headers(request):
  95. "A view that responds with value of the X-ARG-CHECK header"
  96. return HttpResponse('HTTP_X_ARG_CHECK: %s' % request.META.get('HTTP_X_ARG_CHECK', 'Undefined'))
  97. def body(request):
  98. "A view that is requested with GET and accesses request.body. Refs #14753."
  99. return HttpResponse(request.body)
  100. def read_all(request):
  101. "A view that is requested with accesses request.read()."
  102. return HttpResponse(request.read())
  103. def read_buffer(request):
  104. "A view that is requested with accesses request.read(LARGE_BUFFER)."
  105. return HttpResponse(request.read(99999))
  106. def request_context_view(request):
  107. # Special attribute that won't be present on a plain HttpRequest
  108. request.special_path = request.path
  109. return render(request, 'request_context.html')
  110. def render_template_multiple_times(request):
  111. """A view that renders a template multiple times."""
  112. return HttpResponse(
  113. render_to_string('base.html') + render_to_string('base.html'))