Flask: how do I serve an svg that's dynamically generated Flask: how do I serve an svg that's dynamically generated flask flask

Flask: how do I serve an svg that's dynamically generated


Your SVG code is being autoescaped. An appropriate solution is to call Markup(), like so:

return render_template("map.html", svg=Markup(get_map(locations)))


You can use StringIO for this :

from flask import send_filefrom StringIO import StringIOdef serve_content(content):    svg_io = StringIO()    svg_io.write(content)    svg_io.seek(0)    return send_file(svg_io, mimetype='image/svg+xml')


For those with no need for an actual file, here's how I make an SVG from scratch with a custom color and serve it up with Flask.

import flaskcustom_color_global_variable = 'red'@app.route('/circle-thin-custom-color.svg', methods=('GET', 'HEAD'))def circle_thin_custom_color):    """Thin circle with the color set by a global variable."""    return flask.Response(        """            <svg                xmlns="http://www.w3.org/2000/svg"                viewBox="0 0 512 512"            ><path                 fill="{color}"                 d="M256 8C119 8 8 119 8 256s111 248 248 248 248-111                    248-248S393 8 256 8zm216 248c0 118.7-96.1 216-216 216-118.7                    0-216-96.1-216-216 0-118.7 96.1-216 216-216 118.7 0 216 96.1                    216 216z"            /></svg>        \n""".format(            color=custom_color_global_variable,        ),        mimetype='image/svg+xml'    )