Multi-page app with session state

When you use an IDE debugger with this code, it canā€™t get a Session ID from the IDE itself, so you get this message:
" session_id = get_report_ctx().session_id
AttributeError: ā€˜NoneTypeā€™ object has no attribute ā€˜session_idā€™
"

I understand why we get this error, but what is the solution? How do we debug our code using the debugger when our local IDE canā€™t generate a sesion_id?

Hello @euler, if you have some data that must be cleared every run, the best way to do it is to keep them out of the session state I guess. Could you describe more precisely your usecase?

Hello @ksxx, unfortunately itā€™s not possible to change widget values programmatically for now. This session state doesnā€™t support it, and I donā€™t know any that does.

Hello @an_pas, I donā€™t know that object.

If youā€™re still encountering this issue,you could maybe use @thiagoā€™s SessionState which does not use any hashing mechanism. My implementation is mostly useful if you want to bind widget values to session state variables.

1 Like

Hello @OlliePage, your IDE tries to run your app as a regular python script, but in that case it wonā€™t load a ReportContext object.

In your case, try to use this _get_state() function. When run as a script, using a module like sys to keep your session state should work fine.

import sys

# ...

def _get_state(hash_funcs=None):
    try:
        session = _get_session()
    except (AttributeError, RuntimeError):
        session = sys

    if not hasattr(session, "_custom_session_state"):
        session._custom_session_state = _SessionState(session, hash_funcs)

    return session._custom_session_state

1 Like

That did the trick. Thanks very much. Thatā€™s made the world of difference.

1 Like

I tried to set the page config but an error came out stated that I can only call it once. I suspect itā€™s probably due to how multiple app structure calling it. Is there any hack around this? @okld

StreamlitAPIException : set_page_config() can only be called once per app, and must be called as the first Streamlit command in your script.

HI! I have the same problem, i tried your solution but it gives me this error:

NameError: name ā€˜_get_sessionā€™ is not defined

I get the same error as well, did you manage to fix this?

Hello @Paco_Luna, @apol96,

I guess the script you tried to use was just a reply to another post. I was just a subset of the whole session state implementation.

Streamlit introduced a new session state API that I suggest you use instead. Iā€™ve already uploaded my script to use this new implementation:

Related post: