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