Can we get all currently active Session Ids?

Hi everyone,

I am currently working on a app that saves that saves a file for the current user session. I want to clean up this file once the session is inactive.

Is there a way to retrieve all active session ids? Or to trigger a function before a session becomes inactive?

The code basically looks like this:

#Fist step: get the current session id:
from streamlit.runtime.scriptrunner.script_run_context import get_script_run_ctx
ctx = get_script_run_ctx()
session_id =
#Second step:  save a file 
image_as_bytes = "random_bytes_that_make_up_an_image"
path_to_image = f"random_path/{session_id}.png"

with open(path_to_image,"wb") as file:
#Third Step: Delete Images from inactive Sessions


Thank you very much for your help & ideas.

Best regards

Hi @Tian

Perhaps you can explore a timeout logic (see this related thread Timeout a streamlit webapp after certain time) after a certain time span has elapsed.

Another approach is to explicitly delete or clear up data (e.g. using del on the variable).

Hope this helps!