__init__.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376
  1. # -*- coding: utf-8 -*-
  2. """
  3. flask.json
  4. ~~~~~~~~~~
  5. :copyright: 2010 Pallets
  6. :license: BSD-3-Clause
  7. """
  8. import codecs
  9. import io
  10. import uuid
  11. from datetime import date
  12. from datetime import datetime
  13. from itsdangerous import json as _json
  14. from jinja2 import Markup
  15. from werkzeug.http import http_date
  16. from .._compat import PY2
  17. from .._compat import text_type
  18. from ..globals import current_app
  19. from ..globals import request
  20. try:
  21. import dataclasses
  22. except ImportError:
  23. dataclasses = None
  24. # Figure out if simplejson escapes slashes. This behavior was changed
  25. # from one version to another without reason.
  26. _slash_escape = "\\/" not in _json.dumps("/")
  27. __all__ = [
  28. "dump",
  29. "dumps",
  30. "load",
  31. "loads",
  32. "htmlsafe_dump",
  33. "htmlsafe_dumps",
  34. "JSONDecoder",
  35. "JSONEncoder",
  36. "jsonify",
  37. ]
  38. def _wrap_reader_for_text(fp, encoding):
  39. if isinstance(fp.read(0), bytes):
  40. fp = io.TextIOWrapper(io.BufferedReader(fp), encoding)
  41. return fp
  42. def _wrap_writer_for_text(fp, encoding):
  43. try:
  44. fp.write("")
  45. except TypeError:
  46. fp = io.TextIOWrapper(fp, encoding)
  47. return fp
  48. class JSONEncoder(_json.JSONEncoder):
  49. """The default Flask JSON encoder. This one extends the default
  50. encoder by also supporting ``datetime``, ``UUID``, ``dataclasses``,
  51. and ``Markup`` objects.
  52. ``datetime`` objects are serialized as RFC 822 datetime strings.
  53. This is the same as the HTTP date format.
  54. In order to support more data types, override the :meth:`default`
  55. method.
  56. """
  57. def default(self, o):
  58. """Implement this method in a subclass such that it returns a
  59. serializable object for ``o``, or calls the base implementation (to
  60. raise a :exc:`TypeError`).
  61. For example, to support arbitrary iterators, you could implement
  62. default like this::
  63. def default(self, o):
  64. try:
  65. iterable = iter(o)
  66. except TypeError:
  67. pass
  68. else:
  69. return list(iterable)
  70. return JSONEncoder.default(self, o)
  71. """
  72. if isinstance(o, datetime):
  73. return http_date(o.utctimetuple())
  74. if isinstance(o, date):
  75. return http_date(o.timetuple())
  76. if isinstance(o, uuid.UUID):
  77. return str(o)
  78. if dataclasses and dataclasses.is_dataclass(o):
  79. return dataclasses.asdict(o)
  80. if hasattr(o, "__html__"):
  81. return text_type(o.__html__())
  82. return _json.JSONEncoder.default(self, o)
  83. class JSONDecoder(_json.JSONDecoder):
  84. """The default JSON decoder. This one does not change the behavior from
  85. the default simplejson decoder. Consult the :mod:`json` documentation
  86. for more information. This decoder is not only used for the load
  87. functions of this module but also :attr:`~flask.Request`.
  88. """
  89. def _dump_arg_defaults(kwargs, app=None):
  90. """Inject default arguments for dump functions."""
  91. if app is None:
  92. app = current_app
  93. if app:
  94. bp = app.blueprints.get(request.blueprint) if request else None
  95. kwargs.setdefault(
  96. "cls", bp.json_encoder if bp and bp.json_encoder else app.json_encoder
  97. )
  98. if not app.config["JSON_AS_ASCII"]:
  99. kwargs.setdefault("ensure_ascii", False)
  100. kwargs.setdefault("sort_keys", app.config["JSON_SORT_KEYS"])
  101. else:
  102. kwargs.setdefault("sort_keys", True)
  103. kwargs.setdefault("cls", JSONEncoder)
  104. def _load_arg_defaults(kwargs, app=None):
  105. """Inject default arguments for load functions."""
  106. if app is None:
  107. app = current_app
  108. if app:
  109. bp = app.blueprints.get(request.blueprint) if request else None
  110. kwargs.setdefault(
  111. "cls", bp.json_decoder if bp and bp.json_decoder else app.json_decoder
  112. )
  113. else:
  114. kwargs.setdefault("cls", JSONDecoder)
  115. def detect_encoding(data):
  116. """Detect which UTF codec was used to encode the given bytes.
  117. The latest JSON standard (:rfc:`8259`) suggests that only UTF-8 is
  118. accepted. Older documents allowed 8, 16, or 32. 16 and 32 can be big
  119. or little endian. Some editors or libraries may prepend a BOM.
  120. :param data: Bytes in unknown UTF encoding.
  121. :return: UTF encoding name
  122. """
  123. head = data[:4]
  124. if head[:3] == codecs.BOM_UTF8:
  125. return "utf-8-sig"
  126. if b"\x00" not in head:
  127. return "utf-8"
  128. if head in (codecs.BOM_UTF32_BE, codecs.BOM_UTF32_LE):
  129. return "utf-32"
  130. if head[:2] in (codecs.BOM_UTF16_BE, codecs.BOM_UTF16_LE):
  131. return "utf-16"
  132. if len(head) == 4:
  133. if head[:3] == b"\x00\x00\x00":
  134. return "utf-32-be"
  135. if head[::2] == b"\x00\x00":
  136. return "utf-16-be"
  137. if head[1:] == b"\x00\x00\x00":
  138. return "utf-32-le"
  139. if head[1::2] == b"\x00\x00":
  140. return "utf-16-le"
  141. if len(head) == 2:
  142. return "utf-16-be" if head.startswith(b"\x00") else "utf-16-le"
  143. return "utf-8"
  144. def dumps(obj, app=None, **kwargs):
  145. """Serialize ``obj`` to a JSON-formatted string. If there is an
  146. app context pushed, use the current app's configured encoder
  147. (:attr:`~flask.Flask.json_encoder`), or fall back to the default
  148. :class:`JSONEncoder`.
  149. Takes the same arguments as the built-in :func:`json.dumps`, and
  150. does some extra configuration based on the application. If the
  151. simplejson package is installed, it is preferred.
  152. :param obj: Object to serialize to JSON.
  153. :param app: App instance to use to configure the JSON encoder.
  154. Uses ``current_app`` if not given, and falls back to the default
  155. encoder when not in an app context.
  156. :param kwargs: Extra arguments passed to :func:`json.dumps`.
  157. .. versionchanged:: 1.0.3
  158. ``app`` can be passed directly, rather than requiring an app
  159. context for configuration.
  160. """
  161. _dump_arg_defaults(kwargs, app=app)
  162. encoding = kwargs.pop("encoding", None)
  163. rv = _json.dumps(obj, **kwargs)
  164. if encoding is not None and isinstance(rv, text_type):
  165. rv = rv.encode(encoding)
  166. return rv
  167. def dump(obj, fp, app=None, **kwargs):
  168. """Like :func:`dumps` but writes into a file object."""
  169. _dump_arg_defaults(kwargs, app=app)
  170. encoding = kwargs.pop("encoding", None)
  171. if encoding is not None:
  172. fp = _wrap_writer_for_text(fp, encoding)
  173. _json.dump(obj, fp, **kwargs)
  174. def loads(s, app=None, **kwargs):
  175. """Deserialize an object from a JSON-formatted string ``s``. If
  176. there is an app context pushed, use the current app's configured
  177. decoder (:attr:`~flask.Flask.json_decoder`), or fall back to the
  178. default :class:`JSONDecoder`.
  179. Takes the same arguments as the built-in :func:`json.loads`, and
  180. does some extra configuration based on the application. If the
  181. simplejson package is installed, it is preferred.
  182. :param s: JSON string to deserialize.
  183. :param app: App instance to use to configure the JSON decoder.
  184. Uses ``current_app`` if not given, and falls back to the default
  185. encoder when not in an app context.
  186. :param kwargs: Extra arguments passed to :func:`json.dumps`.
  187. .. versionchanged:: 1.0.3
  188. ``app`` can be passed directly, rather than requiring an app
  189. context for configuration.
  190. """
  191. _load_arg_defaults(kwargs, app=app)
  192. if isinstance(s, bytes):
  193. encoding = kwargs.pop("encoding", None)
  194. if encoding is None:
  195. encoding = detect_encoding(s)
  196. s = s.decode(encoding)
  197. return _json.loads(s, **kwargs)
  198. def load(fp, app=None, **kwargs):
  199. """Like :func:`loads` but reads from a file object."""
  200. _load_arg_defaults(kwargs, app=app)
  201. if not PY2:
  202. fp = _wrap_reader_for_text(fp, kwargs.pop("encoding", None) or "utf-8")
  203. return _json.load(fp, **kwargs)
  204. def htmlsafe_dumps(obj, **kwargs):
  205. """Works exactly like :func:`dumps` but is safe for use in ``<script>``
  206. tags. It accepts the same arguments and returns a JSON string. Note that
  207. this is available in templates through the ``|tojson`` filter which will
  208. also mark the result as safe. Due to how this function escapes certain
  209. characters this is safe even if used outside of ``<script>`` tags.
  210. The following characters are escaped in strings:
  211. - ``<``
  212. - ``>``
  213. - ``&``
  214. - ``'``
  215. This makes it safe to embed such strings in any place in HTML with the
  216. notable exception of double quoted attributes. In that case single
  217. quote your attributes or HTML escape it in addition.
  218. .. versionchanged:: 0.10
  219. This function's return value is now always safe for HTML usage, even
  220. if outside of script tags or if used in XHTML. This rule does not
  221. hold true when using this function in HTML attributes that are double
  222. quoted. Always single quote attributes if you use the ``|tojson``
  223. filter. Alternatively use ``|tojson|forceescape``.
  224. """
  225. rv = (
  226. dumps(obj, **kwargs)
  227. .replace(u"<", u"\\u003c")
  228. .replace(u">", u"\\u003e")
  229. .replace(u"&", u"\\u0026")
  230. .replace(u"'", u"\\u0027")
  231. )
  232. if not _slash_escape:
  233. rv = rv.replace("\\/", "/")
  234. return rv
  235. def htmlsafe_dump(obj, fp, **kwargs):
  236. """Like :func:`htmlsafe_dumps` but writes into a file object."""
  237. fp.write(text_type(htmlsafe_dumps(obj, **kwargs)))
  238. def jsonify(*args, **kwargs):
  239. """This function wraps :func:`dumps` to add a few enhancements that make
  240. life easier. It turns the JSON output into a :class:`~flask.Response`
  241. object with the :mimetype:`application/json` mimetype. For convenience, it
  242. also converts multiple arguments into an array or multiple keyword arguments
  243. into a dict. This means that both ``jsonify(1,2,3)`` and
  244. ``jsonify([1,2,3])`` serialize to ``[1,2,3]``.
  245. For clarity, the JSON serialization behavior has the following differences
  246. from :func:`dumps`:
  247. 1. Single argument: Passed straight through to :func:`dumps`.
  248. 2. Multiple arguments: Converted to an array before being passed to
  249. :func:`dumps`.
  250. 3. Multiple keyword arguments: Converted to a dict before being passed to
  251. :func:`dumps`.
  252. 4. Both args and kwargs: Behavior undefined and will throw an exception.
  253. Example usage::
  254. from flask import jsonify
  255. @app.route('/_get_current_user')
  256. def get_current_user():
  257. return jsonify(username=g.user.username,
  258. email=g.user.email,
  259. id=g.user.id)
  260. This will send a JSON response like this to the browser::
  261. {
  262. "username": "admin",
  263. "email": "admin@localhost",
  264. "id": 42
  265. }
  266. .. versionchanged:: 0.11
  267. Added support for serializing top-level arrays. This introduces a
  268. security risk in ancient browsers. See :ref:`json-security` for details.
  269. This function's response will be pretty printed if the
  270. ``JSONIFY_PRETTYPRINT_REGULAR`` config parameter is set to True or the
  271. Flask app is running in debug mode. Compressed (not pretty) formatting
  272. currently means no indents and no spaces after separators.
  273. .. versionadded:: 0.2
  274. """
  275. indent = None
  276. separators = (",", ":")
  277. if current_app.config["JSONIFY_PRETTYPRINT_REGULAR"] or current_app.debug:
  278. indent = 2
  279. separators = (", ", ": ")
  280. if args and kwargs:
  281. raise TypeError("jsonify() behavior undefined when passed both args and kwargs")
  282. elif len(args) == 1: # single args are passed directly to dumps()
  283. data = args[0]
  284. else:
  285. data = args or kwargs
  286. return current_app.response_class(
  287. dumps(data, indent=indent, separators=separators) + "\n",
  288. mimetype=current_app.config["JSONIFY_MIMETYPE"],
  289. )
  290. def tojson_filter(obj, **kwargs):
  291. return Markup(htmlsafe_dumps(obj, **kwargs))