散景会话和文档轮询

Bokeh Session and Document Polling

我正在尝试使用创建 Tornado 实例的 bokeh-server 可执行文件通过 Django 提供散景文档。可以通过 Session.object_link 方法提供的 URL 访问散景文档。导航到时,bokeh-server 可执行文件将其写入标准输出(IP 地址已替换为省略号):

INFO:tornado.access:200 POST /bokeh/bb/71cee48b-5122-4275-bd4f-d137ea1374e5/gc (...) 222.55ms
INFO:tornado.access:200 GET /bokeh/bb/71cee48b-5122-4275-bd4f-d137ea1374e5/ (...) 110.15ms
INFO:tornado.access:200 POST /bokeh/bb/71cee48b-5122-4275-bd4f-d137ea1374e5/gc (...) 232.66ms
INFO:tornado.access:200 GET /bokeh/bb/71cee48b-5122-4275-bd4f-d137ea1374e5/ (...) 114.16ms

这似乎是 python 实例 运行 Django WSGI 应用程序(由 Apache 运行 mod_wsgi 初始化)和 bokeh-server 可执行文件之间的通信。

当浏览器收到响应,包括散景界面所需的图形和数据等时,浏览器会进行一些初始联网,如果与具有 python 回调。当用户关闭 window 或浏览器时,上面的相同网络会继续。此外,网络仅在 Django 或 bokeh-server 进程被终止时停止。

为了启动散景会话并将 URL 传回 Django 模板,有必要在新线程中启动散景会话:

def get_bokeh_url(self, context):
        t = Thread(target=self.run)
        t.start()

        return self.session.object_link(self.document.context) 

def run(self):
    return self.session.poll_document(self.document)

self.sessionself.document 都在线程启动前初始化。所以在 get_bokeh_url 被调用的地方,文档上有一些图表,其中一些有交互回调,会话已经创建但没有通过 poll_document 轮询(这似乎是交互所必需的)。

除非您终止 Django 或 bokeh-server,否则该线程将永远保持 运行。这意味着当更多的请求通过时,就会建立更多的线程,网络的数量也会增加。

我的问题是,一旦文档不再在浏览器中查看,是否有办法终止线程?

我一直在思考的一个答案是在浏览器关闭时向服务器发送快速请求并以某种方式终止该文档的线程。我试过从bokeh界面中删除文档,但是没有效果。

bokeh 服务器会定期检查是否有连接到会话。如果一段时间内没有连接,会话就会过期并销毁。

从版本 0.12.1 开始,检查间隔和最大无连接时间分别默认为 17 秒和 60 秒。您可以像这样 运行 服务器覆盖它们

bokeh serve --check-unused-sessions 1000 --unused-session-lifetime 1000 app.py

这在文档中很难找到,在 CLI documentation and in the developer guide, in a section on Applications, Sessions and Connections in the Server Architecture chapter. There's also a closed Github issue on this topic: Periodic callbacks continue after tabs are closed #3770

中有描述

如果每次销毁会话时都需要自定义逻辑,请使用 directory deploy format for your app and add a server_lifecycle.py file containing your Lifecycle Hooks,特别是这个:

def on_session_destroyed(session_context):
    ''' If present, this function is called when a session is closed. '''
    pass