1

我正在尝试开发一个可以上传文件的网站,然后在后面分析该文件以生成交互式图形(散点图和直方图),然后返回到浏览器供用户操作。(想象一下把 Excel 放到网上,这样人们就可以上传文件、获取图形并操作图形。)我考虑了各种选项,并决定使用 Bokeh 进行绘图。我写了一个python脚本和一个html页面来上传文件。使用 Bokeh,我能够创建一个输出文件(例如“plot.html”)。这很好用。

另外,我已经安装了 Tornado,以便我可以上传和动态读取一个简单的文件(例如“test.txt”),并在 output.html 中简单地返回文件的内容。所以这很好用。

但是,当我修改为 Tornado 使用而编写的脚本以显示较早的 Bokeh 生成的 plot.html 时,这不起作用。Tornado 无法正确渲染 Bokeh 生成的 html(包含绘图对象)有什么问题吗?例如,我读到数据库搜索中的条目可能包含无法序列化的元素,并且在显示搜索结果之前需要删除不可序列化的元素。我想知道这样的事情是否会发生。

以下是一些相关脚本:

display.py:用于使用 Tornado 读取和返回文件的内容。这可以正常工作并按预期返回 test.txt 的内容。

import os.path
import random
import tornado.httpserver
import tornado.ioloop
import tornado.options
import tornado.web
from tornado.options import define, options
define("port", default=80, help="run on the given port", type=int)
class IndexHandler(tornado.web.RequestHandler):
    def get(self):
        self.render('index.html')
class OutputHandler(tornado.web.RequestHandler):
    def post(self):
        fname = self.get_argument('upfile')
        f = open(fname, 'r')
        lines = f.readlines()
        self.render('plot.html', content=lines)
if __name__ == '__main__':
    tornado.options.parse_command_line()
    app = tornado.web.Application(
        handlers=[(r'/', IndexHandler), (r'/content', OutputHandler)],
        template_path=os.path.join(os.path.dirname(__file__), "templates"),
        static_path=os.path.join(os.path.dirname(__file__), "static"),
        debug=True
    )
    http_server = tornado.httpserver.HTTPServer(app)
    http_server.listen(options.port)
    tornado.ioloop.IOLoop.instance().start()

plot.py:用于使用 Bokeh 读取和生成绘图。这可以工作并创建包含生成的图的 plot.html。

from bokeh.plotting import *
output_file("plot.html")
filename = 'test.dat'
f=open(filename,'r')
#####
# deleted lines for manipulating data 
#####
scatter(ndarray[:1000,0], ndarray[:1000,1], color='red', alpha=0.7)
quad(top=hist, bottom=np.zeros(len(hist)), left=edges[:-1], right=edges[1:],
     fill_color="#036564", line_color="#033649")

display_plot.py:用于通过 Tornado 显示 Bokeh 生成的 plot.html。这不起作用。

import os.path
import random
import tornado.httpserver
import tornado.ioloop
import tornado.options
import tornado.web
from tornado.options import define, options
define("port", default=80, help="run on the given port", type=int)
class IndexHandler(tornado.web.RequestHandler):
    def get(self):
        self.render('plot.html')

# the rest the same as in display.py for now.

最后一个脚本让我认为显示包含绘图对象的 Bokeh 生成的 html 与显示仅包含文本和图形的其他 html 文件不同,这些文件可以正确呈现。这是真的吗?我可以做些什么来使用 Tornado(或任何网络服务)显示 plot.html?

谢谢你的帮助。

4

1 回答 1

2

RequestHandler.render将文件解释为 Tornado 模板。这意味着某些字符序列(尤其是双花括号{{ }})具有特殊含义。如果您只想按原样提供文件,请使用write而不是render

with open('plot.html') as f:
    self.write(f.read())
于 2014-07-27T20:28:05.203 回答