I have a pretty beginner-question. Is it possible to display dynamically processed matplotlib images (as shown in https://gist.github.com/wilsaj/862153 or https://gist.github.com/rduplain/1641344) directly via render_template(...) or do I have to use app.route('.../')? The aim is to show a customizable (scientific) plot inside a website.
Is there any clean solution if I want to pass an array (or more than one variable) to the plot function?
You have to use two routes and a template to do this.
The route that shows the page will call render_template()
using your HTML page template. The template has the HTML for the page, but not the PNG data.
In the place in the template where the PNG image goes you have to insert a <img>
element, as if you were trying to display a static image.
The trick is that the src
attribute of this image points to a second route. You can generate it using url_for()
. For example:
<img src="{{ url_for('mypng', data = some_data) }}">
When the browser receives the HTML it will find the link to the image and load that URL. That will execute the second route in the server.
This second route generates the PNG data and returns it as a response, without a template and setting a content type of image/png
so that the browser renders it as an image. This second route will be coded as shown in the two links you referenced.
I hope this helps!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With