response.py 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773
  1. import datetime
  2. import io
  3. import json
  4. import mimetypes
  5. import os
  6. import re
  7. import sys
  8. import time
  9. import warnings
  10. from email.header import Header
  11. from http.client import responses
  12. from urllib.parse import urlsplit
  13. from asgiref.sync import async_to_sync, sync_to_async
  14. from django.conf import settings
  15. from django.core import signals, signing
  16. from django.core.exceptions import DisallowedRedirect
  17. from django.core.serializers.json import DjangoJSONEncoder
  18. from django.http.cookie import SimpleCookie
  19. from django.utils import timezone
  20. from django.utils.datastructures import CaseInsensitiveMapping
  21. from django.utils.encoding import iri_to_uri
  22. from django.utils.functional import cached_property
  23. from django.utils.http import (
  24. MAX_URL_REDIRECT_LENGTH,
  25. content_disposition_header,
  26. http_date,
  27. )
  28. from django.utils.regex_helper import _lazy_re_compile
  29. _charset_from_content_type_re = _lazy_re_compile(
  30. r";\s*charset=(?P<charset>[^\s;]+)", re.I
  31. )
  32. _control_chars_re = _lazy_re_compile(r"[\x00-\x1f\x7f-\x9f]")
  33. class ResponseHeaders(CaseInsensitiveMapping):
  34. def __init__(self, data):
  35. """
  36. Populate the initial data using __setitem__ to ensure values are
  37. correctly encoded.
  38. """
  39. self._store = {}
  40. if data:
  41. for header, value in self._unpack_items(data):
  42. self[header] = value
  43. def _convert_to_charset(self, value, charset, mime_encode=False):
  44. """
  45. Convert headers key/value to ascii/latin-1 native strings.
  46. `charset` must be 'ascii' or 'latin-1'. If `mime_encode` is True and
  47. `value` can't be represented in the given charset, apply MIME-encoding.
  48. """
  49. try:
  50. if isinstance(value, str):
  51. # Ensure string is valid in given charset
  52. value.encode(charset)
  53. elif isinstance(value, bytes):
  54. # Convert bytestring using given charset
  55. value = value.decode(charset)
  56. else:
  57. value = str(value)
  58. # Ensure string is valid in given charset.
  59. value.encode(charset)
  60. if "\n" in value or "\r" in value:
  61. raise BadHeaderError(
  62. f"Header values can't contain newlines (got {value!r})"
  63. )
  64. except UnicodeError as e:
  65. # Encoding to a string of the specified charset failed, but we
  66. # don't know what type that value was, or if it contains newlines,
  67. # which we may need to check for before sending it to be
  68. # encoded for multiple character sets.
  69. if (isinstance(value, bytes) and (b"\n" in value or b"\r" in value)) or (
  70. isinstance(value, str) and ("\n" in value or "\r" in value)
  71. ):
  72. raise BadHeaderError(
  73. f"Header values can't contain newlines (got {value!r})"
  74. ) from e
  75. if mime_encode:
  76. value = Header(value, "utf-8", maxlinelen=sys.maxsize).encode()
  77. else:
  78. e.reason += ", HTTP response headers must be in %s format" % charset
  79. raise
  80. return value
  81. def __delitem__(self, key):
  82. self.pop(key)
  83. def __setitem__(self, key, value):
  84. key = self._convert_to_charset(key, "ascii")
  85. value = self._convert_to_charset(value, "latin-1", mime_encode=True)
  86. self._store[key.lower()] = (key, value)
  87. def pop(self, key, default=None):
  88. return self._store.pop(key.lower(), default)
  89. def setdefault(self, key, value):
  90. if key not in self:
  91. self[key] = value
  92. class BadHeaderError(ValueError):
  93. pass
  94. class HttpResponseBase:
  95. """
  96. An HTTP response base class with dictionary-accessed headers.
  97. This class doesn't handle content. It should not be used directly.
  98. Use the HttpResponse and StreamingHttpResponse subclasses instead.
  99. """
  100. status_code = 200
  101. def __init__(
  102. self, content_type=None, status=None, reason=None, charset=None, headers=None
  103. ):
  104. self.headers = ResponseHeaders(headers)
  105. self._charset = charset
  106. if "Content-Type" not in self.headers:
  107. if content_type is None:
  108. content_type = f"text/html; charset={self.charset}"
  109. self.headers["Content-Type"] = content_type
  110. elif content_type:
  111. raise ValueError(
  112. "'headers' must not contain 'Content-Type' when the "
  113. "'content_type' parameter is provided."
  114. )
  115. self._resource_closers = []
  116. # This parameter is set by the handler. It's necessary to preserve the
  117. # historical behavior of request_finished.
  118. self._handler_class = None
  119. self.cookies = SimpleCookie()
  120. self.closed = False
  121. if status is not None:
  122. try:
  123. self.status_code = int(status)
  124. except (ValueError, TypeError):
  125. raise TypeError("HTTP status code must be an integer.")
  126. if not 100 <= self.status_code <= 599:
  127. raise ValueError("HTTP status code must be an integer from 100 to 599.")
  128. self.reason_phrase = reason
  129. @property
  130. def reason_phrase(self):
  131. if self._reason_phrase is not None:
  132. return self._reason_phrase
  133. # Leave self._reason_phrase unset in order to use the default
  134. # reason phrase for status code.
  135. return responses.get(self.status_code, "Unknown Status Code")
  136. @reason_phrase.setter
  137. def reason_phrase(self, value):
  138. if value and _control_chars_re.search(value):
  139. raise BadHeaderError("reason_phrase can't contain control characters.")
  140. self._reason_phrase = value
  141. @property
  142. def charset(self):
  143. if self._charset is not None:
  144. return self._charset
  145. # The Content-Type header may not yet be set, because the charset is
  146. # being inserted *into* it.
  147. if content_type := self.headers.get("Content-Type"):
  148. if matched := _charset_from_content_type_re.search(content_type):
  149. # Extract the charset and strip its double quotes.
  150. # Note that having parsed it from the Content-Type, we don't
  151. # store it back into the _charset for later intentionally, to
  152. # allow for the Content-Type to be switched again later.
  153. return matched["charset"].replace('"', "")
  154. return settings.DEFAULT_CHARSET
  155. @charset.setter
  156. def charset(self, value):
  157. self._charset = value
  158. def serialize_headers(self):
  159. """HTTP headers as a bytestring."""
  160. return b"\r\n".join(
  161. [
  162. key.encode("ascii") + b": " + value.encode("latin-1")
  163. for key, value in self.headers.items()
  164. ]
  165. )
  166. __bytes__ = serialize_headers
  167. @property
  168. def _content_type_for_repr(self):
  169. return (
  170. ', "%s"' % self.headers["Content-Type"]
  171. if "Content-Type" in self.headers
  172. else ""
  173. )
  174. def __setitem__(self, header, value):
  175. self.headers[header] = value
  176. def __delitem__(self, header):
  177. del self.headers[header]
  178. def __getitem__(self, header):
  179. return self.headers[header]
  180. def has_header(self, header):
  181. """Case-insensitive check for a header."""
  182. return header in self.headers
  183. __contains__ = has_header
  184. def items(self):
  185. return self.headers.items()
  186. def get(self, header, alternate=None):
  187. return self.headers.get(header, alternate)
  188. def set_cookie(
  189. self,
  190. key,
  191. value="",
  192. max_age=None,
  193. expires=None,
  194. path="/",
  195. domain=None,
  196. secure=False,
  197. httponly=False,
  198. samesite=None,
  199. ):
  200. """
  201. Set a cookie.
  202. ``expires`` can be:
  203. - a string in the correct format,
  204. - a naive ``datetime.datetime`` object in UTC,
  205. - an aware ``datetime.datetime`` object in any time zone.
  206. If it is a ``datetime.datetime`` object then calculate ``max_age``.
  207. ``max_age`` can be:
  208. - int/float specifying seconds,
  209. - ``datetime.timedelta`` object.
  210. """
  211. self.cookies[key] = value
  212. if expires is not None:
  213. if isinstance(expires, datetime.datetime):
  214. if timezone.is_naive(expires):
  215. expires = timezone.make_aware(expires, datetime.UTC)
  216. delta = expires - datetime.datetime.now(tz=datetime.UTC)
  217. # Add one second so the date matches exactly (a fraction of
  218. # time gets lost between converting to a timedelta and
  219. # then the date string).
  220. delta += datetime.timedelta(seconds=1)
  221. # Just set max_age - the max_age logic will set expires.
  222. expires = None
  223. if max_age is not None:
  224. raise ValueError("'expires' and 'max_age' can't be used together.")
  225. max_age = max(0, delta.days * 86400 + delta.seconds)
  226. else:
  227. self.cookies[key]["expires"] = expires
  228. else:
  229. self.cookies[key]["expires"] = ""
  230. if max_age is not None:
  231. if isinstance(max_age, datetime.timedelta):
  232. max_age = max_age.total_seconds()
  233. self.cookies[key]["max-age"] = int(max_age)
  234. # IE requires expires, so set it if hasn't been already.
  235. if not expires:
  236. self.cookies[key]["expires"] = http_date(time.time() + max_age)
  237. if path is not None:
  238. self.cookies[key]["path"] = path
  239. if domain is not None:
  240. self.cookies[key]["domain"] = domain
  241. if secure:
  242. self.cookies[key]["secure"] = True
  243. if httponly:
  244. self.cookies[key]["httponly"] = True
  245. if samesite:
  246. if samesite.lower() not in ("lax", "none", "strict"):
  247. raise ValueError('samesite must be "lax", "none", or "strict".')
  248. self.cookies[key]["samesite"] = samesite
  249. def setdefault(self, key, value):
  250. """Set a header unless it has already been set."""
  251. self.headers.setdefault(key, value)
  252. def set_signed_cookie(self, key, value, salt="", **kwargs):
  253. value = signing.get_cookie_signer(
  254. salt=signing._cookie_signer_salt(key, salt)
  255. ).sign(value)
  256. return self.set_cookie(key, value, **kwargs)
  257. def delete_cookie(self, key, path="/", domain=None, samesite=None):
  258. # Browsers can ignore the Set-Cookie header if the cookie doesn't use
  259. # the secure flag and:
  260. # - the cookie name starts with "__Host-" or "__Secure-", or
  261. # - the samesite is "none".
  262. secure = key.startswith(("__Secure-", "__Host-")) or (
  263. samesite and samesite.lower() == "none"
  264. )
  265. self.set_cookie(
  266. key,
  267. max_age=0,
  268. path=path,
  269. domain=domain,
  270. secure=secure,
  271. expires="Thu, 01 Jan 1970 00:00:00 GMT",
  272. samesite=samesite,
  273. )
  274. # Common methods used by subclasses
  275. def make_bytes(self, value):
  276. """Turn a value into a bytestring encoded in the output charset."""
  277. # Per PEP 3333, this response body must be bytes. To avoid returning
  278. # an instance of a subclass, this function returns `bytes(value)`.
  279. # This doesn't make a copy when `value` already contains bytes.
  280. # Handle string types -- we can't rely on force_bytes here because:
  281. # - Python attempts str conversion first
  282. # - when self._charset != 'utf-8' it re-encodes the content
  283. if isinstance(value, (bytes, memoryview)):
  284. return bytes(value)
  285. if isinstance(value, str):
  286. return bytes(value.encode(self.charset))
  287. # Handle non-string types.
  288. return str(value).encode(self.charset)
  289. # These methods partially implement the file-like object interface.
  290. # See https://docs.python.org/library/io.html#io.IOBase
  291. # The WSGI server must call this method upon completion of the request.
  292. # See
  293. # http://blog.dscpl.com.au/2012/10/obligations-for-calling-close-on.html
  294. def close(self):
  295. for closer in self._resource_closers:
  296. try:
  297. closer()
  298. except Exception:
  299. pass
  300. # Free resources that were still referenced.
  301. self._resource_closers.clear()
  302. self.closed = True
  303. signals.request_finished.send(sender=self._handler_class)
  304. def write(self, content):
  305. raise OSError("This %s instance is not writable" % self.__class__.__name__)
  306. def flush(self):
  307. pass
  308. def tell(self):
  309. raise OSError(
  310. "This %s instance cannot tell its position" % self.__class__.__name__
  311. )
  312. # These methods partially implement a stream-like object interface.
  313. # See https://docs.python.org/library/io.html#io.IOBase
  314. def readable(self):
  315. return False
  316. def seekable(self):
  317. return False
  318. def writable(self):
  319. return False
  320. def writelines(self, lines):
  321. raise OSError("This %s instance is not writable" % self.__class__.__name__)
  322. class HttpResponse(HttpResponseBase):
  323. """
  324. An HTTP response class with a string as content.
  325. This content can be read, appended to, or replaced.
  326. """
  327. streaming = False
  328. def __init__(self, content=b"", *args, **kwargs):
  329. super().__init__(*args, **kwargs)
  330. # Content is a bytestring. See the `content` property methods.
  331. self.content = content
  332. def __repr__(self):
  333. return "<%(cls)s status_code=%(status_code)d%(content_type)s>" % {
  334. "cls": self.__class__.__name__,
  335. "status_code": self.status_code,
  336. "content_type": self._content_type_for_repr,
  337. }
  338. def serialize(self):
  339. """Full HTTP message, including headers, as a bytestring."""
  340. return self.serialize_headers() + b"\r\n\r\n" + self.content
  341. __bytes__ = serialize
  342. @property
  343. def content(self):
  344. return b"".join(self._container)
  345. @content.setter
  346. def content(self, value):
  347. # Consume iterators upon assignment to allow repeated iteration.
  348. if hasattr(value, "__iter__") and not isinstance(
  349. value, (bytes, memoryview, str)
  350. ):
  351. content = b"".join(self.make_bytes(chunk) for chunk in value)
  352. if hasattr(value, "close"):
  353. try:
  354. value.close()
  355. except Exception:
  356. pass
  357. else:
  358. content = self.make_bytes(value)
  359. # Create a list of properly encoded bytestrings to support write().
  360. self._container = [content]
  361. self.__dict__.pop("text", None)
  362. @cached_property
  363. def text(self):
  364. return self.content.decode(self.charset or "utf-8")
  365. def __iter__(self):
  366. return iter(self._container)
  367. def write(self, content):
  368. self._container.append(self.make_bytes(content))
  369. def tell(self):
  370. return len(self.content)
  371. def getvalue(self):
  372. return self.content
  373. def writable(self):
  374. return True
  375. def writelines(self, lines):
  376. for line in lines:
  377. self.write(line)
  378. class StreamingHttpResponse(HttpResponseBase):
  379. """
  380. A streaming HTTP response class with an iterator as content.
  381. This should only be iterated once, when the response is streamed to the
  382. client. However, it can be appended to or replaced with a new iterator
  383. that wraps the original content (or yields entirely new content).
  384. """
  385. streaming = True
  386. def __init__(self, streaming_content=(), *args, **kwargs):
  387. super().__init__(*args, **kwargs)
  388. # `streaming_content` should be an iterable of bytestrings.
  389. # See the `streaming_content` property methods.
  390. self.streaming_content = streaming_content
  391. def __repr__(self):
  392. return "<%(cls)s status_code=%(status_code)d%(content_type)s>" % {
  393. "cls": self.__class__.__qualname__,
  394. "status_code": self.status_code,
  395. "content_type": self._content_type_for_repr,
  396. }
  397. @property
  398. def content(self):
  399. raise AttributeError(
  400. "This %s instance has no `content` attribute. Use "
  401. "`streaming_content` instead." % self.__class__.__name__
  402. )
  403. @property
  404. def text(self):
  405. raise AttributeError(
  406. "This %s instance has no `text` attribute." % self.__class__.__name__
  407. )
  408. @property
  409. def streaming_content(self):
  410. if self.is_async:
  411. # pull to lexical scope to capture fixed reference in case
  412. # streaming_content is set again later.
  413. _iterator = self._iterator
  414. async def awrapper():
  415. async for part in _iterator:
  416. yield self.make_bytes(part)
  417. return awrapper()
  418. else:
  419. return map(self.make_bytes, self._iterator)
  420. @streaming_content.setter
  421. def streaming_content(self, value):
  422. self._set_streaming_content(value)
  423. def _set_streaming_content(self, value):
  424. # Ensure we can never iterate on "value" more than once.
  425. try:
  426. self._iterator = iter(value)
  427. self.is_async = False
  428. except TypeError:
  429. self._iterator = aiter(value)
  430. self.is_async = True
  431. if hasattr(value, "close"):
  432. self._resource_closers.append(value.close)
  433. def __iter__(self):
  434. try:
  435. return iter(self.streaming_content)
  436. except TypeError:
  437. warnings.warn(
  438. "StreamingHttpResponse must consume asynchronous iterators in order to "
  439. "serve them synchronously. Use a synchronous iterator instead.",
  440. Warning,
  441. stacklevel=2,
  442. )
  443. # async iterator. Consume in async_to_sync and map back.
  444. async def to_list(_iterator):
  445. as_list = []
  446. async for chunk in _iterator:
  447. as_list.append(chunk)
  448. return as_list
  449. return map(self.make_bytes, iter(async_to_sync(to_list)(self._iterator)))
  450. async def __aiter__(self):
  451. try:
  452. async for part in self.streaming_content:
  453. yield part
  454. except TypeError:
  455. warnings.warn(
  456. "StreamingHttpResponse must consume synchronous iterators in order to "
  457. "serve them asynchronously. Use an asynchronous iterator instead.",
  458. Warning,
  459. stacklevel=2,
  460. )
  461. # sync iterator. Consume via sync_to_async and yield via async
  462. # generator.
  463. for part in await sync_to_async(list)(self.streaming_content):
  464. yield part
  465. def getvalue(self):
  466. return b"".join(self.streaming_content)
  467. class FileResponse(StreamingHttpResponse):
  468. """
  469. A streaming HTTP response class optimized for files.
  470. """
  471. block_size = 4096
  472. def __init__(self, *args, as_attachment=False, filename="", **kwargs):
  473. self.as_attachment = as_attachment
  474. self.filename = filename
  475. self._no_explicit_content_type = (
  476. "content_type" not in kwargs or kwargs["content_type"] is None
  477. )
  478. super().__init__(*args, **kwargs)
  479. def _set_streaming_content(self, value):
  480. if not hasattr(value, "read"):
  481. self.file_to_stream = None
  482. return super()._set_streaming_content(value)
  483. self.file_to_stream = filelike = value
  484. if hasattr(filelike, "close"):
  485. self._resource_closers.append(filelike.close)
  486. value = iter(lambda: filelike.read(self.block_size), b"")
  487. self.set_headers(filelike)
  488. super()._set_streaming_content(value)
  489. def set_headers(self, filelike):
  490. """
  491. Set some common response headers (Content-Length, Content-Type, and
  492. Content-Disposition) based on the `filelike` response content.
  493. """
  494. filename = getattr(filelike, "name", "")
  495. filename = filename if isinstance(filename, str) else ""
  496. seekable = hasattr(filelike, "seek") and (
  497. not hasattr(filelike, "seekable") or filelike.seekable()
  498. )
  499. if hasattr(filelike, "tell"):
  500. if seekable:
  501. initial_position = filelike.tell()
  502. filelike.seek(0, io.SEEK_END)
  503. self.headers["Content-Length"] = filelike.tell() - initial_position
  504. filelike.seek(initial_position)
  505. elif hasattr(filelike, "getbuffer"):
  506. self.headers["Content-Length"] = (
  507. filelike.getbuffer().nbytes - filelike.tell()
  508. )
  509. elif os.path.exists(filename):
  510. self.headers["Content-Length"] = (
  511. os.path.getsize(filename) - filelike.tell()
  512. )
  513. elif seekable:
  514. self.headers["Content-Length"] = sum(
  515. iter(lambda: len(filelike.read(self.block_size)), 0)
  516. )
  517. filelike.seek(-int(self.headers["Content-Length"]), io.SEEK_END)
  518. filename = os.path.basename(self.filename or filename)
  519. if self._no_explicit_content_type:
  520. if filename:
  521. content_type, encoding = mimetypes.guess_type(filename)
  522. # Encoding isn't set to prevent browsers from automatically
  523. # uncompressing files.
  524. content_type = {
  525. "br": "application/x-brotli",
  526. "bzip2": "application/x-bzip",
  527. "compress": "application/x-compress",
  528. "gzip": "application/gzip",
  529. "xz": "application/x-xz",
  530. }.get(encoding, content_type)
  531. self.headers["Content-Type"] = (
  532. content_type or "application/octet-stream"
  533. )
  534. else:
  535. self.headers["Content-Type"] = "application/octet-stream"
  536. if content_disposition := content_disposition_header(
  537. self.as_attachment, filename
  538. ):
  539. self.headers["Content-Disposition"] = content_disposition
  540. class HttpResponseRedirectBase(HttpResponse):
  541. allowed_schemes = ["http", "https", "ftp"]
  542. def __init__(
  543. self,
  544. redirect_to,
  545. preserve_request=False,
  546. *args,
  547. max_length=MAX_URL_REDIRECT_LENGTH,
  548. **kwargs,
  549. ):
  550. super().__init__(*args, **kwargs)
  551. self["Location"] = iri_to_uri(redirect_to)
  552. if max_length is not None and len(self["Location"]) > max_length:
  553. raise DisallowedRedirect(
  554. f"Unsafe redirect exceeding {max_length} characters"
  555. )
  556. parsed = urlsplit(str(redirect_to))
  557. if preserve_request:
  558. self.status_code = self.status_code_preserve_request
  559. if parsed.scheme and parsed.scheme not in self.allowed_schemes:
  560. raise DisallowedRedirect(
  561. "Unsafe redirect to URL with protocol '%s'" % parsed.scheme
  562. )
  563. url = property(lambda self: self["Location"])
  564. def __repr__(self):
  565. return (
  566. '<%(cls)s status_code=%(status_code)d%(content_type)s, url="%(url)s">'
  567. % {
  568. "cls": self.__class__.__name__,
  569. "status_code": self.status_code,
  570. "content_type": self._content_type_for_repr,
  571. "url": self.url,
  572. }
  573. )
  574. class HttpResponseRedirect(HttpResponseRedirectBase):
  575. status_code = 302
  576. status_code_preserve_request = 307
  577. class HttpResponsePermanentRedirect(HttpResponseRedirectBase):
  578. status_code = 301
  579. status_code_preserve_request = 308
  580. class HttpResponseNotModified(HttpResponse):
  581. status_code = 304
  582. def __init__(self, *args, **kwargs):
  583. super().__init__(*args, **kwargs)
  584. del self["content-type"]
  585. @HttpResponse.content.setter
  586. def content(self, value):
  587. if value:
  588. raise AttributeError(
  589. "You cannot set content to a 304 (Not Modified) response"
  590. )
  591. self._container = []
  592. class HttpResponseBadRequest(HttpResponse):
  593. status_code = 400
  594. class HttpResponseNotFound(HttpResponse):
  595. status_code = 404
  596. class HttpResponseForbidden(HttpResponse):
  597. status_code = 403
  598. class HttpResponseNotAllowed(HttpResponse):
  599. status_code = 405
  600. def __init__(self, permitted_methods, *args, **kwargs):
  601. super().__init__(*args, **kwargs)
  602. self["Allow"] = ", ".join(permitted_methods)
  603. def __repr__(self):
  604. return "<%(cls)s [%(methods)s] status_code=%(status_code)d%(content_type)s>" % {
  605. "cls": self.__class__.__name__,
  606. "status_code": self.status_code,
  607. "content_type": self._content_type_for_repr,
  608. "methods": self["Allow"],
  609. }
  610. class HttpResponseGone(HttpResponse):
  611. status_code = 410
  612. class HttpResponseServerError(HttpResponse):
  613. status_code = 500
  614. class Http404(Exception):
  615. pass
  616. class JsonResponse(HttpResponse):
  617. """
  618. An HTTP response class that consumes data to be serialized to JSON.
  619. :param data: Data to be dumped into json. By default only ``dict`` objects
  620. are allowed to be passed due to a security flaw before ECMAScript 5. See
  621. the ``safe`` parameter for more information.
  622. :param encoder: Should be a json encoder class. Defaults to
  623. ``django.core.serializers.json.DjangoJSONEncoder``.
  624. :param safe: Controls if only ``dict`` objects may be serialized. Defaults
  625. to ``True``.
  626. :param json_dumps_params: A dictionary of kwargs passed to json.dumps().
  627. """
  628. def __init__(
  629. self,
  630. data,
  631. encoder=DjangoJSONEncoder,
  632. safe=True,
  633. json_dumps_params=None,
  634. **kwargs,
  635. ):
  636. if safe and not isinstance(data, dict):
  637. raise TypeError(
  638. "In order to allow non-dict objects to be serialized set the "
  639. "safe parameter to False."
  640. )
  641. if json_dumps_params is None:
  642. json_dumps_params = {}
  643. kwargs.setdefault("content_type", "application/json")
  644. data = json.dumps(data, cls=encoder, **json_dumps_params)
  645. super().__init__(content=data, **kwargs)