- 
      
- 
        Save rduplain/1641344 to your computer and use it in GitHub Desktop. 
| "Plot a PNG using matplotlib in a web request, using Flask." | |
| # Install dependencies, preferably in a virtualenv: | |
| # | |
| # pip install flask matplotlib | |
| # | |
| # Run the development server: | |
| # | |
| # python app.py | |
| # | |
| # Go to http://localhost:5000/plot.png and see a plot of random data. | |
| import random | |
| import StringIO | |
| from flask import Flask, make_response | |
| from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas | |
| from matplotlib.figure import Figure | |
| app = Flask(__name__) | |
| @app.route('/plot.png') | |
| def plot(): | |
| fig = Figure() | |
| axis = fig.add_subplot(1, 1, 1) | |
| xs = range(100) | |
| ys = [random.randint(1, 50) for x in xs] | |
| axis.plot(xs, ys) | |
| canvas = FigureCanvas(fig) | |
| output = StringIO.StringIO() | |
| canvas.print_png(output) | |
| response = make_response(output.getvalue()) | |
| response.mimetype = 'image/png' | |
| return response | |
| if __name__ == '__main__': | |
| app.run(debug=True) | 
i like it, thx!!!
thanks!
Awesome. Thank you.
Hi, thank you for the code. I ran it and got this msg '* Restarting with stat'. So i installed watchdog suggested in this post http://stackoverflow.com/questions/28241989/flask-app-restarting-with-stat and now I get this '* '*Restarting with windowsapi reloader'. And the localhost page doesn't work (keeps loading). Would you know how to make this work ? Thank you.
Is there a way to embed this into a flask template? Right now i'm passing the response variable into an html template using the render_template function, but the image is not showing up; instead, only the response string is rendering. Thank you in advance!
thank you for alternative way to show plotted graph !
Thanks a lot! This was super useful :)
I am using python3.5 and ran the code with slight modification:
- Instead of import StringIO, I usedimport io
- Instead of output = StringIO.StringIO(), I usedoutput = io.BytesIO()
Thanks
Great help, thanks
How to embed this response in the html page?
is there a way to embed this response into html template? I have been searching everywhere but have not been able to find a workaround
You saved my life :). Very helpful!
ran the code with slight modification
from flask import send_file
@route("/reports/")
def reports():
    return render_template('report.html')
@app.route('/fig/')
def fig():
  fig = plt.figure()
......
.....
.....
  img = io.BytesIO()
  fig.savefig(img)
  img.seek(0)
  return send_file(img, mimetype='image/png')
report HTML:
 <img src="{{ url_for('fig') }}" alt="Image Placeholder">
I am using python3.5 and ran the code with slight modification:
- Instead of
import StringIO, I usedimport io- Instead of
output = StringIO.StringIO(), I usedoutput = io.BytesIO()Thanks
Very helpful, thanks!
exactly what I needed, thank you.