Skip to content
Myr

Merge pull request #2352 from davidism/json-object-hook

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Make session serializer extensible

authored by David Lord · committed by GitHub · parents c7f433c, fd8b959 · Browse files · 8 files+668 added−381 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

8 files+668 added−381 removed

  • tests:+87 added−19 removed
  • other:+581 added−362 removed

8 files+668 added−381 removed

modified:docs/api.rst+2 added-12 removed
169 unmodified lines
170171.. autoclass:: SessionMixin172 :members:173174.. autodata:: session_json_serializer175176 This object provides dumping and loading methods similar to simplejson177 but it also tags certain builtin Python objects that commonly appear in178 sessions. Currently the following extended values are supported in179 the JSON it dumps:180181 - :class:`~markupsafe.Markup` objects182 - :class:`~uuid.UUID` objects183 - :class:`~datetime.datetime` objects184 - :class:`tuple`\s185174.. admonition:: Notice175176 The ``PERMANENT_SESSION_LIFETIME`` config key can also be an integer177 starting with Flask 0.8. Either catch this down yourself or use
163 unmodified lines
341342.. autoclass:: JSONDecoder343 :members:344345.. automodule:: flask.json.tag346347Template Rendering348------------------349350.. currentmodule:: flask
475 unmodified lines
added:flask/json/__init__.py+271 added
1# -*- coding: utf-8 -*-2import io3import uuid4from datetime import date5from flask.globals import current_app, request6from flask._compat import text_type, PY278from werkzeug.http import http_date9from jinja2 import Markup1011# Use the same json implementation as itsdangerous on which we12# depend anyways.13from itsdangerous import json as _json141516# Figure out if simplejson escapes slashes. This behavior was changed17# from one version to another without reason.18_slash_escape = '\\/' not in _json.dumps('/')192021__all__ = ['dump', 'dumps', 'load', 'loads', 'htmlsafe_dump',22 'htmlsafe_dumps', 'JSONDecoder', 'JSONEncoder',23 'jsonify']242526def _wrap_reader_for_text(fp, encoding):27 if isinstance(fp.read(0), bytes):28 fp = io.TextIOWrapper(io.BufferedReader(fp), encoding)29 return fp303132def _wrap_writer_for_text(fp, encoding):33 try:34 fp.write('')35 except TypeError:36 fp = io.TextIOWrapper(fp, encoding)37 return fp383940class JSONEncoder(_json.JSONEncoder):41 """The default Flask JSON encoder. This one extends the default simplejson42 encoder by also supporting ``datetime`` objects, ``UUID`` as well as43 ``Markup`` objects which are serialized as RFC 822 datetime strings (same44 as the HTTP date format). In order to support more data types override the45 :meth:`default` method.46 """4748 def default(self, o):49 """Implement this method in a subclass such that it returns a50 serializable object for ``o``, or calls the base implementation (to51 raise a :exc:`TypeError`).5253 For example, to support arbitrary iterators, you could implement54 default like this::5556 def default(self, o):57 try:58 iterable = iter(o)59 except TypeError:60 pass61 else:62 return list(iterable)63 return JSONEncoder.default(self, o)64 """65 if isinstance(o, date):66 return http_date(o.timetuple())67 if isinstance(o, uuid.UUID):68 return str(o)69 if hasattr(o, '__html__'):70 return text_type(o.__html__())71 return _json.JSONEncoder.default(self, o)727374class JSONDecoder(_json.JSONDecoder):75 """The default JSON decoder. This one does not change the behavior from76 the default simplejson decoder. Consult the :mod:`json` documentation77 for more information. This decoder is not only used for the load78 functions of this module but also :attr:`~flask.Request`.79 """808182def _dump_arg_defaults(kwargs):83 """Inject default arguments for dump functions."""84 if current_app:85 bp = current_app.blueprints.get(request.blueprint) if request else None86 kwargs.setdefault(87 'cls',88 bp.json_encoder if bp and bp.json_encoder89 else current_app.json_encoder90 )9192 if not current_app.config['JSON_AS_ASCII']:93 kwargs.setdefault('ensure_ascii', False)9495 kwargs.setdefault('sort_keys', current_app.config['JSON_SORT_KEYS'])96 else:97 kwargs.setdefault('sort_keys', True)98 kwargs.setdefault('cls', JSONEncoder)99100101def _load_arg_defaults(kwargs):102 """Inject default arguments for load functions."""103 if current_app:104 bp = current_app.blueprints.get(request.blueprint) if request else None105 kwargs.setdefault(106 'cls',107 bp.json_decoder if bp and bp.json_decoder108 else current_app.json_decoder109 )110 else:111 kwargs.setdefault('cls', JSONDecoder)112113114def dumps(obj, **kwargs):115 """Serialize ``obj`` to a JSON formatted ``str`` by using the application's116 configured encoder (:attr:`~flask.Flask.json_encoder`) if there is an117 application on the stack.118119 This function can return ``unicode`` strings or ascii-only bytestrings by120 default which coerce into unicode strings automatically. That behavior by121 default is controlled by the ``JSON_AS_ASCII`` configuration variable122 and can be overridden by the simplejson ``ensure_ascii`` parameter.123 """124 _dump_arg_defaults(kwargs)125 encoding = kwargs.pop('encoding', None)126 rv = _json.dumps(obj, **kwargs)127 if encoding is not None and isinstance(rv, text_type):128 rv = rv.encode(encoding)129 return rv130131132def dump(obj, fp, **kwargs):133 """Like :func:`dumps` but writes into a file object."""134 _dump_arg_defaults(kwargs)135 encoding = kwargs.pop('encoding', None)136 if encoding is not None:137 fp = _wrap_writer_for_text(fp, encoding)138 _json.dump(obj, fp, **kwargs)139140141def loads(s, **kwargs):142 """Unserialize a JSON object from a string ``s`` by using the application's143 configured decoder (:attr:`~flask.Flask.json_decoder`) if there is an144 application on the stack.145 """146 _load_arg_defaults(kwargs)147 if isinstance(s, bytes):148 s = s.decode(kwargs.pop('encoding', None) or 'utf-8')149 return _json.loads(s, **kwargs)150151152def load(fp, **kwargs):153 """Like :func:`loads` but reads from a file object.154 """155 _load_arg_defaults(kwargs)156 if not PY2:157 fp = _wrap_reader_for_text(fp, kwargs.pop('encoding', None) or 'utf-8')158 return _json.load(fp, **kwargs)159160161def htmlsafe_dumps(obj, **kwargs):162 """Works exactly like :func:`dumps` but is safe for use in ``<script>``163 tags. It accepts the same arguments and returns a JSON string. Note that164 this is available in templates through the ``|tojson`` filter which will165 also mark the result as safe. Due to how this function escapes certain166 characters this is safe even if used outside of ``<script>`` tags.167168 The following characters are escaped in strings:169170 - ``<``171 - ``>``172 - ``&``173 - ``'``174175 This makes it safe to embed such strings in any place in HTML with the176 notable exception of double quoted attributes. In that case single177 quote your attributes or HTML escape it in addition.178179 .. versionchanged:: 0.10180 This function's return value is now always safe for HTML usage, even181 if outside of script tags or if used in XHTML. This rule does not182 hold true when using this function in HTML attributes that are double183 quoted. Always single quote attributes if you use the ``|tojson``184 filter. Alternatively use ``|tojson|forceescape``.185 """186 rv = dumps(obj, **kwargs) \187 .replace(u'<', u'\\u003c') \188 .replace(u'>', u'\\u003e') \189 .replace(u'&', u'\\u0026') \190 .replace(u"'", u'\\u0027')191 if not _slash_escape:192 rv = rv.replace('\\/', '/')193 return rv194195196def htmlsafe_dump(obj, fp, **kwargs):197 """Like :func:`htmlsafe_dumps` but writes into a file object."""198 fp.write(text_type(htmlsafe_dumps(obj, **kwargs)))199200201def jsonify(*args, **kwargs):202 """This function wraps :func:`dumps` to add a few enhancements that make203 life easier. It turns the JSON output into a :class:`~flask.Response`204 object with the :mimetype:`application/json` mimetype. For convenience, it205 also converts multiple arguments into an array or multiple keyword arguments206 into a dict. This means that both ``jsonify(1,2,3)`` and207 ``jsonify([1,2,3])`` serialize to ``[1,2,3]``.208209 For clarity, the JSON serialization behavior has the following differences210 from :func:`dumps`:211212 1. Single argument: Passed straight through to :func:`dumps`.213 2. Multiple arguments: Converted to an array before being passed to214 :func:`dumps`.215 3. Multiple keyword arguments: Converted to a dict before being passed to216 :func:`dumps`.217 4. Both args and kwargs: Behavior undefined and will throw an exception.218219 Example usage::220221 from flask import jsonify222223 @app.route('/_get_current_user')224 def get_current_user():225 return jsonify(username=g.user.username,226 email=g.user.email,227 id=g.user.id)228229 This will send a JSON response like this to the browser::230231 {232 "username": "admin",233 "email": "admin@localhost",234 "id": 42235 }236237238 .. versionchanged:: 0.11239 Added support for serializing top-level arrays. This introduces a240 security risk in ancient browsers. See :ref:`json-security` for details.241242 This function's response will be pretty printed if the243 ``JSONIFY_PRETTYPRINT_REGULAR`` config parameter is set to True or the244 Flask app is running in debug mode. Compressed (not pretty) formatting245 currently means no indents and no spaces after separators.246247 .. versionadded:: 0.2248 """249250 indent = None251 separators = (',', ':')252253 if current_app.config['JSONIFY_PRETTYPRINT_REGULAR'] or current_app.debug:254 indent = 2255 separators = (', ', ': ')256257 if args and kwargs:258 raise TypeError('jsonify() behavior undefined when passed both args and kwargs')259 elif len(args) == 1: # single args are passed directly to dumps()260 data = args[0]261 else:262 data = args or kwargs263264 return current_app.response_class(265 (dumps(data, indent=indent, separators=separators), '\n'),266 mimetype=current_app.config['JSONIFY_MIMETYPE']267 )268269270def tojson_filter(obj, **kwargs):271 return Markup(htmlsafe_dumps(obj, **kwargs))
added:flask/json/tag.py+297 added
1"""2Tagged JSON3~~~~~~~~~~~45A compact representation for lossless serialization of non-standard JSON types.6:class:`~flask.sessions.SecureCookieSessionInterface` uses this to serialize7the session data, but it may be useful in other places. It can be extended to8support other types.910.. autoclass:: TaggedJSONSerializer11 :members:1213.. autoclass:: JSONTag14 :members:1516Let's seen an example that adds support for :class:`~collections.OrderedDict`.17Dicts don't have an order in Python or JSON, so to handle this we will dump18the items as a list of ``[key, value]`` pairs. Subclass :class:`JSONTag` and19give it the new key ``' od'`` to identify the type. The session serializer20processes dicts first, so insert the new tag at the front of the order since21``OrderedDict`` must be processed before ``dict``. ::2223 from flask.json.tag import JSONTag2425 class TagOrderedDict(JSONTag):26 __slots__ = ('serializer',)27 key = ' od'2829 def check(self, value):30 return isinstance(value, OrderedDict)3132 def to_json(self, value):33 return [[k, self.serializer.tag(v)] for k, v in iteritems(value)]3435 def to_python(self, value):36 return OrderedDict(value)3738 app.session_interface.serializer.register(TagOrderedDict, 0)3940"""4142from base64 import b64decode, b64encode43from datetime import datetime44from uuid import UUID4546from jinja2 import Markup47from werkzeug.http import http_date, parse_date4849from flask._compat import iteritems, text_type50from flask.json import dumps, loads515253class JSONTag(object):54 """Base class for defining type tags for :class:`TaggedJSONSerializer`."""5556 __slots__ = ('serializer',)5758 #: The tag to mark the serialized object with. If ``None``, this tag is59 #: only used as an intermediate step during tagging.60 key = None6162 def __init__(self, serializer):63 """Create a tagger for the given serializer."""64 self.serializer = serializer6566 def check(self, value):67 """Check if the given value should be tagged by this tag."""68 raise NotImplementedError6970 def to_json(self, value):71 """Convert the Python object to an object that is a valid JSON type.72 The tag will be added later."""73 raise NotImplementedError7475 def to_python(self, value):76 """Convert the JSON representation back to the correct type. The tag77 will already be removed."""78 raise NotImplementedError7980 def tag(self, value):81 """Convert the value to a valid JSON type and add the tag structure82 around it."""83 return {self.key: self.to_json(value)}848586class TagDict(JSONTag):87 """Tag for 1-item dicts whose only key matches a registered tag.8889 Internally, the dict key is suffixed with `__`, and the suffix is removed90 when deserializing.91 """9293 __slots__ = ()94 key = ' di'9596 def check(self, value):97 return (98 isinstance(value, dict)99 and len(value) == 1100 and next(iter(value)) in self.serializer.tags101 )102103 def to_json(self, value):104 key = next(iter(value))105 return {key + '__': self.serializer.tag(value[key])}106107 def to_python(self, value):108 key = next(iter(value))109 return {key[:-2]: value[key]}110111112class PassDict(JSONTag):113 __slots__ = ()114115 def check(self, value):116 return isinstance(value, dict)117118 def to_json(self, value):119 # JSON objects may only have string keys, so don't bother tagging the120 # key here.121 return dict((k, self.serializer.tag(v)) for k, v in iteritems(value))122123 tag = to_json124125126class TagTuple(JSONTag):127 __slots__ = ()128 key = ' t'129130 def check(self, value):131 return isinstance(value, tuple)132133 def to_json(self, value):134 return [self.serializer.tag(item) for item in value]135136 def to_python(self, value):137 return tuple(value)138139140class PassList(JSONTag):141 __slots__ = ()142143 def check(self, value):144 return isinstance(value, list)145146 def to_json(self, value):147 return [self.serializer.tag(item) for item in value]148149 tag = to_json150151152class TagBytes(JSONTag):153 __slots__ = ()154 key = ' b'155156 def check(self, value):157 return isinstance(value, bytes)158159 def to_json(self, value):160 return b64encode(value).decode('ascii')161162 def to_python(self, value):163 return b64decode(value)164165166class TagMarkup(JSONTag):167 """Serialize anything matching the :class:`~flask.Markup` API by168 having a ``__html__`` method to the result of that method. Always169 deserializes to an instance of :class:`~flask.Markup`."""170171 __slots__ = ()172 key = ' m'173174 def check(self, value):175 return callable(getattr(value, '__html__', None))176177 def to_json(self, value):178 return text_type(value.__html__())179180 def to_python(self, value):181 return Markup(value)182183184class TagUUID(JSONTag):185 __slots__ = ()186 key = ' u'187188 def check(self, value):189 return isinstance(value, UUID)190191 def to_json(self, value):192 return value.hex193194 def to_python(self, value):195 return UUID(value)196197198class TagDateTime(JSONTag):199 __slots__ = ()200 key = ' d'201202 def check(self, value):203 return isinstance(value, datetime)204205 def to_json(self, value):206 return http_date(value)207208 def to_python(self, value):209 return parse_date(value)210211212class TaggedJSONSerializer(object):213 """Serializer that uses a tag system to compactly represent objects that214 are not JSON types. Passed as the intermediate serializer to215 :class:`itsdangerous.Serializer`.216217 The following extra types are supported:218219 * :class:`dict`220 * :class:`tuple`221 * :class:`bytes`222 * :class:`~flask.Markup`223 * :class:`~uuid.UUID`224 * :class:`~datetime.datetime`225 """226227 __slots__ = ('tags', 'order')228229 #: Tag classes to bind when creating the serializer. Other tags can be230 #: added later using :meth:`~register`.231 default_tags = [232 TagDict, PassDict, TagTuple, PassList, TagBytes, TagMarkup, TagUUID,233 TagDateTime,234 ]235236 def __init__(self):237 self.tags = {}238 self.order = []239240 for cls in self.default_tags:241 self.register(cls)242243 def register(self, tag_class, force=False, index=-1):244 """Register a new tag with this serializer.245246 :param tag_class: tag class to register. Will be instantiated with this247 serializer instance.248 :param force: overwrite an existing tag. If false (default), a249 :exc:`KeyError` is raised.250 :param index: index to insert the new tag in the tag order. Useful when251 the new tag is a special case of an existing tag. If -1 (default),252 the tag is appended to the end of the order.253254 :raise KeyError: if the tag key is already registered and ``force`` is255 not true.256 """257 tag = tag_class(self)258 key = tag.key259260 if key is not None:261 if not force and key in self.tags:262 raise KeyError("Tag '{0}' is already registered.".format(key))263264 self.tags[key] = tag265266 if index == -1:267 self.order.append(tag)268 else:269 self.order.insert(index, tag)270271 def tag(self, value):272 """Convert a value to a tagged representation if necessary."""273 for tag in self.order:274 if tag.check(value):275 return tag.tag(value)276277 return value278279 def untag(self, value):280 """Convert a tagged representation back to the original type."""281 if len(value) != 1:282 return value283284 key = next(iter(value))285286 if key not in self.tags:287 return value288289 return self.tags[key].to_python(value[key])290291 def dumps(self, value):292 """Tag the value and dump it to a compact JSON string."""293 return dumps(self.tag(value), separators=(',', ':'))294295 def loads(self, value):296 """Load data from a JSON string and deserialized any tagged objects."""297 return loads(value, object_hook=self.untag)
deleted:flask/json.py-280 removed
1# -*- coding: utf-8 -*-2"""3 flask.json4 ~~~~~~~~~~56 Implementation helpers for the JSON support in Flask.78 :copyright: (c) 2015 by Armin Ronacher.9 :license: BSD, see LICENSE for more details.10"""11import io12import uuid13from datetime import date14from .globals import current_app, request15from ._compat import text_type, PY21617from werkzeug.http import http_date18from jinja2 import Markup1920# Use the same json implementation as itsdangerous on which we21# depend anyways.22from itsdangerous import json as _json232425# Figure out if simplejson escapes slashes. This behavior was changed26# from one version to another without reason.27_slash_escape = '\\/' not in _json.dumps('/')282930__all__ = ['dump', 'dumps', 'load', 'loads', 'htmlsafe_dump',31 'htmlsafe_dumps', 'JSONDecoder', 'JSONEncoder',32 'jsonify']333435def _wrap_reader_for_text(fp, encoding):36 if isinstance(fp.read(0), bytes):37 fp = io.TextIOWrapper(io.BufferedReader(fp), encoding)38 return fp394041def _wrap_writer_for_text(fp, encoding):42 try:43 fp.write('')44 except TypeError:45 fp = io.TextIOWrapper(fp, encoding)46 return fp474849class JSONEncoder(_json.JSONEncoder):50 """The default Flask JSON encoder. This one extends the default simplejson51 encoder by also supporting ``datetime`` objects, ``UUID`` as well as52 ``Markup`` objects which are serialized as RFC 822 datetime strings (same53 as the HTTP date format). In order to support more data types override the54 :meth:`default` method.55 """5657 def default(self, o):58 """Implement this method in a subclass such that it returns a59 serializable object for ``o``, or calls the base implementation (to60 raise a :exc:`TypeError`).6162 For example, to support arbitrary iterators, you could implement63 default like this::6465 def default(self, o):66 try:67 iterable = iter(o)68 except TypeError:69 pass70 else:71 return list(iterable)72 return JSONEncoder.default(self, o)73 """74 if isinstance(o, date):75 return http_date(o.timetuple())76 if isinstance(o, uuid.UUID):77 return str(o)78 if hasattr(o, '__html__'):79 return text_type(o.__html__())80 return _json.JSONEncoder.default(self, o)818283class JSONDecoder(_json.JSONDecoder):84 """The default JSON decoder. This one does not change the behavior from85 the default simplejson decoder. Consult the :mod:`json` documentation86 for more information. This decoder is not only used for the load87 functions of this module but also :attr:`~flask.Request`.88 """899091def _dump_arg_defaults(kwargs):92 """Inject default arguments for dump functions."""93 if current_app:94 bp = current_app.blueprints.get(request.blueprint) if request else None95 kwargs.setdefault(96 'cls',97 bp.json_encoder if bp and bp.json_encoder98 else current_app.json_encoder99 )100101 if not current_app.config['JSON_AS_ASCII']:102 kwargs.setdefault('ensure_ascii', False)103104 kwargs.setdefault('sort_keys', current_app.config['JSON_SORT_KEYS'])105 else:106 kwargs.setdefault('sort_keys', True)107 kwargs.setdefault('cls', JSONEncoder)108109110def _load_arg_defaults(kwargs):111 """Inject default arguments for load functions."""112 if current_app:113 bp = current_app.blueprints.get(request.blueprint) if request else None114 kwargs.setdefault(115 'cls',116 bp.json_decoder if bp and bp.json_decoder117 else current_app.json_decoder118 )119 else:120 kwargs.setdefault('cls', JSONDecoder)121122123def dumps(obj, **kwargs):124 """Serialize ``obj`` to a JSON formatted ``str`` by using the application's125 configured encoder (:attr:`~flask.Flask.json_encoder`) if there is an126 application on the stack.127128 This function can return ``unicode`` strings or ascii-only bytestrings by129 default which coerce into unicode strings automatically. That behavior by130 default is controlled by the ``JSON_AS_ASCII`` configuration variable131 and can be overridden by the simplejson ``ensure_ascii`` parameter.132 """133 _dump_arg_defaults(kwargs)134 encoding = kwargs.pop('encoding', None)135 rv = _json.dumps(obj, **kwargs)136 if encoding is not None and isinstance(rv, text_type):137 rv = rv.encode(encoding)138 return rv139140141def dump(obj, fp, **kwargs):142 """Like :func:`dumps` but writes into a file object."""143 _dump_arg_defaults(kwargs)144 encoding = kwargs.pop('encoding', None)145 if encoding is not None:146 fp = _wrap_writer_for_text(fp, encoding)147 _json.dump(obj, fp, **kwargs)148149150def loads(s, **kwargs):151 """Unserialize a JSON object from a string ``s`` by using the application's152 configured decoder (:attr:`~flask.Flask.json_decoder`) if there is an153 application on the stack.154 """155 _load_arg_defaults(kwargs)156 if isinstance(s, bytes):157 s = s.decode(kwargs.pop('encoding', None) or 'utf-8')158 return _json.loads(s, **kwargs)159160161def 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)168169170def htmlsafe_dumps(obj, **kwargs):171 """Works exactly like :func:`dumps` but is safe for use in ``<script>``172 tags. It accepts the same arguments and returns a JSON string. Note that173 this is available in templates through the ``|tojson`` filter which will174 also mark the result as safe. Due to how this function escapes certain175 characters this is safe even if used outside of ``<script>`` tags.176177 The following characters are escaped in strings:178179 - ``<``180 - ``>``181 - ``&``182 - ``'``183184 This makes it safe to embed such strings in any place in HTML with the185 notable exception of double quoted attributes. In that case single186 quote your attributes or HTML escape it in addition.187188 .. versionchanged:: 0.10189 This function's return value is now always safe for HTML usage, even190 if outside of script tags or if used in XHTML. This rule does not191 hold true when using this function in HTML attributes that are double192 quoted. Always single quote attributes if you use the ``|tojson``193 filter. Alternatively use ``|tojson|forceescape``.194 """195 rv = dumps(obj, **kwargs) \196 .replace(u'<', u'\\u003c') \197 .replace(u'>', u'\\u003e') \198 .replace(u'&', u'\\u0026') \199 .replace(u"'", u'\\u0027')200 if not _slash_escape:201 rv = rv.replace('\\/', '/')202 return rv203204205def htmlsafe_dump(obj, fp, **kwargs):206 """Like :func:`htmlsafe_dumps` but writes into a file object."""207 fp.write(text_type(htmlsafe_dumps(obj, **kwargs)))208209210def jsonify(*args, **kwargs):211 """This function wraps :func:`dumps` to add a few enhancements that make212 life easier. It turns the JSON output into a :class:`~flask.Response`213 object with the :mimetype:`application/json` mimetype. For convenience, it214 also converts multiple arguments into an array or multiple keyword arguments215 into a dict. This means that both ``jsonify(1,2,3)`` and216 ``jsonify([1,2,3])`` serialize to ``[1,2,3]``.217218 For clarity, the JSON serialization behavior has the following differences219 from :func:`dumps`:220221 1. Single argument: Passed straight through to :func:`dumps`.222 2. Multiple arguments: Converted to an array before being passed to223 :func:`dumps`.224 3. Multiple keyword arguments: Converted to a dict before being passed to225 :func:`dumps`.226 4. Both args and kwargs: Behavior undefined and will throw an exception.227228 Example usage::229230 from flask import jsonify231232 @app.route('/_get_current_user')233 def get_current_user():234 return jsonify(username=g.user.username,235 email=g.user.email,236 id=g.user.id)237238 This will send a JSON response like this to the browser::239240 {241 "username": "admin",242 "email": "admin@localhost",243 "id": 42244 }245246247 .. versionchanged:: 0.11248 Added support for serializing top-level arrays. This introduces a249 security risk in ancient browsers. See :ref:`json-security` for details.250251 This function's response will be pretty printed if the252 ``JSONIFY_PRETTYPRINT_REGULAR`` config parameter is set to True or the253 Flask app is running in debug mode. Compressed (not pretty) formatting254 currently means no indents and no spaces after separators.255256 .. versionadded:: 0.2257 """258259 indent = None260 separators = (',', ':')261262 if current_app.config['JSONIFY_PRETTYPRINT_REGULAR'] or current_app.debug:263 indent = 2264 separators = (', ', ': ')265266 if args and kwargs:267 raise TypeError('jsonify() behavior undefined when passed both args and kwargs')268 elif len(args) == 1: # single args are passed directly to dumps()269 data = args[0]270 else:271 data = args or kwargs272273 return current_app.response_class(274 (dumps(data, indent=indent, separators=separators), '\n'),275 mimetype=current_app.config['JSONIFY_MIMETYPE']276 )277278279def tojson_filter(obj, **kwargs):280 return Markup(htmlsafe_dumps(obj, **kwargs))
modified:flask/sessions.py+8 added-70 removed
6 unmodified lines
78 :copyright: (c) 2015 by Armin Ronacher.9 :license: BSD, see LICENSE for more details.10"""1111import hashlib13import uuid12import warnings15from base64 import b64decode, b64encode13from datetime import datetime1415from itsdangerous import BadSignature, URLSafeTimedSerializer16from werkzeug.datastructures import CallbackDict20from werkzeug.http import http_date, parse_date1722from . import Markup, json23from ._compat import iteritems, text_type24from .helpers import is_ip, total_seconds18from flask.helpers import is_ip, total_seconds19from flask.json.tag import TaggedJSONSerializer202122class SessionMixin(object):23 """Expands a basic dictionary with an accessors that are expected
28 unmodified lines
52 #: session cookie as keys when caching pages, preventing multiple users53 #: from being served the same cache.54 accessed = True5561def _tag(value):62 if isinstance(value, tuple):63 return {' t': [_tag(x) for x in value]}64 elif isinstance(value, uuid.UUID):65 return {' u': value.hex}66 elif isinstance(value, bytes):67 return {' b': b64encode(value).decode('ascii')}68 elif callable(getattr(value, '__html__', None)):69 return {' m': text_type(value.__html__())}70 elif isinstance(value, list):71 return [_tag(x) for x in value]72 elif isinstance(value, datetime):73 return {' d': http_date(value)}74 elif isinstance(value, dict):75 return dict((k, _tag(v)) for k, v in iteritems(value))76 elif isinstance(value, str):77 try:78 return text_type(value)79 except UnicodeError:80 from flask.debughelpers import UnexpectedUnicodeError81 raise UnexpectedUnicodeError(u'A byte string with '82 u'non-ASCII data was passed to the session system '83 u'which can only store unicode strings. Consider '84 u'base64 encoding your string (String was %r)' % value)85 return value568788class TaggedJSONSerializer(object):89 """A customized JSON serializer that supports a few extra types that90 we take for granted when serializing (tuples, markup objects, datetime).91 """9293 def dumps(self, value):94 return json.dumps(_tag(value), separators=(',', ':'))9596 LOADS_MAP = {97 ' t': tuple,98 ' u': uuid.UUID,99 ' b': b64decode,100 ' m': Markup,101 ' d': parse_date,102 }103104 def loads(self, value):105 def object_hook(obj):106 if len(obj) != 1:107 return obj108 the_key, the_value = next(iteritems(obj))109 # Check the key for a corresponding function110 return_function = self.LOADS_MAP.get(the_key)111 if return_function:112 # Pass the value to the function113 return return_function(the_value)114 # Didn't find a function for this object115 return obj116 return json.loads(value, object_hook=object_hook)117118119session_json_serializer = TaggedJSONSerializer()12012157class SecureCookieSession(CallbackDict, SessionMixin):58 """Base class for sessions based on signed cookies."""5960 def __init__(self, initial=None):
98 unmodified lines
159 return isinstance(obj, self.null_session_class)160161 def get_cookie_domain(self, app):162 """Returns the domain that should be set for the session cookie.228 163164 Uses ``SESSION_COOKIE_DOMAIN`` if it is configured, otherwise165 falls back to detecting the domain based on ``SERVER_NAME``.231 166167 Once detected (or if not set at all), ``SESSION_COOKIE_DOMAIN`` is168 updated to avoid re-running the logic.169 """170
81 unmodified lines
252 should be set for this session cookie for this response. If the session253 has been modified, the cookie is set. If the session is permanent and254 the ``SESSION_REFRESH_EACH_REQUEST`` config is true, the cookie is255 always set.321 256257 This check is usually skipped if the session was deleted.258259 .. versionadded:: 0.11260 """
18 unmodified lines
279 """280 raise NotImplementedError()281282283session_json_serializer = TaggedJSONSerializer()284285286class SecureCookieSessionInterface(SessionInterface):287 """The default session interface that stores sessions in signed cookies288 through the :mod:`itsdangerous` module.289 """
75 unmodified lines
modified:tests/test_basic.py+22 added-19 removed
433 unmodified lines
434 app.secret_key = 'development-key'435 now = datetime.utcnow().replace(microsecond=0)436 the_uuid = uuid.uuid4()437438 @app.after_request439 def modify_session(response):440 flask.session['m'] = flask.Markup('Hello!')441 flask.session['u'] = the_uuid442 flask.session['dt'] = now443 flask.session['b'] = b'\xff'444 flask.session['t'] = (1, 2, 3)445 return response446438 @app.route('/')439 def dump_session_contents():449 return pickle.dumps(dict(flask.session))440 flask.session['t'] = (1, 2, 3)441 flask.session['b'] = b'\xff'442 flask.session['m'] = flask.Markup('<html>')443 flask.session['u'] = the_uuid444 flask.session['d'] = now445 flask.session['t_tag'] = {' t': 'not-a-tuple'}446 flask.session['di_t_tag'] = {' t__': 'not-a-tuple'}447 flask.session['di_tag'] = {' di': 'not-a-dict'}448 return '', 204449451 client.get('/')452 rv = pickle.loads(client.get('/').data)453 assert rv['m'] == flask.Markup('Hello!')454 assert type(rv['m']) == flask.Markup455 assert rv['dt'] == now456 assert rv['u'] == the_uuid457 assert rv['b'] == b'\xff'458 assert type(rv['b']) == bytes459 assert rv['t'] == (1, 2, 3)450 with client:451 client.get('/')452 s = flask.session453 assert s['t'] == (1, 2, 3)454 assert type(s['b']) == bytes455 assert s['b'] == b'\xff'456 assert type(s['m']) == flask.Markup457 assert s['m'] == flask.Markup('<html>')458 assert s['u'] == the_uuid459 assert s['d'] == now460 assert s['t_tag'] == {' t': 'not-a-tuple'}461 assert s['di_t_tag'] == {' t__': 'not-a-tuple'}462 assert s['di_tag'] == {' di': 'not-a-dict'}463464465def test_session_cookie_setting(app):466 app.secret_key = 'dev key'
1366 unmodified lines
added:tests/test_json_tag.py+65 added
1from datetime import datetime2from uuid import uuid434import pytest56from flask import Markup7from flask.json.tag import TaggedJSONSerializer, JSONTag8910@pytest.mark.parametrize("data", (11 {' t': (1, 2, 3)},12 {' t__': b'a'},13 {' di': ' di'},14 {'x': (1, 2, 3), 'y': 4},15 (1, 2, 3),16 [(1, 2, 3)],17 b'\xff',18 Markup('<html>'),19 uuid4(),20 datetime.utcnow().replace(microsecond=0),21))22def test_dump_load_unchanged(data):23 s = TaggedJSONSerializer()24 assert s.loads(s.dumps(data)) == data252627def test_duplicate_tag():28 class TagDict(JSONTag):29 key = ' d'3031 s = TaggedJSONSerializer()32 pytest.raises(KeyError, s.register, TagDict)33 s.register(TagDict, force=True, index=0)34 assert isinstance(s.tags[' d'], TagDict)35 assert isinstance(s.order[0], TagDict)363738def test_custom_tag():39 class Foo(object):40 def __init__(self, data):41 self.data = data4243 class TagFoo(JSONTag):44 __slots__ = ()45 key = ' f'4647 def check(self, value):48 return isinstance(value, Foo)4950 def to_json(self, value):51 return self.serializer.tag(value.data)5253 def to_python(self, value):54 return Foo(value)5556 s = TaggedJSONSerializer()57 s.register(TagFoo)58 assert s.loads(s.dumps(Foo('bar'))).data == 'bar'596061def test_tag_interface():62 t = JSONTag(None)63 pytest.raises(NotImplementedError, t.check, None)64 pytest.raises(NotImplementedError, t.to_json, None)65 pytest.raises(NotImplementedError, t.to_python, None)
modified:CHANGES+3 added
63 unmodified lines
64 default when it was set to ``None``.65- ``TRAP_BAD_REQUEST_ERRORS`` is enabled by default in debug mode.66 ``BadRequestKeyError`` has a message with the bad key in debug mode instead67 of the generic bad request message. (`#2348`_)68- Allow registering new tags with ``TaggedJSONSerializer`` to support69 storing other types in the session cookie. (`#2352`_)7071.. _#1489: https://github.com/pallets/flask/pull/148972.. _#1621: https://github.com/pallets/flask/pull/162173.. _#1898: https://github.com/pallets/flask/pull/1898
11 unmodified lines
85.. _#2316: https://github.com/pallets/flask/pull/231686.. _#2319: https://github.com/pallets/flask/pull/231987.. _#2326: https://github.com/pallets/flask/pull/232688.. _#2348: https://github.com/pallets/flask/pull/234889.. _#2352: https://github.com/pallets/flask/pull/23529091Version 0.12.292--------------93
617 unmodified lines