Allow per blueprint json encoder decoder
Before adoption: this commit came in with the history the project adopted, so no landing records it.
re #1710
authored by RamiC · committed by RamiC · parent 4f83f70 · Browse files · 3 files·+48 added−4 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
3 files+48 added−4 removed
- tests:+37 added−2 removed
- other:+11 added−2 removed
Provenance
- Commit
501b859- Tree
596aa8c- Author
RamiC <rami.chousein@gmail.com>- Committer
RamiC <rami.chousein@gmail.com>- Parent
4f83f70
3 files changed+48 added−4 removed
modified:flask/blueprints.py+7 added
87 unmodified lines88 89 warn_on_modifications = False90 _got_registered_once = False91 92+ #: Blueprint local JSON decoder class to use.93+ # Set to None to use the :class:`~flask.app.Flask.json_encoder`.94+ json_encoder = None95+ #: Blueprint local JSON decoder class to use.96+ # Set to None to use the :class:`~flask.app.Flask.json_decoder`.97+ json_decoder = None98+99 def __init__(self, name, import_name, static_folder=None,100 static_url_path=None, template_folder=None,101 url_prefix=None, subdomain=None, url_defaults=None,102 root_path=None):318 unmodified linesmodified:flask/json.py+4 added-2 removed
92 unmodified lines93 94 def _dump_arg_defaults(kwargs):95 """Inject default arguments for dump functions."""96 if current_app:97+ bp = current_app.blueprints.get(request.blueprint, None)97- kwargs.setdefault('cls', current_app.json_encoder)98+ kwargs.setdefault('cls', bp.json_encoder if bp else current_app.json_encoder)99 if not current_app.config['JSON_AS_ASCII']:100 kwargs.setdefault('ensure_ascii', False)101 kwargs.setdefault('sort_keys', current_app.config['JSON_SORT_KEYS'])102 else:3 unmodified lines106 107 def _load_arg_defaults(kwargs):108 """Inject default arguments for load functions."""109 if current_app:110+ bp = current_app.blueprints.get(request.blueprint, None)109- kwargs.setdefault('cls', current_app.json_decoder)111+ kwargs.setdefault('cls', bp.json_decoder if bp else current_app.json_decoder)112 else:113 kwargs.setdefault('cls', JSONDecoder)114 115 159 unmodified linesmodified:tests/test_helpers.py+37 added-2 removed
88 unmodified lines89 def test_json_as_unicode(self):90 app = flask.Flask(__name__)91 92 app.config['JSON_AS_ASCII'] = True93- with app.app_context():93+ with app.test_request_context():94 rv = flask.json.dumps(u'\N{SNOWMAN}')95 assert rv == '"\\u2603"'96 97 app.config['JSON_AS_ASCII'] = False98- with app.app_context():98+ with app.test_request_context():99 rv = flask.json.dumps(u'\N{SNOWMAN}')100 assert rv == u'"\u2603"'101 102 def test_jsonify_basic_types(self):130 unmodified lines233 'x': {'_foo': 42}234 }), content_type='application/json')235 assert rv.data == b'"<42>"'236 237+ def test_blueprint_json_customization(self):238+ class X(object):239+ def __init__(self, val):240+ self.val = val241+ class MyEncoder(flask.json.JSONEncoder):242+ def default(self, o):243+ if isinstance(o, X):244+ return '<%d>' % o.val245+ return flask.json.JSONEncoder.default(self, o)246+ class MyDecoder(flask.json.JSONDecoder):247+ def __init__(self, *args, **kwargs):248+ kwargs.setdefault('object_hook', self.object_hook)249+ flask.json.JSONDecoder.__init__(self, *args, **kwargs)250+ def object_hook(self, obj):251+ if len(obj) == 1 and '_foo' in obj:252+ return X(obj['_foo'])253+ return obj254+255+ blue = flask.Blueprint('blue', __name__)256+ blue.json_encoder = MyEncoder257+ blue.json_decoder = MyDecoder258+ @blue.route('/bp', methods=['POST'])259+ def index():260+ return flask.json.dumps(flask.request.get_json()['x'])261+262+ app = flask.Flask(__name__)263+ app.testing = True264+ app.register_blueprint(blue)265+266+ c = app.test_client()267+ rv = c.post('/bp', data=flask.json.dumps({268+ 'x': {'_foo': 42}269+ }), content_type='application/json')270+ assert rv.data == b'"<42>"'271+272 def test_modified_url_encoding(self):273 class ModifiedRequest(flask.Request):274 url_charset = 'euc-kr'275 app = flask.Flask(__name__)538 unmodified lines