How to serve multiple matplotlib images from cherrypy?
Asked Answered
M

1

0

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?

Martimartial answered 7/9, 2017 at 20:55 Comment(0)
M
0

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.

Martimartial answered 8/9, 2017 at 6:4 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.