CherryPy,从matplotlib加载图像,或更一般的情况
我不太确定自己哪里做错了,如果你能告诉我该读些什么就太好了。我已经看过第一个CherryPy的教程“你好,世界”,并添加了一些matplotlib的图表。
问题1:我怎么知道文件会保存在哪里?它似乎保存在我运行文件的地方。
问题2:我好像无法在浏览器中打开/查看这个图片。当我在浏览器中查看源代码时,一切看起来都没问题,但还是没办法显示,即使我包含了完整的图片路径。
我觉得我的问题可能出在路径上,但不太明白具体发生了什么。
谢谢你的帮助,
Vincent
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 个回答
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)