json.py 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272
  1. # -*- coding: utf-8 -*-
  2. """
  3. flask.jsonimpl
  4. ~~~~~~~~~~~~~~
  5. Implementation helpers for the JSON support in Flask.
  6. :copyright: (c) 2015 by Armin Ronacher.
  7. :license: BSD, see LICENSE for more details.
  8. """
  9. import io
  10. import uuid
  11. from datetime import date
  12. from .globals import current_app, request
  13. from ._compat import text_type, PY2
  14. from werkzeug.http import http_date
  15. from jinja2 import Markup
  16. # Use the same json implementation as itsdangerous on which we
  17. # depend anyways.
  18. try:
  19. from itsdangerous import simplejson as _json
  20. except ImportError:
  21. from itsdangerous import json as _json
  22. # Figure out if simplejson escapes slashes. This behavior was changed
  23. # from one version to another without reason.
  24. _slash_escape = '\\/' not in _json.dumps('/')
  25. __all__ = ['dump', 'dumps', 'load', 'loads', 'htmlsafe_dump',
  26. 'htmlsafe_dumps', 'JSONDecoder', 'JSONEncoder',
  27. 'jsonify']
  28. def _wrap_reader_for_text(fp, encoding):
  29. if isinstance(fp.read(0), bytes):
  30. fp = io.TextIOWrapper(io.BufferedReader(fp), encoding)
  31. return fp
  32. def _wrap_writer_for_text(fp, encoding):
  33. try:
  34. fp.write('')
  35. except TypeError:
  36. fp = io.TextIOWrapper(fp, encoding)
  37. return fp
  38. class JSONEncoder(_json.JSONEncoder):
  39. """The default Flask JSON encoder. This one extends the default simplejson
  40. encoder by also supporting ``datetime`` objects, ``UUID`` as well as
  41. ``Markup`` objects which are serialized as RFC 822 datetime strings (same
  42. as the HTTP date format). In order to support more data types override the
  43. :meth:`default` method.
  44. """
  45. def default(self, o):
  46. """Implement this method in a subclass such that it returns a
  47. serializable object for ``o``, or calls the base implementation (to
  48. raise a :exc:`TypeError`).
  49. For example, to support arbitrary iterators, you could implement
  50. default like this::
  51. def default(self, o):
  52. try:
  53. iterable = iter(o)
  54. except TypeError:
  55. pass
  56. else:
  57. return list(iterable)
  58. return JSONEncoder.default(self, o)
  59. """
  60. if isinstance(o, date):
  61. return http_date(o.timetuple())
  62. if isinstance(o, uuid.UUID):
  63. return str(o)
  64. if hasattr(o, '__html__'):
  65. return text_type(o.__html__())
  66. return _json.JSONEncoder.default(self, o)
  67. class JSONDecoder(_json.JSONDecoder):
  68. """The default JSON decoder. This one does not change the behavior from
  69. the default simplejson decoder. Consult the :mod:`json` documentation
  70. for more information. This decoder is not only used for the load
  71. functions of this module but also :attr:`~flask.Request`.
  72. """
  73. def _dump_arg_defaults(kwargs):
  74. """Inject default arguments for dump functions."""
  75. if current_app:
  76. kwargs.setdefault('cls', current_app.json_encoder)
  77. if not current_app.config['JSON_AS_ASCII']:
  78. kwargs.setdefault('ensure_ascii', False)
  79. kwargs.setdefault('sort_keys', current_app.config['JSON_SORT_KEYS'])
  80. else:
  81. kwargs.setdefault('sort_keys', True)
  82. kwargs.setdefault('cls', JSONEncoder)
  83. def _load_arg_defaults(kwargs):
  84. """Inject default arguments for load functions."""
  85. if current_app:
  86. kwargs.setdefault('cls', current_app.json_decoder)
  87. else:
  88. kwargs.setdefault('cls', JSONDecoder)
  89. def dumps(obj, **kwargs):
  90. """Serialize ``obj`` to a JSON formatted ``str`` by using the application's
  91. configured encoder (:attr:`~flask.Flask.json_encoder`) if there is an
  92. application on the stack.
  93. This function can return ``unicode`` strings or ascii-only bytestrings by
  94. default which coerce into unicode strings automatically. That behavior by
  95. default is controlled by the ``JSON_AS_ASCII`` configuration variable
  96. and can be overridden by the simplejson ``ensure_ascii`` parameter.
  97. """
  98. _dump_arg_defaults(kwargs)
  99. encoding = kwargs.pop('encoding', None)
  100. rv = _json.dumps(obj, **kwargs)
  101. if encoding is not None and isinstance(rv, text_type):
  102. rv = rv.encode(encoding)
  103. return rv
  104. def dump(obj, fp, **kwargs):
  105. """Like :func:`dumps` but writes into a file object."""
  106. _dump_arg_defaults(kwargs)
  107. encoding = kwargs.pop('encoding', None)
  108. if encoding is not None:
  109. fp = _wrap_writer_for_text(fp, encoding)
  110. _json.dump(obj, fp, **kwargs)
  111. def loads(s, **kwargs):
  112. """Unserialize a JSON object from a string ``s`` by using the application's
  113. configured decoder (:attr:`~flask.Flask.json_decoder`) if there is an
  114. application on the stack.
  115. """
  116. _load_arg_defaults(kwargs)
  117. if isinstance(s, bytes):
  118. s = s.decode(kwargs.pop('encoding', None) or 'utf-8')
  119. return _json.loads(s, **kwargs)
  120. def load(fp, **kwargs):
  121. """Like :func:`loads` but reads from a file object.
  122. """
  123. _load_arg_defaults(kwargs)
  124. if not PY2:
  125. fp = _wrap_reader_for_text(fp, kwargs.pop('encoding', None) or 'utf-8')
  126. return _json.load(fp, **kwargs)
  127. def htmlsafe_dumps(obj, **kwargs):
  128. """Works exactly like :func:`dumps` but is safe for use in ``<script>``
  129. tags. It accepts the same arguments and returns a JSON string. Note that
  130. this is available in templates through the ``|tojson`` filter which will
  131. also mark the result as safe. Due to how this function escapes certain
  132. characters this is safe even if used outside of ``<script>`` tags.
  133. The following characters are escaped in strings:
  134. - ``<``
  135. - ``>``
  136. - ``&``
  137. - ``'``
  138. This makes it safe to embed such strings in any place in HTML with the
  139. notable exception of double quoted attributes. In that case single
  140. quote your attributes or HTML escape it in addition.
  141. .. versionchanged:: 0.10
  142. This function's return value is now always safe for HTML usage, even
  143. if outside of script tags or if used in XHTML. This rule does not
  144. hold true when using this function in HTML attributes that are double
  145. quoted. Always single quote attributes if you use the ``|tojson``
  146. filter. Alternatively use ``|tojson|forceescape``.
  147. """
  148. rv = dumps(obj, **kwargs) \
  149. .replace(u'<', u'\\u003c') \
  150. .replace(u'>', u'\\u003e') \
  151. .replace(u'&', u'\\u0026') \
  152. .replace(u"'", u'\\u0027')
  153. if not _slash_escape:
  154. rv = rv.replace('\\/', '/')
  155. return rv
  156. def htmlsafe_dump(obj, fp, **kwargs):
  157. """Like :func:`htmlsafe_dumps` but writes into a file object."""
  158. fp.write(text_type(htmlsafe_dumps(obj, **kwargs)))
  159. def jsonify(*args, **kwargs):
  160. """This function wraps :func:`dumps` to add a few enhancements that make
  161. life easier. It turns the JSON output into a :class:`~flask.Response`
  162. object with the :mimetype:`application/json` mimetype. For convenience, it
  163. also converts multiple arguments into an array or multiple keyword arguments
  164. into a dict. This means that both ``jsonify(1,2,3)`` and
  165. ``jsonify([1,2,3])`` serialize to ``[1,2,3]``.
  166. For clarity, the JSON serialization behavior has the following differences
  167. from :func:`dumps`:
  168. 1. Single argument: Passed straight through to :func:`dumps`.
  169. 2. Multiple arguments: Converted to an array before being passed to
  170. :func:`dumps`.
  171. 3. Multiple keyword arguments: Converted to a dict before being passed to
  172. :func:`dumps`.
  173. 4. Both args and kwargs: Behavior undefined and will throw an exception.
  174. Example usage::
  175. from flask import jsonify
  176. @app.route('/_get_current_user')
  177. def get_current_user():
  178. return jsonify(username=g.user.username,
  179. email=g.user.email,
  180. id=g.user.id)
  181. This will send a JSON response like this to the browser::
  182. {
  183. "username": "admin",
  184. "email": "admin@localhost",
  185. "id": 42
  186. }
  187. .. versionchanged:: 0.11
  188. Added support for serializing top-level arrays. This introduces a
  189. security risk in ancient browsers. See :ref:`json-security` for details.
  190. This function's response will be pretty printed if it was not requested
  191. with ``X-Requested-With: XMLHttpRequest`` to simplify debugging unless
  192. the ``JSONIFY_PRETTYPRINT_REGULAR`` config parameter is set to false.
  193. Compressed (not pretty) formatting currently means no indents and no
  194. spaces after separators.
  195. .. versionadded:: 0.2
  196. """
  197. indent = None
  198. separators = (',', ':')
  199. if current_app.config['JSONIFY_PRETTYPRINT_REGULAR'] and not request.is_xhr:
  200. indent = 2
  201. separators = (', ', ': ')
  202. if args and kwargs:
  203. raise TypeError('jsonify() behavior undefined when passed both args and kwargs')
  204. elif len(args) == 1: # single args are passed directly to dumps()
  205. data = args[0]
  206. else:
  207. data = args or kwargs
  208. return current_app.response_class(
  209. (dumps(data, indent=indent, separators=separators), '\n'),
  210. mimetype=current_app.config['JSONIFY_MIMETYPE']
  211. )
  212. def tojson_filter(obj, **kwargs):
  213. return Markup(htmlsafe_dumps(obj, **kwargs))