-
-
Save jarrekk/a9df722bad15c61ea555fa860997edc9 to your computer and use it in GitHub Desktop.
JSONP in Flask
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from functools import wraps | |
from flask import request, current_app, jsonify, Flask | |
app = Flask(__name__) | |
def jsonp(f): | |
"""Wraps JSONified output for JSONP""" | |
@wraps(f) | |
def decorated_function(*args, **kwargs): | |
callback = request.args.get('callback', None) | |
rtn = f(*args, **kwargs) | |
if isinstance(rtn, tuple): | |
content = '{0}({1})'.format(str(callback), rtn[0].data) if callback else rtn[0].data | |
status = rtn[1] | |
else: | |
content = '{0}({1})'.format(str(callback), rtn.data) if callback else rtn.data | |
status = 200 | |
return current_app.response_class(content, mimetype='application/javascript', status=status) | |
return decorated_function | |
# then in your view | |
@app.route('/test', methods=['GET']) | |
@jsonp | |
def test(): | |
return jsonify({"foo": "bar"}) | |
if __name__ == "__main__": | |
app.run() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
at python3.6
should be