Pn.state.on_session_destroyed doesn't work

I would have expected Closed... to be written out when I close browser tab, but maybe I’m misunderstanding what a session is?

import panel as pn
pn.extension()

slider = pn.widgets.IntSlider(name='A Slider', start=0, end=10, value=5)


def callback(session_context):
    with open("test.txt", "w") as f:
        f.write("Closed...")

pn.state.on_session_destroyed(callback)
slider.servable()

I think this is what you are looking for: pn.state.on_session_destroyed() never called · Issue #3601 · holoviz/panel · GitHub

Thanks for pointing to that.

Unfortunately, I couldn’t get it to work; I would have expected destroyed to be printed after closing tab.

import panel as pn


def destroyed(session_context):
    print("destroyed")
    app.stop()


def created(session_context):
    print("created")


def main_app():
    pn.state.on_session_destroyed(destroyed)
    return pn.Row("Test App")


pn.state.on_session_created(created)


app = pn.serve(
    {"Demo": main_app},
    port=8080,
    title="Demo",
    show=True,
    start=True,
)
print("complete")
python test.py
Launching server at http://localhost:8080
created
^Ccomplete

It does not destroy the session instantaneous after you close it:

import panel as pn

pn.extension()

def destroyed(session_context):
    print("Closed...")


def created(session_context):
    pn.state.on_session_destroyed(destroyed)
    print("created")


slider = pn.widgets.IntSlider(name="A Slider", start=0, end=10, value=5)
pn.state.on_session_created(created)
slider.servable()

Gives me this output:

❯ panel serve /home/shh/Desktop/tmp2.py --autoreload --unused-session-lifetime=100 --check-unused-sessions=500                     
2023-07-06 21:43:20,318 Starting Bokeh server version 3.2.0 (running on Tornado 6.3.2)
2023-07-06 21:43:20,319 Check for unused sessions every 500 milliseconds
2023-07-06 21:43:20,319 Unused sessions last for 100 milliseconds
2023-07-06 21:43:20,319 User authentication hooks NOT provided (default user enabled)
2023-07-06 21:43:20,320 Bokeh app running at: http://localhost:5006/tmp2
2023-07-06 21:43:20,320 Starting Bokeh server with process id: 208374
created
2023-07-06 21:43:23,768 WebSocket connection opened
2023-07-06 21:43:23,768 ServerConnection created
2023-07-06 21:43:25,764 WebSocket connection closed: code=1001, reason=None
Closed...
2 Likes