Browse Source

Check for a request ctx before using the request.

Use the app json coder when blueprint json coder is set to none.
Revert the failling test to using an app_context
re #1710
pull/1898/head
RamiC 9 years ago
parent
commit
4305ebdf66
  1. 15
      flask/json.py
  2. 4
      tests/test_helpers.py

15
flask/json.py

@ -13,6 +13,7 @@ import uuid
from datetime import date from datetime import date
from .globals import current_app, request from .globals import current_app, request
from ._compat import text_type, PY2 from ._compat import text_type, PY2
from .ctx import has_request_context
from werkzeug.http import http_date from werkzeug.http import http_date
from jinja2 import Markup from jinja2 import Markup
@ -94,8 +95,11 @@ 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:
bp = current_app.blueprints.get(request.blueprint, None) bp = current_app.blueprints.get(request.blueprint,
kwargs.setdefault('cls', bp.json_encoder if bp else current_app.json_encoder) None) if has_request_context() else None
kwargs.setdefault('cls',
bp.json_encoder if bp and bp.json_encoder
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'])
@ -107,8 +111,11 @@ 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:
bp = current_app.blueprints.get(request.blueprint, None) bp = current_app.blueprints.get(request.blueprint,
kwargs.setdefault('cls', bp.json_decoder if bp else current_app.json_decoder) None) if has_request_context() else None
kwargs.setdefault('cls',
bp.json_decoder if bp and bp.json_decoder
else current_app.json_decoder)
else: else:
kwargs.setdefault('cls', JSONDecoder) kwargs.setdefault('cls', JSONDecoder)

4
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.test_request_context(): with app.app_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.test_request_context(): with app.app_context():
rv = flask.json.dumps(u'\N{SNOWMAN}') rv = flask.json.dumps(u'\N{SNOWMAN}')
assert rv == u'"\u2603"' assert rv == u'"\u2603"'

Loading…
Cancel
Save