Aug 18, 2013

Serving dynamic charts with Flask

I've written a little application to track FlexLM status. It's a script that runs as a cronjob and records the status of various FlexLM licenses to an SQLite database. In addition to logging the data, I've written a simple plotting application in matplotlib, but I really want to add some controls around it to select which license to plot, what date range to query from the database and other similarly straightforward features. The easiest way to do this seems to be setting up a basic web form and rendering the images as needed.

Towards this end, I've been playing around with the Flask web framework which makes setting up a micro web application remarkably easy. The code below is all that's required to set up a web server that will dynamically generate and serve images. The graph is rendered using matplotlib and then served up via Flask.

from flask import Flask
import numpy as np
import cStringIO
import matplotlib.pyplot as plt

app = Flask(__name__)

def build_plot():

  # Generate the plot
  x = np.linspace(0, 10)
  line, = plt.plot(x, np.sin(x))

  f = cStringIO.StringIO()
  plt.savefig(f, format='png')

  # Serve up the data
  header = {'Content-type': 'image/png'}
  data =

  return data, 200, header

if __name__ == '__main__':

This just generates the same plot each time it is loaded, but it is quite easy to move beyond this to generating different views based on user selections.

flask plot

There are comments.

Comments !