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

5 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724
  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 value is None:
  163. raise TypeError(
  164. 'Cannot encode None as POST data. Did you mean to pass an '
  165. 'empty string or omit the value?'
  166. )
  167. elif is_file(value):
  168. lines.extend(encode_file(boundary, key, value))
  169. elif not isinstance(value, str) and is_iterable(value):
  170. for item in value:
  171. if is_file(item):
  172. lines.extend(encode_file(boundary, key, item))
  173. else:
  174. lines.extend(to_bytes(val) for val in [
  175. '--%s' % boundary,
  176. 'Content-Disposition: form-data; name="%s"' % key,
  177. '',
  178. item
  179. ])
  180. else:
  181. lines.extend(to_bytes(val) for val in [
  182. '--%s' % boundary,
  183. 'Content-Disposition: form-data; name="%s"' % key,
  184. '',
  185. value
  186. ])
  187. lines.extend([
  188. to_bytes('--%s--' % boundary),
  189. b'',
  190. ])
  191. return b'\r\n'.join(lines)
  192. def encode_file(boundary, key, file):
  193. def to_bytes(s):
  194. return force_bytes(s, settings.DEFAULT_CHARSET)
  195. # file.name might not be a string. For example, it's an int for
  196. # tempfile.TemporaryFile().
  197. file_has_string_name = hasattr(file, 'name') and isinstance(file.name, str)
  198. filename = os.path.basename(file.name) if file_has_string_name else ''
  199. if hasattr(file, 'content_type'):
  200. content_type = file.content_type
  201. elif filename:
  202. content_type = mimetypes.guess_type(filename)[0]
  203. else:
  204. content_type = None
  205. if content_type is None:
  206. content_type = 'application/octet-stream'
  207. filename = filename or key
  208. return [
  209. to_bytes('--%s' % boundary),
  210. to_bytes('Content-Disposition: form-data; name="%s"; filename="%s"'
  211. % (key, filename)),
  212. to_bytes('Content-Type: %s' % content_type),
  213. b'',
  214. to_bytes(file.read())
  215. ]
  216. class RequestFactory:
  217. """
  218. Class that lets you create mock Request objects for use in testing.
  219. Usage:
  220. rf = RequestFactory()
  221. get_request = rf.get('/hello/')
  222. post_request = rf.post('/submit/', {'foo': 'bar'})
  223. Once you have a request object you can pass it to any view function,
  224. just as if that view had been hooked up using a URLconf.
  225. """
  226. def __init__(self, *, json_encoder=DjangoJSONEncoder, **defaults):
  227. self.json_encoder = json_encoder
  228. self.defaults = defaults
  229. self.cookies = SimpleCookie()
  230. self.errors = BytesIO()
  231. def _base_environ(self, **request):
  232. """
  233. The base environment for a request.
  234. """
  235. # This is a minimal valid WSGI environ dictionary, plus:
  236. # - HTTP_COOKIE: for cookie support,
  237. # - REMOTE_ADDR: often useful, see #8551.
  238. # See https://www.python.org/dev/peps/pep-3333/#environ-variables
  239. return {
  240. 'HTTP_COOKIE': '; '.join(sorted(
  241. '%s=%s' % (morsel.key, morsel.coded_value)
  242. for morsel in self.cookies.values()
  243. )),
  244. 'PATH_INFO': '/',
  245. 'REMOTE_ADDR': '127.0.0.1',
  246. 'REQUEST_METHOD': 'GET',
  247. 'SCRIPT_NAME': '',
  248. 'SERVER_NAME': 'testserver',
  249. 'SERVER_PORT': '80',
  250. 'SERVER_PROTOCOL': 'HTTP/1.1',
  251. 'wsgi.version': (1, 0),
  252. 'wsgi.url_scheme': 'http',
  253. 'wsgi.input': FakePayload(b''),
  254. 'wsgi.errors': self.errors,
  255. 'wsgi.multiprocess': True,
  256. 'wsgi.multithread': False,
  257. 'wsgi.run_once': False,
  258. **self.defaults,
  259. **request,
  260. }
  261. def request(self, **request):
  262. "Construct a generic request object."
  263. return WSGIRequest(self._base_environ(**request))
  264. def _encode_data(self, data, content_type):
  265. if content_type is MULTIPART_CONTENT:
  266. return encode_multipart(BOUNDARY, data)
  267. else:
  268. # Encode the content so that the byte representation is correct.
  269. match = CONTENT_TYPE_RE.match(content_type)
  270. if match:
  271. charset = match.group(1)
  272. else:
  273. charset = settings.DEFAULT_CHARSET
  274. return force_bytes(data, encoding=charset)
  275. def _encode_json(self, data, content_type):
  276. """
  277. Return encoded JSON if data is a dict, list, or tuple and content_type
  278. is application/json.
  279. """
  280. should_encode = JSON_CONTENT_TYPE_RE.match(content_type) and isinstance(data, (dict, list, tuple))
  281. return json.dumps(data, cls=self.json_encoder) if should_encode else data
  282. def _get_path(self, parsed):
  283. path = parsed.path
  284. # If there are parameters, add them
  285. if parsed.params:
  286. path += ";" + parsed.params
  287. path = unquote_to_bytes(path)
  288. # Replace the behavior where non-ASCII values in the WSGI environ are
  289. # arbitrarily decoded with ISO-8859-1.
  290. # Refs comment in `get_bytes_from_wsgi()`.
  291. return path.decode('iso-8859-1')
  292. def get(self, path, data=None, secure=False, **extra):
  293. """Construct a GET request."""
  294. data = {} if data is None else data
  295. return self.generic('GET', path, secure=secure, **{
  296. 'QUERY_STRING': urlencode(data, doseq=True),
  297. **extra,
  298. })
  299. def post(self, path, data=None, content_type=MULTIPART_CONTENT,
  300. secure=False, **extra):
  301. """Construct a POST request."""
  302. data = self._encode_json({} if data is None else data, content_type)
  303. post_data = self._encode_data(data, content_type)
  304. return self.generic('POST', path, post_data, content_type,
  305. secure=secure, **extra)
  306. def head(self, path, data=None, secure=False, **extra):
  307. """Construct a HEAD request."""
  308. data = {} if data is None else data
  309. return self.generic('HEAD', path, secure=secure, **{
  310. 'QUERY_STRING': urlencode(data, doseq=True),
  311. **extra,
  312. })
  313. def trace(self, path, secure=False, **extra):
  314. """Construct a TRACE request."""
  315. return self.generic('TRACE', path, secure=secure, **extra)
  316. def options(self, path, data='', content_type='application/octet-stream',
  317. secure=False, **extra):
  318. "Construct an OPTIONS request."
  319. return self.generic('OPTIONS', path, data, content_type,
  320. secure=secure, **extra)
  321. def put(self, path, data='', content_type='application/octet-stream',
  322. secure=False, **extra):
  323. """Construct a PUT request."""
  324. data = self._encode_json(data, content_type)
  325. return self.generic('PUT', path, data, content_type,
  326. secure=secure, **extra)
  327. def patch(self, path, data='', content_type='application/octet-stream',
  328. secure=False, **extra):
  329. """Construct a PATCH request."""
  330. data = self._encode_json(data, content_type)
  331. return self.generic('PATCH', path, data, content_type,
  332. secure=secure, **extra)
  333. def delete(self, path, data='', content_type='application/octet-stream',
  334. secure=False, **extra):
  335. """Construct a DELETE request."""
  336. data = self._encode_json(data, content_type)
  337. return self.generic('DELETE', path, data, content_type,
  338. secure=secure, **extra)
  339. def generic(self, method, path, data='',
  340. content_type='application/octet-stream', secure=False,
  341. **extra):
  342. """Construct an arbitrary HTTP request."""
  343. parsed = urlparse(str(path)) # path can be lazy
  344. data = force_bytes(data, settings.DEFAULT_CHARSET)
  345. r = {
  346. 'PATH_INFO': self._get_path(parsed),
  347. 'REQUEST_METHOD': method,
  348. 'SERVER_PORT': '443' if secure else '80',
  349. 'wsgi.url_scheme': 'https' if secure else 'http',
  350. }
  351. if data:
  352. r.update({
  353. 'CONTENT_LENGTH': str(len(data)),
  354. 'CONTENT_TYPE': content_type,
  355. 'wsgi.input': FakePayload(data),
  356. })
  357. r.update(extra)
  358. # If QUERY_STRING is absent or empty, we want to extract it from the URL.
  359. if not r.get('QUERY_STRING'):
  360. # WSGI requires latin-1 encoded strings. See get_path_info().
  361. query_string = parsed[4].encode().decode('iso-8859-1')
  362. r['QUERY_STRING'] = query_string
  363. return self.request(**r)
  364. class Client(RequestFactory):
  365. """
  366. A class that can act as a client for testing purposes.
  367. It allows the user to compose GET and POST requests, and
  368. obtain the response that the server gave to those requests.
  369. The server Response objects are annotated with the details
  370. of the contexts and templates that were rendered during the
  371. process of serving the request.
  372. Client objects are stateful - they will retain cookie (and
  373. thus session) details for the lifetime of the Client instance.
  374. This is not intended as a replacement for Twill/Selenium or
  375. the like - it is here to allow testing against the
  376. contexts and templates produced by a view, rather than the
  377. HTML rendered to the end-user.
  378. """
  379. def __init__(self, enforce_csrf_checks=False, **defaults):
  380. super().__init__(**defaults)
  381. self.handler = ClientHandler(enforce_csrf_checks)
  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. try:
  416. response = self.handler(environ)
  417. except TemplateDoesNotExist as e:
  418. # If the view raises an exception, Django will attempt to show
  419. # the 500.html template. If that template is not available,
  420. # we should ignore the error in favor of re-raising the
  421. # underlying exception that caused the 500 error. Any other
  422. # template found to be missing during view error handling
  423. # should be reported as-is.
  424. if e.args != ('500.html',):
  425. raise
  426. # Look for a signalled exception, clear the current context
  427. # exception data, then re-raise the signalled exception.
  428. # Also make sure that the signalled exception is cleared from
  429. # the local cache!
  430. if self.exc_info:
  431. _, exc_value, _ = self.exc_info
  432. self.exc_info = None
  433. raise exc_value
  434. # Save the client and request that stimulated the response.
  435. response.client = self
  436. response.request = request
  437. # Add any rendered template detail to the response.
  438. response.templates = data.get("templates", [])
  439. response.context = data.get("context")
  440. response.json = partial(self._parse_json, response)
  441. # Attach the ResolverMatch instance to the response
  442. response.resolver_match = SimpleLazyObject(lambda: resolve(request['PATH_INFO']))
  443. # Flatten a single context. Not really necessary anymore thanks to
  444. # the __getattr__ flattening in ContextList, but has some edge-case
  445. # backwards-compatibility implications.
  446. if response.context and len(response.context) == 1:
  447. response.context = response.context[0]
  448. # Update persistent cookie data.
  449. if response.cookies:
  450. self.cookies.update(response.cookies)
  451. return response
  452. finally:
  453. signals.template_rendered.disconnect(dispatch_uid=signal_uid)
  454. got_request_exception.disconnect(dispatch_uid=exception_uid)
  455. def get(self, path, data=None, follow=False, secure=False, **extra):
  456. """Request a response from the server using GET."""
  457. response = super().get(path, data=data, secure=secure, **extra)
  458. if follow:
  459. response = self._handle_redirects(response, data=data, **extra)
  460. return response
  461. def post(self, path, data=None, content_type=MULTIPART_CONTENT,
  462. follow=False, secure=False, **extra):
  463. """Request a response from the server using POST."""
  464. response = super().post(path, data=data, content_type=content_type, secure=secure, **extra)
  465. if follow:
  466. response = self._handle_redirects(response, data=data, content_type=content_type, **extra)
  467. return response
  468. def head(self, path, data=None, follow=False, secure=False, **extra):
  469. """Request a response from the server using HEAD."""
  470. response = super().head(path, data=data, secure=secure, **extra)
  471. if follow:
  472. response = self._handle_redirects(response, data=data, **extra)
  473. return response
  474. def options(self, path, data='', content_type='application/octet-stream',
  475. follow=False, secure=False, **extra):
  476. """Request a response from the server using OPTIONS."""
  477. response = super().options(path, data=data, content_type=content_type, secure=secure, **extra)
  478. if follow:
  479. response = self._handle_redirects(response, data=data, content_type=content_type, **extra)
  480. return response
  481. def put(self, path, data='', content_type='application/octet-stream',
  482. follow=False, secure=False, **extra):
  483. """Send a resource to the server using PUT."""
  484. response = super().put(path, data=data, content_type=content_type, secure=secure, **extra)
  485. if follow:
  486. response = self._handle_redirects(response, data=data, content_type=content_type, **extra)
  487. return response
  488. def patch(self, path, data='', content_type='application/octet-stream',
  489. follow=False, secure=False, **extra):
  490. """Send a resource to the server using PATCH."""
  491. response = super().patch(path, data=data, content_type=content_type, secure=secure, **extra)
  492. if follow:
  493. response = self._handle_redirects(response, data=data, content_type=content_type, **extra)
  494. return response
  495. def delete(self, path, data='', content_type='application/octet-stream',
  496. follow=False, secure=False, **extra):
  497. """Send a DELETE request to the server."""
  498. response = super().delete(path, data=data, content_type=content_type, secure=secure, **extra)
  499. if follow:
  500. response = self._handle_redirects(response, data=data, content_type=content_type, **extra)
  501. return response
  502. def trace(self, path, data='', follow=False, secure=False, **extra):
  503. """Send a TRACE request to the server."""
  504. response = super().trace(path, data=data, secure=secure, **extra)
  505. if follow:
  506. response = self._handle_redirects(response, data=data, **extra)
  507. return response
  508. def login(self, **credentials):
  509. """
  510. Set the Factory to appear as if it has successfully logged into a site.
  511. Return True if login is possible; False if the provided credentials
  512. are incorrect.
  513. """
  514. from django.contrib.auth import authenticate
  515. user = authenticate(**credentials)
  516. if user:
  517. self._login(user)
  518. return True
  519. else:
  520. return False
  521. def force_login(self, user, backend=None):
  522. def get_backend():
  523. from django.contrib.auth import load_backend
  524. for backend_path in settings.AUTHENTICATION_BACKENDS:
  525. backend = load_backend(backend_path)
  526. if hasattr(backend, 'get_user'):
  527. return backend_path
  528. if backend is None:
  529. backend = get_backend()
  530. user.backend = backend
  531. self._login(user, backend)
  532. def _login(self, user, backend=None):
  533. from django.contrib.auth import login
  534. engine = import_module(settings.SESSION_ENGINE)
  535. # Create a fake request to store login details.
  536. request = HttpRequest()
  537. if self.session:
  538. request.session = self.session
  539. else:
  540. request.session = engine.SessionStore()
  541. login(request, user, backend)
  542. # Save the session values.
  543. request.session.save()
  544. # Set the cookie to represent the session.
  545. session_cookie = settings.SESSION_COOKIE_NAME
  546. self.cookies[session_cookie] = request.session.session_key
  547. cookie_data = {
  548. 'max-age': None,
  549. 'path': '/',
  550. 'domain': settings.SESSION_COOKIE_DOMAIN,
  551. 'secure': settings.SESSION_COOKIE_SECURE or None,
  552. 'expires': None,
  553. }
  554. self.cookies[session_cookie].update(cookie_data)
  555. def logout(self):
  556. """Log out the user by removing the cookies and session object."""
  557. from django.contrib.auth import get_user, logout
  558. request = HttpRequest()
  559. engine = import_module(settings.SESSION_ENGINE)
  560. if self.session:
  561. request.session = self.session
  562. request.user = get_user(request)
  563. else:
  564. request.session = engine.SessionStore()
  565. logout(request)
  566. self.cookies = SimpleCookie()
  567. def _parse_json(self, response, **extra):
  568. if not hasattr(response, '_json'):
  569. if not JSON_CONTENT_TYPE_RE.match(response.get('Content-Type')):
  570. raise ValueError(
  571. 'Content-Type header is "{0}", not "application/json"'
  572. .format(response.get('Content-Type'))
  573. )
  574. response._json = json.loads(response.content.decode(), **extra)
  575. return response._json
  576. def _handle_redirects(self, response, data='', content_type='', **extra):
  577. """
  578. Follow any redirects by requesting responses from the server using GET.
  579. """
  580. response.redirect_chain = []
  581. redirect_status_codes = (
  582. HTTPStatus.MOVED_PERMANENTLY,
  583. HTTPStatus.FOUND,
  584. HTTPStatus.SEE_OTHER,
  585. HTTPStatus.TEMPORARY_REDIRECT,
  586. HTTPStatus.PERMANENT_REDIRECT,
  587. )
  588. while response.status_code in redirect_status_codes:
  589. response_url = response.url
  590. redirect_chain = response.redirect_chain
  591. redirect_chain.append((response_url, response.status_code))
  592. url = urlsplit(response_url)
  593. if url.scheme:
  594. extra['wsgi.url_scheme'] = url.scheme
  595. if url.hostname:
  596. extra['SERVER_NAME'] = url.hostname
  597. if url.port:
  598. extra['SERVER_PORT'] = str(url.port)
  599. # Prepend the request path to handle relative path redirects
  600. path = url.path
  601. if not path.startswith('/'):
  602. path = urljoin(response.request['PATH_INFO'], path)
  603. if response.status_code in (HTTPStatus.TEMPORARY_REDIRECT, HTTPStatus.PERMANENT_REDIRECT):
  604. # Preserve request method post-redirect for 307/308 responses.
  605. request_method = getattr(self, response.request['REQUEST_METHOD'].lower())
  606. else:
  607. request_method = self.get
  608. data = QueryDict(url.query)
  609. content_type = None
  610. response = request_method(path, data=data, content_type=content_type, follow=False, **extra)
  611. response.redirect_chain = redirect_chain
  612. if redirect_chain[-1] in redirect_chain[:-1]:
  613. # Check that we're not redirecting to somewhere we've already
  614. # been to, to prevent loops.
  615. raise RedirectCycleError("Redirect loop detected.", last_response=response)
  616. if len(redirect_chain) > 20:
  617. # Such a lengthy chain likely also means a loop, but one with
  618. # a growing path, changing view, or changing query argument;
  619. # 20 is the value of "network.http.redirection-limit" from Firefox.
  620. raise RedirectCycleError("Too many redirects.", last_response=response)
  621. return response