Move object_hook outside loads method so class can be extend and reused
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Josh Rowe · committed by Josh Rowe · parent dc5f48f · Browse files · 2 files·+108 added−43 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
2 files+108 added−43 removed
- tests:+6 added−0 removed
- other:+102 added−43 removed
Provenance
- Commit
8a8a608- Tree
42f47fd- Author
Josh Rowe <josh@s-block.com>- Committer
Josh Rowe <josh@s-block.com>- Parent
dc5f48f
2 files changed+108 added−43 removed
modified:flask/sessions.py+102 added-43 removed
6 unmodified lines7 8 :copyright: (c) 2015 by Armin Ronacher.9 :license: BSD, see LICENSE for more details.10 """11-11 import uuid12 import hashlib13 from base64 import b64encode, b64decode14 from datetime import datetime32 unmodified lines47 #: The default mixin implementation just hardcodes ``True`` in.48 modified = True49 50 52-def _tag(value):53- if isinstance(value, tuple):54- return {' t': [_tag(x) for x in value]}55- elif isinstance(value, uuid.UUID):56- return {' u': value.hex}57- elif isinstance(value, bytes):58- return {' b': b64encode(value).decode('ascii')}59- elif callable(getattr(value, '__html__', None)):60- return {' m': text_type(value.__html__())}61- elif isinstance(value, list):62- return [_tag(x) for x in value]63- elif isinstance(value, datetime):64- return {' d': http_date(value)}65- elif isinstance(value, dict):66- return dict((k, _tag(v)) for k, v in iteritems(value))67- elif isinstance(value, str):51+class TaggedJSONSerializer(object):52+ """A customized JSON serializer that supports a few extra types that53+ we take for granted when serializing (tuples, markup objects, datetime).54+ """55+56+ def __init__(self):57+ self.conversions = [58+ {59+ 'check': lambda value: self._is_dict_with_used_key(value),60+ 'tag': lambda value: self._tag_dict_used_with_key(value),61+ 'untag': lambda value: self._untag_dict_used_with_key(value),62+ 'key': ' di',63+ },64+ {65+ 'check': lambda value: isinstance(value, tuple),66+ 'tag': lambda value: [self._tag(x) for x in value],67+ 'untag': lambda value: tuple(value),68+ 'key': ' t',69+ },70+ {71+ 'check': lambda value: isinstance(value, uuid.UUID),72+ 'tag': lambda value: value.hex,73+ 'untag': lambda value: uuid.UUID(value),74+ 'key': ' u',75+ },76+ {77+ 'check': lambda value: isinstance(value, bytes),78+ 'tag': lambda value: b64encode(value).decode('ascii'),79+ 'untag': lambda value: b64decode(value),80+ 'key': ' b',81+ },82+ {83+ 'check': lambda value: callable(getattr(value, '__html__',84+ None)),85+ 'tag': lambda value: text_type(value.__html__()),86+ 'untag': lambda value: Markup(value),87+ 'key': ' m',88+ },89+ {90+ 'check': lambda value: isinstance(value, list),91+ 'tag': lambda value: [self._tag(x) for x in value],92+ },93+ {94+ 'check': lambda value: isinstance(value, datetime),95+ 'tag': lambda value: http_date(value),96+ 'untag': lambda value: parse_date(value),97+ 'key': ' d',98+ },99+ {100+ 'check': lambda value: isinstance(value, dict),101+ 'tag': lambda value: dict((k, self._tag(v)) for k, v in102+ iteritems(value)),103+ },104+ {105+ 'check': lambda value: isinstance(value, str),106+ 'tag': lambda value: self._tag_string(value),107+ }108+ ]109+110+ @property111+ def keys(self):112+ return [c['key'] for c in self.conversions if c.get('key')]113+114+ def _get_conversion_untag(self, key):115+ return next(116+ (c['untag'] for c in self.conversions if c.get('key') == key),117+ lambda v: None118+ )119+120+ def _is_dict_with_used_key(self, v):121+ return isinstance(v, dict) and len(v) == 1 and list(v)[0] in self.keys122+123+ def _was_dict_with_used_key(self, k):124+ return k.endswith('__') and k[:-2] in self.keys125+126+ def _tag_string(self, value):127 try:128 return text_type(value)129 except UnicodeError:130 from flask.debughelpers import UnexpectedUnicodeError131 raise UnexpectedUnicodeError(u'A byte string with '132 u'non-ASCII data was passed to the session system '133 u'which can only store unicode strings. Consider '134 u'base64 encoding your string (String was %r)' % value)76- return value135 136+ def _tag_dict_used_with_key(self, value):137+ k, v = next(iteritems(value))138+ return {'%s__' % k: v}139 79-class TaggedJSONSerializer(object):80- """A customized JSON serializer that supports a few extra types that81- we take for granted when serializing (tuples, markup objects, datetime).82- """140+ def _tag(self, value):141+ for tag_ops in self.conversions:142+ if tag_ops['check'](value):143+ tag = tag_ops.get('key')144+ if tag:145+ return {tag: tag_ops['tag'](value)}146+ return tag_ops['tag'](value)147+ return value148 84- def dumps(self, value):85- return json.dumps(_tag(value), separators=(',', ':'))149+ def _untag_dict_used_with_key(self, the_value):150+ k, v = next(iteritems(the_value))151+ if self._was_dict_with_used_key(k):152+ return {k[:-2]: self._untag(v)}153 87- LOADS_MAP = {88- ' t': tuple,89- ' u': uuid.UUID,90- ' b': b64decode,91- ' m': Markup,92- ' d': parse_date,93- }154+ def _untag(self, obj):155+ if len(obj) != 1:156+ return obj157+ the_key, the_value = next(iteritems(obj))158+ untag = self._get_conversion_untag(the_key)159+ new_value = untag(the_value)160+ return new_value if new_value else obj161 162+ def dumps(self, value):163+ return json.dumps(self._tag(value), separators=(',', ':'))164+165 def loads(self, value):96- def object_hook(obj):97- if len(obj) != 1:98- return obj99- the_key, the_value = next(iteritems(obj))100- # Check the key for a corresponding function101- return_function = self.LOADS_MAP.get(the_key)102- if return_function:103- # Pass the value to the function104- return return_function(the_value)105- # Didn't find a function for this object106- return obj107- return json.loads(value, object_hook=object_hook)166+ return json.loads(value, object_hook=self._untag)167 168 169 session_json_serializer = TaggedJSONSerializer()170 255 unmodified linesmodified:tests/test_basic.py+6 added
381 unmodified lines382 flask.session['u'] = the_uuid383 flask.session['dt'] = now384 flask.session['b'] = b'\xff'385 flask.session['t'] = (1, 2, 3)386+ flask.session['spacefirst'] = {' t': 'not-a-tuple'}387+ flask.session['withunderscores'] = {' t__': 'not-a-tuple'}388+ flask.session['notadict'] = {' di': 'not-a-dict'}389 return response390 391 @app.route('/')392 def dump_session_contents():8 unmodified lines401 assert rv['u'] == the_uuid402 assert rv['b'] == b'\xff'403 assert type(rv['b']) == bytes404 assert rv['t'] == (1, 2, 3)405+ assert rv['spacefirst'] == {' t': 'not-a-tuple'}406+ assert rv['withunderscores'] == {' t__': 'not-a-tuple'}407+ assert rv['notadict'] == {' di': 'not-a-dict'}408 409 410 def test_session_cookie_setting():411 app = flask.Flask(__name__)1295 unmodified lines