首页 > 解决方案 > 散景服务器如何从 server_document() 访问参数

问题描述

我有一个烧瓶应用程序,它与散景服务器对话。

我想将参数传递给散景服务器,以便散景服务器可以使用该信息以不同的方式显示事物。

这是我的烧瓶路线,包括我尝试将参数传递给散景的方式:

@app.route('/test')
def test():
    return render_template(
        'bokeh.html', 
        template='Flask',
        script=server_document(
            url='http://localhost:6001/test',
            arguments={'foo': 'bar'}
    ))

我想我正确地传递了参数,但我不知道如何在散景服务器上访问这些参数。所以我实际上不知道他们是否到达那里,但我没有看到任何错误。

我知道server_document()返回一个javascript字符串:

<script src="http://localhost:6001/test/autoload.js?bokeh-autoload-element=1001&bokeh-app-path=/test&bokeh-absolute-url=http://localhost:6001/test&foo=bar" id="1001"></script>

所以参数嵌入在 url 中,http://localhost:6001/test&foo=bar但我仍然不知道散景服务器如何使它们可用于 python 代码。

如何访问参数:{'foo': 'bar'}在散景服务器上?

编辑:

我以为我在从 Flask api 向 Bokeh autoload_server 传递参数中找到了答案,但我错了。

当我尝试将建议的内容添加到我的 main.ipynb 文件(我们使用面板来提供散景应用程序)时,它不起作用:

main.ipynb:
...
print(doc.session_context.request.arguments)
report.serve()

导致此错误:

Error running application handler <bokeh.application.handlers.directory.DirectoryHandler object at 0x7f981b953cf8>: name 'doc' is not defined
File "main.ipynb"...
File "/conda/lib/python3.7/site-packages/bokeh/application/handlers/code_runner.py", line 179...
NameError: name 'doc' is not defined

标签: flaskbokeh

解决方案


在文档中有所描述:

# request.arguments is a dict that maps argument names to lists of strings,
# e.g, the query string ?N=10 will result in {'N': [b'10']}

args = curdoc().session_context.request.arguments

try:
  N = int(args.get('N')[0])
except:
  N = 200

推荐阅读