Skip to content

Instantly share code, notes, and snippets.

@jeremyjordan
Last active July 22, 2023 13:13
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save jeremyjordan/82115e18c3529f6366f07f6826c87ebb to your computer and use it in GitHub Desktop.
Streamlit Paginated Example
import numpy as np
import streamlit as st
from .streamlit_utils import SessionState
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()
'''
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
@treuille
Copy link

treuille commented Oct 2, 2019

This is great!

@arrabi
Copy link

arrabi commented Feb 21, 2020

I'm getting this error when I import SessionState:

AttributeError: 'ReportSession' object has no attribute '_main_dg'
Traceback:
File "e:\anaconda3\envs\myenv\lib\site-packages\streamlit\ScriptRunner.py", line 314, in _run_script
exec(code, module.dict)
File "CompareModels_img.py", line 139, in
session_state = SessionState.get(question=1)
File "streamlit_utils.py", line 61, in get
if session_info.session._main_dg == ctx.main_dg:

any idea how to fix this?

@jeremyjordan
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment