0% found this document useful (0 votes)
37 views1 page

Cheat Sheet - Streamlit Docs

Uploaded by

Abrao Roberto
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
37 views1 page

Cheat Sheet - Streamlit Docs

Uploaded by

Abrao Roberto
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 1

Documentation  Search Ctrl-K 

Home / Streamlit library / Cheat sheet

 Streamlit library

Get started 
Cheat Sheet
API reference  This is a summary of the docs, as of Streamlit v1.29.0.

Advanced features 
Install & Import Command line
Components 
streamlit run first_app.py streamlit --help
Roadmap 
streamlit run your_script.py
Changelog # Import convention streamlit hello

>>> import streamlit as st streamlit config show


Cheat sheet
streamlit cache clear

streamlit docs
 Streamlit Community Cloud
streamlit --version

Get started 

Deploy your app  Pre-release features


Manage your app  pip uninstall streamlit

pip install streamlit-nightly --upgrade


Share your app 

Manage your account  Learn more about experimental features

Magic commands Build chat-based apps


# Magic commands implicitly # Insert a chat message container.

# call st.write(). >>> with st.chat_message("user"):

'_This_ is some **Markdown***' >>> st.write("Hello 👋")


my_variable >>> st.line_chart(np.random.randn(30, 3))

'dataframe:', my_data_frame
# Display a chat input widget.

>>> st.chat_input("Say something")


Display text
st.text('Fixed width text') Learn how to Build a basic LLM chat app

st.markdown('_Markdown_') # see *

st.latex(r''' e^{i\pi} + 1 = 0 ''') Mutate data


st.write('Most objects') # df, err, func, keras! # Add rows to a dataframe after

st.write(['st', 'is <', 3]) # see * # showing it.

st.title('My title') >>> element = st.dataframe(df1)

st.header('My header') >>> element.add_rows(df2)

st.subheader('My sub')

st.code('for i in range(8): foo()') # Add rows to a chart after

* optional kwarg unsafe_allow_html = True # showing it.

>>> element = st.line_chart(df1)

>>> element.add_rows(df2)
Display data
st.dataframe(my_dataframe)

st.table(data.iloc[0:10]) Display code


st.json({'foo':'bar','fu':'ba'}) >>> with st.echo():
st.metric('My metric', 42, 2) >>> st.write('Code will be executed and printed')

Display media Placeholders, help, and options


st.image('./header.png') # Replace any single element.
st.audio(data) >>> element = st.empty()
st.video(data) >>> element.line_chart(...)

>>> element.text_input(...) # Replaces previous.

Display charts # Insert out of order.


st.area_chart(df) >>> elements = st.container()
st.bar_chart(df) >>> elements.line_chart(...)
st.line_chart(df) >>> st.write("Hello")
st.map(df) >>> elements.text_input(...) # Appears above "Hello".
st.scatter_chart(df)

st.help(pandas.DataFrame)
st.altair_chart(chart)
st.get_option(key)
st.bokeh_chart(fig)
st.set_option(key, value)
st.graphviz_chart(fig) st.set_page_config(layout='wide')
st.plotly_chart(fig) st.experimental_get_query_params()
st.pydeck_chart(chart) st.experimental_set_query_params(**params)
st.pyplot(fig)
st.vega_lite_chart(df)

Connect to data sources


st.connection("pets_db", type="sql")
Add widgets to sidebar
conn = st.connection("sql")
# Just add it after st.sidebar:
conn = st.connection("snowflake")
>>> a = st.sidebar.radio('Select one:', [1, 2])

