Skip to content
Myr

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

9 files+224 added−81 removed

modified:docs/api.rst+50 added-22 removed
310 unmodified lines
311.. autofunction:: flash312313.. autofunction:: get_flashed_messages314315Returning JSON316--------------315JSON Support316------------317318.. autofunction:: jsonify318.. module:: flask.json319320.. data:: json320Flask uses ``simplejson`` for the JSON implementation. Since simplejson321is provided both by the standard library as well as extension Flask will322try simplejson first and then fall back to the stdlib json module. On top323of that it will delegate access to the current application's JSOn encoders324and decoders for easier customization.325322 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::326So for starters instead of doing::327325 try:326 import simplejson as json327 except ImportError:328 import json328 try:329 import simplejson as json330 except ImportError:331 import json332330 You can instead just do this::333You can instead just do this::334332 from flask import json335 from flask import json336334 For usage examples, read the :mod:`json` documentation.337For usage examples, read the :mod:`json` documentation in the standard338lirbary. The following extensions are by default applied to the stdlib's339JSON module:340336 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:3411. ``datetime`` objects are serialized as :rfc:`822` strings.3422. 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.345341 .. sourcecode:: html+jinja346The :func:`~htmlsafe_dumps` function of this json module is also available347as filter called ``|tojson`` in Jinja2. Note that inside `script`348tags no escaping must take place, so make sure to disable escaping349with ``|safe`` if you intend to use it inside `script` tags:350343 <script type=text/javascript>344 doSomethingWith({{ user.username|tojson|safe }});345 </script>351.. sourcecode:: html+jinja352347 Note that the ``|tojson`` filter escapes forward slashes properly.353 <script type=text/javascript>354 doSomethingWith({{ user.username|tojson|safe }});355 </script>356357Note that the ``|tojson`` filter escapes forward slashes properly.358359.. autofunction:: jsonify360361.. autofunction:: dumps362363.. autofunction:: dump364365.. autofunction:: loads366367.. autofunction:: load368369.. autoclass:: JSONEncoder370 :members:371372.. autoclass:: JSONDecoder373 :members:374375Template Rendering376------------------377378.. currentmodule:: flask379380.. autofunction:: render_template381382.. autofunction:: render_template_string383
311 unmodified lines
modified:flask/__init__.py+9 added-5 removed
18 unmodified lines
19from jinja2 import Markup, escape2021from .app import Flask, Request, Response22from .config import Config23from .helpers import url_for, jsonify, flash, \24 send_file, send_from_directory, get_flashed_messages, \25 get_template_attribute, make_response, safe_join, \23from .helpers import url_for, flash, send_file, send_from_directory, \24 get_flashed_messages, get_template_attribute, make_response, safe_join, \25 stream_with_context26from .globals import current_app, g, request, session, _request_ctx_stack, \27 _app_ctx_stack28from .ctx import has_request_context, has_app_context, \
6 unmodified lines
35from .signals import signals_available, template_rendered, request_started, \36 request_finished, got_request_exception, request_tearing_down, \37 appcontext_tearing_down3840# only import json if it's available41from .helpers import json39# We're not exposing the actual json module but a convenient wrapper around40# it.41from . import json4243# This was the only thing that flask used to export at one point and it had44# a more generic name.45jsonify = json.jsonify4647# backwards compat, goes away in 1.048from .sessions import SecureCookieSession as Session49json_available = True
modified:flask/app.py+13 added-3 removed
22 unmodified lines
23from werkzeug.exceptions import HTTPException, InternalServerError, \24 MethodNotAllowed, BadRequest2526from .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_package28from . import json29from .wrappers import Request, Response30from .config import ConfigAttribute, Config31from .ctx import RequestContext, AppContext, _RequestGlobals32from .globals import _request_ctx_stack, request
204 unmodified lines
237 '%(message)s\n' +238 '-' * 80239 )240241 #: The JSON encoder class to use. Defaults to :class:`~flask.json.JSONEncoder`.242 #:243 #: .. versionadded:: 0.10244 json_encoder = json.JSONEncoder245246 #: The JSON decoder class to use. Defaults to :class:`~flask.json.JSONDecoder`.247 #:248 #: .. versionadded:: 0.10249 json_decoder = json.JSONDecoder250251 #: Options that are passed directly to the Jinja2 environment.252 jinja_options = ImmutableDict(253 extensions=['jinja2.ext.autoescape', 'jinja2.ext.with_']254 )
391 unmodified lines
646 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 rv652653 def create_global_jinja_loader(self):654 """Creates the loader for the Jinja2 environment. Can be used to
1100 unmodified lines
modified:flask/exceptions.py+1 added-2 removed
7 unmodified lines
8 :copyright: (c) 2011 by Armin Ronacher.9 :license: BSD, see LICENSE for more details.10"""11from werkzeug.exceptions import HTTPException, BadRequest12from .helpers import json12from . import json131415class JSONHTTPException(HTTPException):16 """A base class for HTTP exceptions with ``Content-Type:
21 unmodified lines
3839class 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).4242 """4344 #: The description of the error which occurred as a string.45 description = (
3 unmodified lines
modified:flask/helpers.py-46 removed
21 unmodified lines
22from werkzeug.routing import BuildError23from werkzeug.urls import url_quote24from functools import update_wrapper2526# Use the same json implementation as itsdangerous on which we27# depend anyways.28from itsdangerous import simplejson as json263027from werkzeug.datastructures import Headers28from werkzeug.exceptions import NotFound2930# this was moved in 0.7
7 unmodified lines
38from .globals import session, _request_ctx_stack, _app_ctx_stack, \39 current_app, request404146# figure out if simplejson escapes slashes. This behavior was changed47# from one version to another without reason.48_slash_escape = '\\/' not in json.dumps('/')4950def _tojson_filter(*args, **kwargs):51 rv = json.dumps(*args, **kwargs)52 if _slash_escape:53 rv = rv.replace('/', '\\/')54 return rv.replace('<!', '<\\u0021')555642# sentinel43_missing = object()4445
84 unmodified lines
130 wrapped_g.next()131 return wrapped_g132133149def 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.153154 Example usage::155156 @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)161162 This will send a JSON response like this to the browser::163164 {165 "username": "admin",166 "email": "admin@localhost",167 "id": 42168 }169170 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`.173174 .. 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')178179134def 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 to
694 unmodified lines
added:flask/json.py+146 added
1# -*- coding: utf-8 -*-2"""3 flask.jsonimpl4 ~~~~~~~~~~~~~~56 Implementation helpers for the JSON support in Flask.78 :copyright: (c) 2012 by Armin Ronacher.9 :license: BSD, see LICENSE for more details.10"""11from datetime import datetime12from .globals import current_app, request1314from werkzeug.http import http_date1516# Use the same json implementation as itsdangerous on which we17# depend anyways.18from itsdangerous import simplejson as _json192021# figure out if simplejson escapes slashes. This behavior was changed22# from one version to another without reason.23_slash_escape = '\\/' not in _json.dumps('/')242526__all__ = ['dump', 'dumps', 'load', 'loads', 'htmlsafe_dump',27 'htmlsafe_dumps', 'JSONDecoder', 'JSONEncoder',28 'jsonify']293031class 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 """3839 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``).4344 For example, to support arbitrary iterators, you could implement45 default like this::4647 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)616263class 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 """697071def 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)777879def 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)838485def 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)919293def 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)9899100def 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')110111112def htmlsafe_dump(obj, fp, **kwargs):113 """Like :func:`htmlsafe_dumps` but writes into a file object."""114 fp.write(htmlsafe_dumps(obj, **kwargs))115116117def 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.121122 Example usage::123124 @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)129130 This will send a JSON response like this to the browser::131132 {133 "username": "admin",134 "email": "admin@localhost",135 "id": 42136 }137138 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`.141142 .. 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 lines
12import hashlib13from datetime import datetime14from werkzeug.http import http_date, parse_date15from werkzeug.datastructures import CallbackDict16from .helpers import json17from . import Markup16from . import Markup, json1718from itsdangerous import URLSafeTimedSerializer, BadSignature1920
274 unmodified lines
modified:flask/wrappers.py+1 added-1 removed
12 unmodified lines
13from werkzeug.utils import cached_property1415from .exceptions import JSONBadRequest16from .debughelpers import attach_enctype_error_multidict17from .helpers import json17from . import json18from .globals import _request_ctx_stack192021class Request(RequestBase):
125 unmodified lines
modified:CHANGES+3 added
15 unmodified lines
16- 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.2324Version 0.925-----------26
365 unmodified lines