CherryPy,从matplotlib或gen中加载图像

2024-10-02 22:25:31 发布

您现在位置:Python中文网/ 问答频道 /正文

我不知道我做错了什么,如果你能告诉我该读什么就好了。我在CherryPy的第一个教程“hello world”中添加了一点matplotlib情节。 问题1:如何知道文件将保存在何处?它正好是我运行文件的地方。 问题2:我似乎无法在浏览器中打开/查看图像。当我在浏览器中查看源代码时,一切看起来都是正确的,但是没有运气,即使我包含了完整的图像路径。 我想我的问题是路径问题,但不确定发生的机制

谢谢你的帮助 文森特

import cherrypy
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt

class HelloWorld:

    def index(self):
        fig = plt.figure()
         ax = fig.add_subplot(111)
         ax.plot([1,2,3])
         fig.savefig('test.png')
        return ''' <img src="test.png" width="640" height="480" border="0" /> '''

    index.exposed = True

import os.path
tutconf = os.path.join(os.path.dirname(__file__), 'tutorial.conf')

if __name__ == '__main__':
    cherrypy.quickstart(HelloWorld(), config=tutconf)
else:
    cherrypy.tree.mount(HelloWorld(), config=tutconf)

Tags: 文件path图像import路径indexmatplotlibos
1条回答
网友
1楼 · 发布于 2024-10-02 22:25:31

下面是一些对我有用的东西,但是在继续之前,我建议您阅读this page关于如何配置包含静态内容的目录。在

问题1:如何知道文件将保存在何处?
如果指定文件的保存位置,则查找该文件的过程将变得更容易。
例如,可以将图像文件保存到CherryPy应用程序目录中名为“img”的子目录中,如下所示:

fig.savefig('img/test.png') # note:  *no* forward slash before "img"

然后像这样显示:

^{pr2}$

问题2:我似乎[无法]在浏览器中打开/查看图像。
下面是我用来让CherryPy应用程序使用静态图像的一种方法:

if __name__ == '__main__':
    import os.path
    currdir = os.path.dirname(os.path.abspath(__file__))
    conf = {'/css/style.css':{'tools.staticfile.on':True,
        'tools.staticfile.filename':os.path.join(currdir,'css','style.css')},
        '/img':{'tools.staticdir.on':True,
        'tools.staticdir.dir':os.path.join(currdir,'img')}}
    cherrypy.quickstart(root, "/", config=conf)

相关问题 更多 >