将URL参数从Flask发送到Bokeh s

2024-03-28 16:48:19 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试将一个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)

对于bokeh服务器:

^{pr2}$

由于autoload_服务器创建了一个Javascript代码段,因此无法使用Bokeh服务器的URL参数来传递此数据(以及curdoc().session_context

所以。。。有什么方法可以把参数传递给Bokeh应用程序吗? 泰亚!在


Tags: 数据fromimport服务器app应用程序flasksession
1条回答
网友
1楼 · 发布于 2024-03-28 16:48:19

您可以将其附加到从autoload_server返回的<script>标记的src属性中。请在源代码中查看我的函数appendQuery,以获取此question

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

这个方法应该在即将到来的Bokeh版本中正式化,根据。。。https://github.com/bokeh/bokeh/issues/5992#issuecomment-287232101

相关问题 更多 >