Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Browse files

Merge remote branch 'njl/master'

Conflicts:
	docs/quickstart.rst
  • Loading branch information...
commit eac350d1e6d53b47b0fd5b111125ee1a208eaf93 2 parents d626787 + 68f9363
@rduplain rduplain authored
Showing with 36 additions and 0 deletions.
  1. +22 −0 flask/helpers.py
  2. +14 −0 flask/testsuite/helpers.py
View
22 flask/helpers.py
@@ -117,9 +117,31 @@ def get_current_user():
information about this, have a look at :ref:`json-security`.
.. versionadded:: 0.2
+
+ .. versionadded:: 0.9
+ If the ``padded`` argument is true, the JSON object will be padded
+ for JSONP calls and the response mimetype will be changed to
+ ``application/javascript``. By default, the request arguments ``callback``
+ and ``jsonp`` will be used as the name for the callback function.
+ This will work with jQuery and most other JavaScript libraries
+ by default.
+
+ If the ``padded`` argument is a string, jsonify will look for
+ the request argument with the same name and use that value as the
+ callback-function name.
"""
if __debug__:
_assert_have_json()
+ if 'padded' in kwargs:
+ if isinstance(kwargs['padded'], str):
+ callback = request.args.get(kwargs['padded']) or 'jsonp'
+ else:
+ callback = request.args.get('callback') or \
+ request.args.get('jsonp') or 'jsonp'
+ del kwargs['padded']
+ json_str = json.dumps(dict(*args, **kwargs), indent=None)
+ content = str(callback) + "(" + json_str + ")"
+ return current_app.response_class(content, mimetype='application/javascript')
return current_app.response_class(json.dumps(dict(*args, **kwargs),
indent=None if request.is_xhr else 2), mimetype='application/json')
View
14 flask/testsuite/helpers.py
@@ -61,11 +61,25 @@ def return_kwargs():
@app.route('/dict')
def return_dict():
return flask.jsonify(d)
+ @app.route("/padded")
+ def return_padded_json():
+ return flask.jsonify(d, padded=True)
+ @app.route("/padded_custom")
+ def return_padded_json_custom_callback():
+ return flask.jsonify(d, padded='my_func_name')
c = app.test_client()
for url in '/kw', '/dict':
rv = c.get(url)
self.assert_equal(rv.mimetype, 'application/json')
self.assert_equal(flask.json.loads(rv.data), d)
+ for get_arg in 'callback=funcName', 'jsonp=funcName':
+ rv = c.get('/padded?' + get_arg)
+ self.assert_( rv.data.startswith("funcName(") )
+ self.assert_( rv.data.endswith(")") )
+ rv_json = rv.data.split('(')[1].split(')')[0]
+ self.assert_equal(flask.json.loads(rv_json), d)
+ rv = c.get('/padded_custom?my_func_name=funcName')
+ self.assert_( rv.data.startswith("funcName(") )
def test_json_attr(self):
app = flask.Flask(__name__)
Please sign in to comment.
Something went wrong with that request. Please try again.