[Answer]-Serving generated charts via AJAX

1👍

Roughly like this:

import django.http
import matplotlib.pyplot

# This is your view function, hook it up to your URLconf.
def chart(request, *args):
    # ...extract chart parameters from request.GET and/or args...
    fig = matplotlib.pyplot.figure(...)
    # ...draw your chart, invoking methods on fig...
    response = django.http.HttpResponse(content_type='image/png')
    fig.savefig(response, format='png')
    return response

Now I’m not sure how you would use AJAX to display this to the user. I think it would be easier to just insert img elements with appropriate src attributes. With jQuery, maybe like this:

var src = '/chart/?' + $.param({
        // This all ends up in request.GET
        type: 'something',
        foo: 'bar',
        myParam: 123
    });
$('#displayArea').empty().append($('<img>').attr('src', src));

But if you do want AJAX, you can of course just use $.ajax.

If a chart is completely defined by the parameters passed in, and a user will likely want to see the same chart several times, consider setting liberal client caching headers to avoid re-requesting the same image from your server. This is just an optimization though.

Leave a comment