Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
JSONP in Flask
import json
from functools import wraps
from flask import redirect, request, current_app
def support_jsonp(f):
"""Wraps JSONified output for JSONP"""
@wraps(f)
def decorated_function(*args, **kwargs):
callback = request.args.get('callback', False)
if callback:
content = str(callback) + '(' + str(f().data) + ')'
return current_app.response_class(content, mimetype='application/json')
else:
return f(*args, **kwargs)
return decorated_function
# then in your view
@default.route('/test', methods=['GET'])
@support_jsonp
def test():
return jsonify({"foo":"bar"})
@aisipos

This comment has been minimized.

Copy link

commented Jul 20, 2011

For views that take arguments, you need to pass args and kwargs to f(). See my fork https://gist.github.com/1094140

Also, according to http://stackoverflow.com/questions/111302/best-content-type-to-serve-jsonp , application/javascript is a more correct content-type for JSONP

@danriti

This comment has been minimized.

Copy link

commented Sep 7, 2012

fantastic! nicely done =)

@jarrekk

This comment has been minimized.

Copy link

commented Dec 25, 2016

@aisipos
Based on your gist, I edit some place to make json response can contain status code, please see my fork https://gist.github.com/JiaKunUp/a9df722bad15c61ea555fa860997edc9

@felixzhooou

This comment has been minimized.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.