Andrew C
Andrew C

Reputation: 699

Serving generated charts via AJAX

The workflow for my Django project should go like this:

The possible number of charts to be generated is very large, because of differences in various parameters, so generating the charts beforehand and serving them statically is not an option.

The matplot commands show() and savfig() don't seem to be suited to the task either.

How best can I achieve this?

Upvotes: 0

Views: 655

Answers (1)

Vasiliy Faronov
Vasiliy Faronov

Reputation: 12310

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.

Upvotes: 1

Related Questions