-
-
Save wilsaj/862153 to your computer and use it in GitHub Desktop.
from flask import Flask, make_response | |
app = Flask(__name__) | |
@app.route("/simple.png") | |
def simple(): | |
import datetime | |
import StringIO | |
import random | |
from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas | |
from matplotlib.figure import Figure | |
from matplotlib.dates import DateFormatter | |
fig=Figure() | |
ax=fig.add_subplot(111) | |
x=[] | |
y=[] | |
now=datetime.datetime.now() | |
delta=datetime.timedelta(days=1) | |
for i in range(10): | |
x.append(now) | |
now+=delta | |
y.append(random.randint(0, 1000)) | |
ax.plot_date(x, y, '-') | |
ax.xaxis.set_major_formatter(DateFormatter('%Y-%m-%d')) | |
fig.autofmt_xdate() | |
canvas=FigureCanvas(fig) | |
png_output = StringIO.StringIO() | |
canvas.print_png(png_output) | |
response=make_response(png_output.getvalue()) | |
response.headers['Content-Type'] = 'image/png' | |
return response | |
if __name__ == "__main__": | |
app.run() |
Hi Thanks for the example. What is I want to put he result back to same home url. What changes I have to do?
This is a good example but what if i wanted to show this image in my Html <img>
tag dynamically without downloading it. I mean within my Markup.
This works quite well. However, after reloading the image a few times, I get errors like this:
Exception RuntimeError: RuntimeError('main thread is not in main loop',) in <bound method PhotoImage.__del__ of <Tkinter.PhotoImage instance at 0x7f5889efcc68>> ignored Tcl_AsyncDelete: async handler deleted by the wrong thread Aborted (core dumped)
or
Tcl_AsyncDelete: cannot find async handler
this doesn't work in pythonanywhere.com anymore. is it maybe outdated? I keep getting a 404 URL not found
mark
from flask import Flask, make_response
app = Flask(name)
@app.route("/simple.png")
def simple():
import datetime
from io import BytesIO
import random
from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas
from matplotlib.figure import Figure
from matplotlib.dates import DateFormatter
fig=Figure()
ax=fig.add_subplot(111)
x=[]
y=[]
now=datetime.datetime.now()
delta=datetime.timedelta(days=1)
for i in range(10):
x.append(now)
now+=delta
y.append(random.randint(0, 1000))
ax.plot_date(x, y, '-')
ax.xaxis.set_major_formatter(DateFormatter('%Y-%m-%d'))
fig.autofmt_xdate()
canvas=FigureCanvas(fig)
png_output = BytesIO()
canvas.print_png(png_output)
response=make_response(png_output.getvalue())
response.headers['Content-Type'] = 'image/png'
return response
if name == "main":
app.run(debug=True)
it is working
Patch to make this work with python 3