GWT, Django, and JSON (with padding)
A couple of months ago I was working on a project where I needed to retrieve data in JSON format from a web service written in Python (using the Django web framework) under GWT. The data is then loaded into GXT/Ext GWT grids and charts.
After looking at a GXT example of loading JSON data to a grid, I thought this would be pretty straightforward, but of course I was wrong. Since the Django app is on a different server and domain/subdomain, I learned something called “ same origin policy“, preventing our two applications to communicate with each other.
Fortunately, there’s an easy workaround to this using “JSON with padding” or JSONP. Here’s one way to get this working:
GWT side:
1. The JsonpRequestBuilder object has been added in GWT 2.0 making these types of cross site requests easier to implement. Here’s a very well written post showing how to do this (yes, I’m lazy and he obviously knows a lot more about these than I do :D).
Now, when you make a request to the web service on the Django side, it will automatically append the callback function in the request and the request may look something like this:
GET /get_gpu_stats/?callback=__gwt__jsonp__.I18.onSuccess HTTP/1.1
Django side:
1. In your Django view, one way to handle this is to inspect the request and see if there’s a parameter called “callback” and change the response so it looks like a function (this is the “padding” part) instead of a regular JSON response. You can do something like this (forgot where I found this example from):
def get_gpu_stats(request): . . . gpu_stats = {'gpu_stats': data} response = simplejson.dumps(gpu_stats) # Return as JSONP if the callback parameter is specified. callback = request.GET.get('callback') if callback: response = '%s(%s)' % (callback, response) return HttpResponse(response, mimetype='application/json')
Yup, that’s it, they should now be able to exchange data!
Tags: howto, python, django, tech, software development, javascript, java