response.py 25 KB

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