client.py 28 KB

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