views.py 4.9 KB

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