How to determine a unique user ID per connection

Hi All,

I am implementing a streamlit Chatbot where I have to save the chat log state as a file.

(Could not save a state as a variable since every time, user input a new chat, streamlit will re-run all codes from the beginning, so the variable always got reset )

My questions are:

  1. how can I get a unique user-connection ID?
    e.g. when user-A connect, he will get a chat-log file-A , and when user-B connect, she will get a chatlog file-B .

  2. Is there a way to know if the connection is close for like 30 minutes ? (similar to Colab), so that I can delete the chatlog of that user

I am a relatively new user but I did something related recently…

For Q1 you could try this:

from streamlit.report_thread import get_report_ctx

def _get_session():
    import streamlit.report_thread as ReportThread
    from streamlit.server.server import Server
    session_id = get_report_ctx().session_id
    session_info = Server.get_current()._get_session_info(session_id)
    if session_info is None:
        raise RuntimeError("Couldn't get your Streamlit Session object.")
    return session_info.session

Then you can get a unique session ID for each connection using the line
user_session = _get_session()

That user_session parameter does not change even when things are reloaded (ie. the streamlit state changes). Then you can use that user_session parameter in the file name (unique for each user).

I am not sure about question 2, but perhaps you can append the datetime in the chat file and check every 5 minutes to see if it is 30 minutes old?


Thanks so much @LukeF !! This is very helpful !

1 Like