Skip to content
Myr

make session serializer extensible

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

support serializing 1-item dicts with tag as key refactor serializer into flask.json.tag module continues #1452, closes #1438, closes #1908

authored by David Lord · committed by David Lord · parent ea2e960 · Browse files · 5 files+470 added−409 removed
This commit

State

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

Diff stats

5 files+470 added−409 removed

  • other:+470 added−409 removed

5 files+470 added−409 removed

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+188 added
1from base64 import b64decode, b64encode2from datetime import datetime3from uuid import UUID45from jinja2 import Markup6from werkzeug.http import http_date, parse_date78from flask._compat import iteritems, text_type9from flask.json import dumps, loads101112class JSONTag(object):13 __slots__ = ()14 key = None1516 def check(self, serializer, value):17 raise NotImplementedError1819 def to_json(self, serializer, value):20 raise NotImplementedError2122 def to_python(self, serializer, value):23 raise NotImplementedError2425 def tag(self, serializer, value):26 return {self.key: self.to_json(serializer, value)}272829class TagDict(JSONTag):30 __slots__ = ()31 key = ' di'3233 def check(self, serializer, value):34 return isinstance(value, dict)3536 def to_json(self, serializer, value, key=None):37 if key is not None:38 return {key + '__': serializer._tag(value[key])}3940 return dict((k, serializer._tag(v)) for k, v in iteritems(value))4142 def to_python(self, serializer, value):43 key = next(iter(value))44 return {key[:-2]: value[key]}4546 def tag(self, serializer, value):47 if len(value) == 1:48 key = next(iter(value))4950 if key in serializer._tags:51 return {self.key: self.to_json(serializer, value, key=key)}5253 return self.to_json(serializer, value)545556class TagTuple(JSONTag):57 __slots__ = ()58 key = ' t'5960 def check(self, serializer, value):61 return isinstance(value, tuple)6263 def to_json(self, serializer, value):64 return [serializer._tag(item) for item in value]6566 def to_python(self, serializer, value):67 return tuple(value)686970class PassList(JSONTag):71 __slots__ = ()7273 def check(self, serializer, value):74 return isinstance(value, list)7576 def to_json(self, serializer, value):77 return [serializer._tag(item) for item in value]7879 tag = to_json808182class TagBytes(JSONTag):83 __slots__ = ()84 key = ' b'8586 def check(self, serializer, value):87 return isinstance(value, bytes)8889 def to_json(self, serializer, value):90 return b64encode(value).decode('ascii')9192 def to_python(self, serializer, value):93 return b64decode(value)949596class TagMarkup(JSONTag):97 __slots__ = ()98 key = ' m'99100 def check(self, serializer, value):101 return callable(getattr(value, '__html__', None))102103 def to_json(self, serializer, value):104 return text_type(value.__html__())105106 def to_python(self, serializer, value):107 return Markup(value)108109110class TagUUID(JSONTag):111 __slots__ = ()112 key = ' u'113114 def check(self, serializer, value):115 return isinstance(value, UUID)116117 def to_json(self, serializer, value):118 return value.hex119120 def to_python(self, serializer, value):121 return UUID(value)122123124class TagDateTime(JSONTag):125 __slots__ = ()126 key = ' d'127128 def check(self, serializer, value):129 return isinstance(value, datetime)130131 def to_json(self, serializer, value):132 return http_date(value)133134 def to_python(self, serializer, value):135 return parse_date(value)136137138class TaggedJSONSerializer(object):139 __slots__ = ('_tags', '_order')140 _default_tags = [141 TagDict(), TagTuple(), PassList(), TagBytes(), TagMarkup(), TagUUID(),142 TagDateTime(),143 ]144145 def __init__(self):146 self._tags = {}147 self._order = []148149 for tag in self._default_tags:150 self.register(tag)151152 def register(self, tag, force=False, index=-1):153 key = tag.key154155 if key is not None:156 if not force and key in self._tags:157 raise KeyError("Tag '{0}' is already registered.".format(key))158159 self._tags[key] = tag160161 if index == -1:162 self._order.append(tag)163 else:164 self._order.insert(index, tag)165166 def _tag(self, value):167 for tag in self._order:168 if tag.check(self, value):169 return tag.tag(self, value)170171 return value172173 def _untag(self, value):174 if len(value) != 1:175 return value176177 key = next(iter(value))178179 if key not in self._tags:180 return value181182 return self._tags[key].to_python(self, value[key])183184 def dumps(self, value):185 return dumps(self._tag(value), separators=(',', ':'))186187 def loads(self, value):188 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-129 removed
7 unmodified lines
8 :copyright: (c) 2015 by Armin Ronacher.9 :license: BSD, see LICENSE for more details.10"""11import hashlib12import uuid12import warnings14from base64 import b64decode, b64encode13from datetime import datetime1415from itsdangerous import BadSignature, URLSafeTimedSerializer16from werkzeug.datastructures import CallbackDict19from werkzeug.http import http_date, parse_date1721from . import Markup, json22from ._compat import iteritems, text_type23from .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 = True5560class TaggedJSONSerializer(object):61 """A customized JSON serializer that supports a few extra types that62 we take for granted when serializing (tuples, markup objects, datetime).63 """5665 def __init__(self):66 self.conversions = [67 {68 'check': lambda value: self._is_dict_with_used_key(value),69 'tag': lambda value: self._tag_dict_used_with_key(value),70 'untag': lambda value: self._untag_dict_used_with_key(value),71 'key': ' di',72 },73 {74 'check': lambda value: isinstance(value, tuple),75 'tag': lambda value: [self._tag(x) for x in value],76 'untag': lambda value: tuple(value),77 'key': ' t',78 },79 {80 'check': lambda value: isinstance(value, uuid.UUID),81 'tag': lambda value: value.hex,82 'untag': lambda value: uuid.UUID(value),83 'key': ' u',84 },85 {86 'check': lambda value: isinstance(value, bytes),87 'tag': lambda value: b64encode(value).decode('ascii'),88 'untag': lambda value: b64decode(value),89 'key': ' b',90 },91 {92 'check': lambda value: callable(getattr(value, '__html__',93 None)),94 'tag': lambda value: text_type(value.__html__()),95 'untag': lambda value: Markup(value),96 'key': ' m',97 },98 {99 'check': lambda value: isinstance(value, list),100 'tag': lambda value: [self._tag(x) for x in value],101 },102 {103 'check': lambda value: isinstance(value, datetime),104 'tag': lambda value: http_date(value),105 'untag': lambda value: parse_date(value),106 'key': ' d',107 },108 {109 'check': lambda value: isinstance(value, dict),110 'tag': lambda value: dict((k, self._tag(v)) for k, v in111 iteritems(value)),112 },113 {114 'check': lambda value: isinstance(value, str),115 'tag': lambda value: self._tag_string(value),116 }117 ]118119 @property120 def keys(self):121 return [c['key'] for c in self.conversions if c.get('key')]122123 def _get_conversion_untag(self, key):124 return next(125 (c['untag'] for c in self.conversions if c.get('key') == key),126 lambda v: None127 )128129 def _is_dict_with_used_key(self, v):130 return isinstance(v, dict) and len(v) == 1 and list(v)[0] in self.keys131132 def _was_dict_with_used_key(self, k):133 return k.endswith('__') and k[:-2] in self.keys134135 def _tag_string(self, value):136 try:137 return text_type(value)138 except UnicodeError:139 from flask.debughelpers import UnexpectedUnicodeError140 raise UnexpectedUnicodeError(u'A byte string with '141 u'non-ASCII data was passed to the session system '142 u'which can only store unicode strings. Consider '143 u'base64 encoding your string (String was %r)' % value)144145 def _tag_dict_used_with_key(self, value):146 k, v = next(iteritems(value))147 return {'%s__' % k: v}148149 def _tag(self, value):150 for tag_ops in self.conversions:151 if tag_ops['check'](value):152 tag = tag_ops.get('key')153 if tag:154 return {tag: tag_ops['tag'](value)}155 return tag_ops['tag'](value)156 return value157158 def _untag_dict_used_with_key(self, the_value):159 k, v = next(iteritems(the_value))160 if self._was_dict_with_used_key(k):161 return {k[:-2]: self._untag(v)}162163 def _untag(self, obj):164 if len(obj) != 1:165 return obj166 the_key, the_value = next(iteritems(obj))167 untag = self._get_conversion_untag(the_key)168 new_value = untag(the_value)169 return new_value if new_value else obj170171 def dumps(self, value):172 return json.dumps(self._tag(value), separators=(',', ':'))173174 def loads(self, value):175 return json.loads(value, object_hook=self._untag)176177178session_json_serializer = TaggedJSONSerializer()17918057class 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.287 163164 Uses ``SESSION_COOKIE_DOMAIN`` if it is configured, otherwise165 falls back to detecting the domain based on ``SERVER_NAME``.290 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.380 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: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