Search code examples
flaskgraphviz

Flask dynamic graphviz and SVG example


I'm trying to create a Graphviz image, however instead of saving the image and loading into the webpage, pass it as SVG.

Its sort of working, here is the example:

from flask import Flask
from graphviz import Graph


app = Flask(__name__)


@app.route('/svgtest')
def svgtest():
  chart_data = Graph()

  chart_data.node('H', 'Hello')
  chart_data.node('W', 'World')
  chart_data.edge('H', 'W')

  chart_output = chart_data.pipe(format='svg')

 return render_template('svgtest.html', chart_output=chart_output)

In My HTML Page I have

<embed type="image/svg+xml" src={{ chart_output|safe }} />

However the output is not right

output example

Any help would really be great, I'm starting to talk to myself, and even that's not helpful.

Thanks.


Solution

  • You can use svg just like this:

    {{ chart_output|safe }}
    

    and also, you can use png format:

    @app.route('/')
    def svgtest():
        chart_data = Graph()
    
        chart_data.node('H', 'Hello')
        chart_data.node('W', 'World')
        chart_data.edge('H', 'W')
    
    
        chart_output = chart_data.pipe(format='png')
        chart_output = base64.b64encode(chart_output).decode('utf-8')
    
        return render_template('svgtest.html', chart_output=chart_output)
    

    and the html like this:

    <img src="data:image/png;base64,{{chart_output|safe}}" />
    

    Happy coding!