Skip to content

Instantly share code, notes, and snippets.

@jeremyjordan
Last active July 1, 2025 22:20
Show Gist options
  • Save jeremyjordan/82115e18c3529f6366f07f6826c87ebb to your computer and use it in GitHub Desktop.
Save jeremyjordan/82115e18c3529f6366f07f6826c87ebb to your computer and use it in GitHub Desktop.

Revisions

  1. jeremyjordan revised this gist Oct 2, 2019. 2 changed files with 71 additions and 66 deletions.
    67 changes: 1 addition & 66 deletions pages.py
    Original file line number Diff line number Diff line change
    @@ -1,72 +1,7 @@
    import numpy as np
    import streamlit as st
    import streamlit.ReportThread as ReportThread
    from streamlit.server.Server import Server


    class SessionState(object):
    def __init__(self, **kwargs):
    """A new SessionState object.
    Parameters
    ----------
    **kwargs : any
    Default values for the session state.
    Example
    -------
    >>> session_state = SessionState(user_name='', favorite_color='black')
    >>> session_state.user_name = 'Mary'
    ''
    >>> session_state.favorite_color
    'black'
    """
    for key, val in kwargs.items():
    setattr(self, key, val)

    def get(**kwargs):
    """Gets a SessionState object for the current session.
    Creates a new object if necessary.
    Parameters
    ----------
    **kwargs : any
    Default values you want to add to the session state, if we're creating a
    new one.
    Example
    -------
    >>> session_state = get(user_name='', favorite_color='black')
    >>> session_state.user_name
    ''
    >>> session_state.user_name = 'Mary'
    >>> session_state.favorite_color
    'black'
    Since you set user_name above, next time your script runs this will be the
    result:
    >>> session_state = get(user_name='', favorite_color='black')
    >>> session_state.user_name
    'Mary'
    """
    # Hack to get the session object from Streamlit.

    ctx = ReportThread.get_report_ctx()

    session = None
    session_infos = Server.get_current()._session_infos.values()

    for session_info in session_infos:
    if session_info.session._main_dg == ctx.main_dg:
    session = session_info.session

    if session is None:
    raise RuntimeError(
    "Oh noes. Couldn't get your Streamlit Session object"
    'Are you doing something fancy with threads?')

    # Got the session object! Now let's attach some state into it.

    if not getattr(session, '_custom_session_state', None):
    session._custom_session_state = SessionState(**kwargs)

    return session._custom_session_state

    from .streamlit_utils import SessionState

    session_state = SessionState.get(page=1)

    70 changes: 70 additions & 0 deletions streamlit_utils.py
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,70 @@
    '''
    An example implementation from https://discuss.streamlit.io/t/preserving-state-across-sidebar-pages/107
    '''

    import streamlit.ReportThread as ReportThread
    from streamlit.server.Server import Server


    class SessionState(object):
    def __init__(self, **kwargs):
    """A new SessionState object.
    Parameters
    ----------
    **kwargs : any
    Default values for the session state.
    Example
    -------
    >>> session_state = SessionState(user_name='', favorite_color='black')
    >>> session_state.user_name = 'Mary'
    ''
    >>> session_state.favorite_color
    'black'
    """
    for key, val in kwargs.items():
    setattr(self, key, val)

    def get(**kwargs):
    """Gets a SessionState object for the current session.
    Creates a new object if necessary.
    Parameters
    ----------
    **kwargs : any
    Default values you want to add to the session state, if we're creating a
    new one.
    Example
    -------
    >>> session_state = get(user_name='', favorite_color='black')
    >>> session_state.user_name
    ''
    >>> session_state.user_name = 'Mary'
    >>> session_state.favorite_color
    'black'
    Since you set user_name above, next time your script runs this will be the
    result:
    >>> session_state = get(user_name='', favorite_color='black')
    >>> session_state.user_name
    'Mary'
    """
    # Hack to get the session object from Streamlit.

    ctx = ReportThread.get_report_ctx()

    session = None
    session_infos = Server.get_current()._session_infos.values()

    for session_info in session_infos:
    if session_info.session._main_dg == ctx.main_dg:
    session = session_info.session

    if session is None:
    raise RuntimeError(
    "Oh noes. Couldn't get your Streamlit Session object"
    'Are you doing something fancy with threads?')

    # Got the session object! Now let's attach some state into it.

    if not getattr(session, '_custom_session_state', None):
    session._custom_session_state = SessionState(**kwargs)

    return session._custom_session_state
  2. jeremyjordan created this gist Oct 2, 2019.
    123 changes: 123 additions & 0 deletions pages.py
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,123 @@
    import numpy as np
    import streamlit as st
    import streamlit.ReportThread as ReportThread
    from streamlit.server.Server import Server


    class SessionState(object):
    def __init__(self, **kwargs):
    """A new SessionState object.
    Parameters
    ----------
    **kwargs : any
    Default values for the session state.
    Example
    -------
    >>> session_state = SessionState(user_name='', favorite_color='black')
    >>> session_state.user_name = 'Mary'
    ''
    >>> session_state.favorite_color
    'black'
    """
    for key, val in kwargs.items():
    setattr(self, key, val)

    def get(**kwargs):
    """Gets a SessionState object for the current session.
    Creates a new object if necessary.
    Parameters
    ----------
    **kwargs : any
    Default values you want to add to the session state, if we're creating a
    new one.
    Example
    -------
    >>> session_state = get(user_name='', favorite_color='black')
    >>> session_state.user_name
    ''
    >>> session_state.user_name = 'Mary'
    >>> session_state.favorite_color
    'black'
    Since you set user_name above, next time your script runs this will be the
    result:
    >>> session_state = get(user_name='', favorite_color='black')
    >>> session_state.user_name
    'Mary'
    """
    # Hack to get the session object from Streamlit.

    ctx = ReportThread.get_report_ctx()

    session = None
    session_infos = Server.get_current()._session_infos.values()

    for session_info in session_infos:
    if session_info.session._main_dg == ctx.main_dg:
    session = session_info.session

    if session is None:
    raise RuntimeError(
    "Oh noes. Couldn't get your Streamlit Session object"
    'Are you doing something fancy with threads?')

    # Got the session object! Now let's attach some state into it.

    if not getattr(session, '_custom_session_state', None):
    session._custom_session_state = SessionState(**kwargs)

    return session._custom_session_state


    session_state = SessionState.get(page=1)


    def main():
    # Render the readme as markdown using st.markdown.
    readme_text = st.markdown('''
    # Instructions
    Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed vel lorem tincidunt,
    congue orci id, pretium augue. Curabitur facilisis malesuada justo. Sed tincidunt
    metus sed arcu blandit efficitur. Vestibulum ut neque sed diam dapibus imperdiet
    id sit amet ante. In in sollicitudin est, ut bibendum lectus. Curabitur posuere
    cursus dui. Nullam interdum eu nunc ac bibendum. Etiam id dolor laoreet nulla euismod
    tristique. Nulla mollis condimentum auctor. Mauris ut diam ante. Maecenas at mauris
    vulputate, hendrerit erat in, viverra libero. Nulla viverra lacus vitae urna hendrerit
    fringilla. Aliquam pharetra justo vitae neque semper, a consequat lorem varius.
    ''')

    # Add a selector for the app mode on the sidebar.
    st.sidebar.title("What to do")
    app_mode = st.sidebar.selectbox(
    "Choose the app mode",
    ["Instructions", "Show paginated content"]
    )
    if app_mode == "Instructions":
    st.sidebar.success('To continue select an option in the dropdown menu.')
    elif app_mode == "Show paginated content":
    readme_text.empty()
    prev_page = st.button('prev')
    if prev_page:
    session_state.page -= 1
    next_page = st.button('next')
    if next_page:
    session_state.page += 1
    st.write(f'page: {session_state.page}')
    load_data(page=session_state.page)


    def load_data(page=1):
    data = np.arange(1, 100)
    page = max(page, 1)
    per_page = 10
    start = (page - 1) * per_page
    end = page * per_page
    results = data[start:end]

    for i in results:
    st.subheader(i)
    st.text('Lorem ipsum dolor sit amet, consectetur adipiscing elit.')


    if __name__ == "__main__":
    main()