Created
July 26, 2012 09:44
-
-
Save nfaggian/3181255 to your computer and use it in GitHub Desktop.
Demonstration of a dynamically generated figure served using the Bottle microframework.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
A simple example that generates a random figure and serves it using Bottle | |
""" | |
import numpy as np | |
import StringIO | |
from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas | |
from matplotlib.figure import Figure | |
from bottle import Bottle, run, response | |
app = Bottle() | |
@app.route("/test") | |
def test(): | |
fig = Figure() | |
ax = fig.add_subplot(111) | |
ax.imshow(np.random.rand(100, 100), interpolation='nearest') | |
canvas = FigureCanvas(fig) | |
png_output = StringIO.StringIO() | |
canvas.print_png(png_output) | |
response.content_type = 'image/png' | |
return png_output.getvalue() | |
run(app, host='localhost', port=8080) |
The response function is handled by the bottle API. Would need to have a look at the app.route decorator for the details.
What if I want to incorporate the png into an HTML template?
Perhaps you could use flask:
Thanks @nfaggian, this is probably what I'm looking for.
@laserson: I have a very simple idea, I don't know if it will work, but it could be a good try:
@app.route("/test.png")
def test():
fig = Figure()
ax = fig.add_subplot(111)
ax.imshow(np.random.rand(100, 100), interpolation='nearest')
canvas = FigureCanvas(fig)
png_output = StringIO.StringIO()
canvas.print_png(png_output)
response.content_type = 'image/png'
return png_output.getvalue()
@app.route("/try_template")
def try_template():
return '<h4>The template</h4><img src="/test.png" />';
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
How does the response object get used by the function?