Skip to content

Instantly share code, notes, and snippets.

@jarrekk
Forked from farazdagi/jsonp-in-flask.py
Last active June 22, 2020 13:41
Show Gist options
  • Save jarrekk/a9df722bad15c61ea555fa860997edc9 to your computer and use it in GitHub Desktop.
Save jarrekk/a9df722bad15c61ea555fa860997edc9 to your computer and use it in GitHub Desktop.
JSONP in Flask
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()
@jarrekk
Copy link
Author

jarrekk commented Jun 17, 2017

at python3.6

            content = '{0}({1})'.format(str(callback), rtn.data) if callback else rtn.data

should be

            content = '{0}({1})'.format(str(callback), eval(rtn.data)) if callback else rtn.data

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment