├── LICENSE
├── README.md
├── app.py
├── logomark_website.png
├── requirements.txt
├── streamlit-cheat-sheet.pdf
└── streamlit-cheat-sheet.png
/LICENSE:
--------------------------------------------------------------------------------
1 | MIT License
2 |
3 | Copyright (c) 2020-2023 Daniel Lewis
4 |
5 | Permission is hereby granted, free of charge, to any person obtaining a copy
6 | of this software and associated documentation files (the "Software"), to deal
7 | in the Software without restriction, including without limitation the rights
8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 | copies of the Software, and to permit persons to whom the Software is
10 | furnished to do so, subject to the following conditions:
11 |
12 | The above copyright notice and this permission notice shall be included in all
13 | copies or substantial portions of the Software.
14 |
15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21 | SOFTWARE.
22 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | [](https://share.streamlit.io/daniellewisdl/streamlit-cheat-sheet/master/app.py)
2 |
3 | # Streamlit Cheat Sheet
4 |
5 | App to summarise streamlit docs v1.25.0
6 |
7 | There is also an accompanying png and pdf version
8 |
9 | https://github.com/daniellewisDL/streamlit-cheat-sheet
10 |
11 | v1.25.0 August 2023
12 |
13 | Author:
14 | * @daniellewisDL : https://github.com/daniellewisDL
15 |
16 | Contributors:
17 | * @arnaudmiribel : https://github.com/arnaudmiribel
18 | * @akrolsmir : https://github.com/akrolsmir
19 | * @nathancarter : https://github.com/nathancarter
20 |
21 | # Versioning
22 | * Based on Streamlit 1.25.0
23 | * Made with Python 3.8.5
24 |
25 | # Requirements
26 | A clean venv with just pip and then Streamlit
27 |
28 | # Deployments
29 | [Streamlit Cheat Sheet - Sharing for Streamlit](https://share.streamlit.io/daniellewisdl/streamlit-cheat-sheet/master/app.py)
30 |
31 | # Show me
32 | 
33 |
34 | ---
35 |
36 | # Cheat sheet content
37 |
38 | ## Magic commands
39 |
40 | ```python
41 | # Magic commands implicitly `st.write()`
42 | ''' _This_ is some __Markdown__ '''
43 | a=3
44 | 'dataframe:', data
45 | ```
46 |
47 |
48 | ## Display text
49 |
50 | ```python
51 | st.text('Fixed width text')
52 | st.markdown('_Markdown_') # see #*
53 | st.caption('Balloons. Hundreds of them...')
54 | st.latex(r\'\'\' e^{i\pi} + 1 = 0 \'\'\')
55 | st.write('Most objects') # df, err, func, keras!
56 | st.write(['st', 'is <', 3]) # see *
57 | st.title('My title')
58 | st.header('My header')
59 | st.subheader('My sub')
60 | st.code('for i in range(8): foo()')
61 |
62 | # * optional kwarg unsafe_allow_html = True
63 | ```
64 |
65 |
66 | ## Display data
67 |
68 | ```python
69 | st.dataframe(my_dataframe)
70 | st.table(data.iloc[0:10])
71 | st.json({'foo':'bar','fu':'ba'})
72 | st.metric(label="Temp", value="273 K", delta="1.2 K")
73 | ```
74 |
75 |
76 | ## Display media
77 |
78 | ```python
79 | st.image('./header.png')
80 | st.audio(data)
81 | st.video(data)
82 | ```
83 |
84 |
85 | ## Columns
86 |
87 | ```python
88 | col1, col2 = st.columns(2)
89 | col1.write('Column 1')
90 | col2.write('Column 2')
91 |
92 | # Three columns with different widths
93 | col1, col2, col3 = st.columns([3,1,1])
94 | # col1 is wider
95 |
96 | # Using 'with' notation:
97 | >>> with col1:
98 | >>> st.write('This is column 1')
99 | ```
100 |
101 |
102 | ## Tabs
103 |
104 | ```python
105 | # Insert containers separated into tabs:
106 | >>> tab1, tab2 = st.tabs(["Tab 1", "Tab2"])
107 | >>> tab1.write("this is tab 1")
108 | >>> tab2.write("this is tab 2")
109 |
110 | # You can also use "with" notation:
111 | >>> with tab1:
112 | >>> st.radio('Select one:', [1, 2])
113 | ```
114 |
115 |
116 | ## Control flow
117 | ```python
118 | # Stop execution immediately:
119 | st.stop()
120 | # Rerun script immediately:
121 | st.experimental_rerun()
122 |
123 | # Group multiple widgets:
124 | >>> with st.form(key='my_form'):
125 | >>> username = st.text_input('Username')
126 | >>> password = st.text_input('Password')
127 | >>> st.form_submit_button('Login')
128 | ```
129 |
130 |
131 | ## Personalize apps for users
132 |
133 | ```python
134 | # Show different content based on the user's email address.
135 | >>> if st.user.email == 'jane@email.com':
136 | >>> display_jane_content()
137 | >>> elif st.user.email == 'adam@foocorp.io':
138 | >>> display_adam_content()
139 | >>> else:
140 | >>> st.write("Please contact us to get access!")
141 | ```
142 |
143 |
144 | ## Display interactive widgets
145 |
146 | ```python
147 | st.button('Hit me')
148 | st.data_editor('Edit data', data)
149 | st.checkbox('Check me out')
150 | st.radio('Pick one:', ['nose','ear'])
151 | st.selectbox('Select', [1,2,3])
152 | st.multiselect('Multiselect', [1,2,3])
153 | st.slider('Slide me', min_value=0, max_value=10)
154 | st.select_slider('Slide to select', options=[1,'2'])
155 | st.text_input('Enter some text')
156 | st.number_input('Enter a number')
157 | st.text_area('Area for textual entry')
158 | st.date_input('Date input')
159 | st.time_input('Time entry')
160 | st.file_uploader('File uploader')
161 | st.download_button('On the dl', data)
162 | st.camera_input("一二三,茄子!")
163 | st.color_picker('Pick a color')
164 |
165 | # Use widgets\' returned values in variables
166 | >>> for i in range(int(st.number_input('Num:'))): foo()
167 | >>> if st.sidebar.selectbox('I:',['f']) == 'f': b()
168 | >>> my_slider_val = st.slider('Quinn Mallory', 1, 88)
169 | >>> st.write(slider_val)
170 |
171 | # Disable widgets to remove interactivity:
172 | >>> st.slider('Pick a number', 0, 100, disabled=True)
173 | ```
174 |
175 |
176 | ## Build chat-based apps
177 |
178 | ```python
179 | # Insert a chat message container.
180 | >>> with st.chat_message("user"):
181 | >>> st.write("Hello 👋")
182 | >>> st.line_chart(np.random.randn(30, 3))
183 |
184 | # Display a chat input widget.
185 | >>> st.chat_input("Say something")
186 | ```
187 |
188 | ## Mutate data
189 |
190 | ```python
191 | # Add rows to a dataframe after showing it.
192 | >>> element = st.dataframe(df1)
193 | >>> element.add_rows(df2)
194 |
195 | # Add rows to a chart after showing it.
196 | >>> element = st.line_chart(df1)
197 | >>> element.add_rows(df2)
198 | ```
199 |
200 | ## Display code
201 |
202 | ```python
203 | st.echo()
204 | >>> with st.echo():
205 | >>> st.write('Code will be executed and printed')
206 | ```
207 |
208 |
209 | ## Placeholders, help, and options
210 |
211 | ```python
212 | # Replace any single element.
213 | >>> element = st.empty()
214 | >>> element.line_chart(...)
215 | >>> element.text_input(...) # Replaces previous.
216 |
217 | # Insert out of order.
218 | >>> elements = st.container()
219 | >>> elements.line_chart(...)
220 | >>> st.write("Hello")
221 | >>> elements.text_input(...) # Appears above "Hello".
222 |
223 | st.help(pandas.DataFrame)
224 | st.get_option(key)
225 | st.set_option(key, value)
226 | st.set_page_config(layout='wide')
227 | st.experimental_show(objects)
228 | st.experimental_get_query_params()
229 | st.experimental_set_query_params(**params)
230 | ```
231 |
232 |
233 | ## Connect to data sources
234 |
235 | ```python
236 | st.experimental_connection('pets_db', type='sql')
237 | conn = st.experimental_connection('sql')
238 | conn = st.experimental_connection('snowpark')
239 |
240 | >>> class MyConnection(ExperimentalBaseConnection[myconn.MyConnection]):
241 | >>> def _connect(self, **kwargs) -> MyConnection:
242 | >>> return myconn.connect(**self._secrets, **kwargs)
243 | >>> def query(self, query):
244 | >>> return self._instance.query(query)
245 | ```
246 |
247 |
248 | ## Optimize performance
249 |
250 | ### Cache data objects
251 |
252 | ```python
253 | # E.g. Dataframe computation, storing downloaded data, etc.
254 | >>> @st.cache_data
255 | ... def foo(bar):
256 | ... # Do something expensive and return data
257 | ... return data
258 | # Executes foo
259 | >>> d1 = foo(ref1)
260 | # Does not execute foo
261 | # Returns cached item by value, d1 == d2
262 | >>> d2 = foo(ref1)
263 | # Different arg, so function foo executes
264 | >>> d3 = foo(ref2)
265 | # Clear all cached entries for this function
266 | >>> foo.clear()
267 | # Clear values from *all* in-memory or on-disk cached functions
268 | >>> st.cache_data.clear()
269 | ```
270 |
271 | ### Cache global resources
272 |
273 | ```python
274 | # E.g. TensorFlow session, database connection, etc.
275 | >>> @st.cache_resource
276 | ... def foo(bar):
277 | ... # Create and return a non-data object
278 | ... return session
279 | # Executes foo
280 | >>> s1 = foo(ref1)
281 | # Does not execute foo
282 | # Returns cached item by reference, s1 == s2
283 | >>> s2 = foo(ref1)
284 | # Different arg, so function foo executes
285 | >>> s3 = foo(ref2)
286 | # Clear all cached entries for this function
287 | >>> foo.clear()
288 | # Clear all global resources from cache
289 | >>> st.cache_resource.clear()
290 | ```
291 |
292 | ### Deprecated caching
293 |
294 | ```python
295 | >>> @st.cache
296 | ... def foo(bar):
297 | ... # Do something expensive in here...
298 | ... return data
299 | >>> # Executes foo
300 | >>> d1 = foo(ref1)
301 | >>> # Does not execute foo
302 | >>> # Returns cached item by reference, d1 == d2
303 | >>> d2 = foo(ref1)
304 | >>> # Different arg, so function foo executes
305 | >>> d3 = foo(ref2)
306 | ```
307 |
308 | ## Display progress and status
309 |
310 | ```python
311 | # Show a spinner during a process
312 | >>> with st.spinner(text='In progress'):
313 | >>> time.sleep(3)
314 | >>> st.success('Done')
315 |
316 | # Show and update progress bar
317 | >>> bar = st.progress(50)
318 | >>> time.sleep(3)
319 | >>> bar.progress(100)
320 |
321 | st.balloons()
322 | st.snow()
323 | st.toast('Mr Stay-Puft')
324 | st.error('Error message')
325 | st.warning('Warning message')
326 | st.info('Info message')
327 | st.success('Success message')
328 | st.exception(e)
329 | ```
330 |
331 | ### Other key parts of the API
332 | [State API](https://docs.streamlit.io/en/stable/session_state_api.html)
333 | [Theme option reference](https://docs.streamlit.io/en/stable/theme_options.html)
334 | [Components API reference](https://docs.streamlit.io/en/stable/develop_streamlit_components.html)
335 |
336 | ---
337 |
--------------------------------------------------------------------------------
/app.py:
--------------------------------------------------------------------------------
1 | """
2 | Streamlit Cheat Sheet
3 |
4 | App to summarise streamlit docs v1.25.0
5 |
6 | There is also an accompanying png and pdf version
7 |
8 | https://github.com/daniellewisDL/streamlit-cheat-sheet
9 |
10 | v1.25.0
11 | 20 August 2023
12 |
13 | Author:
14 | @daniellewisDL : https://github.com/daniellewisDL
15 |
16 | Contributors:
17 | @arnaudmiribel : https://github.com/arnaudmiribel
18 | @akrolsmir : https://github.com/akrolsmir
19 | @nathancarter : https://github.com/nathancarter
20 |
21 | """
22 |
23 | import streamlit as st
24 | from pathlib import Path
25 | import base64
26 |
27 | # Initial page config
28 |
29 | st.set_page_config(
30 | page_title='Streamlit cheat sheet',
31 | layout="wide",
32 | initial_sidebar_state="expanded",
33 | )
34 |
35 | def main():
36 | cs_sidebar()
37 | cs_body()
38 |
39 | return None
40 |
41 | # Thanks to streamlitopedia for the following code snippet
42 |
43 | def img_to_bytes(img_path):
44 | img_bytes = Path(img_path).read_bytes()
45 | encoded = base64.b64encode(img_bytes).decode()
46 | return encoded
47 |
48 | # sidebar
49 |
50 | def cs_sidebar():
51 |
52 | st.sidebar.markdown('''[](https://streamlit.io/)'''.format(img_to_bytes("logomark_website.png")), unsafe_allow_html=True)
53 | st.sidebar.header('Streamlit cheat sheet')
54 |
55 | st.sidebar.markdown('''
56 | Summary of the [docs](https://docs.streamlit.io/), as of [Streamlit v1.25.0](https://www.streamlit.io/).
57 | ''', unsafe_allow_html=True)
58 |
59 | st.sidebar.markdown('__Install and import__')
60 |
61 | st.sidebar.code('$ pip install streamlit')
62 |
63 | st.sidebar.code('''
64 | # Import convention
65 | >>> import streamlit as st
66 | ''')
67 |
68 | st.sidebar.markdown('__Add widgets to sidebar__')
69 | st.sidebar.code('''
70 | # Just add it after st.sidebar:
71 | >>> a = st.sidebar.radio(\'Choose:\',[1,2])
72 | ''')
73 |
74 | st.sidebar.markdown('__Magic commands__')
75 | st.sidebar.code('''
76 | '_This_ is some __Markdown__'
77 | a=3
78 | 'dataframe:', data
79 | ''')
80 |
81 | st.sidebar.markdown('__Command line__')
82 | st.sidebar.code('''
83 | $ streamlit --help
84 | $ streamlit run your_script.py
85 | $ streamlit hello
86 | $ streamlit config show
87 | $ streamlit cache clear
88 | $ streamlit docs
89 | $ streamlit --version
90 | ''')
91 |
92 | st.sidebar.markdown('__Pre-release features__')
93 | st.sidebar.code('''
94 | pip uninstall streamlit
95 | pip install streamlit-nightly --upgrade
96 | ''')
97 | st.sidebar.markdown('Learn more about [experimental features](https://docs.streamlit.io/library/advanced-features/prerelease#beta-and-experimental-features)', unsafe_allow_html=True)
98 |
99 | st.sidebar.markdown('''