1

Bokeh を使用して大規模なデータベースをプロットし、Flask を使用してローカルホストでアプリを提供しています。要約されたコードは次のようになります。

app = Flask(__name__)

def make_doc(doc):

    def plot_time():
        p = figure(plot_height=400, plot_width=1000, tools="xpan,box_zoom,xwheel_zoom,reset,save", 
            x_axis_type="datetime", background_fill_color="#efefef",outline_line_color="#000000")       
        for us,color in zip(lista_plots,colors):
            p.line(x="Instant", y=us, source=source, name=us, line_color=color, line_width=1, legend=us.title())                
        return p

    def plot_time_aux(): 
        p = figure(plot_height=115, plot_width=1000, x_axis_type="datetime", y_axis_type=None, tools="",  background_fill_color="#efefef")
        for us in list_plots:
            p.line(x="Instant", y=us, source=source, name=us, line_color="gray", alpha=0.55)   
        return p

p1 = plot_time()
p2 = plot_time_aux()
doc.add_root(p1)
doc.add_root(p2)
doc.title = "Time Plot"

@app.route('/', methods=['GET'])

def bkapp_page():
    script = server_document('http://localhost:5006/bkapp')
    return render_template("index.html", script=script)

def bk_worker():
    server = Server({'/bkapp': make_doc}, io_loop=IOLoop(), allow_websocket_origin=["localhost:{}".format(port)])
    server.start()
    server.io_loop.start()

from threading import Thread
Thread(target=bk_worker).start()

if __name__ == '__main__':
    print('Opening single process Flask app with embedded Bokeh application on http://localhost:{}/'.format(port))
    webbrowser.open_new("http://localhost:{}/".format(port))
    app.run(port=port, debug=False) 

コードは問題なく実行されますが、p1 と p2 にアクセスして Jinja2 html テンプレートのカスタム div に挿入する場合、その方法がわかりません。html テンプレートは次のようになります。

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Time Plots</title>
</head>
<body>
    {% for root in script.roots %}
        <div>{{ embed(root) }}</div>
    {% endfor %}
    {{ script | safe }}
</body>
</html> 

このままでは、スクリプトは p1 と p2 を次々にプロットし、 Jinja2 forループを無視します (おそらく、テンプレートで参照している変数が存在しないためです...)。ただし、各プロット (p1 と p2) を render_template() 関数の引数として渡したいので、html テンプレートの任意の場所に自由に配置できますが、方法がわかりません.

どんなアイデアでも大歓迎です。

4

1 に答える 1