response.py 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606
  1. import datetime
  2. import json
  3. import mimetypes
  4. import os
  5. import re
  6. import sys
  7. import time
  8. from collections.abc import Mapping
  9. from email.header import Header
  10. from http.client import responses
  11. from urllib.parse import quote, urlparse
  12. from django.conf import settings
  13. from django.core import signals, signing
  14. from django.core.exceptions import DisallowedRedirect
  15. from django.core.serializers.json import DjangoJSONEncoder
  16. from django.http.cookie import SimpleCookie
  17. from django.utils import timezone
  18. from django.utils.datastructures import (
  19. CaseInsensitiveMapping, _destruct_iterable_mapping_values,
  20. )
  21. from django.utils.encoding import iri_to_uri
  22. from django.utils.http import http_date
  23. from django.utils.regex_helper import _lazy_re_compile
  24. _charset_from_content_type_re = _lazy_re_compile(r';\s*charset=(?P<charset>[^\s;]+)', re.I)
  25. class ResponseHeaders(CaseInsensitiveMapping):
  26. def __init__(self, data):
  27. """
  28. Populate the initial data using __setitem__ to ensure values are
  29. correctly encoded.
  30. """
  31. if not isinstance(data, Mapping):
  32. data = {k: v for k, v in _destruct_iterable_mapping_values(data)}
  33. self._store = {}
  34. for header, value in data.items():
  35. self[header] = value
  36. def _convert_to_charset(self, value, charset, mime_encode=False):
  37. """
  38. Convert headers key/value to ascii/latin-1 native strings.
  39. `charset` must be 'ascii' or 'latin-1'. If `mime_encode` is True and
  40. `value` can't be represented in the given charset, apply MIME-encoding.
  41. """
  42. if not isinstance(value, (bytes, str)):
  43. value = str(value)
  44. if (
  45. (isinstance(value, bytes) and (b'\n' in value or b'\r' in value)) or
  46. (isinstance(value, str) and ('\n' in value or '\r' in value))
  47. ):
  48. raise BadHeaderError("Header values can't contain newlines (got %r)" % value)
  49. try:
  50. if isinstance(value, str):
  51. # Ensure string is valid in given charset
  52. value.encode(charset)
  53. else:
  54. # Convert bytestring using given charset
  55. value = value.decode(charset)
  56. except UnicodeError as e:
  57. if mime_encode:
  58. value = Header(value, 'utf-8', maxlinelen=sys.maxsize).encode()
  59. else:
  60. e.reason += ', HTTP response headers must be in %s format' % charset
  61. raise
  62. return value
  63. def __delitem__(self, key):
  64. self.pop(key)
  65. def __setitem__(self, key, value):
  66. key = self._convert_to_charset(key, 'ascii')
  67. value = self._convert_to_charset(value, 'latin-1', mime_encode=True)
  68. self._store[key.lower()] = (key, value)
  69. def pop(self, key, default=None):
  70. return self._store.pop(key.lower(), default)
  71. def setdefault(self, key, value):
  72. if key not in self:
  73. self[key] = value
  74. class BadHeaderError(ValueError):
  75. pass
  76. class HttpResponseBase:
  77. """
  78. An HTTP response base class with dictionary-accessed headers.
  79. This class doesn't handle content. It should not be used directly.
  80. Use the HttpResponse and StreamingHttpResponse subclasses instead.
  81. """
  82. status_code = 200
  83. def __init__(self, content_type=None, status=None, reason=None, charset=None, headers=None):
  84. self.headers = ResponseHeaders(headers or {})
  85. self._charset = charset
  86. if content_type and 'Content-Type' in self.headers:
  87. raise ValueError(
  88. "'headers' must not contain 'Content-Type' when the "
  89. "'content_type' parameter is provided."
  90. )
  91. if 'Content-Type' not in self.headers:
  92. if content_type is None:
  93. content_type = 'text/html; charset=%s' % self.charset
  94. self.headers['Content-Type'] = content_type
  95. self._resource_closers = []
  96. # This parameter is set by the handler. It's necessary to preserve the
  97. # historical behavior of request_finished.
  98. self._handler_class = None
  99. self.cookies = SimpleCookie()
  100. self.closed = False
  101. if status is not None:
  102. try:
  103. self.status_code = int(status)
  104. except (ValueError, TypeError):
  105. raise TypeError('HTTP status code must be an integer.')
  106. if not 100 <= self.status_code <= 599:
  107. raise ValueError('HTTP status code must be an integer from 100 to 599.')
  108. self._reason_phrase = reason
  109. @property
  110. def reason_phrase(self):
  111. if self._reason_phrase is not None:
  112. return self._reason_phrase
  113. # Leave self._reason_phrase unset in order to use the default
  114. # reason phrase for status code.
  115. return responses.get(self.status_code, 'Unknown Status Code')
  116. @reason_phrase.setter
  117. def reason_phrase(self, value):
  118. self._reason_phrase = value
  119. @property
  120. def charset(self):
  121. if self._charset is not None:
  122. return self._charset
  123. content_type = self.get('Content-Type', '')
  124. matched = _charset_from_content_type_re.search(content_type)
  125. if matched:
  126. # Extract the charset and strip its double quotes
  127. return matched['charset'].replace('"', '')
  128. return settings.DEFAULT_CHARSET
  129. @charset.setter
  130. def charset(self, value):
  131. self._charset = value
  132. def serialize_headers(self):
  133. """HTTP headers as a bytestring."""
  134. def to_bytes(val, encoding):
  135. return val if isinstance(val, bytes) else val.encode(encoding)
  136. headers = [
  137. (to_bytes(key, 'ascii') + b': ' + to_bytes(value, 'latin-1'))
  138. for key, value in self.headers.items()
  139. ]
  140. return b'\r\n'.join(headers)
  141. __bytes__ = serialize_headers
  142. @property
  143. def _content_type_for_repr(self):
  144. return ', "%s"' % self.headers['Content-Type'] if 'Content-Type' in self.headers else ''
  145. def __setitem__(self, header, value):
  146. self.headers[header] = value
  147. def __delitem__(self, header):
  148. del self.headers[header]
  149. def __getitem__(self, header):
  150. return self.headers[header]
  151. def has_header(self, header):
  152. """Case-insensitive check for a header."""
  153. return header in self.headers
  154. __contains__ = has_header
  155. def items(self):
  156. return self.headers.items()
  157. def get(self, header, alternate=None):
  158. return self.headers.get(header, alternate)
  159. def set_cookie(self, key, value='', max_age=None, expires=None, path='/',
  160. domain=None, secure=False, httponly=False, samesite=None):
  161. """
  162. Set a cookie.
  163. ``expires`` can be:
  164. - a string in the correct format,
  165. - a naive ``datetime.datetime`` object in UTC,
  166. - an aware ``datetime.datetime`` object in any time zone.
  167. If it is a ``datetime.datetime`` object then calculate ``max_age``.
  168. """
  169. self.cookies[key] = value
  170. if expires is not None:
  171. if isinstance(expires, datetime.datetime):
  172. if timezone.is_aware(expires):
  173. expires = timezone.make_naive(expires, timezone.utc)
  174. delta = expires - expires.utcnow()
  175. # Add one second so the date matches exactly (a fraction of
  176. # time gets lost between converting to a timedelta and
  177. # then the date string).
  178. delta = delta + datetime.timedelta(seconds=1)
  179. # Just set max_age - the max_age logic will set expires.
  180. expires = None
  181. max_age = max(0, delta.days * 86400 + delta.seconds)
  182. else:
  183. self.cookies[key]['expires'] = expires
  184. else:
  185. self.cookies[key]['expires'] = ''
  186. if max_age is not None:
  187. self.cookies[key]['max-age'] = int(max_age)
  188. # IE requires expires, so set it if hasn't been already.
  189. if not expires:
  190. self.cookies[key]['expires'] = http_date(time.time() + max_age)
  191. if path is not None:
  192. self.cookies[key]['path'] = path
  193. if domain is not None:
  194. self.cookies[key]['domain'] = domain
  195. if secure:
  196. self.cookies[key]['secure'] = True
  197. if httponly:
  198. self.cookies[key]['httponly'] = True
  199. if samesite:
  200. if samesite.lower() not in ('lax', 'none', 'strict'):
  201. raise ValueError('samesite must be "lax", "none", or "strict".')
  202. self.cookies[key]['samesite'] = samesite
  203. def setdefault(self, key, value):
  204. """Set a header unless it has already been set."""
  205. self.headers.setdefault(key, value)
  206. def set_signed_cookie(self, key, value, salt='', **kwargs):
  207. value = signing.get_cookie_signer(salt=key + salt).sign(value)
  208. return self.set_cookie(key, value, **kwargs)
  209. def delete_cookie(self, key, path='/', domain=None, samesite=None):
  210. # Browsers can ignore the Set-Cookie header if the cookie doesn't use
  211. # the secure flag and:
  212. # - the cookie name starts with "__Host-" or "__Secure-", or
  213. # - the samesite is "none".
  214. secure = (
  215. key.startswith(('__Secure-', '__Host-')) or
  216. (samesite and samesite.lower() == 'none')
  217. )
  218. self.set_cookie(
  219. key, max_age=0, path=path, domain=domain, secure=secure,
  220. expires='Thu, 01 Jan 1970 00:00:00 GMT', samesite=samesite,
  221. )
  222. # Common methods used by subclasses
  223. def make_bytes(self, value):
  224. """Turn a value into a bytestring encoded in the output charset."""
  225. # Per PEP 3333, this response body must be bytes. To avoid returning
  226. # an instance of a subclass, this function returns `bytes(value)`.
  227. # This doesn't make a copy when `value` already contains bytes.
  228. # Handle string types -- we can't rely on force_bytes here because:
  229. # - Python attempts str conversion first
  230. # - when self._charset != 'utf-8' it re-encodes the content
  231. if isinstance(value, (bytes, memoryview)):
  232. return bytes(value)
  233. if isinstance(value, str):
  234. return bytes(value.encode(self.charset))
  235. # Handle non-string types.
  236. return str(value).encode(self.charset)
  237. # These methods partially implement the file-like object interface.
  238. # See https://docs.python.org/library/io.html#io.IOBase
  239. # The WSGI server must call this method upon completion of the request.
  240. # See http://blog.dscpl.com.au/2012/10/obligations-for-calling-close-on.html
  241. def close(self):
  242. for closer in self._resource_closers:
  243. try:
  244. closer()
  245. except Exception:
  246. pass
  247. # Free resources that were still referenced.
  248. self._resource_closers.clear()
  249. self.closed = True
  250. signals.request_finished.send(sender=self._handler_class)
  251. def write(self, content):
  252. raise OSError('This %s instance is not writable' % self.__class__.__name__)
  253. def flush(self):
  254. pass
  255. def tell(self):
  256. raise OSError('This %s instance cannot tell its position' % self.__class__.__name__)
  257. # These methods partially implement a stream-like object interface.
  258. # See https://docs.python.org/library/io.html#io.IOBase
  259. def readable(self):
  260. return False
  261. def seekable(self):
  262. return False
  263. def writable(self):
  264. return False
  265. def writelines(self, lines):
  266. raise OSError('This %s instance is not writable' % self.__class__.__name__)
  267. class HttpResponse(HttpResponseBase):
  268. """
  269. An HTTP response class with a string as content.
  270. This content can be read, appended to, or replaced.
  271. """
  272. streaming = False
  273. def __init__(self, content=b'', *args, **kwargs):
  274. super().__init__(*args, **kwargs)
  275. # Content is a bytestring. See the `content` property methods.
  276. self.content = content
  277. def __repr__(self):
  278. return '<%(cls)s status_code=%(status_code)d%(content_type)s>' % {
  279. 'cls': self.__class__.__name__,
  280. 'status_code': self.status_code,
  281. 'content_type': self._content_type_for_repr,
  282. }
  283. def serialize(self):
  284. """Full HTTP message, including headers, as a bytestring."""
  285. return self.serialize_headers() + b'\r\n\r\n' + self.content
  286. __bytes__ = serialize
  287. @property
  288. def content(self):
  289. return b''.join(self._container)
  290. @content.setter
  291. def content(self, value):
  292. # Consume iterators upon assignment to allow repeated iteration.
  293. if (
  294. hasattr(value, '__iter__') and
  295. not isinstance(value, (bytes, memoryview, str))
  296. ):
  297. content = b''.join(self.make_bytes(chunk) for chunk in value)
  298. if hasattr(value, 'close'):
  299. try:
  300. value.close()
  301. except Exception:
  302. pass
  303. else:
  304. content = self.make_bytes(value)
  305. # Create a list of properly encoded bytestrings to support write().
  306. self._container = [content]
  307. def __iter__(self):
  308. return iter(self._container)
  309. def write(self, content):
  310. self._container.append(self.make_bytes(content))
  311. def tell(self):
  312. return len(self.content)
  313. def getvalue(self):
  314. return self.content
  315. def writable(self):
  316. return True
  317. def writelines(self, lines):
  318. for line in lines:
  319. self.write(line)
  320. class StreamingHttpResponse(HttpResponseBase):
  321. """
  322. A streaming HTTP response class with an iterator as content.
  323. This should only be iterated once, when the response is streamed to the
  324. client. However, it can be appended to or replaced with a new iterator
  325. that wraps the original content (or yields entirely new content).
  326. """
  327. streaming = True
  328. def __init__(self, streaming_content=(), *args, **kwargs):
  329. super().__init__(*args, **kwargs)
  330. # `streaming_content` should be an iterable of bytestrings.
  331. # See the `streaming_content` property methods.
  332. self.streaming_content = streaming_content
  333. @property
  334. def content(self):
  335. raise AttributeError(
  336. "This %s instance has no `content` attribute. Use "
  337. "`streaming_content` instead." % self.__class__.__name__
  338. )
  339. @property
  340. def streaming_content(self):
  341. return map(self.make_bytes, self._iterator)
  342. @streaming_content.setter
  343. def streaming_content(self, value):
  344. self._set_streaming_content(value)
  345. def _set_streaming_content(self, value):
  346. # Ensure we can never iterate on "value" more than once.
  347. self._iterator = iter(value)
  348. if hasattr(value, 'close'):
  349. self._resource_closers.append(value.close)
  350. def __iter__(self):
  351. return self.streaming_content
  352. def getvalue(self):
  353. return b''.join(self.streaming_content)
  354. class FileResponse(StreamingHttpResponse):
  355. """
  356. A streaming HTTP response class optimized for files.
  357. """
  358. block_size = 4096
  359. def __init__(self, *args, as_attachment=False, filename='', **kwargs):
  360. self.as_attachment = as_attachment
  361. self.filename = filename
  362. super().__init__(*args, **kwargs)
  363. def _set_streaming_content(self, value):
  364. if not hasattr(value, 'read'):
  365. self.file_to_stream = None
  366. return super()._set_streaming_content(value)
  367. self.file_to_stream = filelike = value
  368. if hasattr(filelike, 'close'):
  369. self._resource_closers.append(filelike.close)
  370. value = iter(lambda: filelike.read(self.block_size), b'')
  371. self.set_headers(filelike)
  372. super()._set_streaming_content(value)
  373. def set_headers(self, filelike):
  374. """
  375. Set some common response headers (Content-Length, Content-Type, and
  376. Content-Disposition) based on the `filelike` response content.
  377. """
  378. encoding_map = {
  379. 'bzip2': 'application/x-bzip',
  380. 'gzip': 'application/gzip',
  381. 'xz': 'application/x-xz',
  382. }
  383. filename = getattr(filelike, 'name', None)
  384. filename = filename if (isinstance(filename, str) and filename) else self.filename
  385. if os.path.isabs(filename):
  386. self.headers['Content-Length'] = os.path.getsize(filelike.name)
  387. elif hasattr(filelike, 'getbuffer'):
  388. self.headers['Content-Length'] = filelike.getbuffer().nbytes
  389. if self.headers.get('Content-Type', '').startswith('text/html'):
  390. if filename:
  391. content_type, encoding = mimetypes.guess_type(filename)
  392. # Encoding isn't set to prevent browsers from automatically
  393. # uncompressing files.
  394. content_type = encoding_map.get(encoding, content_type)
  395. self.headers['Content-Type'] = content_type or 'application/octet-stream'
  396. else:
  397. self.headers['Content-Type'] = 'application/octet-stream'
  398. filename = self.filename or os.path.basename(filename)
  399. if filename:
  400. disposition = 'attachment' if self.as_attachment else 'inline'
  401. try:
  402. filename.encode('ascii')
  403. file_expr = 'filename="{}"'.format(
  404. filename.replace('\\', '\\\\').replace('"', r'\"')
  405. )
  406. except UnicodeEncodeError:
  407. file_expr = "filename*=utf-8''{}".format(quote(filename))
  408. self.headers['Content-Disposition'] = '{}; {}'.format(disposition, file_expr)
  409. elif self.as_attachment:
  410. self.headers['Content-Disposition'] = 'attachment'
  411. class HttpResponseRedirectBase(HttpResponse):
  412. allowed_schemes = ['http', 'https', 'ftp']
  413. def __init__(self, redirect_to, *args, **kwargs):
  414. super().__init__(*args, **kwargs)
  415. self['Location'] = iri_to_uri(redirect_to)
  416. parsed = urlparse(str(redirect_to))
  417. if parsed.scheme and parsed.scheme not in self.allowed_schemes:
  418. raise DisallowedRedirect("Unsafe redirect to URL with protocol '%s'" % parsed.scheme)
  419. url = property(lambda self: self['Location'])
  420. def __repr__(self):
  421. return '<%(cls)s status_code=%(status_code)d%(content_type)s, url="%(url)s">' % {
  422. 'cls': self.__class__.__name__,
  423. 'status_code': self.status_code,
  424. 'content_type': self._content_type_for_repr,
  425. 'url': self.url,
  426. }
  427. class HttpResponseRedirect(HttpResponseRedirectBase):
  428. status_code = 302
  429. class HttpResponsePermanentRedirect(HttpResponseRedirectBase):
  430. status_code = 301
  431. class HttpResponseNotModified(HttpResponse):
  432. status_code = 304
  433. def __init__(self, *args, **kwargs):
  434. super().__init__(*args, **kwargs)
  435. del self['content-type']
  436. @HttpResponse.content.setter
  437. def content(self, value):
  438. if value:
  439. raise AttributeError("You cannot set content to a 304 (Not Modified) response")
  440. self._container = []
  441. class HttpResponseBadRequest(HttpResponse):
  442. status_code = 400
  443. class HttpResponseNotFound(HttpResponse):
  444. status_code = 404
  445. class HttpResponseForbidden(HttpResponse):
  446. status_code = 403
  447. class HttpResponseNotAllowed(HttpResponse):
  448. status_code = 405
  449. def __init__(self, permitted_methods, *args, **kwargs):
  450. super().__init__(*args, **kwargs)
  451. self['Allow'] = ', '.join(permitted_methods)
  452. def __repr__(self):
  453. return '<%(cls)s [%(methods)s] status_code=%(status_code)d%(content_type)s>' % {
  454. 'cls': self.__class__.__name__,
  455. 'status_code': self.status_code,
  456. 'content_type': self._content_type_for_repr,
  457. 'methods': self['Allow'],
  458. }
  459. class HttpResponseGone(HttpResponse):
  460. status_code = 410
  461. class HttpResponseServerError(HttpResponse):
  462. status_code = 500
  463. class Http404(Exception):
  464. pass
  465. class JsonResponse(HttpResponse):
  466. """
  467. An HTTP response class that consumes data to be serialized to JSON.
  468. :param data: Data to be dumped into json. By default only ``dict`` objects
  469. are allowed to be passed due to a security flaw before EcmaScript 5. See
  470. the ``safe`` parameter for more information.
  471. :param encoder: Should be a json encoder class. Defaults to
  472. ``django.core.serializers.json.DjangoJSONEncoder``.
  473. :param safe: Controls if only ``dict`` objects may be serialized. Defaults
  474. to ``True``.
  475. :param json_dumps_params: A dictionary of kwargs passed to json.dumps().
  476. """
  477. def __init__(self, data, encoder=DjangoJSONEncoder, safe=True,
  478. json_dumps_params=None, **kwargs):
  479. if safe and not isinstance(data, dict):
  480. raise TypeError(
  481. 'In order to allow non-dict objects to be serialized set the '
  482. 'safe parameter to False.'
  483. )
  484. if json_dumps_params is None:
  485. json_dumps_params = {}
  486. kwargs.setdefault('content_type', 'application/json')
  487. data = json.dumps(data, cls=encoder, **json_dumps_params)
  488. super().__init__(content=data, **kwargs)