Method of implementing session_ids prior to v1.13, no longer works in 1.16

I had this working on streamlit v1.13 but it appears that no longer works on streamlit 1.16

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

With the release 1.16, is there a new approach to handling session_ids for multiple users in a streamlit cloud instance uploading files? It seems the module that it used to live (report_thread>get_report_ctx) in has been renamed or removed.

The above was modeled after the approached discussed in this closed forum thread:

Hi, you honestly shouldnā€™t be using this api but if you want to really keep attempting to use an internal, private api, you can check out this threadā€¦ Because itā€™s an internal api, it can change in any release and thus you run into maintainability problems.

1 Like

Agreed we shouldnā€™t be using it but there are legitimate reasons for wanting to have an identifier that is associated with the session, for example logging user activity with a session - especially if the user can access sensitive data. Iā€™ve been using session_id, in the various hacks, for this since a couple of months after Streamlit was first released. There have been many requests for a standard, supported, API but Iā€™m not aware of one.
Iā€™m currently updating the application to 1.20 and have had to set the applications session tracker to None as I really canā€™t be bothered to find out where the session_id has moved to in the latest refactoring.

Here you go ā€“ for version 1.20.0

from streamlit.runtime.scriptrunner import get_script_run_ctx
import streamlit as st

ctx = get_script_run_ctx()
session_id = ctx.session_id

You could also use one or more websocket headers as a proxy for session_id (perhaps Sec-Websocket-Key):

from streamlit.web.server.websocket_headers import _get_websocket_headers
import streamlit as st

headers = _get_websocket_headers()

session_id = headers.get("Sec-Websocket-Key")

if session_id is not None:
    # ... do something with session_id

See:

If all you need is a session id you can have it using a very stable API.

import uuid

if "session_id" not in st.session_state:
    st.session_state.session_id = uuid.uuid4()
3 Likes

Thanks very much. Iā€™ll likely use that for a session Id and _get_websocket_headers() toset up a basic authentication.

Thanks for this, the websockets approach is the way to go.

This topic was automatically closed 365 days after the last reply. New replies are no longer allowed.