【问题标题】:Sending URL parameter from Flask to a Bokeh server将 URL 参数从 Flask 发送到 Bokeh 服务器
【发布时间】:2017-06-07 07:25:38
【问题描述】:

我正在尝试将 Bokeh“自动加载”服务器集成到 Flask 应用程序中,用户将在另一个页面上选择要加载的数据集。

这组数据的 ID 在 URL(get 参数)中,我无法将其从 Flask 应用程序发送到 Bokeh 服务器。

一些示例代码:

# flask_app.py
import subprocess
import atexit
import subprocess, os

from flask import render_template, render_template_string, Flask

from bokeh.embed import autoload_server
from bokeh.client import pull_session, push_session

app_html = """
<!DOCTYPE html>
<html lang="en">
  <body>
    <div class="bk-root">
      {{ bokeh_script|safe }}
    </div>
  </body>
</html>
"""

app = Flask(__name__)

bokeh_process = subprocess.Popen(
    ['bokeh', 'serve', '--allow-websocket-origin=localhost:5000', 'sample.py'], stdout=subprocess.PIPE)

@atexit.register
def kill_server():
    bokeh_process.kill()

@app.route('/visualization/<int:batchid>')
def visualization(batchid):
    session = pull_session(app_path='/sample')

    # I'd love to do something like that... though it doesn't work :
    session.document.batch_id = batchid
    bokeh_script = autoload_server(None, app_path="/sample", session_id=session.id)
    return render_template_string(app_html, bokeh_script=bokeh_script)

if __name__ == '__main__':
    print("STARTED")
    app.run(debug=True)

对于散景服务器:

# sample.py
import pandas as pd  
import bokeh  

# ... doesn't work
data = pd.read_csv('batch-%i.csv' % (curdoc().batch_id))

由于 autoload_server 创建了 Javascript sn-p,因此无法使用 Bokeh 服务器的 URL 参数来传递此数据(以及 curdoc().session_context

那么...有没有办法以这种方式将参数传递给 Bokeh 应用程序? 泰亚!

【问题讨论】:

    标签: python flask bokeh


    【解决方案1】:

    您可以通过附加到从autoload_server 返回的&lt;script&gt; 标记的src 属性来做到这一点。在这个question的源代码中查看我的函数appendQuery

    def appendQuery( script , key , value) :
        # Pass along the parameter as a query string to the script's src url: TODO this will formally be introduced in next release of Bokeh to avoid this hack
        script_list = script.split("\n")
        idxSrcAttr = 2
        script_list[idxSrcAttr] = script_list[idxSrcAttr][:-1] + "&{}={}\"".format( key , value )
        script = "\n".join(script_list)
        return script
    

    根据...https://github.com/bokeh/bokeh/issues/5992#issuecomment-287232101

    ,该方法应该在即将发布的 Bokeh 版本中正式化

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-03-16
    • 1970-01-01
    • 2019-08-11
    • 1970-01-01
    • 2015-09-20
    • 2017-10-05
    • 1970-01-01
    • 2018-10-19
    相关资源
    最近更新 更多