如何从cherrypy提供多个matplotlib图像? [英] How to serve multiple matplotlib images from cherrypy?
问题描述
我有以下使用Python 3和cherrypy的HelloWorld项目,该项目提供2个matplotlib图像:
I have the following HelloWorld project using Python 3 and cherrypy that serves 2 matplotlib images:
import cherrypy
import matplotlib.pyplot as plt
import numpy as np
from io import BytesIO
class HelloWorld(object):
@cherrypy.expose
def index(self):
output = """
Hello World!
<img src="image1.png" width="640", height="480" border="0" />
<img src="image2.png" width="640", height="480" border="0" />
"""
return output
@cherrypy.expose
def image1_png(self):
img = BytesIO()
self.plot(img)
img.seek(0)
retobj = cherrypy.lib.static.serve_fileobj(img, content_type='png', name='image1.png')
return retobj
@cherrypy.expose
def image2_png(self):
img = BytesIO()
self.plot(img)
img.seek(0)
retobj = cherrypy.lib.static.serve_fileobj(img, content_type='png', name='image2.png')
return retobj
def plot(self, image):
sampleData = np.random.normal(size=100)
plt.hist(sampleData)
plt.savefig(image, format='png')
if __name__ == '__main__':
cherrypy.quickstart(HelloWorld())
仅调用其中一张图像(通过注释掉另一张图像)就可以很好地工作,但同时调用两者均无效.知道如何解决这个问题吗?
Calling only one of the images (by commenting out the other one) works perfectly fine, but calling both doesn't work. Any idea how to fix this?
推荐答案
原来,这是 matplotlib
后端 tkinter
的线程问题.通过 matplotlib.use('agg')
手动更改后端可以修复它.请注意,必须在导入 matplotlib.pyplot
之前放置该代码段.
Turns out this is a threading issue with the matplotlib
backend tkinter
. Manually changing the backend via matplotlib.use('agg')
fixed it. Note that that snippet has to be placed before importing matplotlib.pyplot
.
这篇关于如何从cherrypy提供多个matplotlib图像?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!