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
Provenance
- Commit
5e1ced3- Tree
f316f30- Author
David Lord <davidism@gmail.com>- Committer
David Lord <davidism@gmail.com>- Parent
ea2e960
5 files changed+470 added−409 removed
added: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+188 added
1+from base64 import b64decode, b64encode2+from datetime import datetime3+from uuid import UUID4+5+from jinja2 import Markup6+from werkzeug.http import http_date, parse_date7+8+from flask._compat import iteritems, text_type9+from flask.json import dumps, loads10+11+12+class JSONTag(object):13+ __slots__ = ()14+ key = None15+16+ def check(self, serializer, value):17+ raise NotImplementedError18+19+ def to_json(self, serializer, value):20+ raise NotImplementedError21+22+ def to_python(self, serializer, value):23+ raise NotImplementedError24+25+ def tag(self, serializer, value):26+ return {self.key: self.to_json(serializer, value)}27+28+29+class TagDict(JSONTag):30+ __slots__ = ()31+ key = ' di'32+33+ def check(self, serializer, value):34+ return isinstance(value, dict)35+36+ def to_json(self, serializer, value, key=None):37+ if key is not None:38+ return {key + '__': serializer._tag(value[key])}39+40+ return dict((k, serializer._tag(v)) for k, v in iteritems(value))41+42+ def to_python(self, serializer, value):43+ key = next(iter(value))44+ return {key[:-2]: value[key]}45+46+ def tag(self, serializer, value):47+ if len(value) == 1:48+ key = next(iter(value))49+50+ if key in serializer._tags:51+ return {self.key: self.to_json(serializer, value, key=key)}52+53+ return self.to_json(serializer, value)54+55+56+class TagTuple(JSONTag):57+ __slots__ = ()58+ key = ' t'59+60+ def check(self, serializer, value):61+ return isinstance(value, tuple)62+63+ def to_json(self, serializer, value):64+ return [serializer._tag(item) for item in value]65+66+ def to_python(self, serializer, value):67+ return tuple(value)68+69+70+class PassList(JSONTag):71+ __slots__ = ()72+73+ def check(self, serializer, value):74+ return isinstance(value, list)75+76+ def to_json(self, serializer, value):77+ return [serializer._tag(item) for item in value]78+79+ tag = to_json80+81+82+class TagBytes(JSONTag):83+ __slots__ = ()84+ key = ' b'85+86+ def check(self, serializer, value):87+ return isinstance(value, bytes)88+89+ def to_json(self, serializer, value):90+ return b64encode(value).decode('ascii')91+92+ def to_python(self, serializer, value):93+ return b64decode(value)94+95+96+class TagMarkup(JSONTag):97+ __slots__ = ()98+ key = ' m'99+100+ def check(self, serializer, value):101+ return callable(getattr(value, '__html__', None))102+103+ def to_json(self, serializer, value):104+ return text_type(value.__html__())105+106+ def to_python(self, serializer, value):107+ return Markup(value)108+109+110+class TagUUID(JSONTag):111+ __slots__ = ()112+ key = ' u'113+114+ def check(self, serializer, value):115+ return isinstance(value, UUID)116+117+ def to_json(self, serializer, value):118+ return value.hex119+120+ def to_python(self, serializer, value):121+ return UUID(value)122+123+124+class TagDateTime(JSONTag):125+ __slots__ = ()126+ key = ' d'127+128+ def check(self, serializer, value):129+ return isinstance(value, datetime)130+131+ def to_json(self, serializer, value):132+ return http_date(value)133+134+ def to_python(self, serializer, value):135+ return parse_date(value)136+137+138+class TaggedJSONSerializer(object):139+ __slots__ = ('_tags', '_order')140+ _default_tags = [141+ TagDict(), TagTuple(), PassList(), TagBytes(), TagMarkup(), TagUUID(),142+ TagDateTime(),143+ ]144+145+ def __init__(self):146+ self._tags = {}147+ self._order = []148+149+ for tag in self._default_tags:150+ self.register(tag)151+152+ def register(self, tag, force=False, index=-1):153+ key = tag.key154+155+ if key is not None:156+ if not force and key in self._tags:157+ raise KeyError("Tag '{0}' is already registered.".format(key))158+159+ self._tags[key] = tag160+161+ if index == -1:162+ self._order.append(tag)163+ else:164+ self._order.insert(index, tag)165+166+ def _tag(self, value):167+ for tag in self._order:168+ if tag.check(self, value):169+ return tag.tag(self, value)170+171+ return value172+173+ def _untag(self, value):174+ if len(value) != 1:175+ return value176+177+ key = next(iter(value))178+179+ if key not in self._tags:180+ return value181+182+ return self._tags[key].to_python(self, value[key])183+184+ def dumps(self, value):185+ return dumps(self._tag(value), separators=(',', ':'))186+187+ 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- ~~~~~~~~~~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-129 removed
7 unmodified lines8 :copyright: (c) 2015 by Armin Ronacher.9 :license: BSD, see LICENSE for more details.10 """11 import hashlib12-import uuid12 import warnings14-from base64 import b64decode, b64encode13 from datetime import datetime14 15 from itsdangerous import BadSignature, URLSafeTimedSerializer16 from werkzeug.datastructures import CallbackDict19-from werkzeug.http import http_date, parse_date17 21-from . import Markup, json22-from ._compat import iteritems, text_type23-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 60-class 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- """56 65- 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- ]118-119- @property120- def keys(self):121- return [c['key'] for c in self.conversions if c.get('key')]122-123- 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- )128-129- def _is_dict_with_used_key(self, v):130- return isinstance(v, dict) and len(v) == 1 and list(v)[0] in self.keys131-132- def _was_dict_with_used_key(self, k):133- return k.endswith('__') and k[:-2] in self.keys134-135- 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)144-145- def _tag_dict_used_with_key(self, value):146- k, v = next(iteritems(value))147- return {'%s__' % k: v}148-149- 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 value157-158- 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)}162-163- 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 obj170-171- def dumps(self, value):172- return json.dumps(self._tag(value), separators=(',', ':'))173-174- def loads(self, value):175- return json.loads(value, object_hook=self._untag)176-177-178-session_json_serializer = TaggedJSONSerializer()179-180-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.287- 163+164 Uses ``SESSION_COOKIE_DOMAIN`` if it is configured, otherwise165 falls back to detecting the domain based on ``SERVER_NAME``.290- 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.380- 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: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