Skip to content

Instantly share code, notes, and snippets.

@tvst
Last active May 18, 2023 12:05
Show Gist options
  • Star 9 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tvst/6ef6287b2f3363265d51531c62a84f51 to your computer and use it in GitHub Desktop.
Save tvst/6ef6287b2f3363265d51531c62a84f51 to your computer and use it in GitHub Desktop.
Hack to get a session-specific ID in Streamlit. See https://discuss.streamlit.io/t/session-specific-caching/271
import streamlit.ReportThread as ReportThread
from streamlit.server.Server import Server
def get_session_id():
# Hack to get the session object from Streamlit.
ctx = ReportThread.get_report_ctx()
this_session = None
current_server = Server.get_current()
if hasattr(current_server, '_session_infos'):
# Streamlit < 0.56
session_infos = Server.get_current()._session_infos.values()
else:
session_infos = Server.get_current()._session_info_by_id.values()
for session_info in session_infos:
s = session_info.session
if (
# Streamlit < 0.54.0
(hasattr(s, '_main_dg') and s._main_dg == ctx.main_dg)
or
# Streamlit >= 0.54.0
(not hasattr(s, '_main_dg') and s.enqueue == ctx.enqueue)
):
this_session = s
if this_session is None:
raise RuntimeError(
"Oh noes. Couldn't get your Streamlit Session object"
'Are you doing something fancy with threads?')
return id(this_session)
@walterwang
Copy link

thanks this is awesome since it allows people to see headers as well from the session object!

@pommedeterresautee
Copy link

Now it is simpler:

from streamlit.report_thread import get_report_ctx
ctx = get_report_ctx()
print(ctx.session_id)

@akaJasonK
Copy link

it looks like they removed the report_thread module in the latest version of Streamlit (1.16).

When I was on v1.13 I was able to get the simpler approach that @pommedeterresautee mentioned above to work. Not sure at which version between 1.13 and 1.16 they removed report_thread. If anyone else stumbles on this gist and finds a new session_id approach compatible with Streamlit >=1.16, please tag me

@Alex1802
Copy link

Alex1802 commented May 18, 2023

I have used this for version 1.22.0 @akaJasonK

from streamlit.runtime.scriptrunner.script_run_context import get_script_run_ctx
ctx = get_script_run_ctx()
print(ctx.session_id)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment