Dynamically serving a matplotlib image to the web using python

后端 未结 6 1505
悲哀的现实
悲哀的现实 2020-11-29 02:43

This question has been asked in a similar way here but the answer was way over my head (I\'m super new to python and web development) so I\'m hoping there\'s a simpler way o

6条回答
  •  半阙折子戏
    2020-11-29 03:30

    The above answers are a little outdated -- here's what works for me on Python3+ to get the raw bytes of the figure data.

    import matplotlib.pyplot as plt
    from io import BytesIO
    fig = plt.figure()
    plt.plot(range(10))
    figdata = BytesIO()
    fig.savefig(figdata, format='png')
    

    As mentioned in other answers you now need to set a 'Content-Type' header to 'image/png' and write out the bytes.

    Depending on what you are using as your webserver the code may vary. I use Tornado as my webserver and the code to do that is:

    self.set_header('Content-Type', 'image/png')
    self.write(figdata.getvalue())
    

提交回复
热议问题