This question has been asked in a similar way here but the answer was way over my head (I\'m super new to python and web development) so I\'m hoping there\'s a simpler way o
My first question is: Does the image change often? Do you want to keep the older ones? If it's a real-time thing, then your quest for optimisation is justified. Otherwise, the benefits from generating the image on the fly aren't that significant.
The code as it stands would require 2 requests:
Probably the simplest way (keeping the web requests to a minimum) is @Alex L's comment, which would allow you to do it in a single request, by building a HTML with the image embedded in it.
Your code would be something like:
# Build your matplotlib image in a iostring here
# ......
#
# Initialise the base64 string
#
imgStr = "data:image/png;base64,"
imgStr += base64.b64encode(mybuffer)
print "Content-type: text/html\n"
print """
# ...a bunch of text and html here...
#...more text and html...
""" % imgStr
This code will probably not work out of the box, but shows the idea.
Note that this is a bad idea in general if your image doesn't really change too often or generating it takes a long time, because it will be generated every time.
Another way would be to generate the original html. Loading it will trigger a request for the "test.png". You can serve that separately, either via the buffer streaming solution you already mention, or from a static file.
Personally, I'd stick with a decoupled solution: generate the image by another process (making sure that there's always an image available) and use a very light thing to generate and serve the HTML.
HTH,