Skip to content

Instantly share code, notes, and snippets.

@PablocFonseca
Last active November 22, 2021 23:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save PablocFonseca/44744aeef7b61184d8b81b55ec494dd2 to your computer and use it in GitHub Desktop.
Save PablocFonseca/44744aeef7b61184d8b81b55ec494dd2 to your computer and use it in GitHub Desktop.
Component state management example
import streamlit as st #pip install streamlit
import yaml #pip install pyyaml
from streamlit_ace import st_ace #to install: pip install streamlit_ace
#allow user to edit config file in yaml format. Add couple checks below
with st.expander('example', expanded=True):
st.markdown("""
for this example, yaml must define at least a sample_list member. As the example below:
```yaml
sample_list:
- item 1
- item 2
- item 3
```
If key is not fixed, component will sometime reset between refreshs, causing bad user experience.
if key is fixed component state will be held between refreshs... to reset the component, one must change the key.
""")
fix_key = st.checkbox("Fix component key")
content = st_ace(
auto_update=True,
placeholder="Edit yaml",
language="yaml",
show_gutter=True,
value = st.session_state.get('content', ''),
theme='dawn',
key=None if not fix_key else 'fixed_key',
height=400
)
try:
yaml_content = yaml.load(content, yaml.Loader)
#Some basic validation of configuration just for post-processing example
if ('sample_list' not in yaml_content):
raise ValueError('file must define at least a **sample_list:** key')
if not yaml_content['sample_list']:
raise ValueError('sample_list list is empty!')
st.session_state['content'] = content
#if is valid yaml allows user to save file back to disk
st.download_button("Download yaml", data=content, file_name="config.yaml")
except ValueError as ex:
st.error(ex)
except:
st.error("Bad YAML syntax")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment