__init__.py 10 KB

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