Background: I'm starting off with Django, and have limited experience with Python, so please bear with me. I've written a Python script that runs periodically (in a cron job) to store data into a SQLite3 database, from which I'd like to read from and generate images with Matplotlib (more specifically, with Basemap). This started off as an interest in learning Python and building an "interesting" enough project. I'm picking the Django framework because it seems reasonably-well documented, although I was pleasantly surprised by web.py because of its "lightweightness" in its requirements (but web.py's sparse documentation makes it a bit harder to start off with); but at the moment, I'm not entirely dead-set on a framework.
The example in question 1874642 is almost what I'm looking for, with an image being generated on-the-fly without requiring having to write it to disk (and thusly having to deal with periodically cleaning up the generated files).
However, what is not clear to me is how the generated image can be incorporated in a template, instead of having the browser simply showing the image. From the tutorial material, I'm guessing that it should be possible to represent the variables incorporated in some django.template.Context
into the django.http.HttpResponse
, but the referenced example shortcuts it by responding directly with a Mime object instead of building it with a Context.
So what I'm asking is:
Is it necessary to invoke a print_png
on the generated Matplotlib FigureCanvas
object? Or is the FigureCanvas
copyied "unprinted" to the Context, so that in the Django template I explicity write the HTML img
tag and put by hand the tag's attributes?
I'm under the impression that I have to write the Canvas to disk (i.e. do a canvas.print_figure("image.png")
), so that the HTML img
tag sees it in the Django template. But I want to be sure that there isn't a "more manageable way" -- i.e. passing the image in the Context
and having the template "magically" generate it. If it's really necessary to write to disk, I suppose I could use Django's filesystem caching facility to write the generated images in some way (checking whether an image was already written for a given input parameter set, of course). I welcome your suggestions on this regard, since it's not yet clear at this time the size and number of the images that will be generated, and thusly I'm looking to avoid spending disk space and instead prefer waiting for an image to be generated (even if it takes a few seconds).
Thank you in advance.
you can pass a StringIO
object to pyplot.savefig()
, and get the PNG file content by StringIO.getvalue()
.
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