Development of an internal social media platform with personalised dashboards for students
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

client.py 28KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716
  1. import json
  2. import mimetypes
  3. import os
  4. import re
  5. import sys
  6. from copy import copy
  7. from functools import partial
  8. from http import HTTPStatus
  9. from importlib import import_module
  10. from io import BytesIO
  11. from urllib.parse import unquote_to_bytes, urljoin, urlparse, urlsplit
  12. from django.conf import settings
  13. from django.core.handlers.base import BaseHandler
  14. from django.core.handlers.wsgi import WSGIRequest
  15. from django.core.serializers.json import DjangoJSONEncoder
  16. from django.core.signals import (
  17. got_request_exception, request_finished, request_started,
  18. )
  19. from django.db import close_old_connections
  20. from django.http import HttpRequest, QueryDict, SimpleCookie
  21. from django.template import TemplateDoesNotExist
  22. from django.test import signals
  23. from django.test.utils import ContextList
  24. from django.urls import resolve
  25. from django.utils.encoding import force_bytes
  26. from django.utils.functional import SimpleLazyObject
  27. from django.utils.http import urlencode
  28. from django.utils.itercompat import is_iterable
  29. __all__ = ('Client', 'RedirectCycleError', 'RequestFactory', 'encode_file', 'encode_multipart')
  30. BOUNDARY = 'BoUnDaRyStRiNg'
  31. MULTIPART_CONTENT = 'multipart/form-data; boundary=%s' % BOUNDARY
  32. CONTENT_TYPE_RE = re.compile(r'.*; charset=([\w\d-]+);?')
  33. # Structured suffix spec: https://tools.ietf.org/html/rfc6838#section-4.2.8
  34. JSON_CONTENT_TYPE_RE = re.compile(r'^application\/(.+\+)?json')
  35. class RedirectCycleError(Exception):
  36. """The test client has been asked to follow a redirect loop."""
  37. def __init__(self, message, last_response):
  38. super().__init__(message)
  39. self.last_response = last_response
  40. self.redirect_chain = last_response.redirect_chain
  41. class FakePayload:
  42. """
  43. A wrapper around BytesIO that restricts what can be read since data from
  44. the network can't be seeked and cannot be read outside of its content
  45. length. This makes sure that views can't do anything under the test client
  46. that wouldn't work in real life.
  47. """
  48. def __init__(self, content=None):
  49. self.__content = BytesIO()
  50. self.__len = 0
  51. self.read_started = False
  52. if content is not None:
  53. self.write(content)
  54. def __len__(self):
  55. return self.__len
  56. def read(self, num_bytes=None):
  57. if not self.read_started:
  58. self.__content.seek(0)
  59. self.read_started = True
  60. if num_bytes is None:
  61. num_bytes = self.__len or 0
  62. assert self.__len >= num_bytes, "Cannot read more than the available bytes from the HTTP incoming data."
  63. content = self.__content.read(num_bytes)
  64. self.__len -= num_bytes
  65. return content
  66. def write(self, content):
  67. if self.read_started:
  68. raise ValueError("Unable to write a payload after he's been read")
  69. content = force_bytes(content)
  70. self.__content.write(content)
  71. self.__len += len(content)
  72. def closing_iterator_wrapper(iterable, close):
  73. try:
  74. yield from iterable
  75. finally:
  76. request_finished.disconnect(close_old_connections)
  77. close() # will fire request_finished
  78. request_finished.connect(close_old_connections)
  79. def conditional_content_removal(request, response):
  80. """
  81. Simulate the behavior of most Web servers by removing the content of
  82. responses for HEAD requests, 1xx, 204, and 304 responses. Ensure
  83. compliance with RFC 7230, section 3.3.3.
  84. """
  85. if 100 <= response.status_code < 200 or response.status_code in (204, 304):
  86. if response.streaming:
  87. response.streaming_content = []
  88. else:
  89. response.content = b''
  90. if request.method == 'HEAD':
  91. if response.streaming:
  92. response.streaming_content = []
  93. else:
  94. response.content = b''
  95. return response
  96. class ClientHandler(BaseHandler):
  97. """
  98. A HTTP Handler that can be used for testing purposes. Use the WSGI
  99. interface to compose requests, but return the raw HttpResponse object with
  100. the originating WSGIRequest attached to its ``wsgi_request`` attribute.
  101. """
  102. def __init__(self, enforce_csrf_checks=True, *args, **kwargs):
  103. self.enforce_csrf_checks = enforce_csrf_checks
  104. super().__init__(*args, **kwargs)
  105. def __call__(self, environ):
  106. # Set up middleware if needed. We couldn't do this earlier, because
  107. # settings weren't available.
  108. if self._middleware_chain is None:
  109. self.load_middleware()
  110. request_started.disconnect(close_old_connections)
  111. request_started.send(sender=self.__class__, environ=environ)
  112. request_started.connect(close_old_connections)
  113. request = WSGIRequest(environ)
  114. # sneaky little hack so that we can easily get round
  115. # CsrfViewMiddleware. This makes life easier, and is probably
  116. # required for backwards compatibility with external tests against
  117. # admin views.
  118. request._dont_enforce_csrf_checks = not self.enforce_csrf_checks
  119. # Request goes through middleware.
  120. response = self.get_response(request)
  121. # Simulate behaviors of most Web servers.
  122. conditional_content_removal(request, response)
  123. # Attach the originating request to the response so that it could be
  124. # later retrieved.
  125. response.wsgi_request = request
  126. # Emulate a WSGI server by calling the close method on completion.
  127. if response.streaming:
  128. response.streaming_content = closing_iterator_wrapper(
  129. response.streaming_content, response.close)
  130. else:
  131. request_finished.disconnect(close_old_connections)
  132. response.close() # will fire request_finished
  133. request_finished.connect(close_old_connections)
  134. return response
  135. def store_rendered_templates(store, signal, sender, template, context, **kwargs):
  136. """
  137. Store templates and contexts that are rendered.
  138. The context is copied so that it is an accurate representation at the time
  139. of rendering.
  140. """
  141. store.setdefault('templates', []).append(template)
  142. if 'context' not in store:
  143. store['context'] = ContextList()
  144. store['context'].append(copy(context))
  145. def encode_multipart(boundary, data):
  146. """
  147. Encode multipart POST data from a dictionary of form values.
  148. The key will be used as the form data name; the value will be transmitted
  149. as content. If the value is a file, the contents of the file will be sent
  150. as an application/octet-stream; otherwise, str(value) will be sent.
  151. """
  152. lines = []
  153. def to_bytes(s):
  154. return force_bytes(s, settings.DEFAULT_CHARSET)
  155. # Not by any means perfect, but good enough for our purposes.
  156. def is_file(thing):
  157. return hasattr(thing, "read") and callable(thing.read)
  158. # Each bit of the multipart form data could be either a form value or a
  159. # file, or a *list* of form values and/or files. Remember that HTTP field
  160. # names can be duplicated!
  161. for (key, value) in data.items():
  162. if is_file(value):
  163. lines.extend(encode_file(boundary, key, value))
  164. elif not isinstance(value, str) and is_iterable(value):
  165. for item in value:
  166. if is_file(item):
  167. lines.extend(encode_file(boundary, key, item))
  168. else:
  169. lines.extend(to_bytes(val) for val in [
  170. '--%s' % boundary,
  171. 'Content-Disposition: form-data; name="%s"' % key,
  172. '',
  173. item
  174. ])
  175. else:
  176. lines.extend(to_bytes(val) for val in [
  177. '--%s' % boundary,
  178. 'Content-Disposition: form-data; name="%s"' % key,
  179. '',
  180. value
  181. ])
  182. lines.extend([
  183. to_bytes('--%s--' % boundary),
  184. b'',
  185. ])
  186. return b'\r\n'.join(lines)
  187. def encode_file(boundary, key, file):
  188. def to_bytes(s):
  189. return force_bytes(s, settings.DEFAULT_CHARSET)
  190. # file.name might not be a string. For example, it's an int for
  191. # tempfile.TemporaryFile().
  192. file_has_string_name = hasattr(file, 'name') and isinstance(file.name, str)
  193. filename = os.path.basename(file.name) if file_has_string_name else ''
  194. if hasattr(file, 'content_type'):
  195. content_type = file.content_type
  196. elif filename:
  197. content_type = mimetypes.guess_type(filename)[0]
  198. else:
  199. content_type = None
  200. if content_type is None:
  201. content_type = 'application/octet-stream'
  202. filename = filename or key
  203. return [
  204. to_bytes('--%s' % boundary),
  205. to_bytes('Content-Disposition: form-data; name="%s"; filename="%s"'
  206. % (key, filename)),
  207. to_bytes('Content-Type: %s' % content_type),
  208. b'',
  209. to_bytes(file.read())
  210. ]
  211. class RequestFactory:
  212. """
  213. Class that lets you create mock Request objects for use in testing.
  214. Usage:
  215. rf = RequestFactory()
  216. get_request = rf.get('/hello/')
  217. post_request = rf.post('/submit/', {'foo': 'bar'})
  218. Once you have a request object you can pass it to any view function,
  219. just as if that view had been hooked up using a URLconf.
  220. """
  221. def __init__(self, *, json_encoder=DjangoJSONEncoder, **defaults):
  222. self.json_encoder = json_encoder
  223. self.defaults = defaults
  224. self.cookies = SimpleCookie()
  225. self.errors = BytesIO()
  226. def _base_environ(self, **request):
  227. """
  228. The base environment for a request.
  229. """
  230. # This is a minimal valid WSGI environ dictionary, plus:
  231. # - HTTP_COOKIE: for cookie support,
  232. # - REMOTE_ADDR: often useful, see #8551.
  233. # See http://www.python.org/dev/peps/pep-3333/#environ-variables
  234. return {
  235. 'HTTP_COOKIE': self.cookies.output(header='', sep='; '),
  236. 'PATH_INFO': '/',
  237. 'REMOTE_ADDR': '127.0.0.1',
  238. 'REQUEST_METHOD': 'GET',
  239. 'SCRIPT_NAME': '',
  240. 'SERVER_NAME': 'testserver',
  241. 'SERVER_PORT': '80',
  242. 'SERVER_PROTOCOL': 'HTTP/1.1',
  243. 'wsgi.version': (1, 0),
  244. 'wsgi.url_scheme': 'http',
  245. 'wsgi.input': FakePayload(b''),
  246. 'wsgi.errors': self.errors,
  247. 'wsgi.multiprocess': True,
  248. 'wsgi.multithread': False,
  249. 'wsgi.run_once': False,
  250. **self.defaults,
  251. **request,
  252. }
  253. def request(self, **request):
  254. "Construct a generic request object."
  255. return WSGIRequest(self._base_environ(**request))
  256. def _encode_data(self, data, content_type):
  257. if content_type is MULTIPART_CONTENT:
  258. return encode_multipart(BOUNDARY, data)
  259. else:
  260. # Encode the content so that the byte representation is correct.
  261. match = CONTENT_TYPE_RE.match(content_type)
  262. if match:
  263. charset = match.group(1)
  264. else:
  265. charset = settings.DEFAULT_CHARSET
  266. return force_bytes(data, encoding=charset)
  267. def _encode_json(self, data, content_type):
  268. """
  269. Return encoded JSON if data is a dict and content_type is
  270. application/json.
  271. """
  272. should_encode = JSON_CONTENT_TYPE_RE.match(content_type) and isinstance(data, dict)
  273. return json.dumps(data, cls=self.json_encoder) if should_encode else data
  274. def _get_path(self, parsed):
  275. path = parsed.path
  276. # If there are parameters, add them
  277. if parsed.params:
  278. path += ";" + parsed.params
  279. path = unquote_to_bytes(path)
  280. # Replace the behavior where non-ASCII values in the WSGI environ are
  281. # arbitrarily decoded with ISO-8859-1.
  282. # Refs comment in `get_bytes_from_wsgi()`.
  283. return path.decode('iso-8859-1')
  284. def get(self, path, data=None, secure=False, **extra):
  285. """Construct a GET request."""
  286. data = {} if data is None else data
  287. return self.generic('GET', path, secure=secure, **{
  288. 'QUERY_STRING': urlencode(data, doseq=True),
  289. **extra,
  290. })
  291. def post(self, path, data=None, content_type=MULTIPART_CONTENT,
  292. secure=False, **extra):
  293. """Construct a POST request."""
  294. data = self._encode_json({} if data is None else data, content_type)
  295. post_data = self._encode_data(data, content_type)
  296. return self.generic('POST', path, post_data, content_type,
  297. secure=secure, **extra)
  298. def head(self, path, data=None, secure=False, **extra):
  299. """Construct a HEAD request."""
  300. data = {} if data is None else data
  301. return self.generic('HEAD', path, secure=secure, **{
  302. 'QUERY_STRING': urlencode(data, doseq=True),
  303. **extra,
  304. })
  305. def trace(self, path, secure=False, **extra):
  306. """Construct a TRACE request."""
  307. return self.generic('TRACE', path, secure=secure, **extra)
  308. def options(self, path, data='', content_type='application/octet-stream',
  309. secure=False, **extra):
  310. "Construct an OPTIONS request."
  311. return self.generic('OPTIONS', path, data, content_type,
  312. secure=secure, **extra)
  313. def put(self, path, data='', content_type='application/octet-stream',
  314. secure=False, **extra):
  315. """Construct a PUT request."""
  316. data = self._encode_json(data, content_type)
  317. return self.generic('PUT', path, data, content_type,
  318. secure=secure, **extra)
  319. def patch(self, path, data='', content_type='application/octet-stream',
  320. secure=False, **extra):
  321. """Construct a PATCH request."""
  322. data = self._encode_json(data, content_type)
  323. return self.generic('PATCH', path, data, content_type,
  324. secure=secure, **extra)
  325. def delete(self, path, data='', content_type='application/octet-stream',
  326. secure=False, **extra):
  327. """Construct a DELETE request."""
  328. data = self._encode_json(data, content_type)
  329. return self.generic('DELETE', path, data, content_type,
  330. secure=secure, **extra)
  331. def generic(self, method, path, data='',
  332. content_type='application/octet-stream', secure=False,
  333. **extra):
  334. """Construct an arbitrary HTTP request."""
  335. parsed = urlparse(str(path)) # path can be lazy
  336. data = force_bytes(data, settings.DEFAULT_CHARSET)
  337. r = {
  338. 'PATH_INFO': self._get_path(parsed),
  339. 'REQUEST_METHOD': method,
  340. 'SERVER_PORT': '443' if secure else '80',
  341. 'wsgi.url_scheme': 'https' if secure else 'http',
  342. }
  343. if data:
  344. r.update({
  345. 'CONTENT_LENGTH': len(data),
  346. 'CONTENT_TYPE': content_type,
  347. 'wsgi.input': FakePayload(data),
  348. })
  349. r.update(extra)
  350. # If QUERY_STRING is absent or empty, we want to extract it from the URL.
  351. if not r.get('QUERY_STRING'):
  352. # WSGI requires latin-1 encoded strings. See get_path_info().
  353. query_string = parsed[4].encode().decode('iso-8859-1')
  354. r['QUERY_STRING'] = query_string
  355. return self.request(**r)
  356. class Client(RequestFactory):
  357. """
  358. A class that can act as a client for testing purposes.
  359. It allows the user to compose GET and POST requests, and
  360. obtain the response that the server gave to those requests.
  361. The server Response objects are annotated with the details
  362. of the contexts and templates that were rendered during the
  363. process of serving the request.
  364. Client objects are stateful - they will retain cookie (and
  365. thus session) details for the lifetime of the Client instance.
  366. This is not intended as a replacement for Twill/Selenium or
  367. the like - it is here to allow testing against the
  368. contexts and templates produced by a view, rather than the
  369. HTML rendered to the end-user.
  370. """
  371. def __init__(self, enforce_csrf_checks=False, **defaults):
  372. super().__init__(**defaults)
  373. self.handler = ClientHandler(enforce_csrf_checks)
  374. self.exc_info = None
  375. def store_exc_info(self, **kwargs):
  376. """Store exceptions when they are generated by a view."""
  377. self.exc_info = sys.exc_info()
  378. @property
  379. def session(self):
  380. """Return the current session variables."""
  381. engine = import_module(settings.SESSION_ENGINE)
  382. cookie = self.cookies.get(settings.SESSION_COOKIE_NAME)
  383. if cookie:
  384. return engine.SessionStore(cookie.value)
  385. session = engine.SessionStore()
  386. session.save()
  387. self.cookies[settings.SESSION_COOKIE_NAME] = session.session_key
  388. return session
  389. def request(self, **request):
  390. """
  391. The master request method. Compose the environment dictionary and pass
  392. to the handler, return the result of the handler. Assume defaults for
  393. the query environment, which can be overridden using the arguments to
  394. the request.
  395. """
  396. environ = self._base_environ(**request)
  397. # Curry a data dictionary into an instance of the template renderer
  398. # callback function.
  399. data = {}
  400. on_template_render = partial(store_rendered_templates, data)
  401. signal_uid = "template-render-%s" % id(request)
  402. signals.template_rendered.connect(on_template_render, dispatch_uid=signal_uid)
  403. # Capture exceptions created by the handler.
  404. exception_uid = "request-exception-%s" % id(request)
  405. got_request_exception.connect(self.store_exc_info, dispatch_uid=exception_uid)
  406. try:
  407. try:
  408. response = self.handler(environ)
  409. except TemplateDoesNotExist as e:
  410. # If the view raises an exception, Django will attempt to show
  411. # the 500.html template. If that template is not available,
  412. # we should ignore the error in favor of re-raising the
  413. # underlying exception that caused the 500 error. Any other
  414. # template found to be missing during view error handling
  415. # should be reported as-is.
  416. if e.args != ('500.html',):
  417. raise
  418. # Look for a signalled exception, clear the current context
  419. # exception data, then re-raise the signalled exception.
  420. # Also make sure that the signalled exception is cleared from
  421. # the local cache!
  422. if self.exc_info:
  423. _, exc_value, _ = self.exc_info
  424. self.exc_info = None
  425. raise exc_value
  426. # Save the client and request that stimulated the response.
  427. response.client = self
  428. response.request = request
  429. # Add any rendered template detail to the response.
  430. response.templates = data.get("templates", [])
  431. response.context = data.get("context")
  432. response.json = partial(self._parse_json, response)
  433. # Attach the ResolverMatch instance to the response
  434. response.resolver_match = SimpleLazyObject(lambda: resolve(request['PATH_INFO']))
  435. # Flatten a single context. Not really necessary anymore thanks to
  436. # the __getattr__ flattening in ContextList, but has some edge-case
  437. # backwards-compatibility implications.
  438. if response.context and len(response.context) == 1:
  439. response.context = response.context[0]
  440. # Update persistent cookie data.
  441. if response.cookies:
  442. self.cookies.update(response.cookies)
  443. return response
  444. finally:
  445. signals.template_rendered.disconnect(dispatch_uid=signal_uid)
  446. got_request_exception.disconnect(dispatch_uid=exception_uid)
  447. def get(self, path, data=None, follow=False, secure=False, **extra):
  448. """Request a response from the server using GET."""
  449. response = super().get(path, data=data, secure=secure, **extra)
  450. if follow:
  451. response = self._handle_redirects(response, data=data, **extra)
  452. return response
  453. def post(self, path, data=None, content_type=MULTIPART_CONTENT,
  454. follow=False, secure=False, **extra):
  455. """Request a response from the server using POST."""
  456. response = super().post(path, data=data, content_type=content_type, secure=secure, **extra)
  457. if follow:
  458. response = self._handle_redirects(response, data=data, content_type=content_type, **extra)
  459. return response
  460. def head(self, path, data=None, follow=False, secure=False, **extra):
  461. """Request a response from the server using HEAD."""
  462. response = super().head(path, data=data, secure=secure, **extra)
  463. if follow:
  464. response = self._handle_redirects(response, data=data, **extra)
  465. return response
  466. def options(self, path, data='', content_type='application/octet-stream',
  467. follow=False, secure=False, **extra):
  468. """Request a response from the server using OPTIONS."""
  469. response = super().options(path, data=data, content_type=content_type, secure=secure, **extra)
  470. if follow:
  471. response = self._handle_redirects(response, data=data, content_type=content_type, **extra)
  472. return response
  473. def put(self, path, data='', content_type='application/octet-stream',
  474. follow=False, secure=False, **extra):
  475. """Send a resource to the server using PUT."""
  476. response = super().put(path, data=data, content_type=content_type, secure=secure, **extra)
  477. if follow:
  478. response = self._handle_redirects(response, data=data, content_type=content_type, **extra)
  479. return response
  480. def patch(self, path, data='', content_type='application/octet-stream',
  481. follow=False, secure=False, **extra):
  482. """Send a resource to the server using PATCH."""
  483. response = super().patch(path, data=data, content_type=content_type, secure=secure, **extra)
  484. if follow:
  485. response = self._handle_redirects(response, data=data, content_type=content_type, **extra)
  486. return response
  487. def delete(self, path, data='', content_type='application/octet-stream',
  488. follow=False, secure=False, **extra):
  489. """Send a DELETE request to the server."""
  490. response = super().delete(path, data=data, content_type=content_type, secure=secure, **extra)
  491. if follow:
  492. response = self._handle_redirects(response, data=data, content_type=content_type, **extra)
  493. return response
  494. def trace(self, path, data='', follow=False, secure=False, **extra):
  495. """Send a TRACE request to the server."""
  496. response = super().trace(path, data=data, secure=secure, **extra)
  497. if follow:
  498. response = self._handle_redirects(response, data=data, **extra)
  499. return response
  500. def login(self, **credentials):
  501. """
  502. Set the Factory to appear as if it has successfully logged into a site.
  503. Return True if login is possible; False if the provided credentials
  504. are incorrect.
  505. """
  506. from django.contrib.auth import authenticate
  507. user = authenticate(**credentials)
  508. if user:
  509. self._login(user)
  510. return True
  511. else:
  512. return False
  513. def force_login(self, user, backend=None):
  514. def get_backend():
  515. from django.contrib.auth import load_backend
  516. for backend_path in settings.AUTHENTICATION_BACKENDS:
  517. backend = load_backend(backend_path)
  518. if hasattr(backend, 'get_user'):
  519. return backend_path
  520. if backend is None:
  521. backend = get_backend()
  522. user.backend = backend
  523. self._login(user, backend)
  524. def _login(self, user, backend=None):
  525. from django.contrib.auth import login
  526. engine = import_module(settings.SESSION_ENGINE)
  527. # Create a fake request to store login details.
  528. request = HttpRequest()
  529. if self.session:
  530. request.session = self.session
  531. else:
  532. request.session = engine.SessionStore()
  533. login(request, user, backend)
  534. # Save the session values.
  535. request.session.save()
  536. # Set the cookie to represent the session.
  537. session_cookie = settings.SESSION_COOKIE_NAME
  538. self.cookies[session_cookie] = request.session.session_key
  539. cookie_data = {
  540. 'max-age': None,
  541. 'path': '/',
  542. 'domain': settings.SESSION_COOKIE_DOMAIN,
  543. 'secure': settings.SESSION_COOKIE_SECURE or None,
  544. 'expires': None,
  545. }
  546. self.cookies[session_cookie].update(cookie_data)
  547. def logout(self):
  548. """Log out the user by removing the cookies and session object."""
  549. from django.contrib.auth import get_user, logout
  550. request = HttpRequest()
  551. engine = import_module(settings.SESSION_ENGINE)
  552. if self.session:
  553. request.session = self.session
  554. request.user = get_user(request)
  555. else:
  556. request.session = engine.SessionStore()
  557. logout(request)
  558. self.cookies = SimpleCookie()
  559. def _parse_json(self, response, **extra):
  560. if not hasattr(response, '_json'):
  561. if not JSON_CONTENT_TYPE_RE.match(response.get('Content-Type')):
  562. raise ValueError(
  563. 'Content-Type header is "{0}", not "application/json"'
  564. .format(response.get('Content-Type'))
  565. )
  566. response._json = json.loads(response.content.decode(), **extra)
  567. return response._json
  568. def _handle_redirects(self, response, data='', content_type='', **extra):
  569. """
  570. Follow any redirects by requesting responses from the server using GET.
  571. """
  572. response.redirect_chain = []
  573. redirect_status_codes = (
  574. HTTPStatus.MOVED_PERMANENTLY,
  575. HTTPStatus.FOUND,
  576. HTTPStatus.SEE_OTHER,
  577. HTTPStatus.TEMPORARY_REDIRECT,
  578. HTTPStatus.PERMANENT_REDIRECT,
  579. )
  580. while response.status_code in redirect_status_codes:
  581. response_url = response.url
  582. redirect_chain = response.redirect_chain
  583. redirect_chain.append((response_url, response.status_code))
  584. url = urlsplit(response_url)
  585. if url.scheme:
  586. extra['wsgi.url_scheme'] = url.scheme
  587. if url.hostname:
  588. extra['SERVER_NAME'] = url.hostname
  589. if url.port:
  590. extra['SERVER_PORT'] = str(url.port)
  591. # Prepend the request path to handle relative path redirects
  592. path = url.path
  593. if not path.startswith('/'):
  594. path = urljoin(response.request['PATH_INFO'], path)
  595. if response.status_code in (HTTPStatus.TEMPORARY_REDIRECT, HTTPStatus.PERMANENT_REDIRECT):
  596. # Preserve request method post-redirect for 307/308 responses.
  597. request_method = getattr(self, response.request['REQUEST_METHOD'].lower())
  598. else:
  599. request_method = self.get
  600. data = QueryDict(url.query)
  601. content_type = None
  602. response = request_method(path, data=data, content_type=content_type, follow=False, **extra)
  603. response.redirect_chain = redirect_chain
  604. if redirect_chain[-1] in redirect_chain[:-1]:
  605. # Check that we're not redirecting to somewhere we've already
  606. # been to, to prevent loops.
  607. raise RedirectCycleError("Redirect loop detected.", last_response=response)
  608. if len(redirect_chain) > 20:
  609. # Such a lengthy chain likely also means a loop, but one with
  610. # a growing path, changing view, or changing query argument;
  611. # 20 is the value of "network.http.redirection-limit" from Firefox.
  612. raise RedirectCycleError("Too many redirects.", last_response=response)
  613. return response