Added wrapper module around simplejson/json for much simplified customization.
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Armin Ronacher · committed by Armin Ronacher · parent 301e244 · Browse files · 9 files·+224 added−81 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
9 files+224 added−81 removed
- other:+224 added−81 removed
Provenance
- Commit
b146d82- Tree
7ed0e64- Author
Armin Ronacher <armin.ronacher@active-4.com>- Committer
Armin Ronacher <armin.ronacher@active-4.com>- Parent
301e244
9 files changed+224 added−81 removed
modified:docs/api.rst+50 added-22 removed
310 unmodified lines311 .. autofunction:: flash312 313 .. autofunction:: get_flashed_messages314 315-Returning JSON316---------------315+JSON Support316+------------317 318-.. autofunction:: jsonify318+.. module:: flask.json319 320-.. data:: json320+Flask uses ``simplejson`` for the JSON implementation. Since simplejson321+is provided both by the standard library as well as extension Flask will322+try simplejson first and then fall back to the stdlib json module. On top323+of that it will delegate access to the current application's JSOn encoders324+and decoders for easier customization.325 322- If JSON support is picked up, this will be the module that Flask is323- using to parse and serialize JSON. So instead of doing this yourself::326+So for starters instead of doing::327 325- try:326- import simplejson as json327- except ImportError:328- import json328+ try:329+ import simplejson as json330+ except ImportError:331+ import json332 330- You can instead just do this::333+You can instead just do this::334 332- from flask import json335+ from flask import json336 334- For usage examples, read the :mod:`json` documentation.337+For usage examples, read the :mod:`json` documentation in the standard338+lirbary. The following extensions are by default applied to the stdlib's339+JSON module:340 336- The :func:`~json.dumps` function of this json module is also available337- as filter called ``|tojson`` in Jinja2. Note that inside `script`338- tags no escaping must take place, so make sure to disable escaping339- with ``|safe`` if you intend to use it inside `script` tags:341+1. ``datetime`` objects are serialized as :rfc:`822` strings.342+2. Any object with an ``__html__`` method (like :class:`~flask.Markup`)343+ will ahve that method called and then the return value is serialized344+ as string.345 341- .. sourcecode:: html+jinja346+The :func:`~htmlsafe_dumps` function of this json module is also available347+as filter called ``|tojson`` in Jinja2. Note that inside `script`348+tags no escaping must take place, so make sure to disable escaping349+with ``|safe`` if you intend to use it inside `script` tags:350 343- <script type=text/javascript>344- doSomethingWith({{ user.username|tojson|safe }});345- </script>351+.. sourcecode:: html+jinja352 347- Note that the ``|tojson`` filter escapes forward slashes properly.353+ <script type=text/javascript>354+ doSomethingWith({{ user.username|tojson|safe }});355+ </script>356 357+Note that the ``|tojson`` filter escapes forward slashes properly.358+359+.. autofunction:: jsonify360+361+.. autofunction:: dumps362+363+.. autofunction:: dump364+365+.. autofunction:: loads366+367+.. autofunction:: load368+369+.. autoclass:: JSONEncoder370+ :members:371+372+.. autoclass:: JSONDecoder373+ :members:374+375 Template Rendering376 ------------------377 378+.. currentmodule:: flask379+380 .. autofunction:: render_template381 382 .. autofunction:: render_template_string383 311 unmodified linesmodified:flask/__init__.py+9 added-5 removed
18 unmodified lines19 from jinja2 import Markup, escape20 21 from .app import Flask, Request, Response22 from .config import Config23-from .helpers import url_for, jsonify, flash, \24- send_file, send_from_directory, get_flashed_messages, \25- get_template_attribute, make_response, safe_join, \23+from .helpers import url_for, flash, send_file, send_from_directory, \24+ get_flashed_messages, get_template_attribute, make_response, safe_join, \25 stream_with_context26 from .globals import current_app, g, request, session, _request_ctx_stack, \27 _app_ctx_stack28 from .ctx import has_request_context, has_app_context, \6 unmodified lines35 from .signals import signals_available, template_rendered, request_started, \36 request_finished, got_request_exception, request_tearing_down, \37 appcontext_tearing_down38 40-# only import json if it's available41-from .helpers import json39+# We're not exposing the actual json module but a convenient wrapper around40+# it.41+from . import json42 43+# This was the only thing that flask used to export at one point and it had44+# a more generic name.45+jsonify = json.jsonify46+47 # backwards compat, goes away in 1.048 from .sessions import SecureCookieSession as Session49 json_available = Truemodified:flask/app.py+13 added-3 removed
22 unmodified lines23 from werkzeug.exceptions import HTTPException, InternalServerError, \24 MethodNotAllowed, BadRequest25 26 from .helpers import _PackageBoundObject, url_for, get_flashed_messages, \27- locked_cached_property, _tojson_filter, _endpoint_from_view_func, \28- find_package27+ locked_cached_property, _endpoint_from_view_func, find_package28+from . import json29 from .wrappers import Request, Response30 from .config import ConfigAttribute, Config31 from .ctx import RequestContext, AppContext, _RequestGlobals32 from .globals import _request_ctx_stack, request204 unmodified lines237 '%(message)s\n' +238 '-' * 80239 )240 241+ #: The JSON encoder class to use. Defaults to :class:`~flask.json.JSONEncoder`.242+ #:243+ #: .. versionadded:: 0.10244+ json_encoder = json.JSONEncoder245+246+ #: The JSON decoder class to use. Defaults to :class:`~flask.json.JSONDecoder`.247+ #:248+ #: .. versionadded:: 0.10249+ json_decoder = json.JSONDecoder250+251 #: Options that are passed directly to the Jinja2 environment.252 jinja_options = ImmutableDict(253 extensions=['jinja2.ext.autoescape', 'jinja2.ext.with_']254 )391 unmodified lines646 rv.globals.update(647 url_for=url_for,648 get_flashed_messages=get_flashed_messages649 )640- rv.filters['tojson'] = _tojson_filter650+ rv.filters['tojson'] = json.htmlsafe_dumps651 return rv652 653 def create_global_jinja_loader(self):654 """Creates the loader for the Jinja2 environment. Can be used to1100 unmodified linesmodified:flask/exceptions.py+1 added-2 removed
7 unmodified lines8 :copyright: (c) 2011 by Armin Ronacher.9 :license: BSD, see LICENSE for more details.10 """11 from werkzeug.exceptions import HTTPException, BadRequest12-from .helpers import json12+from . import json13 14 15 class JSONHTTPException(HTTPException):16 """A base class for HTTP exceptions with ``Content-Type:21 unmodified lines38 39 class JSONBadRequest(JSONHTTPException, BadRequest):40 """Represents an HTTP ``400 Bad Request`` error whose body contains an41 error message in JSON format instead of HTML format (as in the superclass).42-42 """43 44 #: The description of the error which occurred as a string.45 description = (3 unmodified linesmodified:flask/helpers.py-46 removed
21 unmodified lines22 from werkzeug.routing import BuildError23 from werkzeug.urls import url_quote24 from functools import update_wrapper25 26-# Use the same json implementation as itsdangerous on which we27-# depend anyways.28-from itsdangerous import simplejson as json26 30-27 from werkzeug.datastructures import Headers28 from werkzeug.exceptions import NotFound29 30 # this was moved in 0.77 unmodified lines38 from .globals import session, _request_ctx_stack, _app_ctx_stack, \39 current_app, request40 41 46-# figure out if simplejson escapes slashes. This behavior was changed47-# from one version to another without reason.48-_slash_escape = '\\/' not in json.dumps('/')49-50-def _tojson_filter(*args, **kwargs):51- rv = json.dumps(*args, **kwargs)52- if _slash_escape:53- rv = rv.replace('/', '\\/')54- return rv.replace('<!', '<\\u0021')55-56-42 # sentinel43 _missing = object()44 45 84 unmodified lines130 wrapped_g.next()131 return wrapped_g132 133 149-def jsonify(*args, **kwargs):150- """Creates a :class:`~flask.Response` with the JSON representation of151- the given arguments with an `application/json` mimetype. The arguments152- to this function are the same as to the :class:`dict` constructor.153-154- Example usage::155-156- @app.route('/_get_current_user')157- def get_current_user():158- return jsonify(username=g.user.username,159- email=g.user.email,160- id=g.user.id)161-162- This will send a JSON response like this to the browser::163-164- {165- "username": "admin",166- "email": "admin@localhost",167- "id": 42168- }169-170- This requires Python 2.6 or an installed version of simplejson. For171- security reasons only objects are supported toplevel. For more172- information about this, have a look at :ref:`json-security`.173-174- .. versionadded:: 0.2175- """176- return current_app.response_class(json.dumps(dict(*args, **kwargs),177- indent=None if request.is_xhr else 2), mimetype='application/json')178-179-134 def make_response(*args):135 """Sometimes it is necessary to set additional headers in a view. Because136 views do not have to return response objects but can return a value that137 is converted into a response object by Flask itself, it becomes tricky to694 unmodified linesadded:flask/json.py+146 added
1+# -*- coding: utf-8 -*-2+"""3+ flask.jsonimpl4+ ~~~~~~~~~~~~~~5+6+ Implementation helpers for the JSON support in Flask.7+8+ :copyright: (c) 2012 by Armin Ronacher.9+ :license: BSD, see LICENSE for more details.10+"""11+from datetime import datetime12+from .globals import current_app, request13+14+from werkzeug.http import http_date15+16+# Use the same json implementation as itsdangerous on which we17+# depend anyways.18+from itsdangerous import simplejson as _json19+20+21+# figure out if simplejson escapes slashes. This behavior was changed22+# from one version to another without reason.23+_slash_escape = '\\/' not in _json.dumps('/')24+25+26+__all__ = ['dump', 'dumps', 'load', 'loads', 'htmlsafe_dump',27+ 'htmlsafe_dumps', 'JSONDecoder', 'JSONEncoder',28+ 'jsonify']29+30+31+class JSONEncoder(_json.JSONEncoder):32+ """The default Flask JSON encoder. This one extends the default simplejson33+ encoder by also supporting ``datetime`` objects as well as ``Markup``34+ objects which are serialized as RFC 822 datetime strings (same as the HTTP35+ date format). In order to support more data types override the36+ :meth:`default` method.37+ """38+39+ def default(self, o):40+ """Implement this method in a subclass such that it returns a41+ serializable object for ``o``, or calls the base implementation (to42+ raise a ``TypeError``).43+44+ For example, to support arbitrary iterators, you could implement45+ default like this::46+47+ def default(self, o):48+ try:49+ iterable = iter(o)50+ except TypeError:51+ pass52+ else:53+ return list(iterable)54+ return JSONEncoder.default(self, o)55+ """56+ if isinstance(o, datetime):57+ return http_date(o)58+ if hasattr(o, '__html__'):59+ return unicode(o.__html__())60+ return _json.JSONEncoder.default(self, o)61+62+63+class JSONDecoder(_json.JSONDecoder):64+ """The default JSON decoder. This one does not change the behavior from65+ the default simplejson encoder. Consult the :mod:`json` documentation66+ for more information. This decoder is not only used for the load67+ functions of this module but also :attr:`~flask.Request`.68+ """69+70+71+def dumps(obj, **kwargs):72+ """Serialize ``obj`` to a JSON formatted ``str`` by using the application's73+ configured encoder (:attr:`~flask.Flask.json_encoder`).74+ """75+ kwargs.setdefault('cls', current_app.json_encoder)76+ return _json.dumps(obj, **kwargs)77+78+79+def dump(obj, fp, **kwargs):80+ """Like :func:`dumps` but writes into a file object."""81+ kwargs.setdefault('cls', current_app.json_encoder)82+ return _json.dump(obj, fp, **kwargs)83+84+85+def loads(s, **kwargs):86+ """Unserialize a JSON object from a string ``s`` by using the application's87+ configured decoder (:attr:`~flask.Flask.json_decoder`).88+ """89+ kwargs.setdefault('cls', current_app.json_decoder)90+ return _json.loads(s, **kwargs)91+92+93+def load(fp, **kwargs):94+ """Like :func:`loads` but reads from a file object.95+ """96+ kwargs.setdefault('cls', current_app.json_decoder)97+ return _json.load(fp, **kwargs)98+99+100+def htmlsafe_dumps(obj, **kwargs):101+ """Works exactly like :func:`dumps` but is safe for use in ``<script>``102+ tags. It accepts the same arguments and returns a JSON string. Note that103+ this is available in templates through the ``|tojson`` filter but it will104+ have to be wrapped in ``|safe`` unless **true** XHTML is being used.105+ """106+ rv = dumps(obj, **kwargs)107+ if _slash_escape:108+ rv = rv.replace('/', '\\/')109+ return rv.replace('<!', '<\\u0021')110+111+112+def htmlsafe_dump(obj, fp, **kwargs):113+ """Like :func:`htmlsafe_dumps` but writes into a file object."""114+ fp.write(htmlsafe_dumps(obj, **kwargs))115+116+117+def jsonify(*args, **kwargs):118+ """Creates a :class:`~flask.Response` with the JSON representation of119+ the given arguments with an `application/json` mimetype. The arguments120+ to this function are the same as to the :class:`dict` constructor.121+122+ Example usage::123+124+ @app.route('/_get_current_user')125+ def get_current_user():126+ return jsonify(username=g.user.username,127+ email=g.user.email,128+ id=g.user.id)129+130+ This will send a JSON response like this to the browser::131+132+ {133+ "username": "admin",134+ "email": "admin@localhost",135+ "id": 42136+ }137+138+ This requires Python 2.6 or an installed version of simplejson. For139+ security reasons only objects are supported toplevel. For more140+ information about this, have a look at :ref:`json-security`.141+142+ .. versionadded:: 0.2143+ """144+ return current_app.response_class(dumps(dict(*args, **kwargs),145+ indent=None if request.is_xhr else 2),146+ mimetype='application/json')modified:flask/sessions.py+1 added-2 removed
11 unmodified lines12 import hashlib13 from datetime import datetime14 from werkzeug.http import http_date, parse_date15 from werkzeug.datastructures import CallbackDict16-from .helpers import json17-from . import Markup16+from . import Markup, json17 18 from itsdangerous import URLSafeTimedSerializer, BadSignature19 20 274 unmodified linesmodified:flask/wrappers.py+1 added-1 removed
12 unmodified lines13 from werkzeug.utils import cached_property14 15 from .exceptions import JSONBadRequest16 from .debughelpers import attach_enctype_error_multidict17-from .helpers import json17+from . import json18 from .globals import _request_ctx_stack19 20 21 class Request(RequestBase):125 unmodified linesmodified:CHANGES+3 added
15 unmodified lines16 - Set the content-length header for x-sendfile.17 - ``tojson`` filter now does not escape script blocks in HTML5 parsers.18 - Flask will now raise an error if you attempt to register a new function19 on an already used endpoint.20+- Added wrapper module around simplejson and added default serialization21+ of datetime objects. This allows much easier customization of how22+ JSON is handled by Flask or any Flask extension.23 24 Version 0.925 -----------26 365 unmodified lines