Pygal SVG graphs with Flask Tutorial

In this Flask web development tutorial with Python, I am going to be showing you how to incorporate Pygal with your Flask web application. Pygal is a Python module that creates SVG (Scalable Vector Graphics) graphs/charts in a variety of styles. Pygal is highly customize-able, yet also extremely simplistic, which is a very rare combination.

You can make line graphs, bar graphs, histograms, pie charts, maps, and a whole lot more. From there you can further customize the look and feel of the graphs.

To get started, first you will need to install: pip install pygal

Next, let's create a simple line graph, the code we'll use for the graph:

graph = pygal.Line() graph.title = '% Change Coolness of programming languages over time.' graph.x_labels = ['2011','2012','2013','2014','2015','2016'] graph.add('Python', [15, 31, 89, 200, 356, 900]) graph.add('Java', [15, 45, 76, 80, 91, 95]) graph.add('C++', [5, 51, 54, 102, 150, 201]) graph.add('All others combined!', [5, 15, 21, 55, 92, 105])

That's all there is to it. The graph this creates is:

This graph is pretty good looking, interactive, and scales to just about any size. So how do we get this to display with Flask? It turns out, Pygal has a special Flask response, but this means the entire response is a graph, and a graph only. What if you want to embed the graph into the rest of the webpage? No problem! Let's create a new page, add the code, and see what we need to do:

@app.route('/pygalexample/') def pygalexample(): try: graph = pygal.Line() graph.title = '% Change Coolness of programming languages over time.' graph.x_labels = ['2011','2012','2013','2014','2015','2016'] graph.add('Python', [15, 31, 89, 200, 356, 900]) graph.add('Java', [15, 45, 76, 80, 91, 95]) graph.add('C++', [5, 51, 54, 102, 150, 201]) graph.add('All others combined!', [5, 15, 21, 55, 92, 105]) graph_data = graph.render_data_uri() return render_template("graphing.html", graph_data = graph_data) except Exception, e: return(str(e))

Pretty much all is the same here, except we call graph_data = graph.render_data_uri() . This gives us the raw SVG data for the graph, which we can next pass into our template. Let's make that template real quick:

templates/graphing.html

{% extends "header.html" %} {% block body %} <body class="body"> <div class="container" align="left"> <embed type="image/svg+xml" src={{graph_data|safe}} style='max-width:1000px'/> </div> </body> {% endblock %}

Note that we have to use the |safe filter here, so the actual graph shows and not the data. That's all there is to it. I highly encourage you to poke through their documentation. I've never found such an easy integration of graphs and Python for web apps, I am a big fan. You can do things like create your own custom styles and change all sorts of options.

Next on our to-do list is PayPal integration!

Sign up to +=1