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
Provenance
- Commit
62406e6- Tree
43d65fb- Author
David Lord <davidism@gmail.com>- Committer
GitHub <noreply@github.com>- Parent 1
c7f433c- Parent 2
fd8b959
8 files changed+668 added−381 removed
modified:docs/api.rst+2 added-12 removed
169 unmodified lines170 171 .. autoclass:: SessionMixin172 :members:173 174-.. autodata:: session_json_serializer175-176- 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:180-181- - :class:`~markupsafe.Markup` objects182- - :class:`~uuid.UUID` objects183- - :class:`~datetime.datetime` objects184- - :class:`tuple`\s185-174 .. admonition:: Notice175 176 The ``PERMANENT_SESSION_LIFETIME`` config key can also be an integer177 starting with Flask 0.8. Either catch this down yourself or use163 unmodified lines341 342 .. autoclass:: JSONDecoder343 :members:344 345+.. automodule:: flask.json.tag346+347 Template Rendering348 ------------------349 350 .. currentmodule:: flask475 unmodified linesadded:flask/json/__init__.py+271 added
1+# -*- coding: utf-8 -*-2+import io3+import uuid4+from datetime import date5+from flask.globals import current_app, request6+from flask._compat import text_type, PY27+8+from werkzeug.http import http_date9+from jinja2 import Markup10+11+# Use the same json implementation as itsdangerous on which we12+# depend anyways.13+from itsdangerous import json as _json14+15+16+# Figure out if simplejson escapes slashes. This behavior was changed17+# from one version to another without reason.18+_slash_escape = '\\/' not in _json.dumps('/')19+20+21+__all__ = ['dump', 'dumps', 'load', 'loads', 'htmlsafe_dump',22+ 'htmlsafe_dumps', 'JSONDecoder', 'JSONEncoder',23+ 'jsonify']24+25+26+def _wrap_reader_for_text(fp, encoding):27+ if isinstance(fp.read(0), bytes):28+ fp = io.TextIOWrapper(io.BufferedReader(fp), encoding)29+ return fp30+31+32+def _wrap_writer_for_text(fp, encoding):33+ try:34+ fp.write('')35+ except TypeError:36+ fp = io.TextIOWrapper(fp, encoding)37+ return fp38+39+40+class 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+ """47+48+ 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`).52+53+ For example, to support arbitrary iterators, you could implement54+ default like this::55+56+ 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)72+73+74+class 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+ """80+81+82+def _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+ )91+92+ if not current_app.config['JSON_AS_ASCII']:93+ kwargs.setdefault('ensure_ascii', False)94+95+ kwargs.setdefault('sort_keys', current_app.config['JSON_SORT_KEYS'])96+ else:97+ kwargs.setdefault('sort_keys', True)98+ kwargs.setdefault('cls', JSONEncoder)99+100+101+def _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)112+113+114+def 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.118+119+ 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 rv130+131+132+def 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)139+140+141+def 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)150+151+152+def 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)159+160+161+def 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.167+168+ The following characters are escaped in strings:169+170+ - ``<``171+ - ``>``172+ - ``&``173+ - ``'``174+175+ 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.178+179+ .. 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 rv194+195+196+def 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)))199+200+201+def 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]``.208+209+ For clarity, the JSON serialization behavior has the following differences210+ from :func:`dumps`:211+212+ 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.218+219+ Example usage::220+221+ from flask import jsonify222+223+ @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)228+229+ This will send a JSON response like this to the browser::230+231+ {232+ "username": "admin",233+ "email": "admin@localhost",234+ "id": 42235+ }236+237+238+ .. versionchanged:: 0.11239+ Added support for serializing top-level arrays. This introduces a240+ security risk in ancient browsers. See :ref:`json-security` for details.241+242+ 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.246+247+ .. versionadded:: 0.2248+ """249+250+ indent = None251+ separators = (',', ':')252+253+ if current_app.config['JSONIFY_PRETTYPRINT_REGULAR'] or current_app.debug:254+ indent = 2255+ separators = (', ', ': ')256+257+ 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 kwargs263+264+ return current_app.response_class(265+ (dumps(data, indent=indent, separators=separators), '\n'),266+ mimetype=current_app.config['JSONIFY_MIMETYPE']267+ )268+269+270+def tojson_filter(obj, **kwargs):271+ return Markup(htmlsafe_dumps(obj, **kwargs))added:flask/json/tag.py+297 added
1+"""2+Tagged JSON3+~~~~~~~~~~~4+5+A compact representation for lossless serialization of non-standard JSON types.6+:class:`~flask.sessions.SecureCookieSessionInterface` uses this to serialize7+the session data, but it may be useful in other places. It can be extended to8+support other types.9+10+.. autoclass:: TaggedJSONSerializer11+ :members:12+13+.. autoclass:: JSONTag14+ :members:15+16+Let's seen an example that adds support for :class:`~collections.OrderedDict`.17+Dicts don't have an order in Python or JSON, so to handle this we will dump18+the items as a list of ``[key, value]`` pairs. Subclass :class:`JSONTag` and19+give it the new key ``' od'`` to identify the type. The session serializer20+processes dicts first, so insert the new tag at the front of the order since21+``OrderedDict`` must be processed before ``dict``. ::22+23+ from flask.json.tag import JSONTag24+25+ class TagOrderedDict(JSONTag):26+ __slots__ = ('serializer',)27+ key = ' od'28+29+ def check(self, value):30+ return isinstance(value, OrderedDict)31+32+ def to_json(self, value):33+ return [[k, self.serializer.tag(v)] for k, v in iteritems(value)]34+35+ def to_python(self, value):36+ return OrderedDict(value)37+38+ app.session_interface.serializer.register(TagOrderedDict, 0)39+40+"""41+42+from base64 import b64decode, b64encode43+from datetime import datetime44+from uuid import UUID45+46+from jinja2 import Markup47+from werkzeug.http import http_date, parse_date48+49+from flask._compat import iteritems, text_type50+from flask.json import dumps, loads51+52+53+class JSONTag(object):54+ """Base class for defining type tags for :class:`TaggedJSONSerializer`."""55+56+ __slots__ = ('serializer',)57+58+ #: The tag to mark the serialized object with. If ``None``, this tag is59+ #: only used as an intermediate step during tagging.60+ key = None61+62+ def __init__(self, serializer):63+ """Create a tagger for the given serializer."""64+ self.serializer = serializer65+66+ def check(self, value):67+ """Check if the given value should be tagged by this tag."""68+ raise NotImplementedError69+70+ 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 NotImplementedError74+75+ def to_python(self, value):76+ """Convert the JSON representation back to the correct type. The tag77+ will already be removed."""78+ raise NotImplementedError79+80+ 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)}84+85+86+class TagDict(JSONTag):87+ """Tag for 1-item dicts whose only key matches a registered tag.88+89+ Internally, the dict key is suffixed with `__`, and the suffix is removed90+ when deserializing.91+ """92+93+ __slots__ = ()94+ key = ' di'95+96+ def check(self, value):97+ return (98+ isinstance(value, dict)99+ and len(value) == 1100+ and next(iter(value)) in self.serializer.tags101+ )102+103+ def to_json(self, value):104+ key = next(iter(value))105+ return {key + '__': self.serializer.tag(value[key])}106+107+ def to_python(self, value):108+ key = next(iter(value))109+ return {key[:-2]: value[key]}110+111+112+class PassDict(JSONTag):113+ __slots__ = ()114+115+ def check(self, value):116+ return isinstance(value, dict)117+118+ 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))122+123+ tag = to_json124+125+126+class TagTuple(JSONTag):127+ __slots__ = ()128+ key = ' t'129+130+ def check(self, value):131+ return isinstance(value, tuple)132+133+ def to_json(self, value):134+ return [self.serializer.tag(item) for item in value]135+136+ def to_python(self, value):137+ return tuple(value)138+139+140+class PassList(JSONTag):141+ __slots__ = ()142+143+ def check(self, value):144+ return isinstance(value, list)145+146+ def to_json(self, value):147+ return [self.serializer.tag(item) for item in value]148+149+ tag = to_json150+151+152+class TagBytes(JSONTag):153+ __slots__ = ()154+ key = ' b'155+156+ def check(self, value):157+ return isinstance(value, bytes)158+159+ def to_json(self, value):160+ return b64encode(value).decode('ascii')161+162+ def to_python(self, value):163+ return b64decode(value)164+165+166+class 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`."""170+171+ __slots__ = ()172+ key = ' m'173+174+ def check(self, value):175+ return callable(getattr(value, '__html__', None))176+177+ def to_json(self, value):178+ return text_type(value.__html__())179+180+ def to_python(self, value):181+ return Markup(value)182+183+184+class TagUUID(JSONTag):185+ __slots__ = ()186+ key = ' u'187+188+ def check(self, value):189+ return isinstance(value, UUID)190+191+ def to_json(self, value):192+ return value.hex193+194+ def to_python(self, value):195+ return UUID(value)196+197+198+class TagDateTime(JSONTag):199+ __slots__ = ()200+ key = ' d'201+202+ def check(self, value):203+ return isinstance(value, datetime)204+205+ def to_json(self, value):206+ return http_date(value)207+208+ def to_python(self, value):209+ return parse_date(value)210+211+212+class 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`.216+217+ The following extra types are supported:218+219+ * :class:`dict`220+ * :class:`tuple`221+ * :class:`bytes`222+ * :class:`~flask.Markup`223+ * :class:`~uuid.UUID`224+ * :class:`~datetime.datetime`225+ """226+227+ __slots__ = ('tags', 'order')228+229+ #: 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+ ]235+236+ def __init__(self):237+ self.tags = {}238+ self.order = []239+240+ for cls in self.default_tags:241+ self.register(cls)242+243+ def register(self, tag_class, force=False, index=-1):244+ """Register a new tag with this serializer.245+246+ :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.253+254+ :raise KeyError: if the tag key is already registered and ``force`` is255+ not true.256+ """257+ tag = tag_class(self)258+ key = tag.key259+260+ if key is not None:261+ if not force and key in self.tags:262+ raise KeyError("Tag '{0}' is already registered.".format(key))263+264+ self.tags[key] = tag265+266+ if index == -1:267+ self.order.append(tag)268+ else:269+ self.order.insert(index, tag)270+271+ 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)276+277+ return value278+279+ def untag(self, value):280+ """Convert a tagged representation back to the original type."""281+ if len(value) != 1:282+ return value283+284+ key = next(iter(value))285+286+ if key not in self.tags:287+ return value288+289+ return self.tags[key].to_python(value[key])290+291+ def dumps(self, value):292+ """Tag the value and dump it to a compact JSON string."""293+ return dumps(self.tag(value), separators=(',', ':'))294+295+ 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- ~~~~~~~~~~5-6- Implementation helpers for the JSON support in Flask.7-8- :copyright: (c) 2015 by Armin Ronacher.9- :license: BSD, see LICENSE for more details.10-"""11-import io12-import uuid13-from datetime import date14-from .globals import current_app, request15-from ._compat import text_type, PY216-17-from werkzeug.http import http_date18-from jinja2 import Markup19-20-# Use the same json implementation as itsdangerous on which we21-# depend anyways.22-from itsdangerous import json as _json23-24-25-# Figure out if simplejson escapes slashes. This behavior was changed26-# from one version to another without reason.27-_slash_escape = '\\/' not in _json.dumps('/')28-29-30-__all__ = ['dump', 'dumps', 'load', 'loads', 'htmlsafe_dump',31- 'htmlsafe_dumps', 'JSONDecoder', 'JSONEncoder',32- 'jsonify']33-34-35-def _wrap_reader_for_text(fp, encoding):36- if isinstance(fp.read(0), bytes):37- fp = io.TextIOWrapper(io.BufferedReader(fp), encoding)38- return fp39-40-41-def _wrap_writer_for_text(fp, encoding):42- try:43- fp.write('')44- except TypeError:45- fp = io.TextIOWrapper(fp, encoding)46- return fp47-48-49-class 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- """56-57- 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`).61-62- For example, to support arbitrary iterators, you could implement63- default like this::64-65- 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)81-82-83-class 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- """89-90-91-def _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- )100-101- if not current_app.config['JSON_AS_ASCII']:102- kwargs.setdefault('ensure_ascii', False)103-104- kwargs.setdefault('sort_keys', current_app.config['JSON_SORT_KEYS'])105- else:106- kwargs.setdefault('sort_keys', True)107- kwargs.setdefault('cls', JSONEncoder)108-109-110-def _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)121-122-123-def 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.127-128- 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 rv139-140-141-def 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)148-149-150-def 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)159-160-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-169-170-def 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.176-177- The following characters are escaped in strings:178-179- - ``<``180- - ``>``181- - ``&``182- - ``'``183-184- 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.187-188- .. 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 rv203-204-205-def 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)))208-209-210-def 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]``.217-218- For clarity, the JSON serialization behavior has the following differences219- from :func:`dumps`:220-221- 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.227-228- Example usage::229-230- from flask import jsonify231-232- @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)237-238- This will send a JSON response like this to the browser::239-240- {241- "username": "admin",242- "email": "admin@localhost",243- "id": 42244- }245-246-247- .. versionchanged:: 0.11248- Added support for serializing top-level arrays. This introduces a249- security risk in ancient browsers. See :ref:`json-security` for details.250-251- 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.255-256- .. versionadded:: 0.2257- """258-259- indent = None260- separators = (',', ':')261-262- if current_app.config['JSONIFY_PRETTYPRINT_REGULAR'] or current_app.debug:263- indent = 2264- separators = (', ', ': ')265-266- 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 kwargs272-273- return current_app.response_class(274- (dumps(data, indent=indent, separators=separators), '\n'),275- mimetype=current_app.config['JSONIFY_MIMETYPE']276- )277-278-279-def tojson_filter(obj, **kwargs):280- return Markup(htmlsafe_dumps(obj, **kwargs))modified:flask/sessions.py+8 added-70 removed
6 unmodified lines7 8 :copyright: (c) 2015 by Armin Ronacher.9 :license: BSD, see LICENSE for more details.10 """11-11 import hashlib13-import uuid12 import warnings15-from base64 import b64decode, b64encode13 from datetime import datetime14 15 from itsdangerous import BadSignature, URLSafeTimedSerializer16 from werkzeug.datastructures import CallbackDict20-from werkzeug.http import http_date, parse_date17 22-from . import Markup, json23-from ._compat import iteritems, text_type24-from .helpers import is_ip, total_seconds18+from flask.helpers import is_ip, total_seconds19+from flask.json.tag import TaggedJSONSerializer20 21 22 class SessionMixin(object):23 """Expands a basic dictionary with an accessors that are expected28 unmodified lines52 #: session cookie as keys when caching pages, preventing multiple users53 #: from being served the same cache.54 accessed = True55 61-def _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 value56 87-88-class 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- """92-93- def dumps(self, value):94- return json.dumps(_tag(value), separators=(',', ':'))95-96- LOADS_MAP = {97- ' t': tuple,98- ' u': uuid.UUID,99- ' b': b64decode,100- ' m': Markup,101- ' d': parse_date,102- }103-104- 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)117-118-119-session_json_serializer = TaggedJSONSerializer()120-121-57 class SecureCookieSession(CallbackDict, SessionMixin):58 """Base class for sessions based on signed cookies."""59 60 def __init__(self, initial=None):98 unmodified lines159 return isinstance(obj, self.null_session_class)160 161 def get_cookie_domain(self, app):162 """Returns the domain that should be set for the session cookie.228- 163+164 Uses ``SESSION_COOKIE_DOMAIN`` if it is configured, otherwise165 falls back to detecting the domain based on ``SERVER_NAME``.231- 166+167 Once detected (or if not set at all), ``SESSION_COOKIE_DOMAIN`` is168 updated to avoid re-running the logic.169 """170 81 unmodified lines252 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- 256+257 This check is usually skipped if the session was deleted.258 259 .. versionadded:: 0.11260 """18 unmodified lines279 """280 raise NotImplementedError()281 282 283+session_json_serializer = TaggedJSONSerializer()284+285+286 class SecureCookieSessionInterface(SessionInterface):287 """The default session interface that stores sessions in signed cookies288 through the :mod:`itsdangerous` module.289 """75 unmodified linesmodified:tests/test_basic.py+22 added-19 removed
433 unmodified lines434 app.secret_key = 'development-key'435 now = datetime.utcnow().replace(microsecond=0)436 the_uuid = uuid.uuid4()437 438- @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 response446-438 @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 '', 204449 451- 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'}463 464 465 def test_session_cookie_setting(app):466 app.secret_key = 'dev key'1366 unmodified linesadded:tests/test_json_tag.py+65 added
1+from datetime import datetime2+from uuid import uuid43+4+import pytest5+6+from flask import Markup7+from flask.json.tag import TaggedJSONSerializer, JSONTag8+9+10+@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+))22+def test_dump_load_unchanged(data):23+ s = TaggedJSONSerializer()24+ assert s.loads(s.dumps(data)) == data25+26+27+def test_duplicate_tag():28+ class TagDict(JSONTag):29+ key = ' d'30+31+ 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)36+37+38+def test_custom_tag():39+ class Foo(object):40+ def __init__(self, data):41+ self.data = data42+43+ class TagFoo(JSONTag):44+ __slots__ = ()45+ key = ' f'46+47+ def check(self, value):48+ return isinstance(value, Foo)49+50+ def to_json(self, value):51+ return self.serializer.tag(value.data)52+53+ def to_python(self, value):54+ return Foo(value)55+56+ s = TaggedJSONSerializer()57+ s.register(TagFoo)58+ assert s.loads(s.dumps(Foo('bar'))).data == 'bar'59+60+61+def 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 lines64 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`_)70 71 .. _#1489: https://github.com/pallets/flask/pull/148972 .. _#1621: https://github.com/pallets/flask/pull/162173 .. _#1898: https://github.com/pallets/flask/pull/189811 unmodified lines85 .. _#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/235290 91 Version 0.12.292 --------------93 617 unmodified lines