Browse Source

Allow per blueprint json encoder decoder

re #1710
pull/1898/head
RamiC 9 years ago
parent
commit
501b8590dd
  1. 7
      flask/blueprints.py
  2. 6
      flask/json.py
  3. 39
      tests/test_helpers.py

7
flask/blueprints.py

@ -89,6 +89,13 @@ class Blueprint(_PackageBoundObject):
warn_on_modifications = False warn_on_modifications = False
_got_registered_once = False _got_registered_once = False
#: Blueprint local JSON decoder class to use.
# Set to None to use the :class:`~flask.app.Flask.json_encoder`.
json_encoder = None
#: Blueprint local JSON decoder class to use.
# Set to None to use the :class:`~flask.app.Flask.json_decoder`.
json_decoder = None
def __init__(self, name, import_name, static_folder=None, def __init__(self, name, import_name, static_folder=None,
static_url_path=None, template_folder=None, static_url_path=None, template_folder=None,
url_prefix=None, subdomain=None, url_defaults=None, url_prefix=None, subdomain=None, url_defaults=None,

6
flask/json.py

@ -94,7 +94,8 @@ class JSONDecoder(_json.JSONDecoder):
def _dump_arg_defaults(kwargs): def _dump_arg_defaults(kwargs):
"""Inject default arguments for dump functions.""" """Inject default arguments for dump functions."""
if current_app: if current_app:
kwargs.setdefault('cls', current_app.json_encoder) bp = current_app.blueprints.get(request.blueprint, None)
kwargs.setdefault('cls', bp.json_encoder if bp else current_app.json_encoder)
if not current_app.config['JSON_AS_ASCII']: if not current_app.config['JSON_AS_ASCII']:
kwargs.setdefault('ensure_ascii', False) kwargs.setdefault('ensure_ascii', False)
kwargs.setdefault('sort_keys', current_app.config['JSON_SORT_KEYS']) kwargs.setdefault('sort_keys', current_app.config['JSON_SORT_KEYS'])
@ -106,7 +107,8 @@ def _dump_arg_defaults(kwargs):
def _load_arg_defaults(kwargs): def _load_arg_defaults(kwargs):
"""Inject default arguments for load functions.""" """Inject default arguments for load functions."""
if current_app: if current_app:
kwargs.setdefault('cls', current_app.json_decoder) bp = current_app.blueprints.get(request.blueprint, None)
kwargs.setdefault('cls', bp.json_decoder if bp else current_app.json_decoder)
else: else:
kwargs.setdefault('cls', JSONDecoder) kwargs.setdefault('cls', JSONDecoder)

39
tests/test_helpers.py

@ -90,12 +90,12 @@ class TestJSON(object):
app = flask.Flask(__name__) app = flask.Flask(__name__)
app.config['JSON_AS_ASCII'] = True app.config['JSON_AS_ASCII'] = True
with app.app_context(): with app.test_request_context():
rv = flask.json.dumps(u'\N{SNOWMAN}') rv = flask.json.dumps(u'\N{SNOWMAN}')
assert rv == '"\\u2603"' assert rv == '"\\u2603"'
app.config['JSON_AS_ASCII'] = False app.config['JSON_AS_ASCII'] = False
with app.app_context(): with app.test_request_context():
rv = flask.json.dumps(u'\N{SNOWMAN}') rv = flask.json.dumps(u'\N{SNOWMAN}')
assert rv == u'"\u2603"' assert rv == u'"\u2603"'
@ -234,6 +234,41 @@ class TestJSON(object):
}), content_type='application/json') }), content_type='application/json')
assert rv.data == b'"<42>"' assert rv.data == b'"<42>"'
def test_blueprint_json_customization(self):
class X(object):
def __init__(self, val):
self.val = val
class MyEncoder(flask.json.JSONEncoder):
def default(self, o):
if isinstance(o, X):
return '<%d>' % o.val
return flask.json.JSONEncoder.default(self, o)
class MyDecoder(flask.json.JSONDecoder):
def __init__(self, *args, **kwargs):
kwargs.setdefault('object_hook', self.object_hook)
flask.json.JSONDecoder.__init__(self, *args, **kwargs)
def object_hook(self, obj):
if len(obj) == 1 and '_foo' in obj:
return X(obj['_foo'])
return obj
blue = flask.Blueprint('blue', __name__)
blue.json_encoder = MyEncoder
blue.json_decoder = MyDecoder
@blue.route('/bp', methods=['POST'])
def index():
return flask.json.dumps(flask.request.get_json()['x'])
app = flask.Flask(__name__)
app.testing = True
app.register_blueprint(blue)
c = app.test_client()
rv = c.post('/bp', data=flask.json.dumps({
'x': {'_foo': 42}
}), content_type='application/json')
assert rv.data == b'"<42>"'
def test_modified_url_encoding(self): def test_modified_url_encoding(self):
class ModifiedRequest(flask.Request): class ModifiedRequest(flask.Request):
url_charset = 'euc-kr' url_charset = 'euc-kr'

Loading…
Cancel
Save