response.py 25 KB

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