>>> class MyConnection(BaseConnection[myconn.MyConnectio


# Or use "with" notation:
>>> def _connect(self, **kwargs) -> MyConnection:
>>> with st.sidebar: >>> return myconn.connect(**self._secrets, **kwar
>>> st.radio('Select one:', [1, 2]) >>> def query(self, query):

>>> return self._instance.query(query)

Columns
# Two equal columns:
Optimize performance
>>> col1, col2 = st.columns(2)

>>> col1.write("This is column 1") Cache data objects

>>> col2.write("This is column 2") # E.g. Dataframe computation, storing downloaded data, e

>>> @st.cache_data

# Three different columns: ... def foo(bar):

>>> col1, col2, col3 = st.columns([3, 1, 1]) ... # Do something expensive and return data

# col1 is larger. ... return data

# Executes foo

# You can also use "with" notation: >>> d1 = foo(ref1)

>>> with col1: # Does not execute foo

>>> st.radio('Select one:', [1, 2]) # Returns cached item by value, d1 == d2

>>> d2 = foo(ref1)

# Different arg, so function foo executes


Tabs >>> d3 = foo(ref2)
# Insert containers separated into tabs: # Clear all cached entries for this function
>>> tab1, tab2 = st.tabs(["Tab 1", "Tab2"]) >>> foo.clear()
>>> tab1.write("this is tab 1") # Clear values from *all* in-memory or on-disk cached fu
>>> tab2.write("this is tab 2") >>> st.cache_data.clear()

# You can also use "with" notation:

>>> with tab1: Cache global resources

>>> st.radio('Select one:', [1, 2]) # E.g. TensorFlow session, database connection, etc.

>>> @st.cache_resource

... def foo(bar):


Control flow ... # Create and return a non-data object
# Stop execution immediately: ... return session
st.stop() # Executes foo
# Rerun script immediately: >>> s1 = foo(ref1)
st.rerun() # Does not execute foo

# Returns cached item by reference, s1 == s2


# Group multiple widgets: >>> s2 = foo(ref1)
>>> with st.form(key='my_form'): # Different arg, so function foo executes
>>> username = st.text_input('Username') >>> s3 = foo(ref2)
>>> password = st.text_input('Password') # Clear all cached entries for this function
>>> st.form_submit_button('Login') >>> foo.clear()

# Clear all global resources from cache

>>> st.cache_resource.clear()
Display interactive widgets
st.button("Click me")

st.download_button("Download file", data) Deprecated caching


st.link_button("Go to gallery", url) >>> @st.cache

st.data_editor("Edit data", data) ... def foo(bar):

st.checkbox("I agree") ... # Do something expensive in here...

st.toggle("Enable") ... return data

st.radio("Pick one", ["cats", "dogs"]) >>> # Executes foo

st.selectbox("Pick one", ["cats", "dogs"]) >>> d1 = foo(ref1)

st.multiselect("Buy", ["milk", "apples", "potatoes"]) >>> # Does not execute foo

st.slider("Pick a number", 0, 100) >>> # Returns cached item by reference, d1 == d2


st.select_slider("Pick a size", ["S", "M", "L"]) >>> d2 = foo(ref1)
st.text_input("First name") >>> # Different arg, so function foo executes
st.number_input("Pick a number", 0, 10) >>> d3 = foo(ref2)
st.text_area("Text to translate")

st.date_input("Your birthday")
st.time_input("Meeting time") Display progress and status
st.file_uploader("Upload a CSV") # Show a spinner during a process
st.camera_input("Take a picture") >>> with st.spinner(text='In progress'):
st.color_picker("Pick a color") >>> time.sleep(3)

>>> st.success('Done')
# Use widgets' returned values in variables:

>>> for i in range(int(st.number_input('Num:'))): # Show and update progress bar


>>> foo() >>> bar = st.progress(50)
>>> if st.sidebar.selectbox('I:',['f']) == 'f': >>> time.sleep(3)
>>> b() >>> bar.progress(100)
>>> my_slider_val = st.slider('Quinn Mallory', 1, 88)
>>> st.write(slider_val) >>> with st.status('Authenticating...') as s:
>>> time.sleep(2)
# Disable widgets to remove interactivity: >>> st.write('Some long response.')
>>> st.slider('Pick a number', 0, 100, disabled=True) >>> s.update(label='Response')

st.balloons()
st.snow()

st.toast('Warming up...')
st.error('Error message')

st.warning('Warning message')
st.info('Info message')

st.success('Success message')
st.exception(e)

Personalize apps for users


# Show different content based on the user's email addre

>>> if st.user.email == '[email protected]':


>>> display_jane_content()
>>> elif st.user.email == '[email protected]':

>>> display_adam_content()
>>> else:

>>> st.write("Please contact us to get access!")

Previous: Changelog Next: Streamlit Community Cloud

Still have questions?


 Our forums are full of helpful information and Streamlit experts.

Was this page helpful?  Yes  No  Edit this page on GitHub

Home Contact Us Community

Copyright © 2023, Streamlit Inc. Cookie policy

You might also like