Skip to content

Instantly share code, notes, and snippets.

@nfaggian
Created July 26, 2012 09:44
Show Gist options
  • Save nfaggian/3181255 to your computer and use it in GitHub Desktop.
Save nfaggian/3181255 to your computer and use it in GitHub Desktop.
Demonstration of a dynamically generated figure served using the Bottle microframework.
"""
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)
@riaanvddool
Copy link

How does the response object get used by the function?

@nfaggian
Copy link
Author

The response function is handled by the bottle API. Would need to have a look at the app.route decorator for the details.

@laserson
Copy link

What if I want to incorporate the png into an HTML template?

@nfaggian
Copy link
Author

nfaggian commented Jan 3, 2013

Perhaps you could use flask:

https://gist.github.com/862153

@goFrendiAsgard
Copy link

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