4

我不确定我做错了什么,如果您能指出我要阅读的内容,那就太好了。我在第一个 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)
4

1 回答 1

5

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

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

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)
于 2009-10-21T22:33:32.563 回答