我不确定自己做错了什么,如果你能指出我要阅读的内容,那就太好了。我已经采用了第一个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)
有帮助吗?

解决方案

以下是一些对我有用的事情,但在您继续进行之前,我建议您阅读此页面关于如何配置包含静态内容的目录。

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

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

然后显示如下:

return '<img src="/img/test.png" />' # note:  forward slash before "img"

问题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)
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top