Link,Text https://docs.streamlit.io/develop/api-reference/charts#chart-elements,"DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceremovePAGE ELEMENTSWrite and magicaddText elementsaddData elementsaddChart elementsremoveSIMPLEst.area_chartst.bar_chartst.line_chartst.mapst.scatter_chartADVANCEDst.altair_chartst.bokeh_chartst.graphviz_chartst.plotly_chartst.pydeck_chartst.pyplotst.vega_lite_chartInput widgetsaddMedia elementsaddLayouts and containersaddChat elementsaddStatus elementsaddThird-party componentsopen_in_newAPPLICATION LOGICNavigation and pagesaddExecution flowaddCaching and stateaddConnections and secretsaddCustom componentsaddUtilitiesaddConfigurationaddTOOLSApp testingaddCommand lineaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Develop/API reference/Chart elementsChart elements Streamlit supports several different charting libraries, and our goal is to continually add support for more. Right now, the most basic library in our arsenal is Matplotlib. Then there are also interactive charting libraries like Vega Lite (2D charts) and deck.gl (maps and 3D charts). And finally we also provide a few chart types that are ""native"" to Streamlit, like st.line_chart and st.area_chart. Simple chart elements Simple area chartsDisplay an area chart.st.area_chart(my_data_frame) Simple bar chartsDisplay a bar chart.st.bar_chart(my_data_frame) Simple line chartsDisplay a line chart.st.line_chart(my_data_frame) Simple scatter chartsDisplay a line chart.st.scatter_chart(my_data_frame) Scatterplots on mapsDisplay a map with points on it.st.map(my_data_frame) Advanced chart elements MatplotlibDisplay a matplotlib.pyplot figure.st.pyplot(my_mpl_figure) AltairDisplay a chart using the Altair library.st.altair_chart(my_altair_chart) Vega-LiteDisplay a chart using the Vega-Lite library.st.vega_lite_chart(my_vega_lite_chart) PlotlyDisplay an interactive Plotly chart.st.plotly_chart(my_plotly_chart) BokehDisplay an interactive Bokeh chart.st.bokeh_chart(my_bokeh_chart) PyDeckDisplay a chart using the PyDeck library.st.pydeck_chart(my_pydeck_chart) GraphVizDisplay a graph using the dagre-d3 library.st.graphviz_chart(my_graphviz_spec) Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration! PreviousStreamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl(""https://assets5.lottiefiles.com/packages/lf20_V9t630.json"") st_lottie(lottie_hello, key=""hello"") Plotly EventsMake Plotly charts interactive!. Created by @null-jones.fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.chart += get_annotations_chart(annotations=[(""Mar 01, 2008"", ""Pretty good day for GOOG""), (""Dec 01, 2007"", ""Something's going wrong for GOOG & AAPL""), (""Nov 01, 2008"", ""Market starts again thanks to...""), (""Dec 01, 2009"", ""Small crash for GOOG after...""),],) st.altair_chart(chart, use_container_width=True) PlostA deceptively simple plotting library for Streamlit. Created by @tvst.import plost plost.line_chart(my_dataframe, x='time', y='stock_value', color='stock_name',) HiPlotHigh dimensional Interactive Plotting. Created by @facebookresearch.data = [{'dropout':0.1, 'lr': 0.001, 'loss': 10.0, 'optimizer': 'SGD'}, {'dropout':0.15, 'lr': 0.01, 'loss': 3.5, 'optimizer': 'Adam'}, {'dropout':0.3, 'lr': 0.1, 'loss': 4.5, 'optimizer': 'Adam'}] hip.Experiment.from_iterable(data).display() EChartsHigh dimensional Interactive Plotting. Created by @andfanilo.from streamlit_echarts import st_echarts st_echarts(options=options) Streamlit FoliumStreamlit Component for rendering Folium maps. Created by @randyzwitch.m = folium.Map(location=[39.949610, -75.150282], zoom_start=16) st_data = st_folium(m, width=725) Spacy-StreamlitspaCy building blocks and visualizers for Streamlit apps. Created by @explosion.models = [""en_core_web_sm"", ""en_core_web_md""] spacy_streamlit.visualize(models, ""Sundar Pichai is the CEO of Google."") Streamlit AgraphA Streamlit Graph Vis, based on react-grah-vis. Created by @ChrisDelClea.from streamlit_agraph import agraph, Node, Edge, Config agraph(nodes=nodes, edges=edges, config=config) Streamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl(""https://assets5.lottiefiles.com/packages/lf20_V9t630.json"") st_lottie(lottie_hello, key=""hello"") Plotly EventsMake Plotly charts interactive!. Created by @null-jones.fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.chart += get_annotations_chart(annotations=[(""Mar 01, 2008"", ""Pretty good day for GOOG""), (""Dec 01, 2007"", ""Something's going wrong for GOOG & AAPL""), (""Nov 01, 2008"", ""Market starts again thanks to...""), (""Dec 01, 2009"", ""Small crash for GOOG after...""),],) st.altair_chart(chart, use_container_width=True) PlostA deceptively simple plotting library for Streamlit. Created by @tvst.import plost plost.line_chart(my_dataframe, x='time', y='stock_value', color='stock_name',) HiPlotHigh dimensional Interactive Plotting. Created by @facebookresearch.data = [{'dropout':0.1, 'lr': 0.001, 'loss': 10.0, 'optimizer': 'SGD'}, {'dropout':0.15, 'lr': 0.01, 'loss': 3.5, 'optimizer': 'Adam'}, {'dropout':0.3, 'lr': 0.1, 'loss': 4.5, 'optimizer': 'Adam'}] hip.Experiment.from_iterable(data).display() EChartsHigh dimensional Interactive Plotting. Created by @andfanilo.from streamlit_echarts import st_echarts st_echarts(options=options) Streamlit FoliumStreamlit Component for rendering Folium maps. Created by @randyzwitch.m = folium.Map(location=[39.949610, -75.150282], zoom_start=16) st_data = st_folium(m, width=725) Spacy-StreamlitspaCy building blocks and visualizers for Streamlit apps. Created by @explosion.models = [""en_core_web_sm"", ""en_core_web_md""] spacy_streamlit.visualize(models, ""Sundar Pichai is the CEO of Google."") Streamlit AgraphA Streamlit Graph Vis, based on react-grah-vis. Created by @ChrisDelClea.from streamlit_agraph import agraph, Node, Edge, Config agraph(nodes=nodes, edges=edges, config=config) Streamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl(""https://assets5.lottiefiles.com/packages/lf20_V9t630.json"") st_lottie(lottie_hello, key=""hello"") Plotly EventsMake Plotly charts interactive!. Created by @null-jones.fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.chart += get_annotations_chart(annotations=[(""Mar 01, 2008"", ""Pretty good day for GOOG""), (""Dec 01, 2007"", ""Something's going wrong for GOOG & AAPL""), (""Nov 01, 2008"", ""Market starts again thanks to...""), (""Dec 01, 2009"", ""Small crash for GOOG after...""),],) st.altair_chart(chart, use_container_width=True) NextPrevious: Data elementsNext: st.area_chartforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy" https://docs.streamlit.io/deploy/streamlit-community-cloud/share-your-app/share-previews#descriptions,"DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudremoveGet startedaddDeploy your appaddManage your appaddShare your appremoveEmbed your appSearch indexabilityShare previewsManage your accountaddTroubleshootingStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Deploy/Streamlit Community Cloud/Share your app/Share previewsShare previews Social media sites generate a card with a title, preview image, and description when you share a link. This feature is called a ""share preview."" In the same way, when you share a link to a public Streamlit app on social media, a share preview is also generated. Here's an example of a share preview for a public Streamlit app posted on Twitter: Share preview for a public Streamlit app push_pinNoteShare previews are generated only for public apps deployed on Streamlit Community Cloud. Titles The title is the text that appears at the top of the share preview. The text also appears in the browser tab when you visit the app. You should set the title to something that will make sense to your app's audience and describe what the app does. It is best practice to keep the title concise, ideally under 60 characters. There are two ways to set the title of a share preview: Set the page_title parameter in st.set_page_config() to your desired title. E.g.: import streamlit as st st.set_page_config(page_title=""My App"") # ... rest of your app If you don't set the page_title parameter, the title of the share preview will be the name of your app's GitHub repository. For example, the default title for an app hosted on GitHub at github.com/jrieke/traingenerator will be ""traingenerator"". Descriptions The description is the text that appears below the title in the share preview. The description should summarize what the app does and ideally should be under 100 characters. Streamlit pulls the description from the README in the app's GitHub repository. If there is no README, the description will default to: This app was built in Streamlit! Check it out and visit https://streamlit.io for more awesome community apps. 🎈 Default share preview when a description is missing If you want your share previews to look great and want users to share your app and click on your links, you should write a good description in the README of your app’s GitHub repository. Preview images Streamlit Community Cloud takes a screenshot of your app once a day and uses it as the preview image, unlike titles and descriptions which are pulled directly from your app's code or GitHub repository. This screenshot may take up to 24 hours to update. Switching your app from public to private If you initially made your app public and later decided to make it private, we will stop generating share previews for the app. However, it may take up to 24 hours for the share previews to stop appearing.Previous: Search indexabilityNext: Manage your accountforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy" https://docs.streamlit.io/en/0.74.0/api.html#data-elements,"DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceremovePAGE ELEMENTSWrite and magicaddText elementsaddData elementsaddChart elementsaddInput widgetsaddMedia elementsaddLayouts and containersaddChat elementsaddStatus elementsaddThird-party componentsopen_in_newAPPLICATION LOGICNavigation and pagesaddExecution flowaddCaching and stateaddConnections and secretsaddCustom componentsaddUtilitiesaddConfigurationaddTOOLSApp testingaddCommand lineaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Develop/API referenceAPI reference Streamlit makes it easy for you to visualize, mutate, and share data. The API reference is organized by activity type, like displaying data or optimizing performance. Each section includes methods associated with the activity type, including examples. Browse our API below and click to learn more about any of our available commands! 🎈 Display almost anything Write and magic st.writeWrite arguments to the app.st.write(""Hello **world**!"") st.write(my_data_frame) st.write(my_mpl_figure) st.write_streamWrite generators or streams to the app with a typewriter effect.st.write_stream(my_generator) st.write_stream(my_llm_stream) MagicAny time Streamlit sees either a variable or literal value on its own line, it automatically writes that to your app using st.write""Hello **world**!"" my_data_frame my_mpl_figure Text elements MarkdownDisplay string formatted as Markdown.st.markdown(""Hello **world**!"") TitleDisplay text in title formatting.st.title(""The app title"") HeaderDisplay text in header formatting.st.header(""This is a header"") SubheaderDisplay text in subheader formatting.st.subheader(""This is a subheader"") CaptionDisplay text in small font.st.caption(""This is written small caption text"") Code blockDisplay a code block with optional syntax highlighting.st.code(""a = 1234"") EchoDisplay some code in the app, then execute it. Useful for tutorials.with st.echo(): st.write('This code will be printed') LaTeXDisplay mathematical expressions formatted as LaTeX.st.latex(""\int a x^2 \,dx"") Preformatted textWrite fixed-width and preformatted text.st.text(""Hello world"") DividerDisplay a horizontal rule.st.divider() Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration! PreviousTagsAdd tags to your Streamlit apps. Created by @gagan3012.st_tags(label='# Enter Keywords:', text='Press enter to add more', value=['Zero', 'One', 'Two'], suggestions=['five', 'six', 'seven', 'eight', 'nine', 'three', 'eleven', 'ten', 'four'], maxtags = 4, key='1') NLUApply text mining on a dataframe. Created by @JohnSnowLabs.nlu.load('sentiment').predict('I love NLU! <3') Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.mention(label=""An awesome Streamlit App"", icon=""streamlit"", url=""https://extras.streamlit.app"",) Annotated textDisplay annotated text in Streamlit apps. Created by @tvst.annotated_text(""This "", (""is"", ""verb""), "" some "", (""annotated"", ""adj""), (""text"", ""noun""), "" for those of "", (""you"", ""pronoun""), "" who "", (""like"", ""verb""), "" this sort of "", (""thing"", ""noun""), ""."") Drawable CanvasProvides a sketching canvas using Fabric.js. Created by @andfanilo.st_canvas(fill_color=""rgba(255, 165, 0, 0.3)"", stroke_width=stroke_width, stroke_color=stroke_color, background_color=bg_color, background_image=Image.open(bg_image) if bg_image else None, update_streamlit=realtime_update, height=150, drawing_mode=drawing_mode, point_display_radius=point_display_radius if drawing_mode == 'point' else 0, key=""canvas"",) TagsAdd tags to your Streamlit apps. Created by @gagan3012.st_tags(label='# Enter Keywords:', text='Press enter to add more', value=['Zero', 'One', 'Two'], suggestions=['five', 'six', 'seven', 'eight', 'nine', 'three', 'eleven', 'ten', 'four'], maxtags = 4, key='1') NLUApply text mining on a dataframe. Created by @JohnSnowLabs.nlu.load('sentiment').predict('I love NLU! <3') Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.mention(label=""An awesome Streamlit App"", icon=""streamlit"", url=""https://extras.streamlit.app"",) Annotated textDisplay annotated text in Streamlit apps. Created by @tvst.annotated_text(""This "", (""is"", ""verb""), "" some "", (""annotated"", ""adj""), (""text"", ""noun""), "" for those of "", (""you"", ""pronoun""), "" who "", (""like"", ""verb""), "" this sort of "", (""thing"", ""noun""), ""."") Drawable CanvasProvides a sketching canvas using Fabric.js. Created by @andfanilo.st_canvas(fill_color=""rgba(255, 165, 0, 0.3)"", stroke_width=stroke_width, stroke_color=stroke_color, background_color=bg_color, background_image=Image.open(bg_image) if bg_image else None, update_streamlit=realtime_update, height=150, drawing_mode=drawing_mode, point_display_radius=point_display_radius if drawing_mode == 'point' else 0, key=""canvas"",) TagsAdd tags to your Streamlit apps. Created by @gagan3012.st_tags(label='# Enter Keywords:', text='Press enter to add more', value=['Zero', 'One', 'Two'], suggestions=['five', 'six', 'seven', 'eight', 'nine', 'three', 'eleven', 'ten', 'four'], maxtags = 4, key='1') NLUApply text mining on a dataframe. Created by @JohnSnowLabs.nlu.load('sentiment').predict('I love NLU! <3') Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.mention(label=""An awesome Streamlit App"", icon=""streamlit"", url=""https://extras.streamlit.app"",) Next Data elements DataframesDisplay a dataframe as an interactive table.st.dataframe(my_data_frame) Data editorDisplay a data editor widget.edited = st.data_editor(df, num_rows=""dynamic"") Column configurationConfigure the display and editing behavior of dataframes and data editors.st.column_config.NumberColumn(""Price (in USD)"", min_value=0, format=""$%d"") Static tablesDisplay a static table.st.table(my_data_frame) MetricsDisplay a metric in big bold font, with an optional indicator of how the metric changed.st.metric(""My metric"", 42, 2) Dicts and JSONDisplay object or string as a pretty-printed JSON string.st.json(my_dict) Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration! PreviousImage CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates value = streamlit_image_coordinates(""https://placekitten.com/200/300"") st.write(value) Plotly EventsMake Plotly charts interactive!. Created by @null-jones.from streamlit_plotly_events import plotly_events fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.metric_cards import style_metric_cards col3.metric(label=""No Change"", value=5000, delta=0) style_metric_cards() Streamlit AggridImplementation of Ag-Grid component for Streamlit. Created by @PablocFonseca.df = pd.DataFrame({'col1': [1, 2, 3], 'col2': [4, 5, 6]}) grid_return = AgGrid(df, editable=True) new_df = grid_return['data'] Streamlit FoliumStreamlit Component for rendering Folium maps. Created by @randyzwitch.m = folium.Map(location=[39.949610, -75.150282], zoom_start=16) folium.Marker([39.949610, -75.150282], popup=""Liberty Bell"", tooltip=""Liberty Bell"").add_to(m) st_data = st_folium(m, width=725) Pandas ProfilingPandas profiling component for Streamlit. Created by @okld.df = pd.read_csv(""https://storage.googleapis.com/tf-datasets/titanic/train.csv"") pr = df.profile_report() st_profile_report(pr) Image CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates value = streamlit_image_coordinates(""https://placekitten.com/200/300"") st.write(value) Plotly EventsMake Plotly charts interactive!. Created by @null-jones.from streamlit_plotly_events import plotly_events fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.metric_cards import style_metric_cards col3.metric(label=""No Change"", value=5000, delta=0) style_metric_cards() Streamlit AggridImplementation of Ag-Grid component for Streamlit. Created by @PablocFonseca.df = pd.DataFrame({'col1': [1, 2, 3], 'col2': [4, 5, 6]}) grid_return = AgGrid(df, editable=True) new_df = grid_return['data'] Streamlit FoliumStreamlit Component for rendering Folium maps. Created by @randyzwitch.m = folium.Map(location=[39.949610, -75.150282], zoom_start=16) folium.Marker([39.949610, -75.150282], popup=""Liberty Bell"", tooltip=""Liberty Bell"").add_to(m) st_data = st_folium(m, width=725) Pandas ProfilingPandas profiling component for Streamlit. Created by @okld.df = pd.read_csv(""https://storage.googleapis.com/tf-datasets/titanic/train.csv"") pr = df.profile_report() st_profile_report(pr) Image CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates value = streamlit_image_coordinates(""https://placekitten.com/200/300"") st.write(value) Plotly EventsMake Plotly charts interactive!. Created by @null-jones.from streamlit_plotly_events import plotly_events fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.metric_cards import style_metric_cards col3.metric(label=""No Change"", value=5000, delta=0) style_metric_cards() Next Chart elements Simple area chartsDisplay an area chart.st.area_chart(my_data_frame) Simple bar chartsDisplay a bar chart.st.bar_chart(my_data_frame) Simple line chartsDisplay a line chart.st.line_chart(my_data_frame) Simple scatter chartsDisplay a line chart.st.scatter_chart(my_data_frame) Scatterplots on mapsDisplay a map with points on it.st.map(my_data_frame) MatplotlibDisplay a matplotlib.pyplot figure.st.pyplot(my_mpl_figure) AltairDisplay a chart using the Altair library.st.altair_chart(my_altair_chart) Vega-LiteDisplay a chart using the Vega-Lite library.st.vega_lite_chart(my_vega_lite_chart) PlotlyDisplay an interactive Plotly chart.st.plotly_chart(my_plotly_chart) BokehDisplay an interactive Bokeh chart.st.bokeh_chart(my_bokeh_chart) PyDeckDisplay a chart using the PyDeck library.st.pydeck_chart(my_pydeck_chart) GraphVizDisplay a graph using the dagre-d3 library.st.graphviz_chart(my_graphviz_spec) Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration! PreviousStreamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl(""https://assets5.lottiefiles.com/packages/lf20_V9t630.json"") st_lottie(lottie_hello, key=""hello"") Plotly EventsMake Plotly charts interactive!. Created by @null-jones.fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.chart += get_annotations_chart(annotations=[(""Mar 01, 2008"", ""Pretty good day for GOOG""), (""Dec 01, 2007"", ""Something's going wrong for GOOG & AAPL""), (""Nov 01, 2008"", ""Market starts again thanks to...""), (""Dec 01, 2009"", ""Small crash for GOOG after...""),],) st.altair_chart(chart, use_container_width=True) PlostA deceptively simple plotting library for Streamlit. Created by @tvst.import plost plost.line_chart(my_dataframe, x='time', y='stock_value', color='stock_name',) HiPlotHigh dimensional Interactive Plotting. Created by @facebookresearch.data = [{'dropout':0.1, 'lr': 0.001, 'loss': 10.0, 'optimizer': 'SGD'}, {'dropout':0.15, 'lr': 0.01, 'loss': 3.5, 'optimizer': 'Adam'}, {'dropout':0.3, 'lr': 0.1, 'loss': 4.5, 'optimizer': 'Adam'}] hip.Experiment.from_iterable(data).display() EChartsHigh dimensional Interactive Plotting. Created by @andfanilo.from streamlit_echarts import st_echarts st_echarts(options=options) Streamlit FoliumStreamlit Component for rendering Folium maps. Created by @randyzwitch.m = folium.Map(location=[39.949610, -75.150282], zoom_start=16) st_data = st_folium(m, width=725) Spacy-StreamlitspaCy building blocks and visualizers for Streamlit apps. Created by @explosion.models = [""en_core_web_sm"", ""en_core_web_md""] spacy_streamlit.visualize(models, ""Sundar Pichai is the CEO of Google."") Streamlit AgraphA Streamlit Graph Vis, based on react-grah-vis. Created by @ChrisDelClea.from streamlit_agraph import agraph, Node, Edge, Config agraph(nodes=nodes, edges=edges, config=config) Streamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl(""https://assets5.lottiefiles.com/packages/lf20_V9t630.json"") st_lottie(lottie_hello, key=""hello"") Plotly EventsMake Plotly charts interactive!. Created by @null-jones.fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.chart += get_annotations_chart(annotations=[(""Mar 01, 2008"", ""Pretty good day for GOOG""), (""Dec 01, 2007"", ""Something's going wrong for GOOG & AAPL""), (""Nov 01, 2008"", ""Market starts again thanks to...""), (""Dec 01, 2009"", ""Small crash for GOOG after...""),],) st.altair_chart(chart, use_container_width=True) PlostA deceptively simple plotting library for Streamlit. Created by @tvst.import plost plost.line_chart(my_dataframe, x='time', y='stock_value', color='stock_name',) HiPlotHigh dimensional Interactive Plotting. Created by @facebookresearch.data = [{'dropout':0.1, 'lr': 0.001, 'loss': 10.0, 'optimizer': 'SGD'}, {'dropout':0.15, 'lr': 0.01, 'loss': 3.5, 'optimizer': 'Adam'}, {'dropout':0.3, 'lr': 0.1, 'loss': 4.5, 'optimizer': 'Adam'}] hip.Experiment.from_iterable(data).display() EChartsHigh dimensional Interactive Plotting. Created by @andfanilo.from streamlit_echarts import st_echarts st_echarts(options=options) Streamlit FoliumStreamlit Component for rendering Folium maps. Created by @randyzwitch.m = folium.Map(location=[39.949610, -75.150282], zoom_start=16) st_data = st_folium(m, width=725) Spacy-StreamlitspaCy building blocks and visualizers for Streamlit apps. Created by @explosion.models = [""en_core_web_sm"", ""en_core_web_md""] spacy_streamlit.visualize(models, ""Sundar Pichai is the CEO of Google."") Streamlit AgraphA Streamlit Graph Vis, based on react-grah-vis. Created by @ChrisDelClea.from streamlit_agraph import agraph, Node, Edge, Config agraph(nodes=nodes, edges=edges, config=config) Streamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl(""https://assets5.lottiefiles.com/packages/lf20_V9t630.json"") st_lottie(lottie_hello, key=""hello"") Plotly EventsMake Plotly charts interactive!. Created by @null-jones.fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.chart += get_annotations_chart(annotations=[(""Mar 01, 2008"", ""Pretty good day for GOOG""), (""Dec 01, 2007"", ""Something's going wrong for GOOG & AAPL""), (""Nov 01, 2008"", ""Market starts again thanks to...""), (""Dec 01, 2009"", ""Small crash for GOOG after...""),],) st.altair_chart(chart, use_container_width=True) Next Input widgets ButtonDisplay a button widget.clicked = st.button(""Click me"") Download buttonDisplay a download button widget.st.download_button(""Download file"", file) Form buttonDisplay a form submit button. For use with st.form.st.form_submit_button(""Sign up"") Link buttonDisplay a link button.st.link_button(""Go to gallery"", url) Page linkDisplay a link to another page in a multipage app.st.page_link(""app.py"", label=""Home"", icon=""🏠"") st.page_link(""pages/profile.py"", label=""My profile"") CheckboxDisplay a checkbox widget.selected = st.checkbox(""I agree"") Color pickerDisplay a color picker widget.color = st.color_picker(""Pick a color"") MultiselectDisplay a multiselect widget. The multiselect widget starts as empty.choices = st.multiselect(""Buy"", [""milk"", ""apples"", ""potatoes""]) RadioDisplay a radio button widget.choice = st.radio(""Pick one"", [""cats"", ""dogs""]) SelectboxDisplay a select widget.choice = st.selectbox(""Pick one"", [""cats"", ""dogs""]) Select-sliderDisplay a slider widget to select items from a list.size = st.select_slider(""Pick a size"", [""S"", ""M"", ""L""]) ToggleDisplay a toggle widget.activated = st.toggle(""Activate"") Number inputDisplay a numeric input widget.choice = st.number_input(""Pick a number"", 0, 10) SliderDisplay a slider widget.number = st.slider(""Pick a number"", 0, 100) Date inputDisplay a date input widget.date = st.date_input(""Your birthday"") Time inputDisplay a time input widget.time = st.time_input(""Meeting time"") Chat inputDisplay a chat input widget.prompt = st.chat_input(""Say something"") if prompt: st.write(f""The user has sent: {prompt}"") Text-areaDisplay a multi-line text input widget.text = st.text_area(""Text to translate"") Text inputDisplay a single-line text input widget.name = st.text_input(""First name"") Data editorDisplay a data editor widget.edited = st.experimental_data_editor(df, num_rows=""dynamic"") File UploaderDisplay a file uploader widget.data = st.file_uploader(""Upload a CSV"") Camera inputDisplay a widget that allows users to upload images directly from a camera.image = st.camera_input(""Take a picture"") Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration! PreviousStreamlit ChatStreamlit Component for a Chatbot UI. Created by @AI-Yash.from streamlit_chat import message message(""My message"") message(""Hello bot!"", is_user=True) # align's the message to the right Streamlit Option MenuSelect a single item from a list of options in a menu. Created by @victoryhb.from streamlit_option_menu import option_menu option_menu(""Main Menu"", [""Home"", 'Settings'], icons=['house', 'gear'], menu_icon=""cast"", default_index=1) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.stoggle import stoggle stoggle( ""Click me!"", """"""🥷 Surprise! Here's some additional content"""""",) Streamlit ElementsCreate a draggable and resizable dashboard in Streamlit. Created by @okls.from streamlit_elements import elements, mui, html with elements(""new_element""): mui.Typography(""Hello world"") TagsAdd tags to your Streamlit apps. Created by @gagan3012.from streamlit_tags import st_tags st_tags(label='# Enter Keywords:', text='Press enter to add more', value=['Zero', 'One', 'Two'], suggestions=['five', 'six', 'seven', 'eight', 'nine', 'three', 'eleven', 'ten', 'four'], maxtags = 4, key='1') StqdmThe simplest way to handle a progress bar in streamlit app. Created by @Wirg.from stqdm import stqdm for _ in stqdm(range(50)): sleep(0.5) TimelineDisplay a Timeline in Streamlit apps using TimelineJS. Created by @innerdoc.from streamlit_timeline import timeline with open('example.json', ""r"") as f: timeline(f.read(), height=800) Camera input liveAlternative for st.camera_input which returns the webcam images live. Created by @blackary.from camera_input_live import camera_input_live image = camera_input_live() st.image(value) Streamlit AceAce editor component for Streamlit. Created by @okld.from streamlit_ace import st_ace content = st_ace() content Streamlit ChatStreamlit Component for a Chatbot UI. Created by @AI-Yash.from streamlit_chat import message message(""My message"") message(""Hello bot!"", is_user=True) # align's the message to the right Streamlit Option MenuSelect a single item from a list of options in a menu. Created by @victoryhb.from streamlit_option_menu import option_menu option_menu(""Main Menu"", [""Home"", 'Settings'], icons=['house', 'gear'], menu_icon=""cast"", default_index=1) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.stoggle import stoggle stoggle( ""Click me!"", """"""🥷 Surprise! Here's some additional content"""""",) Streamlit ElementsCreate a draggable and resizable dashboard in Streamlit. Created by @okls.from streamlit_elements import elements, mui, html with elements(""new_element""): mui.Typography(""Hello world"") TagsAdd tags to your Streamlit apps. Created by @gagan3012.from streamlit_tags import st_tags st_tags(label='# Enter Keywords:', text='Press enter to add more', value=['Zero', 'One', 'Two'], suggestions=['five', 'six', 'seven', 'eight', 'nine', 'three', 'eleven', 'ten', 'four'], maxtags = 4, key='1') StqdmThe simplest way to handle a progress bar in streamlit app. Created by @Wirg.from stqdm import stqdm for _ in stqdm(range(50)): sleep(0.5) TimelineDisplay a Timeline in Streamlit apps using TimelineJS. Created by @innerdoc.from streamlit_timeline import timeline with open('example.json', ""r"") as f: timeline(f.read(), height=800) Camera input liveAlternative for st.camera_input which returns the webcam images live. Created by @blackary.from camera_input_live import camera_input_live image = camera_input_live() st.image(value) Streamlit AceAce editor component for Streamlit. Created by @okld.from streamlit_ace import st_ace content = st_ace() content Streamlit ChatStreamlit Component for a Chatbot UI. Created by @AI-Yash.from streamlit_chat import message message(""My message"") message(""Hello bot!"", is_user=True) # align's the message to the right Streamlit Option MenuSelect a single item from a list of options in a menu. Created by @victoryhb.from streamlit_option_menu import option_menu option_menu(""Main Menu"", [""Home"", 'Settings'], icons=['house', 'gear'], menu_icon=""cast"", default_index=1) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.stoggle import stoggle stoggle( ""Click me!"", """"""🥷 Surprise! Here's some additional content"""""",) Next Media elements ImageDisplay an image or list of images.st.image(numpy_array) st.image(image_bytes) st.image(file) st.image(""https://example.com/myimage.jpg"") AudioDisplay an audio player.st.audio(numpy_array) st.audio(audio_bytes) st.audio(file) st.audio(""https://example.com/myaudio.mp3"", format=""audio/mp3"") VideoDisplay a video player.st.video(numpy_array) st.video(video_bytes) st.video(file) st.video(""https://example.com/myvideo.mp4"", format=""video/mp4"") Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration! PreviousStreamlit CropperA simple image cropper for Streamlit. Created by @turner-anderson.from streamlit_cropper import st_cropper st_cropper(img, realtime_update=realtime_update, box_color=box_color, aspect_ratio=aspect_ratio) Image CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates streamlit_image_coordinates(""https://placekitten.com/200/300"") Streamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl(""https://assets5.lottiefiles.com/packages/lf20_V9t630.json"") st_lottie(lottie_hello, key=""hello"") Streamlit WebrtcHandling and transmitting real-time video/audio streams with Streamlit. Created by @whitphx.from streamlit_webrtc import webrtc_streamer webrtc_streamer(key=""sample"") Drawable CanvasProvides a sketching canvas using Fabric.js. Created by @andfanilo.from streamlit_drawable_canvas import st_canvas st_canvas(fill_color=""rgba(255, 165, 0, 0.3)"", stroke_width=stroke_width, stroke_color=stroke_color, background_color=bg_color, background_image=Image.open(bg_image) if bg_image else None, update_streamlit=realtime_update, height=150, drawing_mode=drawing_mode, point_display_radius=point_display_radius if drawing_mode == 'point' else 0, key=""canvas"",) Image ComparisonCompare images with a slider using JuxtaposeJS. Created by @fcakyon.from streamlit_image_comparison import image_comparison image_comparison(img1=""image1.jpg"", img2=""image2.jpg"",) Streamlit CropperA simple image cropper for Streamlit. Created by @turner-anderson.from streamlit_cropper import st_cropper st_cropper(img, realtime_update=realtime_update, box_color=box_color, aspect_ratio=aspect_ratio) Image CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates streamlit_image_coordinates(""https://placekitten.com/200/300"") Streamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl(""https://assets5.lottiefiles.com/packages/lf20_V9t630.json"") st_lottie(lottie_hello, key=""hello"") Streamlit WebrtcHandling and transmitting real-time video/audio streams with Streamlit. Created by @whitphx.from streamlit_webrtc import webrtc_streamer webrtc_streamer(key=""sample"") Drawable CanvasProvides a sketching canvas using Fabric.js. Created by @andfanilo.from streamlit_drawable_canvas import st_canvas st_canvas(fill_color=""rgba(255, 165, 0, 0.3)"", stroke_width=stroke_width, stroke_color=stroke_color, background_color=bg_color, background_image=Image.open(bg_image) if bg_image else None, update_streamlit=realtime_update, height=150, drawing_mode=drawing_mode, point_display_radius=point_display_radius if drawing_mode == 'point' else 0, key=""canvas"",) Image ComparisonCompare images with a slider using JuxtaposeJS. Created by @fcakyon.from streamlit_image_comparison import image_comparison image_comparison(img1=""image1.jpg"", img2=""image2.jpg"",) Streamlit CropperA simple image cropper for Streamlit. Created by @turner-anderson.from streamlit_cropper import st_cropper st_cropper(img, realtime_update=realtime_update, box_color=box_color, aspect_ratio=aspect_ratio) Image CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates streamlit_image_coordinates(""https://placekitten.com/200/300"") Streamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl(""https://assets5.lottiefiles.com/packages/lf20_V9t630.json"") st_lottie(lottie_hello, key=""hello"") Next Layouts and containers ColumnsInsert containers laid out as side-by-side columns.col1, col2 = st.columns(2) col1.write(""this is column 1"") col2.write(""this is column 2"") ContainerInsert a multi-element container.c = st.container() st.write(""This will show last"") c.write(""This will show first"") c.write(""This will show second"") Modal dialogsInsert a modal dialog that can rerun independently from the rest of the script.@st.experimental_dialog(""Sign up"") def email_form(): name = st.text_input(""Name"") email = st.text_input(""Email"") EmptyInsert a single-element container.c = st.empty() st.write(""This will show last"") c.write(""This will be replaced"") c.write(""This will show first"") ExpanderInsert a multi-element container that can be expanded/collapsed.with st.expander(""Open to see more""): st.write(""This is more content"") PopoverInsert a multi-element popover container that can be opened/closed.with st.popover(""Settings""): st.checkbox(""Show completed"") SidebarDisplay items in a sidebar.st.sidebar.write(""This lives in the sidebar"") st.sidebar.button(""Click me!"") TabsInsert containers separated into tabs.tab1, tab2 = st.tabs([""Tab 1"", ""Tab2""]) tab1.write(""this is tab 1"") tab2.write(""this is tab 2"") Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration!Streamlit ElementsCreate a draggable and resizable dashboard in Streamlit. Created by @okls.from streamlit_elements import elements, mui, html with elements(""new_element""): mui.Typography(""Hello world"") PydanticAuto-generate Streamlit UI from Pydantic Models and Dataclasses. Created by @lukasmasuch.import streamlit_pydantic as sp sp.pydantic_form(key=""my_form"", model=ExampleModel) Streamlit PagesAn experimental version of Streamlit Multi-Page Apps. Created by @blackary.from st_pages import Page, show_pages, add_page_title show_pages([ Page(""streamlit_app.py"", ""Home"", ""🏠""), Page(""other_pages/page2.py"", ""Page 2"", "":books:""), ]) Chat elements Streamlit provides a few commands to help you build conversational apps. These chat elements are designed to be used in conjunction with each other, but you can also use them separately. st.chat_message lets you insert a chat message container into the app so you can display messages from the user or the app. Chat containers can contain other Streamlit elements, including charts, tables, text, and more. st.chat_input lets you display a chat input widget so the user can type in a message. Chat inputDisplay a chat input widget.prompt = st.chat_input(""Say something"") if prompt: st.write(f""The user has sent: {prompt}"") Chat messageInsert a chat message container.import numpy as np with st.chat_message(""user""): st.write(""Hello 👋"") st.line_chart(np.random.randn(30, 3)) Status containerDisplay output of long-running tasks in a container.with st.status('Running'): do_something_slow() st.write_streamWrite generators or streams to the app with a typewriter effect.st.write_stream(my_generator) st.write_stream(my_llm_stream) Status elements Progress barDisplay a progress bar.for i in range(101): st.progress(i) do_something_slow() SpinnerTemporarily displays a message while executing a block of code.with st.spinner(""Please wait...""): do_something_slow() Status containerDisplay output of long-running tasks in a container.with st.status('Running'): do_something_slow() ToastBriefly displays a toast message in the bottom-right corner.st.toast('Butter!', icon='🧈') BalloonsDisplay celebratory balloons!do_something() # Celebrate when all done! st.balloons() SnowflakesDisplay celebratory snowflakes!do_something() # Celebrate when all done! st.snow() Success boxDisplay a success message.st.success(""Match found!"") Info boxDisplay an informational message.st.info(""Dataset is updated every day at midnight."") Warning boxDisplay warning message.st.warning(""Unable to fetch image. Skipping..."") Error boxDisplay error message.st.error(""We encountered an error"") Exception outputDisplay an exception.e = RuntimeError(""This is an exception of type RuntimeError"") st.exception(e) Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration!StqdmThe simplest way to handle a progress bar in streamlit app. Created by @Wirg.from stqdm import stqdm for _ in stqdm(range(50)): sleep(0.5) Custom notification boxA custom notification box with the ability to close it out. Created by @Socvest.from streamlit_custom_notification_box import custom_notification_box styles = {'material-icons':{'color': 'red'}, 'text-icon-link-close-container': {'box-shadow': '#3896de 0px 4px'}, 'notification-text': {'':''}, 'close-button':{'':''}, 'link':{'':''}} custom_notification_box(icon='info', textDisplay='We are almost done with your registration...', externalLink='more info', url='#', styles=styles, key=""foo"") Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.let_it_rain import rain rain(emoji=""🎈"", font_size=54, falling_speed=5, animation_length=""infinite"",) App logic and configuration Navigation and pages Switch pageProgrammatically navigates to a specified page.st.switch_page(""pages/my_page.py"") Page linkDisplay a link to another page in a multipage app.st.page_link(""app.py"", label=""Home"", icon=""🏠"") st.page_link(""pages/profile.py"", label=""My profile"") Execution flow Modal dialogsInsert a modal dialog that can rerun independently from the rest of the script.@st.experimental_dialog(""Sign up"") def email_form(): name = st.text_input(""Name"") email = st.text_input(""Email"") FormsCreate a form that batches elements together with a “Submit"" button.with st.form(key='my_form'): name = st.text_input(""Name"") email = st.text_input(""Email"") st.form_submit_button(""Sign up"") Partial rerunsDefine a fragment to rerun independently from the rest of the script.@st.experimental_fragment(run_every=""10s"") def fragment(): df = get_data() st.line_chart(df) Rerun scriptRerun the script immediately.st.rerun() Stop executionStops execution immediately.st.stop() Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration!AutorefreshForce a refresh without tying up a script. Created by @kmcgrady.from streamlit_autorefresh import st_autorefresh st_autorefresh(interval=2000, limit=100, key=""fizzbuzzcounter"") PydanticAuto-generate Streamlit UI from Pydantic Models and Dataclasses. Created by @lukasmasuch.import streamlit_pydantic as sp sp.pydantic_form(key=""my_form"", model=ExampleModel) Streamlit PagesAn experimental version of Streamlit Multi-Page Apps. Created by @blackary.from st_pages import Page, show_pages, add_page_title show_pages([ Page(""streamlit_app.py"", ""Home"", ""🏠""), Page(""other_pages/page2.py"", ""Page 2"", "":books:""), ]) Caching and state Cache dataFunction decorator to cache functions that return data (e.g. dataframe transforms, database queries, ML inference).@st.cache_data def long_function(param1, param2): # Perform expensive computation here or # fetch data from the web here return data Cache resourceFunction decorator to cache functions that return global resources (e.g. database connections, ML models).@st.cache_resource def init_model(): # Return a global resource here return pipeline( ""sentiment-analysis"", model=""distilbert-base-uncased-finetuned-sst-2-english"" ) Session stateSession state is a way to share variables between reruns, for each user session.st.session_state['key'] = value Query parametersGet, set, or clear the query parameters that are shown in the browser's URL bar.st.query_params[key] = value st.query_params.clear() Connections and databases Setup your connection Create a connectionConnect to a data source or APIconn = st.connection('pets_db', type='sql') pet_owners = conn.query('select * from pet_owners') st.dataframe(pet_owners) Built-in connections SnowflakeConnectionA connection to Snowflake.conn = st.connection('snowflake') SQLConnectionA connection to a SQL database using SQLAlchemy.conn = st.connection('sql') Build your own connections Connection base classBuild your own connection with BaseConnection.class MyConnection(BaseConnection[myconn.MyConnection]): def _connect(self, **kwargs) -> MyConnection: return myconn.connect(**self._secrets, **kwargs) def query(self, query): return self._instance.query(query) Secrets management Secrets singletonAccess secrets from a local TOML file.key = st.secrets[""OpenAI_key""] Secrets fileSave your secrets in a per-project or per-profile TOML file.OpenAI_key = """" Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration!AuthenticatorA secure authentication module to validate user credentials. Created by @mkhorasani.import streamlit_authenticator as stauth authenticator = stauth.Authenticate( config['credentials'], config['cookie']['name'], config['cookie']['key'], config['cookie']['expiry_days'], config['preauthorized']) WS localStorageA simple synchronous way of accessing localStorage from your app. Created by @gagangoku.from streamlit_ws_localstorage import injectWebsocketCode ret = conn.setLocalStorageVal(key='k1', val='v1') st.write('ret: ' + ret) Streamlit Auth0The fastest way to provide comprehensive login inside Streamlit. Created by @conradbez.from auth0_component import login_button user_info = login_button(clientId, domain = domain) st.write(user_info) Custom Components Declare a componentCreate and register a custom component.st.components.v1.declare_component( ""custom_slider"", ""/frontend"", ) HTMLDisplay an HTML string in an iframe.st.components.v1.html( ""

Foo bar.

"" ) iframeLoad a remote URL in an iframe.st.components.v1.iframe( ""docs.streamlit.io"" ) Utilities and user info User infost.experimental_user returns information about the logged-in user of private apps on Streamlit Community Cloud.if st.experimental_user.email == ""foo@corp.com"": st.write(""Welcome back, "", st.experimental_user.email) else: st.write(""You are not authorized to view this page."") Get helpDisplay object’s doc string, nicely formatted.st.help(st.write) st.help(pd.DataFrame) Render HTMLRenders HTML strings to your app.css = """""" """""" st.html(css) Configuration Configuration fileConfigures the default settings for your app.your-project/ ├── .streamlit/ │ └── config.toml └── your_app.py Set page title, favicon, and moreConfigures the default settings of the page.st.set_page_config( page_title=""My app"", page_icon="":shark:"", ) Developer tools App testing st.testing.v1.AppTestst.testing.v1.AppTest simulates a running Streamlit app for testing.from streamlit.testing.v1 import AppTest at = AppTest.from_file(""streamlit_app.py"") at.secrets[""WORD""] = ""Foobar"" at.run() assert not at.exception at.text_input(""word"").input(""Bazbat"").run() assert at.warning[0].value == ""Try again."" AppTest.from_filest.testing.v1.AppTest.from_file initializes a simulated app from a file.from streamlit.testing.v1 import AppTest at = AppTest.from_file(""streamlit_app.py"") at.run() AppTest.from_stringst.testing.v1.AppTest.from_string initializes a simulated app from a string.from streamlit.testing.v1 import AppTest at = AppTest.from_string(app_script_as_string) at.run() AppTest.from_functionst.testing.v1.AppTest.from_function initializes a simulated app from a function.from streamlit.testing.v1 import AppTest at = AppTest.from_function(app_script_as_callable) at.run() BlockA representation of container elements, including: st.chat_message st.columns st.sidebar st.tabs The main body of the app. # at.sidebar returns a Block at.sidebar.button[0].click().run() assert not at.exception ElementThe base class for representation of all elements, including: st.title st.header st.markdown st.dataframe # at.title returns a sequence of Title # Title inherits from Element assert at.title[0].value == ""My awesome app"" ButtonA representation of st.button and st.form_submit_button.at.button[0].click().run() ChatInputA representation of st.chat_input.at.chat_input[0].set_value(""What is Streamlit?"").run() CheckboxA representation of st.checkbox.at.checkbox[0].check().run() ColorPickerA representation of st.color_picker.at.color_picker[0].pick(""#FF4B4B"").run() DateInputA representation of st.date_input.release_date = datetime.date(2023, 10, 26) at.date_input[0].set_value(release_date).run() MultiselectA representation of st.multiselect.at.multiselect[0].select(""New York"").run() NumberInputA representation of st.number_input.at.number_input[0].increment().run() RadioA representation of st.radio.at.radio[0].set_value(""New York"").run() SelectSliderA representation of st.select_slider.at.select_slider[0].set_range(""A"",""C"").run() SelectboxA representation of st.selectbox.at.selectbox[0].select(""New York"").run() SliderA representation of st.slider.at.slider[0].set_range(2,5).run() TextAreaA representation of st.text_area.at.text_area[0].input(""Streamlit is awesome!"").run() TextInputA representation of st.text_input.at.text_input[0].input(""Streamlit"").run() TimeInputA representation of st.time_input.at.time_input[0].increment().run() ToggleA representation of st.toggle.at.toggle[0].set_value(""True"").run() Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration!Pandas ProfilingPandas profiling component for Streamlit. Created by @okld.df = pd.read_csv(""https://storage.googleapis.com/tf-datasets/titanic/train.csv"") pr = df.profile_report() st_profile_report(pr) Streamlit AceAce editor component for Streamlit. Created by @okld.from streamlit_ace import st_ace content = st_ace() content Streamlit AnalyticsTrack & visualize user interactions with your streamlit app. Created by @jrieke.import streamlit_analytics with streamlit_analytics.track(): st.text_input(""Write something"") Previous: ConceptsNext: Write and magicforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy" https://docs.streamlit.io/develop/api-reference/app-testing/testing-element-classes#sttestingv1element_treeselectslider,"DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceremovePAGE ELEMENTSWrite and magicaddText elementsaddData elementsaddChart elementsaddInput widgetsaddMedia elementsaddLayouts and containersaddChat elementsaddStatus elementsaddThird-party componentsopen_in_newAPPLICATION LOGICNavigation and pagesaddExecution flowaddCaching and stateaddConnections and secretsaddCustom componentsaddUtilitiesaddConfigurationaddTOOLSApp testingremovest.testing.v1.AppTestTesting element classesCommand lineaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Develop/API reference/App testing/Testing element classesTesting element classes st.testing.v1.element_tree.Block The Block class has the same methods and attributes as AppTest. A Block instance represents a container of elements just as AppTest represents the entire app. For example, Block.button will produce a WidgetList of Button in the same manner as AppTest.button. ChatMessage, Column, and Tab all inherit from Block. For all container classes, parameters of the original element can be obtained as properties. For example, ChatMessage.avatar and Tab.label. st.testing.v1.element_tree.ElementStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeElement base class for testing. This class's methods and attributes are universal for all elements implemented in testing. For example, Caption, Code, Text, and Title inherit from Element. All widget classes also inherit from Element, but have additional methods specific to each widget type. See the AppTest class for the full list of supported elements. For all element classes, parameters of the original element can be obtained as properties. For example, Button.label, Caption.help, and Toast.icon. Class description[source] st.testing.v1.element_tree.Element(proto, root) Methods run(*, timeout=None) Run the AppTest script which contains the element. Attributes value The value or contents of the element. st.testing.v1.element_tree.ButtonStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.button and st.form_submit_button. Class description[source] st.testing.v1.element_tree.Button(proto, root) Methods click() Set the value of the button to True. run(*, timeout=None) Run the AppTest script which contains the element. set_value(v) Set the value of the button. Attributes value The value of the button. (bool) st.testing.v1.element_tree.ChatInputStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.chat_input. Class description[source] st.testing.v1.element_tree.ChatInput(proto, root) Methods run(*, timeout=None) Run the AppTest script which contains the element. set_value(v) Set the value of the widget. Attributes value The value of the widget. (str) st.testing.v1.element_tree.CheckboxStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.checkbox. Class description[source] st.testing.v1.element_tree.Checkbox(proto, root) Methods check() Set the value of the widget to True. run(*, timeout=None) Run the AppTest script which contains the element. set_value(v) Set the value of the widget. uncheck() Set the value of the widget to False. Attributes value The value of the widget. (bool) st.testing.v1.element_tree.ColorPickerStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.color_picker. Class description[source] st.testing.v1.element_tree.ColorPicker(proto, root) Methods pick(v) Set the value of the widget as a hex string. May omit the ""#"" prefix. run(*, timeout=None) Run the AppTest script which contains the element. set_value(v) Set the value of the widget as a hex string. Attributes value The currently selected value as a hex string. (str) st.testing.v1.element_tree.DateInputStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.date_input. Class description[source] st.testing.v1.element_tree.DateInput(proto, root) Methods run(*, timeout=None) Run the AppTest script which contains the element. set_value(v) Set the value of the widget. Attributes value The value of the widget. (date or Tuple of date) st.testing.v1.element_tree.MultiselectStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.multiselect. Class description[source] st.testing.v1.element_tree.Multiselect(proto, root) Methods run(*, timeout=None) Run the AppTest script which contains the element. select(v) Add a selection to the widget. Do nothing if the value is already selected. If testing a multiselect widget with repeated options, use set_value instead. set_value(v) Set the value of the multiselect widget. (list) unselect(v) Remove a selection from the widget. Do nothing if the value is not already selected. If a value is selected multiple times, the first instance is removed. Attributes format_func The widget's formatting function for displaying options. (callable) indices The indices of the currently selected values from the options. (list) value The currently selected values from the options. (list) st.testing.v1.element_tree.NumberInputStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.number_input. Class description[source] st.testing.v1.element_tree.NumberInput(proto, root) Methods decrement() Decrement the st.number_input widget as if the user clicked ""-"". increment() Increment the st.number_input widget as if the user clicked ""+"". run(*, timeout=None) Run the AppTest script which contains the element. set_value(v) Set the value of the st.number_input widget. Attributes value Get the current value of the st.number_input widget. st.testing.v1.element_tree.RadioStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.radio. Class description[source] st.testing.v1.element_tree.Radio(proto, root) Methods run(*, timeout=None) Run the AppTest script which contains the element. set_value(v) Set the selection by value. Attributes format_func The widget's formatting function for displaying options. (callable) index The index of the current selection. (int) value The currently selected value from the options. (Any) st.testing.v1.element_tree.SelectSliderStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.select_slider. Class description[source] st.testing.v1.element_tree.SelectSlider(proto, root) Methods run(*, timeout=None) Run the AppTest script which contains the element. set_range(lower, upper) Set the ranged selection by values. set_value(v) Set the (single) selection by value. Attributes format_func The widget's formatting function for displaying options. (callable) value The currently selected value or range. (Any or Sequence of Any) st.testing.v1.element_tree.SelectboxStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.selectbox. Class description[source] st.testing.v1.element_tree.Selectbox(proto, root) Methods run(*, timeout=None) Run the AppTest script which contains the element. select(v) Set the selection by value. select_index(index) Set the selection by index. set_value(v) Set the selection by value. Attributes format_func The widget's formatting function for displaying options. (callable) index The index of the current selection. (int) value The currently selected value from the options. (Any) st.testing.v1.element_tree.SliderStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.slider. Class description[source] st.testing.v1.element_tree.Slider(proto, root) Methods run(*, timeout=None) Run the AppTest script which contains the element. set_range(lower, upper) Set the ranged value of the slider. set_value(v) Set the (single) value of the slider. Attributes value The currently selected value or range. (Any or Sequence of Any) st.testing.v1.element_tree.TextAreaStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.text_area. Class description[source] st.testing.v1.element_tree.TextArea(proto, root) Methods input(v) Set the value of the widget only if the value does not exceed the maximum allowed characters. run(*, timeout=None) Run the AppTest script which contains the element. set_value(v) Set the value of the widget. Attributes value The current value of the widget. (str) st.testing.v1.element_tree.TextInputStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.text_input. Class description[source] st.testing.v1.element_tree.TextInput(proto, root) Methods input(v) Set the value of the widget only if the value does not exceed the maximum allowed characters. run(*, timeout=None) Run the AppTest script which contains the element. set_value(v) Set the value of the widget. Attributes value The current value of the widget. (str) st.testing.v1.element_tree.TimeInputStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.time_input. Class description[source] st.testing.v1.element_tree.TimeInput(proto, root) Methods decrement() Select the previous available time. increment() Select the next available time. run(*, timeout=None) Run the AppTest script which contains the element. set_value(v) Set the value of the widget. Attributes value The current value of the widget. (time) st.testing.v1.element_tree.ToggleStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.toggle. Class description[source] st.testing.v1.element_tree.Toggle(proto, root) Methods run(*, timeout=None) Run the AppTest script which contains the element. set_value(v) Set the value of the widget. Attributes value The current value of the widget. (bool) Previous: st.testing.v1.AppTestNext: Command lineforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy" https://docs.streamlit.io/develop/api-reference/execution-flow/st.rerun#using-strerun-to-update-an-earlier-header,"DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceremovePAGE ELEMENTSWrite and magicaddText elementsaddData elementsaddChart elementsaddInput widgetsaddMedia elementsaddLayouts and containersaddChat elementsaddStatus elementsaddThird-party componentsopen_in_newAPPLICATION LOGICNavigation and pagesaddExecution flowremovest.dialogst.formst.form_submit_buttonst.fragmentst.rerunst.stopCaching and stateaddConnections and secretsaddCustom componentsaddUtilitiesaddConfigurationaddTOOLSApp testingaddCommand lineaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Develop/API reference/Execution flow/st.rerunst.rerunStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeRerun the script immediately. When st.rerun() is called, the script is halted - no more statements will be run, and the script will be queued to re-run from the top. Function signature[source] st.rerun() Caveats for st.rerun st.rerun is one of the tools to control the logic of your app. While it is great for prototyping, there can be adverse side effects: Additional script runs may be inefficient and slower. Excessive reruns may complicate your app's logic and be harder to follow. If misused, infinite looping may crash your app. In many cases where st.rerun works, callbacks may be a cleaner alternative. Containers may also be helpful. A simple example in three variations Using st.rerun to update an earlier header import streamlit as st if ""value"" not in st.session_state: st.session_state.value = ""Title"" ##### Option using st.rerun ##### st.header(st.session_state.value) if st.button(""Foo""): st.session_state.value = ""Foo"" st.rerun() Using a callback to update an earlier header ##### Option using a callback ##### st.header(st.session_state.value) def update_value(): st.session_state.value = ""Bar"" st.button(""Bar"", on_click=update_value) Using containers to update an earlier header ##### Option using a container ##### container = st.container() if st.button(""Baz""): st.session_state.value = ""Baz"" container.header(st.session_state.value) Previous: st.fragmentNext: st.stopforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy" https://docs.streamlit.io/develop/api-reference/configuration/config.toml#deprecation,"DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceremovePAGE ELEMENTSWrite and magicaddText elementsaddData elementsaddChart elementsaddInput widgetsaddMedia elementsaddLayouts and containersaddChat elementsaddStatus elementsaddThird-party componentsopen_in_newAPPLICATION LOGICNavigation and pagesaddExecution flowaddCaching and stateaddConnections and secretsaddCustom componentsaddUtilitiesaddConfigurationremoveconfig.tomlst.set_page_configTOOLSApp testingaddCommand lineaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Develop/API reference/Configuration/config.tomlconfig.toml config.toml is an optional file you can define for your working directory or global development environment. When config.toml is defined both globally and in your working directory, Streamlit combines the configuration options and gives precendence to the working-directory configuration. Additionally, you can use environment variables and command-line options to override additional configuration options. For more information, see Configuration options. File location To define your configuration locally or per-project, add .streamlit/config.toml to your working directory. Your working directory is wherever you call streamlit run. If you haven't previously created the .streamlit directory, you will need to add it. To define your configuration globally, you must first locate your global .streamlit directory. Streamlit adds this hidden directory to your OS user profile during installation. For MacOS/Linx, this will be ~/.streamlit/config.toml. For Windows, this will be %userprofile%/.streamlit/config.toml. File format config.toml is a TOML file. Example [client] showErrorDetails = false [theme] primaryColor = ""#F63366"" backgroundColor = ""black"" Available configuration options Below are all the sections and options you can have in your .streamlit/config.toml file. To see all configurations, use the following command in your terminal or CLI: streamlit config show Global [global] # ***DEPRECATED*** # global.disableWatchdogWarning has been deprecated has been deprecated and # will be removed in a future version. This option will be removed on or after # 2024-01-20. # **************** # By default, Streamlit checks if the Python watchdog module is available # and, if not, prints a warning asking for you to install it. The watchdog # module is not required, but highly recommended. It improves Streamlit's # ability to detect changes to files in your filesystem. # If you'd like to turn off this warning, set this to True. # Default: false disableWatchdogWarning = false # By default, Streamlit displays a warning when a user sets both a widget # default value in the function defining the widget and a widget value via # the widget's key in `st.session_state`. # If you'd like to turn off this warning, set this to True. # Default: false disableWidgetStateDuplicationWarning = false # If True, will show a warning when you run a Streamlit-enabled script # via ""python my_script.py"". # Default: true showWarningOnDirectExecution = true Logger [logger] # Level of logging: 'error', 'warning', 'info', or 'debug'. # Default: 'info' level = ""info"" # String format for logging messages. If logger.datetimeFormat is set, # logger messages will default to `%(asctime)s.%(msecs)03d %(message)s`. See # Python's documentation for available attributes: # https://docs.python.org/2.6/develop/logging.html#formatter-objects # Default: ""%(asctime)s %(message)s"" messageFormat = ""%(asctime)s %(message)s"" Client [client] # ***DEPRECATED*** # client.caching has been deprecated and is not required anymore for our new # caching commands. This option will be removed on or after 2024-01-20. # **************** # Whether to enable st.cache. This does not affect st.cache_data or # st.cache_resource. # Default: true caching = true # ***DEPRECATED*** # client.displayEnabled has been deprecated and will be removed in a future # version. This option will be removed on or after 2024-01-20. # **************** # If false, makes your Streamlit script not draw to a Streamlit app. # Default: true displayEnabled = true # Controls whether uncaught app exceptions and deprecation warnings # are displayed in the browser. By default, this is set to True and # Streamlit displays app exceptions and associated tracebacks, and # deprecation warnings, in the browser. # # If set to False, deprecation warnings and full exception messages # will print to the console only. Exceptions will still display in the # browser with a generic error message. For now, the exception type and # traceback show in the browser also, but they will be removed in the # future. # Default: true showErrorDetails = true # Change the visibility of items in the toolbar, options menu, # and settings dialog (top right of the app). # Allowed values: # * ""auto"" : Show the developer options if the app is accessed through # localhost or through Streamlit Community Cloud as a developer. # Hide them otherwise. # * ""developer"" : Show the developer options. # * ""viewer"" : Hide the developer options. # * ""minimal"" : Show only options set externally (e.g. through # Streamlit Community Cloud) or through st.set_page_config. # If there are no options left, hide the menu. # Default: ""auto"" toolbarMode = ""auto"" # Controls whether the default sidebar page navigation in a multipage app is # displayed. # Default: true showSidebarNavigation = true Runner [runner] # Allows you to type a variable or string by itself in a single line of # Python code to write it to the app. # Default: true magicEnabled = true # ***DEPRECATED*** # runner.installTracer has been deprecated and will be removed in a future # version. This option will be removed on or after 2024-01-20. # **************** # Install a Python tracer to allow you to stop or pause your script at # any point and introspect it. As a side-effect, this slows down your # script's execution. # Default: false installTracer = false # ***DEPRECATED*** # runner.fixMatplotlib has been deprecated and will be removed in a future # version. This option will be removed on or after 2024-01-20. # **************** # Sets the MPLBACKEND environment variable to Agg inside Streamlit to # prevent Python crashing. # Default: true fixMatplotlib = true # Handle script rerun requests immediately, rather than waiting for script # execution to reach a yield point. This makes Streamlit much more # responsive to user interaction, but it can lead to race conditions in # apps that mutate session_state data outside of explicit session_state # assignment statements. # Default: true fastReruns = true # Raise an exception after adding unserializable data to Session State. # Some execution environments may require serializing all data in Session # State, so it may be useful to detect incompatibility during development, # or when the execution environment will stop supporting it in the future. # Default: false enforceSerializableSessionState = false # Adjust how certain 'options' widgets like radio, selectbox, and # multiselect coerce Enum members when the Enum class gets # re-defined during a script re-run. For more information, check out the docs: # https://docs.streamlit.io/develop/concepts/design/custom-classes#enums # # Allowed values: # * ""off"" : Disables Enum coercion. # * ""nameOnly"" : Enum classes can be coerced if their member names match. # * ""nameAndValue"" : Enum classes can be coerced if their member names AND # member values match. # Default: ""nameOnly"" enumCoercion = ""nameOnly"" Server [server] # List of folders that should not be watched for changes. This # impacts both ""Run on Save"" and @st.cache. # Relative paths will be taken as relative to the current working directory. # Example: ['/home/user1/env', 'relative/path/to/folder'] # Default: [] folderWatchBlacklist = [] # Change the type of file watcher used by Streamlit, or turn it off # completely. # Allowed values: # * ""auto"" : Streamlit will attempt to use the watchdog module, and # falls back to polling if watchdog is not available. # * ""watchdog"" : Force Streamlit to use the watchdog module. # * ""poll"" : Force Streamlit to always use polling. # * ""none"" : Streamlit will not watch files. # Default: ""auto"" fileWatcherType = ""auto"" # Symmetric key used to produce signed cookies. If deploying on multiple # replicas, this should be set to the same value across all replicas to ensure # they all share the same secret. # Default: randomly generated secret key. cookieSecret = ""a-random-key-appears-here"" # If false, will attempt to open a browser window on start. # Default: false unless (1) we are on a Linux box where DISPLAY is unset, or # (2) we are running in the Streamlit Atom plugin. headless = false # Automatically rerun script when the file is modified on disk. # Default: false runOnSave = false # The address where the server will listen for client and browser # connections. Use this if you want to bind the server to a specific address. # If set, the server will only be accessible from this address, and not from # any aliases (like localhost). # Default: (unset) address = # The port where the server will listen for browser connections. # Don't use port 3000 which is reserved for internal development. # Default: 8501 port = 8501 # The base path for the URL where Streamlit should be served from. # Default: """" baseUrlPath = """" # Enables support for Cross-Origin Resource Sharing (CORS) protection, for # added security. # Due to conflicts between CORS and XSRF, if `server.enableXsrfProtection` is # on and `server.enableCORS` is off at the same time, we will prioritize # `server.enableXsrfProtection`. # Default: true enableCORS = true # Enables support for Cross-Site Request Forgery (XSRF) protection, for added # security. # Due to conflicts between CORS and XSRF, if `server.enableXsrfProtection` is # on and `server.enableCORS` is off at the same time, we will prioritize # `server.enableXsrfProtection`. # Default: true enableXsrfProtection = true # Max size, in megabytes, for files uploaded with the file_uploader. # Default: 200 maxUploadSize = 200 # Max size, in megabytes, of messages that can be sent via the WebSocket # connection. # Default: 200 maxMessageSize = 200 # Enables support for websocket compression. # Default: false enableWebsocketCompression = false # Enable serving files from a `static` directory in the running app's # directory. # Default: false enableStaticServing = false # Server certificate file for connecting via HTTPS. # Must be set at the same time as ""server.sslKeyFile"". # ['DO NOT USE THIS OPTION IN A PRODUCTION ENVIRONMENT. It has not gone through # security audits or performance tests. For the production environment, we # recommend performing SSL termination by the load balancer or the reverse # proxy.'] # sslCertFile = # Cryptographic key file for connecting via HTTPS. # Must be set at the same time as ""server.sslCertFile"". # ['DO NOT USE THIS OPTION IN A PRODUCTION ENVIRONMENT. It has not gone through # security audits or performance tests. For the production environment, we # recommend performing SSL termination by the load balancer or the reverse # proxy.'] # sslKeyFile = Browser [browser] # Internet address where users should point their browsers in order to # connect to the app. Can be IP address or DNS name and path. # This is used to: # - Set the correct URL for CORS and XSRF protection purposes. # - Show the URL on the terminal # - Open the browser # Default: ""localhost"" serverAddress = ""localhost"" # Whether to send usage statistics to Streamlit. # Default: true gatherUsageStats = true # Port where users should point their browsers in order to connect to the # app. # This is used to: # - Set the correct URL for XSRF protection purposes. # - Show the URL on the terminal (part of `streamlit run`). # - Open the browser automatically (part of `streamlit run`). # This option is for advanced use cases. To change the port of your app, use # `server.Port` instead. Don't use port 3000 which is reserved for internal # development. # Default: whatever value is set in server.port. serverPort = 8501 Mapbox [mapbox] # Configure Streamlit to use a custom Mapbox # token for elements like st.pydeck_chart and st.map. # To get a token for yourself, create an account at # https://mapbox.com. It's free (for moderate usage levels)! # Default: """" token = """" Deprecation [deprecation] # Set to false to disable the deprecation warning for using the global pyplot # instance. # Default: true showPyplotGlobalUse = true Theme [theme] # The preset Streamlit theme that your custom theme inherits from. # One of ""light"" or ""dark"". # base = # Primary accent color for interactive elements. # primaryColor = # Background color for the main content area. # backgroundColor = # Background color used for the sidebar and most interactive widgets. # secondaryBackgroundColor = # Color used for almost all text. # textColor = # Font family for all text in the app, except code blocks. One of ""sans serif"", # ""serif"", or ""monospace"". # font = Previous: ConfigurationNext: st.set_page_configforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy" https://docs.streamlit.io/library/advanced-features/caching#behavior-1,"DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsremoveCOREArchitecture & executionremoveRunning your appStreamlit's architectureThe app chromeCachingSession StateFormsFragmentsWidget behaviorMultipage appsaddApp designaddADDITIONALConnections and secretsaddCustom componentsaddConfiguration and themingaddApp testingaddAPI referenceaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Develop/Concepts/Architecture & execution/Cachingpush_pinNoteDocumentation for the deprecated @st.cache decorator can be found in Optimize performance with st.cache. Caching overview Streamlit runs your script from top to bottom at every user interaction or code change. This execution model makes development super easy. But it comes with two major challenges: Long-running functions run again and again, which slows down your app. Objects get recreated again and again, which makes it hard to persist them across reruns or sessions. But don't worry! Streamlit lets you tackle both issues with its built-in caching mechanism. Caching stores the results of slow function calls, so they only need to run once. This makes your app much faster and helps with persisting objects across reruns. Table of contentsexpand_more Minimal example Basic usage Advanced usage Migrating from st.cache Minimal example To cache a function in Streamlit, you must decorate it with one of two decorators (st.cache_data or st.cache_resource): @st.cache_data def long_running_function(param1, param2): return … In this example, decorating long_running_function with @st.cache_data tells Streamlit that whenever the function is called, it checks two things: The values of the input parameters (in this case, param1 and param2). The code inside the function. If this is the first time Streamlit sees these parameter values and function code, it runs the function and stores the return value in a cache. The next time the function is called with the same parameters and code (e.g., when a user interacts with the app), Streamlit will skip executing the function altogether and return the cached value instead. During development, the cache updates automatically as the function code changes, ensuring that the latest changes are reflected in the cache. As mentioned, there are two caching decorators: st.cache_data is the recommended way to cache computations that return data: loading a DataFrame from CSV, transforming a NumPy array, querying an API, or any other function that returns a serializable data object (str, int, float, DataFrame, array, list, …). It creates a new copy of the data at each function call, making it safe against mutations and race conditions. The behavior of st.cache_data is what you want in most cases – so if you're unsure, start with st.cache_data and see if it works! st.cache_resource is the recommended way to cache global resources like ML models or database connections – unserializable objects that you don't want to load multiple times. Using it, you can share these resources across all reruns and sessions of an app without copying or duplication. Note that any mutations to the cached return value directly mutate the object in the cache (more details below). Streamlit's two caching decorators and their use cases. Basic usage st.cache_data st.cache_data is your go-to command for all functions that return data – whether DataFrames, NumPy arrays, str, int, float, or other serializable types. It's the right command for almost all use cases! Usage Let's look at an example of using st.cache_data. Suppose your app loads the Uber ride-sharing dataset – a CSV file of 50 MB – from the internet into a DataFrame: def load_data(url): df = pd.read_csv(url) # 👈 Download the data return df df = load_data(""https://github.com/plotly/datasets/raw/master/uber-rides-data1.csv"") st.dataframe(df) st.button(""Rerun"") Running the load_data function takes 2 to 30 seconds, depending on your internet connection. (Tip: if you are on a slow connection, use this 5 MB dataset instead). Without caching, the download is rerun each time the app is loaded or with user interaction. Try it yourself by clicking the button we added! Not a great experience… 😕 Now let's add the @st.cache_data decorator on load_data: @st.cache_data # 👈 Add the caching decorator def load_data(url): df = pd.read_csv(url) return df df = load_data(""https://github.com/plotly/datasets/raw/master/uber-rides-data1.csv"") st.dataframe(df) st.button(""Rerun"") Run the app again. You'll notice that the slow download only happens on the first run. Every subsequent rerun should be almost instant! 💨 Behavior How does this work? Let's go through the behavior of st.cache_data step by step: On the first run, Streamlit recognizes that it has never called the load_data function with the specified parameter value (the URL of the CSV file) So it runs the function and downloads the data. Now our caching mechanism becomes active: the returned DataFrame is serialized (converted to bytes) via pickle and stored in the cache (together with the value of the url parameter). On the next run, Streamlit checks the cache for an entry of load_data with the specific url. There is one! So it retrieves the cached object, deserializes it to a DataFrame, and returns it instead of re-running the function and downloading the data again. This process of serializing and deserializing the cached object creates a copy of our original DataFrame. While this copying behavior may seem unnecessary, it's what we want when caching data objects since it effectively prevents mutation and concurrency issues. Read the section “Mutation and concurrency issues"" below to understand this in more detail. priority_highWarningst.cache_data implicitly uses the pickle module, which is known to be insecure. Anything your cached function returns is pickled and stored, then unpickled on retrieval. Ensure your cached functions return trusted values because it is possible to construct malicious pickle data that will execute arbitrary code during unpickling. Never load data that could have come from an untrusted source in an unsafe mode or that could have been tampered with. Only load data you trust. Examples DataFrame transformations In the example above, we already showed how to cache loading a DataFrame. It can also be useful to cache DataFrame transformations such as df.filter, df.apply, or df.sort_values. Especially with large DataFrames, these operations can be slow. @st.cache_data def transform(df): df = df.filter(items=['one', 'three']) df = df.apply(np.sum, axis=0) return df Array computations Similarly, it can make sense to cache computations on NumPy arrays: @st.cache_data def add(arr1, arr2): return arr1 + arr2 Database queries You usually make SQL queries to load data into your app when working with databases. Repeatedly running these queries can be slow, cost money, and degrade the performance of your database. We strongly recommend caching any database queries in your app. See also our guides on connecting Streamlit to different databases for in-depth examples. connection = database.connect() @st.cache_data def query(): return pd.read_sql_query(""SELECT * from table"", connection) starTipYou should set a ttl (time to live) to get new results from your database. If you set st.cache_data(ttl=3600), Streamlit invalidates any cached values after 1 hour (3600 seconds) and runs the cached function again. See details in Controlling cache size and duration. API calls Similarly, it makes sense to cache API calls. Doing so also avoids rate limits. @st.cache_data def api_call(): response = requests.get('https://jsonplaceholder.typicode.com/posts/1') return response.json() Running ML models (inference) Running complex machine learning models can use significant time and memory. To avoid rerunning the same computations over and over, use caching. @st.cache_data def run_model(inputs): return model(inputs) st.cache_resource st.cache_resource is the right command to cache “resources"" that should be available globally across all users, sessions, and reruns. It has more limited use cases than st.cache_data, especially for caching database connections and ML models. Usage As an example for st.cache_resource, let's look at a typical machine learning app. As a first step, we need to load an ML model. We do this with Hugging Face's transformers library: from transformers import pipeline model = pipeline(""sentiment-analysis"") # 👈 Load the model If we put this code into a Streamlit app directly, the app will load the model at each rerun or user interaction. Repeatedly loading the model poses two problems: Loading the model takes time and slows down the app. Each session loads the model from scratch, which takes up a huge amount of memory. Instead, it would make much more sense to load the model once and use that same object across all users and sessions. That's exactly the use case for st.cache_resource! Let's add it to our app and process some text the user entered: from transformers import pipeline @st.cache_resource # 👈 Add the caching decorator def load_model(): return pipeline(""sentiment-analysis"") model = load_model() query = st.text_input(""Your query"", value=""I love Streamlit! 🎈"") if query: result = model(query)[0] # 👈 Classify the query text st.write(result) If you run this app, you'll see that the app calls load_model only once – right when the app starts. Subsequent runs will reuse that same model stored in the cache, saving time and memory! Behavior Using st.cache_resource is very similar to using st.cache_data. But there are a few important differences in behavior: st.cache_resource does not create a copy of the cached return value but instead stores the object itself in the cache. All mutations on the function's return value directly affect the object in the cache, so you must ensure that mutations from multiple sessions do not cause problems. In short, the return value must be thread-safe. priority_highWarningUsing st.cache_resource on objects that are not thread-safe might lead to crashes or corrupted data. Learn more below under Mutation and concurrency issues. Not creating a copy means there's just one global instance of the cached return object, which saves memory, e.g. when using a large ML model. In computer science terms, we create a singleton. Return values of functions do not need to be serializable. This behavior is great for types not serializable by nature, e.g., database connections, file handles, or threads. Caching these objects with st.cache_data is not possible. Examples Database connections st.cache_resource is useful for connecting to databases. Usually, you're creating a connection object that you want to reuse globally for every query. Creating a new connection object at each run would be inefficient and might lead to connection errors. That's exactly what st.cache_resource can do, e.g., for a Postgres database: @st.cache_resource def init_connection(): host = ""hh-pgsql-public.ebi.ac.uk"" database = ""pfmegrnargs"" user = ""reader"" password = ""NWDMCE5xdipIjRrp"" return psycopg2.connect(host=host, database=database, user=user, password=password) conn = init_connection() Of course, you can do the same for any other database. Have a look at our guides on how to connect Streamlit to databases for in-depth examples. Loading ML models Your app should always cache ML models, so they are not loaded into memory again for every new session. See the example above for how this works with 🤗 Hugging Face models. You can do the same thing for PyTorch, TensorFlow, etc. Here's an example for PyTorch: @st.cache_resource def load_model(): model = torchvision.models.resnet50(weights=ResNet50_Weights.DEFAULT) model.eval() return model model = load_model() Deciding which caching decorator to use The sections above showed many common examples for each caching decorator. But there are edge cases for which it's less trivial to decide which caching decorator to use. Eventually, it all comes down to the difference between “data"" and “resource"": Data are serializable objects (objects that can be converted to bytes via pickle) that you could easily save to disk. Imagine all the types you would usually store in a database or on a file system – basic types like str, int, and float, but also arrays, DataFrames, images, or combinations of these types (lists, tuples, dicts, and so on). Resources are unserializable objects that you usually would not save to disk or a database. They are often more complex, non-permanent objects like database connections, ML models, file handles, threads, etc. From the types listed above, it should be obvious that most objects in Python are “data."" That's also why st.cache_data is the correct command for almost all use cases. st.cache_resource is a more exotic command that you should only use in specific situations. Or if you're lazy and don't want to think too much, look up your use case or return type in the table below 😉: Use caseTypical return typesCaching decoratorReading a CSV file with pd.read_csvpandas.DataFramest.cache_dataReading a text filestr, list of strst.cache_dataTransforming pandas dataframespandas.DataFrame, pandas.Seriesst.cache_dataComputing with numpy arraysnumpy.ndarrayst.cache_dataSimple computations with basic typesstr, int, float, …st.cache_dataQuerying a databasepandas.DataFramest.cache_dataQuerying an APIpandas.DataFrame, str, dictst.cache_dataRunning an ML model (inference)pandas.DataFrame, str, int, dict, listst.cache_dataCreating or processing imagesPIL.Image.Image, numpy.ndarrayst.cache_dataCreating chartsmatplotlib.figure.Figure, plotly.graph_objects.Figure, altair.Chartst.cache_data (but some libraries require st.cache_resource, since the chart object is not serializable – make sure not to mutate the chart after creation!)Loading ML modelstransformers.Pipeline, torch.nn.Module, tensorflow.keras.Modelst.cache_resourceInitializing database connectionspyodbc.Connection, sqlalchemy.engine.base.Engine, psycopg2.connection, mysql.connector.MySQLConnection, sqlite3.Connectionst.cache_resourceOpening persistent file handles_io.TextIOWrapperst.cache_resourceOpening persistent threadsthreading.threadst.cache_resource Advanced usage Controlling cache size and duration If your app runs for a long time and constantly caches functions, you might run into two problems: The app runs out of memory because the cache is too large. Objects in the cache become stale, e.g. because you cached old data from a database. You can combat these problems with the ttl and max_entries parameters, which are available for both caching decorators. The ttl (time-to-live) parameter ttl sets a time to live on a cached function. If that time is up and you call the function again, the app will discard any old, cached values, and the function will be rerun. The newly computed value will then be stored in the cache. This behavior is useful for preventing stale data (problem 2) and the cache from growing too large (problem 1). Especially when pulling data from a database or API, you should always set a ttl so you are not using old data. Here's an example: @st.cache_data(ttl=3600) # 👈 Cache data for 1 hour (=3600 seconds) def get_api_data(): data = api.get(...) return data starTipYou can also set ttl values using timedelta, e.g., ttl=datetime.timedelta(hours=1). The max_entries parameter max_entries sets the maximum number of entries in the cache. An upper bound on the number of cache entries is useful for limiting memory (problem 1), especially when caching large objects. The oldest entry will be removed when a new entry is added to a full cache. Here's an example: @st.cache_data(max_entries=1000) # 👈 Maximum 1000 entries in the cache def get_large_array(seed): np.random.seed(seed) arr = np.random.rand(100000) return arr Customizing the spinner By default, Streamlit shows a small loading spinner in the app when a cached function is running. You can modify it easily with the show_spinner parameter, which is available for both caching decorators: @st.cache_data(show_spinner=False) # 👈 Disable the spinner def get_api_data(): data = api.get(...) return data @st.cache_data(show_spinner=""Fetching data from API..."") # 👈 Use custom text for spinner def get_api_data(): data = api.get(...) return data Excluding input parameters In a cached function, all input parameters must be hashable. Let's quickly explain why and what it means. When the function is called, Streamlit looks at its parameter values to determine if it was cached before. Therefore, it needs a reliable way to compare the parameter values across function calls. Trivial for a string or int – but complex for arbitrary objects! Streamlit uses hashing to solve that. It converts the parameter to a stable key and stores that key. At the next function call, it hashes the parameter again and compares it with the stored hash key. Unfortunately, not all parameters are hashable! E.g., you might pass an unhashable database connection or ML model to your cached function. In this case, you can exclude input parameters from caching. Simply prepend the parameter name with an underscore (e.g., _param1), and it will not be used for caching. Even if it changes, Streamlit will return a cached result if all the other parameters match up. Here's an example: @st.cache_data def fetch_data(_db_connection, num_rows): # 👈 Don't hash _db_connection data = _db_connection.fetch(num_rows) return data connection = init_connection() fetch_data(connection, 10) But what if you want to cache a function that takes an unhashable parameter? For example, you might want to cache a function that takes an ML model as input and returns the layer names of that model. Since the model is the only input parameter, you cannot exclude it from caching. In this case you can use the hash_funcs parameter to specify a custom hashing function for the model. The hash_funcs parameter As described above, Streamlit's caching decorators hash the input parameters and cached function's signature to determine whether the function has been run before and has a return value stored (""cache hit"") or needs to be run (""cache miss""). Input parameters that are not hashable by Streamlit's hashing implementation can be ignored by prepending an underscore to their name. But there two rare cases where this is undesirable. i.e. where you want to hash the parameter that Streamlit is unable to hash: When Streamlit's hashing mechanism fails to hash a parameter, resulting in a UnhashableParamError being raised. When you want to override Streamlit's default hashing mechanism for a parameter. Let's discuss each of these cases in turn with examples. Example 1: Hashing a custom class Streamlit does not know how to hash custom classes. If you pass a custom class to a cached function, Streamlit will raise a UnhashableParamError. For example, let's define a custom class MyCustomClass that accepts an initial integer score. Let's also define a cached function multiply_score that multiplies the score by a multiplier: import streamlit as st class MyCustomClass: def __init__(self, initial_score: int): self.my_score = initial_score @st.cache_data def multiply_score(obj: MyCustomClass, multiplier: int) -> int: return obj.my_score * multiplier initial_score = st.number_input(""Enter initial score"", value=15) score = MyCustomClass(initial_score) multiplier = 2 st.write(multiply_score(score, multiplier)) If you run this app, you'll see that Streamlit raises a UnhashableParamError since it does not know how to hash MyCustomClass: UnhashableParamError: Cannot hash argument 'obj' (of type __main__.MyCustomClass) in 'multiply_score'. To fix this, we can use the hash_funcs parameter to tell Streamlit how to hash MyCustomClass. We do this by passing a dictionary to hash_funcs that maps the name of the parameter to a hash function. The choice of hash function is up to the developer. In this case, let's define a custom hash function hash_func that takes the custom class as input and returns the score. We want the score to be the unique identifier of the object, so we can use it to deterministically hash the object: import streamlit as st class MyCustomClass: def __init__(self, initial_score: int): self.my_score = initial_score def hash_func(obj: MyCustomClass) -> int: return obj.my_score # or any other value that uniquely identifies the object @st.cache_data(hash_funcs={MyCustomClass: hash_func}) def multiply_score(obj: MyCustomClass, multiplier: int) -> int: return obj.my_score * multiplier initial_score = st.number_input(""Enter initial score"", value=15) score = MyCustomClass(initial_score) multiplier = 2 st.write(multiply_score(score, multiplier)) Now if you run the app, you'll see that Streamlit no longer raises a UnhashableParamError and the app runs as expected. Let's now consider the case where multiply_score is an attribute of MyCustomClass and we want to hash the entire object: import streamlit as st class MyCustomClass: def __init__(self, initial_score: int): self.my_score = initial_score @st.cache_data def multiply_score(self, multiplier: int) -> int: return self.my_score * multiplier initial_score = st.number_input(""Enter initial score"", value=15) score = MyCustomClass(initial_score) multiplier = 2 st.write(score.multiply_score(multiplier)) If you run this app, you'll see that Streamlit raises a UnhashableParamError since it cannot hash the argument 'self' (of type __main__.MyCustomClass) in 'multiply_score'. A simple fix here could be to use Python's hash() function to hash the object: import streamlit as st class MyCustomClass: def __init__(self, initial_score: int): self.my_score = initial_score @st.cache_data(hash_funcs={""__main__.MyCustomClass"": lambda x: hash(x.my_score)}) def multiply_score(self, multiplier: int) -> int: return self.my_score * multiplier initial_score = st.number_input(""Enter initial score"", value=15) score = MyCustomClass(initial_score) multiplier = 2 st.write(score.multiply_score(multiplier)) Above, the hash function is defined as lambda x: hash(x.my_score). This creates a hash based on the my_score attribute of the MyCustomClass instance. As long as my_score remains the same, the hash remains the same. Thus, the result of multiply_score can be retrieved from the cache without recomputation. As an astute Pythonista, you may have been tempted to use Python's id() function to hash the object like so: import streamlit as st class MyCustomClass: def __init__(self, initial_score: int): self.my_score = initial_score @st.cache_data(hash_funcs={""__main__.MyCustomClass"": id}) def multiply_score(self, multiplier: int) -> int: return self.my_score * multiplier initial_score = st.number_input(""Enter initial score"", value=15) score = MyCustomClass(initial_score) multiplier = 2 st.write(score.multiply_score(multiplier)) If you run the app, you'll notice that Streamlit recomputes multiply_score each time even if my_score hasn't changed! Puzzled? In Python, id() returns the identity of an object, which is unique and constant for the object during its lifetime. This means that even if the my_score value is the same between two instances of MyCustomClass, id() will return different values for these two instances, leading to different hash values. As a result, Streamlit considers these two different instances as needing separate cached values, thus it recomputes the multiply_score each time even if my_score hasn't changed. This is why we discourage using it as hash func, and instead encourage functions that return deterministic, true hash values. That said, if you know what you're doing, you can use id() as a hash function. Just be aware of the consequences. For example, id is often the correct hash func when you're passing the result of an @st.cache_resource function as the input param to another cached function. There's a whole class of object types that aren’t otherwise hashable. Example 2: Hashing a Pydantic model Let's consider another example where we want to hash a Pydantic model: import streamlit as st from pydantic import BaseModel class Person(BaseModel): name: str @st.cache_data def identity(person: Person): return person person = identity(Person(name=""Lee"")) st.write(f""The person is {person.name}"") Above, we define a custom class Person using Pydantic's BaseModel with a single attribute name. We also define an identity function which accepts an instance of Person as an arg and returns it without modification. This function is intended to cache the result, therefore, if called multiple times with the same Person instance, it won't recompute but return the cached instance. If you run the app, however, you'll run into a UnhashableParamError: Cannot hash argument 'person' (of type __main__.Person) in 'identity'. error. This is because Streamlit does not know how to hash the Person class. To fix this, we can use the hash_funcs kwarg to tell Streamlit how to hash Person. In the version below, we define a custom hash function hash_func that takes the Person instance as input and returns the name attribute. We want the name to be the unique identifier of the object, so we can use it to deterministically hash the object: import streamlit as st from pydantic import BaseModel class Person(BaseModel): name: str @st.cache_data(hash_funcs={Person: lambda p: p.name}) def identity(person: Person): return person person = identity(Person(name=""Lee"")) st.write(f""The person is {person.name}"") Example 3: Hashing a ML model There may be cases where you want to pass your favorite machine learning model to a cached function. For example, let's say you want to pass a TensorFlow model to a cached function, based on what model the user selects in the app. You might try something like this: import streamlit as st import tensorflow as tf @st.cache_resource def load_base_model(option): if option == 1: return tf.keras.applications.ResNet50(include_top=False, weights=""imagenet"") else: return tf.keras.applications.MobileNetV2(include_top=False, weights=""imagenet"") @st.cache_resource def load_layers(base_model): return [layer.name for layer in base_model.layers] option = st.radio(""Model 1 or 2"", [1, 2]) base_model = load_base_model(option) layers = load_layers(base_model) st.write(layers) In the above app, the user can select one of two models. Based on the selection, the app loads the corresponding model and passes it to load_layers. This function then returns the names of the layers in the model. If you run the app, you'll see that Streamlit raises a UnhashableParamError since it cannot hash the argument 'base_model' (of type keras.engine.functional.Functional) in 'load_layers'. If you disable hashing for base_model by prepending an underscore to its name, you'll observe that regardless of which base model is chosen, the layers displayed are same. This subtle bug is due to the fact that the load_layers function is not re-run when the base model changes. This is because Streamlit does not hash the base_model argument, so it does not know that the function needs to be re-run when the base model changes. To fix this, we can use the hash_funcs kwarg to tell Streamlit how to hash the base_model argument. In the version below, we define a custom hash function hash_func: Functional: lambda x: x.name. Our choice of hash func is informed by our knowledge that the name attribute of a Functional object or model uniquely identifies it. As long as the name attribute remains the same, the hash remains the same. Thus, the result of load_layers can be retrieved from the cache without recomputation. import streamlit as st import tensorflow as tf from keras.engine.functional import Functional @st.cache_resource def load_base_model(option): if option == 1: return tf.keras.applications.ResNet50(include_top=False, weights=""imagenet"") else: return tf.keras.applications.MobileNetV2(include_top=False, weights=""imagenet"") @st.cache_resource(hash_funcs={Functional: lambda x: x.name}) def load_layers(base_model): return [layer.name for layer in base_model.layers] option = st.radio(""Model 1 or 2"", [1, 2]) base_model = load_base_model(option) layers = load_layers(base_model) st.write(layers) In the above case, we could also have used hash_funcs={Functional: id} as the hash function. This is because id is often the correct hash func when you're passing the result of an @st.cache_resource function as the input param to another cached function. Example 4: Overriding Streamlit's default hashing mechanism Let's consider another example where we want to override Streamlit's default hashing mechanism for a pytz-localized datetime object: from datetime import datetime import pytz import streamlit as st tz = pytz.timezone(""Europe/Berlin"") @st.cache_data def load_data(dt): return dt now = datetime.now() st.text(load_data(dt=now)) now_tz = tz.localize(datetime.now()) st.text(load_data(dt=now_tz)) It may be surprising to see that although now and now_tz are of the same type, Streamlit does not how to hash now_tz and raises a UnhashableParamError. In this case, we can override Streamlit's default hashing mechanism for datetime objects by passing a custom hash function to the hash_funcs kwarg: from datetime import datetime import pytz import streamlit as st tz = pytz.timezone(""Europe/Berlin"") @st.cache_data(hash_funcs={datetime: lambda x: x.strftime(""%a %d %b %Y, %I:%M%p"")}) def load_data(dt): return dt now = datetime.now() st.text(load_data(dt=now)) now_tz = tz.localize(datetime.now()) st.text(load_data(dt=now_tz)) Let's now consider a case where we want to override Streamlit's default hashing mechanism for NumPy arrays. While Streamlit natively hashes Pandas and NumPy objects, there may be cases where you want to override Streamlit's default hashing mechanism for these objects. For example, let's say we create a cache-decorated show_data function that accepts a NumPy array and returns it without modification. In the bellow app, data = df[""str""].unique() (which is a NumPy array) is passed to the show_data function. import time import numpy as np import pandas as pd import streamlit as st @st.cache_data def get_data(): df = pd.DataFrame({""num"": [112, 112, 2, 3], ""str"": [""be"", ""a"", ""be"", ""c""]}) return df @st.cache_data def show_data(data): time.sleep(2) # This makes the function take 2s to run return data df = get_data() data = df[""str""].unique() st.dataframe(show_data(data)) st.button(""Re-run"") Since data is always the same, we expect the show_data function to return the cached value. However, if you run the app, and click the Re-run button, you'll notice that the show_data function is re-run each time. We can assume this behavior is a consequence of Streamlit's default hashing mechanism for NumPy arrays. To work around this, let's define a custom hash function hash_func that takes a NumPy array as input and returns a string representation of the array: import time import numpy as np import pandas as pd import streamlit as st @st.cache_data def get_data(): df = pd.DataFrame({""num"": [112, 112, 2, 3], ""str"": [""be"", ""a"", ""be"", ""c""]}) return df @st.cache_data(hash_funcs={np.ndarray: str}) def show_data(data): time.sleep(2) # This makes the function take 2s to run return data df = get_data() data = df[""str""].unique() st.dataframe(show_data(data)) st.button(""Re-run"") Now if you run the app, and click the Re-run button, you'll notice that the show_data function is no longer re-run each time. It's important to note here that our choice of hash function was very naive and not necessarily the best choice. For example, if the NumPy array is large, converting it to a string representation may be expensive. In such cases, it is up to you as the developer to define what a good hash function is for your use case. Static elements Since version 1.16.0, cached functions can contain Streamlit commands! For example, you can do this: @st.cache_data def get_api_data(): data = api.get(...) st.success(""Fetched data from API!"") # 👈 Show a success message return data As we know, Streamlit only runs this function if it hasn't been cached before. On this first run, the st.success message will appear in the app. But what happens on subsequent runs? It still shows up! Streamlit realizes that there is an st. command inside the cached function, saves it during the first run, and replays it on subsequent runs. Replaying static elements works for both caching decorators. You can also use this functionality to cache entire parts of your UI: @st.cache_data def show_data(): st.header(""Data analysis"") data = api.get(...) st.success(""Fetched data from API!"") st.write(""Here is a plot of the data:"") st.line_chart(data) st.write(""And here is the raw data:"") st.dataframe(data) Input widgets You can also use interactive input widgets like st.slider or st.text_input in cached functions. Widget replay is an experimental feature at the moment. To enable it, you need to set the experimental_allow_widgets parameter: @st.cache_data(experimental_allow_widgets=True) # 👈 Set the parameter def get_data(): num_rows = st.slider(""Number of rows to get"") # 👈 Add a slider data = api.get(..., num_rows) return data Streamlit treats the slider like an additional input parameter to the cached function. If you change the slider position, Streamlit will see if it has already cached the function for this slider value. If yes, it will return the cached value. If not, it will rerun the function using the new slider value. Using widgets in cached functions is extremely powerful because it lets you cache entire parts of your app. But it can be dangerous! Since Streamlit treats the widget value as an additional input parameter, it can easily lead to excessive memory usage. Imagine your cached function has five sliders and returns a 100 MB DataFrame. Then we'll add 100 MB to the cache for every permutation of these five slider values – even if the sliders do not influence the returned data! These additions can make your cache explode very quickly. Please be aware of this limitation if you use widgets in cached functions. We recommend using this feature only for isolated parts of your UI where the widgets directly influence the cached return value. priority_highWarningSupport for widgets in cached functions is experimental. We may change or remove it anytime without warning. Please use it with care! push_pinNoteTwo widgets are currently not supported in cached functions: st.file_uploader and st.camera_input. We may support them in the future. Feel free to open a GitHub issue if you need them! Dealing with large data As we explained, you should cache data objects with st.cache_data. But this can be slow for extremely large data, e.g., DataFrames or arrays with >100 million rows. That's because of the copying behavior of st.cache_data: on the first run, it serializes the return value to bytes and deserializes it on subsequent runs. Both operations take time. If you're dealing with extremely large data, it can make sense to use st.cache_resource instead. It does not create a copy of the return value via serialization/deserialization and is almost instant. But watch out: any mutation to the function's return value (such as dropping a column from a DataFrame or setting a value in an array) directly manipulates the object in the cache. You must ensure this doesn't corrupt your data or lead to crashes. See the section on Mutation and concurrency issues below. When benchmarking st.cache_data on pandas DataFrames with four columns, we found that it becomes slow when going beyond 100 million rows. The table shows runtimes for both caching decorators at different numbers of rows (all with four columns): 10M rows50M rows100M rows200M rowsst.cache_dataFirst run*0.4 s3 s14 s28 sSubsequent runs0.2 s1 s2 s7 sst.cache_resourceFirst run*0.01 s0.1 s0.2 s1 sSubsequent runs0 s0 s0 s0 s *For the first run, the table only shows the overhead time of using the caching decorator. It does not include the runtime of the cached function itself. Mutation and concurrency issues In the sections above, we talked a lot about issues when mutating return objects of cached functions. This topic is complicated! But it's central to understanding the behavior differences between st.cache_data and st.cache_resource. So let's dive in a bit deeper. First, we should clearly define what we mean by mutations and concurrency: By mutations, we mean any changes made to a cached function's return value after that function has been called. I.e. something like this: @st.cache_data def create_list(): l = [1, 2, 3] l = create_list() # 👈 Call the function l[0] = 2 # 👈 Mutate its return value By concurrency, we mean that multiple sessions can cause these mutations at the same time. Streamlit is a web framework that needs to handle many users and sessions connecting to an app. If two people view an app at the same time, they will both cause the Python script to rerun, which may manipulate cached return objects at the same time – concurrently. Mutating cached return objects can be dangerous. It can lead to exceptions in your app and even corrupt your data (which can be worse than a crashed app!). Below, we'll first explain the copying behavior of st.cache_data and show how it can avoid mutation issues. Then, we'll show how concurrent mutations can lead to data corruption and how to prevent it. Copying behavior st.cache_data creates a copy of the cached return value each time the function is called. This avoids most mutations and concurrency issues. To understand it in detail, let's go back to the Uber ridesharing example from the section on st.cache_data above. We are making two modifications to it: We are using st.cache_resource instead of st.cache_data. st.cache_resource does not create a copy of the cached object, so we can see what happens without the copying behavior. After loading the data, we manipulate the returned DataFrame (in place!) by dropping the column ""Lat"". Here's the code: @st.cache_resource # 👈 Turn off copying behavior def load_data(url): df = pd.read_csv(url) return df df = load_data(""https://raw.githubusercontent.com/plotly/datasets/master/uber-rides-data1.csv"") st.dataframe(df) df.drop(columns=['Lat'], inplace=True) # 👈 Mutate the dataframe inplace st.button(""Rerun"") Let's run it and see what happens! The first run should work fine. But in the second run, you see an exception: KeyError: ""['Lat'] not found in axis"". Why is that happening? Let's go step by step: On the first run, Streamlit runs load_data and stores the resulting DataFrame in the cache. Since we're using st.cache_resource, it does not create a copy but stores the original DataFrame. Then we drop the column ""Lat"" from the DataFrame. Note that this is dropping the column from the original DataFrame stored in the cache. We are manipulating it! On the second run, Streamlit returns that exact same manipulated DataFrame from the cache. It does not have the column ""Lat"" anymore! So our call to df.drop results in an exception. Pandas cannot drop a column that doesn't exist. The copying behavior of st.cache_data prevents this kind of mutation error. Mutations can only affect a specific copy and not the underlying object in the cache. The next rerun will get its own, unmutated copy of the DataFrame. You can try it yourself, just replace st.cache_resource with st.cache_data above, and you'll see that everything works. Because of this copying behavior, st.cache_data is the recommended way to cache data transforms and computations – anything that returns a serializable object. Concurrency issues Now let's look at what can happen when multiple users concurrently mutate an object in the cache. Let's say you have a function that returns a list. Again, we are using st.cache_resource to cache it so that we are not creating a copy: @st.cache_resource def create_list(): l = [1, 2, 3] return l l = create_list() first_list_value = l[0] l[0] = first_list_value + 1 st.write(""l[0] is:"", l[0]) Let's say user A runs the app. They will see the following output: l[0] is: 2 Let's say another user, B, visits the app right after. In contrast to user A, they will see the following output: l[0] is: 3 Now, user A reruns the app immediately after user B. They will see the following output: l[0] is: 4 What is happening here? Why are all outputs different? When user A visits the app, create_list() is called, and the list [1, 2, 3] is stored in the cache. This list is then returned to user A. The first value of the list, 1, is assigned to first_list_value , and l[0] is changed to 2. When user B visits the app, create_list() returns the mutated list from the cache: [2, 2, 3]. The first value of the list, 2, is assigned to first_list_value and l[0] is changed to 3. When user A reruns the app, create_list() returns the mutated list again: [3, 2, 3]. The first value of the list, 3, is assigned to first_list_value, and l[0] is changed to 4. If you think about it, this makes sense. Users A and B use the same list object (the one stored in the cache). And since the list object is mutated, user A's change to the list object is also reflected in user B's app. This is why you must be careful about mutating objects cached with st.cache_resource, especially when multiple users access the app concurrently. If we had used st.cache_data instead of st.cache_resource, the app would have copied the list object for each user, and the above example would have worked as expected – users A and B would have both seen: l[0] is: 2 push_pinNoteThis toy example might seem benign. But data corruption can be extremely dangerous! Imagine we had worked with the financial records of a large bank here. You surely don't want to wake up with less money on your account just because someone used the wrong caching decorator 😉 Migrating from st.cache We introduced the caching commands described above in Streamlit 1.18.0. Before that, we had one catch-all command st.cache. Using it was often confusing, resulted in weird exceptions, and was slow. That's why we replaced st.cache with the new commands in 1.18.0 (read more in this blog post). The new commands provide a more intuitive and efficient way to cache your data and resources and are intended to replace st.cache in all new development. If your app is still using st.cache, don't despair! Here are a few notes on migrating: Streamlit will show a deprecation warning if your app uses st.cache. We will not remove st.cache soon, so you don't need to worry about your 2-year-old app breaking. But we encourage you to try the new commands going forward – they will be way less annoying! Switching code to the new commands should be easy in most cases. To decide whether to use st.cache_data or st.cache_resource, read Deciding which caching decorator to use. Streamlit will also recognize common use cases and show hints right in the deprecation warnings. Most parameters from st.cache are also present in the new commands, with a few exceptions: allow_output_mutation does not exist anymore. You can safely delete it. Just make sure you use the right caching command for your use case. suppress_st_warning does not exist anymore. You can safely delete it. Cached functions can now contain Streamlit commands and will replay them. If you want to use widgets inside cached functions, set experimental_allow_widgets=True. See Input widgets for an example. If you have any questions or issues during the migration process, please contact us on the forum, and we will be happy to assist you. 🎈Previous: The app chromeNext: Optimize performance with st.cacheforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy" https://docs.streamlit.io/deploy/streamlit-community-cloud/manage-your-account/manage-your-github-connection#connecting-github-to-an-existing-primary-identity,"DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudremoveGet startedaddDeploy your appaddManage your appaddShare your appaddManage your accountremoveSign in & sign outWorkspace settingsManage your GitHub connectionUpdate your emailDelete your accountTroubleshootingStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Deploy/Streamlit Community Cloud/Manage your account/Manage your GitHub connectionManage your GitHub connection If you did not connect GitHub when you created your account or need to correct your GitHub authorization, this page is for you! If you just need to add an organization to your account, skip ahead to Authorizing with an organization. If you are not fully logged in and authorized to both a primary identity (Google or email) and source control (GitHub), there will be a warning symbol in the upper-right corner of your workspace. This can mean one of three things: You are not signed in to a primary identity (Google or email). See Connect Google to your account. You are not signed in to source control (GitHub.) See Connecting GitHub to an existing primary identity. Your source control has incomplete permissions. Access your workspace settings see Authorize Streamlit to access private repositories. Connecting GitHub to an existing primary identity If you created your account without connecting GitHub or if you disconnected GitHub from your account, you can reconnect. Click ""Settings"" in the upper-right corner of your workspace. If you do not have GitHub connected, a warning is displayed saying, ""You are not signed in with a source control account"". If instead you see ""Streamlit does not have access to private repos on this GitHub account"" skip to step 5. 3. Click ""Sign in with GitHub"". Click ""Authorize streamlit"". Authorize Streamlit to access private repositories After completing the first authorization, your workspace settings will still have a warning, ""Streamlit does not have access to private repos on this GitHub account"". Click ""Allow access"". Click ""Authorize streamlit"". GitHub is now connected to your account! 🥳 Authorizing with an organization If you are in an organization, you can grant or request access to that organization when you connect your GitHub account. Read more about Organization access. If your GitHub account is already connected, you can remove permissions in your GitHub settings and force Streamlit to reprompt for GitHub authorization the next time you sign into Streamlit Community Cloud. Revoke and reauthorize From your workspace, click on your workspace name in the upper-right corner. Click ""Sign out"" to sign out of Streamlit Community Cloud. Go to your GitHub application settings at github.com/settings/applications. Click on the three dots to open the overflow menu for ""Streamlit"" and click ""Revoke"". Click ""I understand, revoke access"". Return to share.streamlit.io and sign in. You will be prompted to authorize GitHub as explained in Connect GitHub. Granting previously denied access If an organization owner has restricted Streamlit's access or restricted all OAuth applications, they may need to directly modify their permissions in GitHub. If an organization has restricted Streamlit's access, a red ""X"" will appear next to the organization when you are prompted to authorize with your GitHub account. See GitHub's documentation on OAuth apps and organizations.Previous: Workspace settingsNext: Update your emailforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy" https://docs.streamlit.io/en/0.70.0/api.html#developer-tools,"DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceremovePAGE ELEMENTSWrite and magicaddText elementsaddData elementsaddChart elementsaddInput widgetsaddMedia elementsaddLayouts and containersaddChat elementsaddStatus elementsaddThird-party componentsopen_in_newAPPLICATION LOGICNavigation and pagesaddExecution flowaddCaching and stateaddConnections and secretsaddCustom componentsaddUtilitiesaddConfigurationaddTOOLSApp testingaddCommand lineaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Develop/API referenceAPI reference Streamlit makes it easy for you to visualize, mutate, and share data. The API reference is organized by activity type, like displaying data or optimizing performance. Each section includes methods associated with the activity type, including examples. Browse our API below and click to learn more about any of our available commands! 🎈 Display almost anything Write and magic st.writeWrite arguments to the app.st.write(""Hello **world**!"") st.write(my_data_frame) st.write(my_mpl_figure) st.write_streamWrite generators or streams to the app with a typewriter effect.st.write_stream(my_generator) st.write_stream(my_llm_stream) MagicAny time Streamlit sees either a variable or literal value on its own line, it automatically writes that to your app using st.write""Hello **world**!"" my_data_frame my_mpl_figure Text elements MarkdownDisplay string formatted as Markdown.st.markdown(""Hello **world**!"") TitleDisplay text in title formatting.st.title(""The app title"") HeaderDisplay text in header formatting.st.header(""This is a header"") SubheaderDisplay text in subheader formatting.st.subheader(""This is a subheader"") CaptionDisplay text in small font.st.caption(""This is written small caption text"") Code blockDisplay a code block with optional syntax highlighting.st.code(""a = 1234"") EchoDisplay some code in the app, then execute it. Useful for tutorials.with st.echo(): st.write('This code will be printed') LaTeXDisplay mathematical expressions formatted as LaTeX.st.latex(""\int a x^2 \,dx"") Preformatted textWrite fixed-width and preformatted text.st.text(""Hello world"") DividerDisplay a horizontal rule.st.divider() Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration! PreviousTagsAdd tags to your Streamlit apps. Created by @gagan3012.st_tags(label='# Enter Keywords:', text='Press enter to add more', value=['Zero', 'One', 'Two'], suggestions=['five', 'six', 'seven', 'eight', 'nine', 'three', 'eleven', 'ten', 'four'], maxtags = 4, key='1') NLUApply text mining on a dataframe. Created by @JohnSnowLabs.nlu.load('sentiment').predict('I love NLU! <3') Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.mention(label=""An awesome Streamlit App"", icon=""streamlit"", url=""https://extras.streamlit.app"",) Annotated textDisplay annotated text in Streamlit apps. Created by @tvst.annotated_text(""This "", (""is"", ""verb""), "" some "", (""annotated"", ""adj""), (""text"", ""noun""), "" for those of "", (""you"", ""pronoun""), "" who "", (""like"", ""verb""), "" this sort of "", (""thing"", ""noun""), ""."") Drawable CanvasProvides a sketching canvas using Fabric.js. Created by @andfanilo.st_canvas(fill_color=""rgba(255, 165, 0, 0.3)"", stroke_width=stroke_width, stroke_color=stroke_color, background_color=bg_color, background_image=Image.open(bg_image) if bg_image else None, update_streamlit=realtime_update, height=150, drawing_mode=drawing_mode, point_display_radius=point_display_radius if drawing_mode == 'point' else 0, key=""canvas"",) TagsAdd tags to your Streamlit apps. Created by @gagan3012.st_tags(label='# Enter Keywords:', text='Press enter to add more', value=['Zero', 'One', 'Two'], suggestions=['five', 'six', 'seven', 'eight', 'nine', 'three', 'eleven', 'ten', 'four'], maxtags = 4, key='1') NLUApply text mining on a dataframe. Created by @JohnSnowLabs.nlu.load('sentiment').predict('I love NLU! <3') Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.mention(label=""An awesome Streamlit App"", icon=""streamlit"", url=""https://extras.streamlit.app"",) Annotated textDisplay annotated text in Streamlit apps. Created by @tvst.annotated_text(""This "", (""is"", ""verb""), "" some "", (""annotated"", ""adj""), (""text"", ""noun""), "" for those of "", (""you"", ""pronoun""), "" who "", (""like"", ""verb""), "" this sort of "", (""thing"", ""noun""), ""."") Drawable CanvasProvides a sketching canvas using Fabric.js. Created by @andfanilo.st_canvas(fill_color=""rgba(255, 165, 0, 0.3)"", stroke_width=stroke_width, stroke_color=stroke_color, background_color=bg_color, background_image=Image.open(bg_image) if bg_image else None, update_streamlit=realtime_update, height=150, drawing_mode=drawing_mode, point_display_radius=point_display_radius if drawing_mode == 'point' else 0, key=""canvas"",) TagsAdd tags to your Streamlit apps. Created by @gagan3012.st_tags(label='# Enter Keywords:', text='Press enter to add more', value=['Zero', 'One', 'Two'], suggestions=['five', 'six', 'seven', 'eight', 'nine', 'three', 'eleven', 'ten', 'four'], maxtags = 4, key='1') NLUApply text mining on a dataframe. Created by @JohnSnowLabs.nlu.load('sentiment').predict('I love NLU! <3') Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.mention(label=""An awesome Streamlit App"", icon=""streamlit"", url=""https://extras.streamlit.app"",) Next Data elements DataframesDisplay a dataframe as an interactive table.st.dataframe(my_data_frame) Data editorDisplay a data editor widget.edited = st.data_editor(df, num_rows=""dynamic"") Column configurationConfigure the display and editing behavior of dataframes and data editors.st.column_config.NumberColumn(""Price (in USD)"", min_value=0, format=""$%d"") Static tablesDisplay a static table.st.table(my_data_frame) MetricsDisplay a metric in big bold font, with an optional indicator of how the metric changed.st.metric(""My metric"", 42, 2) Dicts and JSONDisplay object or string as a pretty-printed JSON string.st.json(my_dict) Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration! PreviousImage CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates value = streamlit_image_coordinates(""https://placekitten.com/200/300"") st.write(value) Plotly EventsMake Plotly charts interactive!. Created by @null-jones.from streamlit_plotly_events import plotly_events fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.metric_cards import style_metric_cards col3.metric(label=""No Change"", value=5000, delta=0) style_metric_cards() Streamlit AggridImplementation of Ag-Grid component for Streamlit. Created by @PablocFonseca.df = pd.DataFrame({'col1': [1, 2, 3], 'col2': [4, 5, 6]}) grid_return = AgGrid(df, editable=True) new_df = grid_return['data'] Streamlit FoliumStreamlit Component for rendering Folium maps. Created by @randyzwitch.m = folium.Map(location=[39.949610, -75.150282], zoom_start=16) folium.Marker([39.949610, -75.150282], popup=""Liberty Bell"", tooltip=""Liberty Bell"").add_to(m) st_data = st_folium(m, width=725) Pandas ProfilingPandas profiling component for Streamlit. Created by @okld.df = pd.read_csv(""https://storage.googleapis.com/tf-datasets/titanic/train.csv"") pr = df.profile_report() st_profile_report(pr) Image CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates value = streamlit_image_coordinates(""https://placekitten.com/200/300"") st.write(value) Plotly EventsMake Plotly charts interactive!. Created by @null-jones.from streamlit_plotly_events import plotly_events fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.metric_cards import style_metric_cards col3.metric(label=""No Change"", value=5000, delta=0) style_metric_cards() Streamlit AggridImplementation of Ag-Grid component for Streamlit. Created by @PablocFonseca.df = pd.DataFrame({'col1': [1, 2, 3], 'col2': [4, 5, 6]}) grid_return = AgGrid(df, editable=True) new_df = grid_return['data'] Streamlit FoliumStreamlit Component for rendering Folium maps. Created by @randyzwitch.m = folium.Map(location=[39.949610, -75.150282], zoom_start=16) folium.Marker([39.949610, -75.150282], popup=""Liberty Bell"", tooltip=""Liberty Bell"").add_to(m) st_data = st_folium(m, width=725) Pandas ProfilingPandas profiling component for Streamlit. Created by @okld.df = pd.read_csv(""https://storage.googleapis.com/tf-datasets/titanic/train.csv"") pr = df.profile_report() st_profile_report(pr) Image CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates value = streamlit_image_coordinates(""https://placekitten.com/200/300"") st.write(value) Plotly EventsMake Plotly charts interactive!. Created by @null-jones.from streamlit_plotly_events import plotly_events fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.metric_cards import style_metric_cards col3.metric(label=""No Change"", value=5000, delta=0) style_metric_cards() Next Chart elements Simple area chartsDisplay an area chart.st.area_chart(my_data_frame) Simple bar chartsDisplay a bar chart.st.bar_chart(my_data_frame) Simple line chartsDisplay a line chart.st.line_chart(my_data_frame) Simple scatter chartsDisplay a line chart.st.scatter_chart(my_data_frame) Scatterplots on mapsDisplay a map with points on it.st.map(my_data_frame) MatplotlibDisplay a matplotlib.pyplot figure.st.pyplot(my_mpl_figure) AltairDisplay a chart using the Altair library.st.altair_chart(my_altair_chart) Vega-LiteDisplay a chart using the Vega-Lite library.st.vega_lite_chart(my_vega_lite_chart) PlotlyDisplay an interactive Plotly chart.st.plotly_chart(my_plotly_chart) BokehDisplay an interactive Bokeh chart.st.bokeh_chart(my_bokeh_chart) PyDeckDisplay a chart using the PyDeck library.st.pydeck_chart(my_pydeck_chart) GraphVizDisplay a graph using the dagre-d3 library.st.graphviz_chart(my_graphviz_spec) Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration! PreviousStreamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl(""https://assets5.lottiefiles.com/packages/lf20_V9t630.json"") st_lottie(lottie_hello, key=""hello"") Plotly EventsMake Plotly charts interactive!. Created by @null-jones.fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.chart += get_annotations_chart(annotations=[(""Mar 01, 2008"", ""Pretty good day for GOOG""), (""Dec 01, 2007"", ""Something's going wrong for GOOG & AAPL""), (""Nov 01, 2008"", ""Market starts again thanks to...""), (""Dec 01, 2009"", ""Small crash for GOOG after...""),],) st.altair_chart(chart, use_container_width=True) PlostA deceptively simple plotting library for Streamlit. Created by @tvst.import plost plost.line_chart(my_dataframe, x='time', y='stock_value', color='stock_name',) HiPlotHigh dimensional Interactive Plotting. Created by @facebookresearch.data = [{'dropout':0.1, 'lr': 0.001, 'loss': 10.0, 'optimizer': 'SGD'}, {'dropout':0.15, 'lr': 0.01, 'loss': 3.5, 'optimizer': 'Adam'}, {'dropout':0.3, 'lr': 0.1, 'loss': 4.5, 'optimizer': 'Adam'}] hip.Experiment.from_iterable(data).display() EChartsHigh dimensional Interactive Plotting. Created by @andfanilo.from streamlit_echarts import st_echarts st_echarts(options=options) Streamlit FoliumStreamlit Component for rendering Folium maps. Created by @randyzwitch.m = folium.Map(location=[39.949610, -75.150282], zoom_start=16) st_data = st_folium(m, width=725) Spacy-StreamlitspaCy building blocks and visualizers for Streamlit apps. Created by @explosion.models = [""en_core_web_sm"", ""en_core_web_md""] spacy_streamlit.visualize(models, ""Sundar Pichai is the CEO of Google."") Streamlit AgraphA Streamlit Graph Vis, based on react-grah-vis. Created by @ChrisDelClea.from streamlit_agraph import agraph, Node, Edge, Config agraph(nodes=nodes, edges=edges, config=config) Streamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl(""https://assets5.lottiefiles.com/packages/lf20_V9t630.json"") st_lottie(lottie_hello, key=""hello"") Plotly EventsMake Plotly charts interactive!. Created by @null-jones.fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.chart += get_annotations_chart(annotations=[(""Mar 01, 2008"", ""Pretty good day for GOOG""), (""Dec 01, 2007"", ""Something's going wrong for GOOG & AAPL""), (""Nov 01, 2008"", ""Market starts again thanks to...""), (""Dec 01, 2009"", ""Small crash for GOOG after...""),],) st.altair_chart(chart, use_container_width=True) PlostA deceptively simple plotting library for Streamlit. Created by @tvst.import plost plost.line_chart(my_dataframe, x='time', y='stock_value', color='stock_name',) HiPlotHigh dimensional Interactive Plotting. Created by @facebookresearch.data = [{'dropout':0.1, 'lr': 0.001, 'loss': 10.0, 'optimizer': 'SGD'}, {'dropout':0.15, 'lr': 0.01, 'loss': 3.5, 'optimizer': 'Adam'}, {'dropout':0.3, 'lr': 0.1, 'loss': 4.5, 'optimizer': 'Adam'}] hip.Experiment.from_iterable(data).display() EChartsHigh dimensional Interactive Plotting. Created by @andfanilo.from streamlit_echarts import st_echarts st_echarts(options=options) Streamlit FoliumStreamlit Component for rendering Folium maps. Created by @randyzwitch.m = folium.Map(location=[39.949610, -75.150282], zoom_start=16) st_data = st_folium(m, width=725) Spacy-StreamlitspaCy building blocks and visualizers for Streamlit apps. Created by @explosion.models = [""en_core_web_sm"", ""en_core_web_md""] spacy_streamlit.visualize(models, ""Sundar Pichai is the CEO of Google."") Streamlit AgraphA Streamlit Graph Vis, based on react-grah-vis. Created by @ChrisDelClea.from streamlit_agraph import agraph, Node, Edge, Config agraph(nodes=nodes, edges=edges, config=config) Streamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl(""https://assets5.lottiefiles.com/packages/lf20_V9t630.json"") st_lottie(lottie_hello, key=""hello"") Plotly EventsMake Plotly charts interactive!. Created by @null-jones.fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.chart += get_annotations_chart(annotations=[(""Mar 01, 2008"", ""Pretty good day for GOOG""), (""Dec 01, 2007"", ""Something's going wrong for GOOG & AAPL""), (""Nov 01, 2008"", ""Market starts again thanks to...""), (""Dec 01, 2009"", ""Small crash for GOOG after...""),],) st.altair_chart(chart, use_container_width=True) Next Input widgets ButtonDisplay a button widget.clicked = st.button(""Click me"") Download buttonDisplay a download button widget.st.download_button(""Download file"", file) Form buttonDisplay a form submit button. For use with st.form.st.form_submit_button(""Sign up"") Link buttonDisplay a link button.st.link_button(""Go to gallery"", url) Page linkDisplay a link to another page in a multipage app.st.page_link(""app.py"", label=""Home"", icon=""🏠"") st.page_link(""pages/profile.py"", label=""My profile"") CheckboxDisplay a checkbox widget.selected = st.checkbox(""I agree"") Color pickerDisplay a color picker widget.color = st.color_picker(""Pick a color"") MultiselectDisplay a multiselect widget. The multiselect widget starts as empty.choices = st.multiselect(""Buy"", [""milk"", ""apples"", ""potatoes""]) RadioDisplay a radio button widget.choice = st.radio(""Pick one"", [""cats"", ""dogs""]) SelectboxDisplay a select widget.choice = st.selectbox(""Pick one"", [""cats"", ""dogs""]) Select-sliderDisplay a slider widget to select items from a list.size = st.select_slider(""Pick a size"", [""S"", ""M"", ""L""]) ToggleDisplay a toggle widget.activated = st.toggle(""Activate"") Number inputDisplay a numeric input widget.choice = st.number_input(""Pick a number"", 0, 10) SliderDisplay a slider widget.number = st.slider(""Pick a number"", 0, 100) Date inputDisplay a date input widget.date = st.date_input(""Your birthday"") Time inputDisplay a time input widget.time = st.time_input(""Meeting time"") Chat inputDisplay a chat input widget.prompt = st.chat_input(""Say something"") if prompt: st.write(f""The user has sent: {prompt}"") Text-areaDisplay a multi-line text input widget.text = st.text_area(""Text to translate"") Text inputDisplay a single-line text input widget.name = st.text_input(""First name"") Data editorDisplay a data editor widget.edited = st.experimental_data_editor(df, num_rows=""dynamic"") File UploaderDisplay a file uploader widget.data = st.file_uploader(""Upload a CSV"") Camera inputDisplay a widget that allows users to upload images directly from a camera.image = st.camera_input(""Take a picture"") Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration! PreviousStreamlit ChatStreamlit Component for a Chatbot UI. Created by @AI-Yash.from streamlit_chat import message message(""My message"") message(""Hello bot!"", is_user=True) # align's the message to the right Streamlit Option MenuSelect a single item from a list of options in a menu. Created by @victoryhb.from streamlit_option_menu import option_menu option_menu(""Main Menu"", [""Home"", 'Settings'], icons=['house', 'gear'], menu_icon=""cast"", default_index=1) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.stoggle import stoggle stoggle( ""Click me!"", """"""🥷 Surprise! Here's some additional content"""""",) Streamlit ElementsCreate a draggable and resizable dashboard in Streamlit. Created by @okls.from streamlit_elements import elements, mui, html with elements(""new_element""): mui.Typography(""Hello world"") TagsAdd tags to your Streamlit apps. Created by @gagan3012.from streamlit_tags import st_tags st_tags(label='# Enter Keywords:', text='Press enter to add more', value=['Zero', 'One', 'Two'], suggestions=['five', 'six', 'seven', 'eight', 'nine', 'three', 'eleven', 'ten', 'four'], maxtags = 4, key='1') StqdmThe simplest way to handle a progress bar in streamlit app. Created by @Wirg.from stqdm import stqdm for _ in stqdm(range(50)): sleep(0.5) TimelineDisplay a Timeline in Streamlit apps using TimelineJS. Created by @innerdoc.from streamlit_timeline import timeline with open('example.json', ""r"") as f: timeline(f.read(), height=800) Camera input liveAlternative for st.camera_input which returns the webcam images live. Created by @blackary.from camera_input_live import camera_input_live image = camera_input_live() st.image(value) Streamlit AceAce editor component for Streamlit. Created by @okld.from streamlit_ace import st_ace content = st_ace() content Streamlit ChatStreamlit Component for a Chatbot UI. Created by @AI-Yash.from streamlit_chat import message message(""My message"") message(""Hello bot!"", is_user=True) # align's the message to the right Streamlit Option MenuSelect a single item from a list of options in a menu. Created by @victoryhb.from streamlit_option_menu import option_menu option_menu(""Main Menu"", [""Home"", 'Settings'], icons=['house', 'gear'], menu_icon=""cast"", default_index=1) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.stoggle import stoggle stoggle( ""Click me!"", """"""🥷 Surprise! Here's some additional content"""""",) Streamlit ElementsCreate a draggable and resizable dashboard in Streamlit. Created by @okls.from streamlit_elements import elements, mui, html with elements(""new_element""): mui.Typography(""Hello world"") TagsAdd tags to your Streamlit apps. Created by @gagan3012.from streamlit_tags import st_tags st_tags(label='# Enter Keywords:', text='Press enter to add more', value=['Zero', 'One', 'Two'], suggestions=['five', 'six', 'seven', 'eight', 'nine', 'three', 'eleven', 'ten', 'four'], maxtags = 4, key='1') StqdmThe simplest way to handle a progress bar in streamlit app. Created by @Wirg.from stqdm import stqdm for _ in stqdm(range(50)): sleep(0.5) TimelineDisplay a Timeline in Streamlit apps using TimelineJS. Created by @innerdoc.from streamlit_timeline import timeline with open('example.json', ""r"") as f: timeline(f.read(), height=800) Camera input liveAlternative for st.camera_input which returns the webcam images live. Created by @blackary.from camera_input_live import camera_input_live image = camera_input_live() st.image(value) Streamlit AceAce editor component for Streamlit. Created by @okld.from streamlit_ace import st_ace content = st_ace() content Streamlit ChatStreamlit Component for a Chatbot UI. Created by @AI-Yash.from streamlit_chat import message message(""My message"") message(""Hello bot!"", is_user=True) # align's the message to the right Streamlit Option MenuSelect a single item from a list of options in a menu. Created by @victoryhb.from streamlit_option_menu import option_menu option_menu(""Main Menu"", [""Home"", 'Settings'], icons=['house', 'gear'], menu_icon=""cast"", default_index=1) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.stoggle import stoggle stoggle( ""Click me!"", """"""🥷 Surprise! Here's some additional content"""""",) Next Media elements ImageDisplay an image or list of images.st.image(numpy_array) st.image(image_bytes) st.image(file) st.image(""https://example.com/myimage.jpg"") AudioDisplay an audio player.st.audio(numpy_array) st.audio(audio_bytes) st.audio(file) st.audio(""https://example.com/myaudio.mp3"", format=""audio/mp3"") VideoDisplay a video player.st.video(numpy_array) st.video(video_bytes) st.video(file) st.video(""https://example.com/myvideo.mp4"", format=""video/mp4"") Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration! PreviousStreamlit CropperA simple image cropper for Streamlit. Created by @turner-anderson.from streamlit_cropper import st_cropper st_cropper(img, realtime_update=realtime_update, box_color=box_color, aspect_ratio=aspect_ratio) Image CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates streamlit_image_coordinates(""https://placekitten.com/200/300"") Streamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl(""https://assets5.lottiefiles.com/packages/lf20_V9t630.json"") st_lottie(lottie_hello, key=""hello"") Streamlit WebrtcHandling and transmitting real-time video/audio streams with Streamlit. Created by @whitphx.from streamlit_webrtc import webrtc_streamer webrtc_streamer(key=""sample"") Drawable CanvasProvides a sketching canvas using Fabric.js. Created by @andfanilo.from streamlit_drawable_canvas import st_canvas st_canvas(fill_color=""rgba(255, 165, 0, 0.3)"", stroke_width=stroke_width, stroke_color=stroke_color, background_color=bg_color, background_image=Image.open(bg_image) if bg_image else None, update_streamlit=realtime_update, height=150, drawing_mode=drawing_mode, point_display_radius=point_display_radius if drawing_mode == 'point' else 0, key=""canvas"",) Image ComparisonCompare images with a slider using JuxtaposeJS. Created by @fcakyon.from streamlit_image_comparison import image_comparison image_comparison(img1=""image1.jpg"", img2=""image2.jpg"",) Streamlit CropperA simple image cropper for Streamlit. Created by @turner-anderson.from streamlit_cropper import st_cropper st_cropper(img, realtime_update=realtime_update, box_color=box_color, aspect_ratio=aspect_ratio) Image CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates streamlit_image_coordinates(""https://placekitten.com/200/300"") Streamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl(""https://assets5.lottiefiles.com/packages/lf20_V9t630.json"") st_lottie(lottie_hello, key=""hello"") Streamlit WebrtcHandling and transmitting real-time video/audio streams with Streamlit. Created by @whitphx.from streamlit_webrtc import webrtc_streamer webrtc_streamer(key=""sample"") Drawable CanvasProvides a sketching canvas using Fabric.js. Created by @andfanilo.from streamlit_drawable_canvas import st_canvas st_canvas(fill_color=""rgba(255, 165, 0, 0.3)"", stroke_width=stroke_width, stroke_color=stroke_color, background_color=bg_color, background_image=Image.open(bg_image) if bg_image else None, update_streamlit=realtime_update, height=150, drawing_mode=drawing_mode, point_display_radius=point_display_radius if drawing_mode == 'point' else 0, key=""canvas"",) Image ComparisonCompare images with a slider using JuxtaposeJS. Created by @fcakyon.from streamlit_image_comparison import image_comparison image_comparison(img1=""image1.jpg"", img2=""image2.jpg"",) Streamlit CropperA simple image cropper for Streamlit. Created by @turner-anderson.from streamlit_cropper import st_cropper st_cropper(img, realtime_update=realtime_update, box_color=box_color, aspect_ratio=aspect_ratio) Image CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates streamlit_image_coordinates(""https://placekitten.com/200/300"") Streamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl(""https://assets5.lottiefiles.com/packages/lf20_V9t630.json"") st_lottie(lottie_hello, key=""hello"") Next Layouts and containers ColumnsInsert containers laid out as side-by-side columns.col1, col2 = st.columns(2) col1.write(""this is column 1"") col2.write(""this is column 2"") ContainerInsert a multi-element container.c = st.container() st.write(""This will show last"") c.write(""This will show first"") c.write(""This will show second"") Modal dialogsInsert a modal dialog that can rerun independently from the rest of the script.@st.experimental_dialog(""Sign up"") def email_form(): name = st.text_input(""Name"") email = st.text_input(""Email"") EmptyInsert a single-element container.c = st.empty() st.write(""This will show last"") c.write(""This will be replaced"") c.write(""This will show first"") ExpanderInsert a multi-element container that can be expanded/collapsed.with st.expander(""Open to see more""): st.write(""This is more content"") PopoverInsert a multi-element popover container that can be opened/closed.with st.popover(""Settings""): st.checkbox(""Show completed"") SidebarDisplay items in a sidebar.st.sidebar.write(""This lives in the sidebar"") st.sidebar.button(""Click me!"") TabsInsert containers separated into tabs.tab1, tab2 = st.tabs([""Tab 1"", ""Tab2""]) tab1.write(""this is tab 1"") tab2.write(""this is tab 2"") Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration!Streamlit ElementsCreate a draggable and resizable dashboard in Streamlit. Created by @okls.from streamlit_elements import elements, mui, html with elements(""new_element""): mui.Typography(""Hello world"") PydanticAuto-generate Streamlit UI from Pydantic Models and Dataclasses. Created by @lukasmasuch.import streamlit_pydantic as sp sp.pydantic_form(key=""my_form"", model=ExampleModel) Streamlit PagesAn experimental version of Streamlit Multi-Page Apps. Created by @blackary.from st_pages import Page, show_pages, add_page_title show_pages([ Page(""streamlit_app.py"", ""Home"", ""🏠""), Page(""other_pages/page2.py"", ""Page 2"", "":books:""), ]) Chat elements Streamlit provides a few commands to help you build conversational apps. These chat elements are designed to be used in conjunction with each other, but you can also use them separately. st.chat_message lets you insert a chat message container into the app so you can display messages from the user or the app. Chat containers can contain other Streamlit elements, including charts, tables, text, and more. st.chat_input lets you display a chat input widget so the user can type in a message. Chat inputDisplay a chat input widget.prompt = st.chat_input(""Say something"") if prompt: st.write(f""The user has sent: {prompt}"") Chat messageInsert a chat message container.import numpy as np with st.chat_message(""user""): st.write(""Hello 👋"") st.line_chart(np.random.randn(30, 3)) Status containerDisplay output of long-running tasks in a container.with st.status('Running'): do_something_slow() st.write_streamWrite generators or streams to the app with a typewriter effect.st.write_stream(my_generator) st.write_stream(my_llm_stream) Status elements Progress barDisplay a progress bar.for i in range(101): st.progress(i) do_something_slow() SpinnerTemporarily displays a message while executing a block of code.with st.spinner(""Please wait...""): do_something_slow() Status containerDisplay output of long-running tasks in a container.with st.status('Running'): do_something_slow() ToastBriefly displays a toast message in the bottom-right corner.st.toast('Butter!', icon='🧈') BalloonsDisplay celebratory balloons!do_something() # Celebrate when all done! st.balloons() SnowflakesDisplay celebratory snowflakes!do_something() # Celebrate when all done! st.snow() Success boxDisplay a success message.st.success(""Match found!"") Info boxDisplay an informational message.st.info(""Dataset is updated every day at midnight."") Warning boxDisplay warning message.st.warning(""Unable to fetch image. Skipping..."") Error boxDisplay error message.st.error(""We encountered an error"") Exception outputDisplay an exception.e = RuntimeError(""This is an exception of type RuntimeError"") st.exception(e) Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration!StqdmThe simplest way to handle a progress bar in streamlit app. Created by @Wirg.from stqdm import stqdm for _ in stqdm(range(50)): sleep(0.5) Custom notification boxA custom notification box with the ability to close it out. Created by @Socvest.from streamlit_custom_notification_box import custom_notification_box styles = {'material-icons':{'color': 'red'}, 'text-icon-link-close-container': {'box-shadow': '#3896de 0px 4px'}, 'notification-text': {'':''}, 'close-button':{'':''}, 'link':{'':''}} custom_notification_box(icon='info', textDisplay='We are almost done with your registration...', externalLink='more info', url='#', styles=styles, key=""foo"") Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.let_it_rain import rain rain(emoji=""🎈"", font_size=54, falling_speed=5, animation_length=""infinite"",) App logic and configuration Navigation and pages Switch pageProgrammatically navigates to a specified page.st.switch_page(""pages/my_page.py"") Page linkDisplay a link to another page in a multipage app.st.page_link(""app.py"", label=""Home"", icon=""🏠"") st.page_link(""pages/profile.py"", label=""My profile"") Execution flow Modal dialogsInsert a modal dialog that can rerun independently from the rest of the script.@st.experimental_dialog(""Sign up"") def email_form(): name = st.text_input(""Name"") email = st.text_input(""Email"") FormsCreate a form that batches elements together with a “Submit"" button.with st.form(key='my_form'): name = st.text_input(""Name"") email = st.text_input(""Email"") st.form_submit_button(""Sign up"") Partial rerunsDefine a fragment to rerun independently from the rest of the script.@st.experimental_fragment(run_every=""10s"") def fragment(): df = get_data() st.line_chart(df) Rerun scriptRerun the script immediately.st.rerun() Stop executionStops execution immediately.st.stop() Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration!AutorefreshForce a refresh without tying up a script. Created by @kmcgrady.from streamlit_autorefresh import st_autorefresh st_autorefresh(interval=2000, limit=100, key=""fizzbuzzcounter"") PydanticAuto-generate Streamlit UI from Pydantic Models and Dataclasses. Created by @lukasmasuch.import streamlit_pydantic as sp sp.pydantic_form(key=""my_form"", model=ExampleModel) Streamlit PagesAn experimental version of Streamlit Multi-Page Apps. Created by @blackary.from st_pages import Page, show_pages, add_page_title show_pages([ Page(""streamlit_app.py"", ""Home"", ""🏠""), Page(""other_pages/page2.py"", ""Page 2"", "":books:""), ]) Caching and state Cache dataFunction decorator to cache functions that return data (e.g. dataframe transforms, database queries, ML inference).@st.cache_data def long_function(param1, param2): # Perform expensive computation here or # fetch data from the web here return data Cache resourceFunction decorator to cache functions that return global resources (e.g. database connections, ML models).@st.cache_resource def init_model(): # Return a global resource here return pipeline( ""sentiment-analysis"", model=""distilbert-base-uncased-finetuned-sst-2-english"" ) Session stateSession state is a way to share variables between reruns, for each user session.st.session_state['key'] = value Query parametersGet, set, or clear the query parameters that are shown in the browser's URL bar.st.query_params[key] = value st.query_params.clear() Connections and databases Setup your connection Create a connectionConnect to a data source or APIconn = st.connection('pets_db', type='sql') pet_owners = conn.query('select * from pet_owners') st.dataframe(pet_owners) Built-in connections SnowflakeConnectionA connection to Snowflake.conn = st.connection('snowflake') SQLConnectionA connection to a SQL database using SQLAlchemy.conn = st.connection('sql') Build your own connections Connection base classBuild your own connection with BaseConnection.class MyConnection(BaseConnection[myconn.MyConnection]): def _connect(self, **kwargs) -> MyConnection: return myconn.connect(**self._secrets, **kwargs) def query(self, query): return self._instance.query(query) Secrets management Secrets singletonAccess secrets from a local TOML file.key = st.secrets[""OpenAI_key""] Secrets fileSave your secrets in a per-project or per-profile TOML file.OpenAI_key = """" Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration!AuthenticatorA secure authentication module to validate user credentials. Created by @mkhorasani.import streamlit_authenticator as stauth authenticator = stauth.Authenticate( config['credentials'], config['cookie']['name'], config['cookie']['key'], config['cookie']['expiry_days'], config['preauthorized']) WS localStorageA simple synchronous way of accessing localStorage from your app. Created by @gagangoku.from streamlit_ws_localstorage import injectWebsocketCode ret = conn.setLocalStorageVal(key='k1', val='v1') st.write('ret: ' + ret) Streamlit Auth0The fastest way to provide comprehensive login inside Streamlit. Created by @conradbez.from auth0_component import login_button user_info = login_button(clientId, domain = domain) st.write(user_info) Custom Components Declare a componentCreate and register a custom component.st.components.v1.declare_component( ""custom_slider"", ""/frontend"", ) HTMLDisplay an HTML string in an iframe.st.components.v1.html( ""

Foo bar.

"" ) iframeLoad a remote URL in an iframe.st.components.v1.iframe( ""docs.streamlit.io"" ) Utilities and user info User infost.experimental_user returns information about the logged-in user of private apps on Streamlit Community Cloud.if st.experimental_user.email == ""foo@corp.com"": st.write(""Welcome back, "", st.experimental_user.email) else: st.write(""You are not authorized to view this page."") Get helpDisplay object’s doc string, nicely formatted.st.help(st.write) st.help(pd.DataFrame) Render HTMLRenders HTML strings to your app.css = """""" """""" st.html(css) Configuration Configuration fileConfigures the default settings for your app.your-project/ ├── .streamlit/ │ └── config.toml └── your_app.py Set page title, favicon, and moreConfigures the default settings of the page.st.set_page_config( page_title=""My app"", page_icon="":shark:"", ) Developer tools App testing st.testing.v1.AppTestst.testing.v1.AppTest simulates a running Streamlit app for testing.from streamlit.testing.v1 import AppTest at = AppTest.from_file(""streamlit_app.py"") at.secrets[""WORD""] = ""Foobar"" at.run() assert not at.exception at.text_input(""word"").input(""Bazbat"").run() assert at.warning[0].value == ""Try again."" AppTest.from_filest.testing.v1.AppTest.from_file initializes a simulated app from a file.from streamlit.testing.v1 import AppTest at = AppTest.from_file(""streamlit_app.py"") at.run() AppTest.from_stringst.testing.v1.AppTest.from_string initializes a simulated app from a string.from streamlit.testing.v1 import AppTest at = AppTest.from_string(app_script_as_string) at.run() AppTest.from_functionst.testing.v1.AppTest.from_function initializes a simulated app from a function.from streamlit.testing.v1 import AppTest at = AppTest.from_function(app_script_as_callable) at.run() BlockA representation of container elements, including: st.chat_message st.columns st.sidebar st.tabs The main body of the app. # at.sidebar returns a Block at.sidebar.button[0].click().run() assert not at.exception ElementThe base class for representation of all elements, including: st.title st.header st.markdown st.dataframe # at.title returns a sequence of Title # Title inherits from Element assert at.title[0].value == ""My awesome app"" ButtonA representation of st.button and st.form_submit_button.at.button[0].click().run() ChatInputA representation of st.chat_input.at.chat_input[0].set_value(""What is Streamlit?"").run() CheckboxA representation of st.checkbox.at.checkbox[0].check().run() ColorPickerA representation of st.color_picker.at.color_picker[0].pick(""#FF4B4B"").run() DateInputA representation of st.date_input.release_date = datetime.date(2023, 10, 26) at.date_input[0].set_value(release_date).run() MultiselectA representation of st.multiselect.at.multiselect[0].select(""New York"").run() NumberInputA representation of st.number_input.at.number_input[0].increment().run() RadioA representation of st.radio.at.radio[0].set_value(""New York"").run() SelectSliderA representation of st.select_slider.at.select_slider[0].set_range(""A"",""C"").run() SelectboxA representation of st.selectbox.at.selectbox[0].select(""New York"").run() SliderA representation of st.slider.at.slider[0].set_range(2,5).run() TextAreaA representation of st.text_area.at.text_area[0].input(""Streamlit is awesome!"").run() TextInputA representation of st.text_input.at.text_input[0].input(""Streamlit"").run() TimeInputA representation of st.time_input.at.time_input[0].increment().run() ToggleA representation of st.toggle.at.toggle[0].set_value(""True"").run() Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration!Pandas ProfilingPandas profiling component for Streamlit. Created by @okld.df = pd.read_csv(""https://storage.googleapis.com/tf-datasets/titanic/train.csv"") pr = df.profile_report() st_profile_report(pr) Streamlit AceAce editor component for Streamlit. Created by @okld.from streamlit_ace import st_ace content = st_ace() content Streamlit AnalyticsTrack & visualize user interactions with your streamlit app. Created by @jrieke.import streamlit_analytics with streamlit_analytics.track(): st.text_input(""Write something"") Previous: ConceptsNext: Write and magicforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy" https://docs.streamlit.io/develop/api-reference/data/st.column_config/st.column_config.linkcolumn#stcolumn_configlinkcolumn,"DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceremovePAGE ELEMENTSWrite and magicaddText elementsaddData elementsremovest.dataframest.data_editorst.column_configremoveColumnText columnNumber columnCheckbox columnSelectbox columnDatetime columnDate columnTime columnList columnLink columnImage columnArea chart columnLine chart columnBar chart columnProgress columnst.tablest.metricst.jsonChart elementsaddInput widgetsaddMedia elementsaddLayouts and containersaddChat elementsaddStatus elementsaddThird-party componentsopen_in_newAPPLICATION LOGICNavigation and pagesaddExecution flowaddCaching and stateaddConnections and secretsaddCustom componentsaddUtilitiesaddConfigurationaddTOOLSApp testingaddCommand lineaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Develop/API reference/Data elements/st.column_config/Link columnst.column_config.LinkColumnStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeConfigure a link column in st.dataframe or st.data_editor. The cell values need to be string and will be shown as clickable links. This command needs to be used in the column_config parameter of st.dataframe or st.data_editor. When used with st.data_editor, editing will be enabled with a text input widget. Function signature[source] st.column_config.LinkColumn(label=None, *, width=None, help=None, disabled=None, required=None, default=None, max_chars=None, validate=None, display_text=None) Parameters label (str or None) The label shown at the top of the column. If None (default), the column name is used. width (""small"", ""medium"", ""large"", or None) The display width of the column. Can be one of ""small"", ""medium"", or ""large"". If None (default), the column will be sized to fit the cell contents. help (str or None) An optional tooltip that gets displayed when hovering over the column label. disabled (bool or None) Whether editing should be disabled for this column. Defaults to False. required (bool or None) Whether edited cells in the column need to have a value. If True, an edited cell can only be submitted if it has a value other than None. Defaults to False. default (str or None) Specifies the default value in this column when a new row is added by the user. max_chars (int or None) The maximum number of characters that can be entered. If None (default), there will be no maximum. validate (str or None) A regular expression (JS flavor, e.g. ""^https://.+$"") that edited values are validated against. If the input is invalid, it will not be submitted. display_text (str or None) The text that is displayed in the cell. Can be one of: None (default) to display the URL itself. A string that is displayed in every cell, e.g. ""Open link"". A regular expression (JS flavor, detected by usage of parentheses) to extract a part of the URL via a capture group, e.g. ""https://(.*?)\.example\.com"" to extract the display text ""foo"" from the URL ""https://foo.example.com"". For more complex cases, you may use Pandas Styler's format function on the underlying dataframe. Note that this makes the app slow, doesn't work with editable columns, and might be removed in the future. Examples import pandas as pd import streamlit as st data_df = pd.DataFrame( { ""apps"": [ ""https://roadmap.streamlit.app"", ""https://extras.streamlit.app"", ""https://issues.streamlit.app"", ""https://30days.streamlit.app"", ], ""creator"": [ ""https://github.com/streamlit"", ""https://github.com/arnaudmiribel"", ""https://github.com/streamlit"", ""https://github.com/streamlit"", ], } ) st.data_editor( data_df, column_config={ ""apps"": st.column_config.LinkColumn( ""Trending apps"", help=""The top trending Streamlit apps"", validate=""^https://[a-z]+\.streamlit\.app$"", max_chars=100, display_text=""https://(.*?)\.streamlit\.app"" ), ""creator"": st.column_config.LinkColumn( ""App Creator"", display_text=""Open profile"" ), }, hide_index=True, ) Built with Streamlit 🎈Fullscreen open_in_new Previous: List columnNext: Image columnforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy" https://docs.streamlit.io/develop/tutorials/llms/build-conversational-apps#build-a-simple-chatbot-gui-with-streaming,"DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceaddTutorialsremoveExecution flowaddConnect to data sourcesaddMultipage appsaddWork with LLMsremoveBuild a basic LLM chat appBuild an LLM app using LangChainQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Develop/Tutorials/Work with LLMs/Build a basic LLM chat appBuild a basic LLM chat app Introduction The advent of large language models like GPT has revolutionized the ease of developing chat-based applications. Streamlit offers several Chat elements, enabling you to build Graphical User Interfaces (GUIs) for conversational agents or chatbots. Leveraging session state along with these elements allows you to construct anything from a basic chatbot to a more advanced, ChatGPT-like experience using purely Python code. In this tutorial, we'll start by walking through Streamlit's chat elements, st.chat_message and st.chat_input. Then we'll proceed to construct three distinct applications, each showcasing an increasing level of complexity and functionality: First, we'll Build a bot that mirrors your input to get a feel for the chat elements and how they work. We'll also introduce session state and how it can be used to store the chat history. This section will serve as a foundation for the rest of the tutorial. Next, you'll learn how to Build a simple chatbot GUI with streaming. Finally, we'll Build a ChatGPT-like app that leverages session state to remember conversational context, all within less than 50 lines of code. Here's a sneak peek of the LLM-powered chatbot GUI with streaming we'll build in this tutorial: Built with Streamlit 🎈Fullscreen open_in_new Play around with the above demo to get a feel for what we'll build in this tutorial. A few things to note: There's a chat input at the bottom of the screen that's always visible. It contains some placeholder text. You can type in a message and press Enter or click the run button to send it. When you enter a message, it appears as a chat message in the container above. The container is scrollable, so you can scroll up to see previous messages. A default avatar is displayed to your messages' left. The assistant's responses are streamed to the frontend and are displayed with a different default avatar. Before we start building, let's take a closer look at the chat elements we'll use. Chat elements Streamlit offers several commands to help you build conversational apps. These chat elements are designed to be used in conjunction with each other, but you can also use them separately. st.chat_message lets you insert a chat message container into the app so you can display messages from the user or the app. Chat containers can contain other Streamlit elements, including charts, tables, text, and more. st.chat_input lets you display a chat input widget so the user can type in a message. For an overview of the API, check out this video tutorial by Chanin Nantasenamat (@dataprofessor), a Senior Developer Advocate at Streamlit. st.chat_message st.chat_message lets you insert a multi-element chat message container into your app. The returned container can contain any Streamlit element, including charts, tables, text, and more. To add elements to the returned container, you can use with notation. st.chat_message's first parameter is the name of the message author, which can be either ""user"" or ""assistant"" to enable preset styling and avatars, like in the demo above. You can also pass in a custom string to use as the author name. Currently, the name is not shown in the UI but is only set as an accessibility label. For accessibility reasons, you should not use an empty string. Here's an minimal example of how to use st.chat_message to display a welcome message: import streamlit as st with st.chat_message(""user""): st.write(""Hello 👋"") Notice the message is displayed with a default avatar and styling since we passed in ""user"" as the author name. You can also pass in ""assistant"" as the author name to use a different default avatar and styling, or pass in a custom name and avatar. See the API reference for more details. import streamlit as st import numpy as np with st.chat_message(""assistant""): st.write(""Hello human"") st.bar_chart(np.random.randn(30, 3)) Built with Streamlit 🎈Fullscreen open_in_new While we've used the preferred with notation in the above examples, you can also just call methods directly in the returned objects. The below example is equivalent to the one above: import streamlit as st import numpy as np message = st.chat_message(""assistant"") message.write(""Hello human"") message.bar_chart(np.random.randn(30, 3)) So far, we've displayed predefined messages. But what if we want to display messages based on user input? st.chat_input st.chat_input lets you display a chat input widget so the user can type in a message. The returned value is the user's input, which is None if the user hasn't sent a message yet. You can also pass in a default prompt to display in the input widget. Here's an example of how to use st.chat_input to display a chat input widget and show the user's input: import streamlit as st prompt = st.chat_input(""Say something"") if prompt: st.write(f""User has sent the following prompt: {prompt}"") Built with Streamlit 🎈Fullscreen open_in_new Pretty straightforward, right? Now let's combine st.chat_message and st.chat_input to build a bot the mirrors or echoes your input. Build a bot that mirrors your input In this section, we'll build a bot that mirrors or echoes your input. More specifically, the bot will respond to your input with the same message. We'll use st.chat_message to display the user's input and st.chat_input to accept user input. We'll also use session state to store the chat history so we can display it in the chat message container. First, let's think about the different components we'll need to build our bot: Two chat message containers to display messages from the user and the bot, respectively. A chat input widget so the user can type in a message. A way to store the chat history so we can display it in the chat message containers. We can use a list to store the messages, and append to it every time the user or bot sends a message. Each entry in the list will be a dictionary with the following keys: role (the author of the message), and content (the message content). import streamlit as st st.title(""Echo Bot"") # Initialize chat history if ""messages"" not in st.session_state: st.session_state.messages = [] # Display chat messages from history on app rerun for message in st.session_state.messages: with st.chat_message(message[""role""]): st.markdown(message[""content""]) In the above snippet, we've added a title to our app and a for loop to iterate through the chat history and display each message in the chat message container (with the author role and message content). We've also added a check to see if the messages key is in st.session_state. If it's not, we initialize it to an empty list. This is because we'll be adding messages to the list later on, and we don't want to overwrite the list every time the app reruns. Now let's accept user input with st.chat_input, display the user's message in the chat message container, and add it to the chat history. # React to user input if prompt := st.chat_input(""What is up?""): # Display user message in chat message container with st.chat_message(""user""): st.markdown(prompt) # Add user message to chat history st.session_state.messages.append({""role"": ""user"", ""content"": prompt}) We used the := operator to assign the user's input to the prompt variable and checked if it's not None in the same line. If the user has sent a message, we display the message in the chat message container and append it to the chat history. All that's left to do is add the chatbot's responses within the if block. We'll use the same logic as before to display the bot's response (which is just the user's prompt) in the chat message container and add it to the history. response = f""Echo: {prompt}"" # Display assistant response in chat message container with st.chat_message(""assistant""): st.markdown(response) # Add assistant response to chat history st.session_state.messages.append({""role"": ""assistant"", ""content"": response}) Putting it all together, here's the full code for our simple chatbot GUI and the result: View full codeexpand_moreimport streamlit as st st.title(""Echo Bot"") # Initialize chat history if ""messages"" not in st.session_state: st.session_state.messages = [] # Display chat messages from history on app rerun for message in st.session_state.messages: with st.chat_message(message[""role""]): st.markdown(message[""content""]) # React to user input if prompt := st.chat_input(""What is up?""): # Display user message in chat message container st.chat_message(""user"").markdown(prompt) # Add user message to chat history st.session_state.messages.append({""role"": ""user"", ""content"": prompt}) response = f""Echo: {prompt}"" # Display assistant response in chat message container with st.chat_message(""assistant""): st.markdown(response) # Add assistant response to chat history st.session_state.messages.append({""role"": ""assistant"", ""content"": response}) Built with Streamlit 🎈Fullscreen open_in_new While the above example is very simple, it's a good starting point for building more complex conversational apps. Notice how the bot responds instantly to your input. In the next section, we'll add a delay to simulate the bot ""thinking"" before responding. Build a simple chatbot GUI with streaming In this section, we'll build a simple chatbot GUI that responds to user input with a random message from a list of pre-determind responses. In the next section, we'll convert this simple toy example into a ChatGPT-like experience using OpenAI. Just like previously, we still require the same components to build our chatbot. Two chat message containers to display messages from the user and the bot, respectively. A chat input widget so the user can type in a message. And a way to store the chat history so we can display it in the chat message containers. Let's just copy the code from the previous section and add a few tweaks to it. import streamlit as st import random import time st.title(""Simple chat"") # Initialize chat history if ""messages"" not in st.session_state: st.session_state.messages = [] # Display chat messages from history on app rerun for message in st.session_state.messages: with st.chat_message(message[""role""]): st.markdown(message[""content""]) # Accept user input if prompt := st.chat_input(""What is up?""): # Display user message in chat message container with st.chat_message(""user""): st.markdown(prompt) # Add user message to chat history st.session_state.messages.append({""role"": ""user"", ""content"": prompt}) The only difference so far is we've changed the title of our app and added imports for random and time. We'll use random to randomly select a response from a list of responses and time to add a delay to simulate the chatbot ""thinking"" before responding. All that's left to do is add the chatbot's responses within the if block. We'll use a list of responses and randomly select one to display. We'll also add a delay to simulate the chatbot ""thinking"" before responding (or stream its response). Let's make a helper function for this and insert it at the top of our app. # Streamed response emulator def response_generator(): response = random.choice( [ ""Hello there! How can I assist you today?"", ""Hi, human! Is there anything I can help you with?"", ""Do you need help?"", ] ) for word in response.split(): yield word + "" "" time.sleep(0.05) Back to writing the response in our chat interface, we'll use st.write_stream to write out the streamed response with a typewriter effect. # Display assistant response in chat message container with st.chat_message(""assistant""): response = st.write_stream(response_generator()) # Add assistant response to chat history st.session_state.messages.append({""role"": ""assistant"", ""content"": response}) Above, we've added a placeholder to display the chatbot's response. We've also added a for loop to iterate through the response and display it one word at a time. We've added a delay of 0.05 seconds between each word to simulate the chatbot ""thinking"" before responding. Finally, we append the chatbot's response to the chat history. As you've probably guessed, this is a naive implementation of streaming. We'll see how to implement streaming with OpenAI in the next section. Putting it all together, here's the full code for our simple chatbot GUI and the result: View full codeexpand_moreimport streamlit as st import random import time # Streamed response emulator def response_generator(): response = random.choice( [ ""Hello there! How can I assist you today?"", ""Hi, human! Is there anything I can help you with?"", ""Do you need help?"", ] ) for word in response.split(): yield word + "" "" time.sleep(0.05) st.title(""Simple chat"") # Initialize chat history if ""messages"" not in st.session_state: st.session_state.messages = [] # Display chat messages from history on app rerun for message in st.session_state.messages: with st.chat_message(message[""role""]): st.markdown(message[""content""]) # Accept user input if prompt := st.chat_input(""What is up?""): # Add user message to chat history st.session_state.messages.append({""role"": ""user"", ""content"": prompt}) # Display user message in chat message container with st.chat_message(""user""): st.markdown(prompt) # Display assistant response in chat message container with st.chat_message(""assistant""): response = st.write_stream(response_generator()) # Add assistant response to chat history st.session_state.messages.append({""role"": ""assistant"", ""content"": response}) Built with Streamlit 🎈Fullscreen open_in_new Play around with the above demo to get a feel for what we've built. It's a very simple chatbot GUI, but it has all the components of a more sophisticated chatbot. In the next section, we'll see how to build a ChatGPT-like app using OpenAI. Build a ChatGPT-like app Now that you've understood the basics of Streamlit's chat elements, let's make a few tweaks to it to build our own ChatGPT-like app. You'll need to install the OpenAI Python library and get an API key to follow along. Install dependencies First let's install the dependencies we'll need for this section: pip install openai streamlit Add OpenAI API key to Streamlit secrets Next, let's add our OpenAI API key to Streamlit secrets. We do this by creating .streamlit/secrets.toml file in our project directory and adding the following lines to it: # .streamlit/secrets.toml OPENAI_API_KEY = ""YOUR_API_KEY"" Write the app Now let's write the app. We'll use the same code as before, but we'll replace the list of responses with a call to the OpenAI API. We'll also add a few more tweaks to make the app more ChatGPT-like. import streamlit as st from openai import OpenAI st.title(""ChatGPT-like clone"") # Set OpenAI API key from Streamlit secrets client = OpenAI(api_key=st.secrets[""OPENAI_API_KEY""]) # Set a default model if ""openai_model"" not in st.session_state: st.session_state[""openai_model""] = ""gpt-3.5-turbo"" # Initialize chat history if ""messages"" not in st.session_state: st.session_state.messages = [] # Display chat messages from history on app rerun for message in st.session_state.messages: with st.chat_message(message[""role""]): st.markdown(message[""content""]) # Accept user input if prompt := st.chat_input(""What is up?""): # Add user message to chat history st.session_state.messages.append({""role"": ""user"", ""content"": prompt}) # Display user message in chat message container with st.chat_message(""user""): st.markdown(prompt) All that's changed is that we've added a default model to st.session_state and set our OpenAI API key from Streamlit secrets. Here's where it gets interesting. We can replace our emulated stream with the model's responses from OpenAI: # Display assistant response in chat message container with st.chat_message(""assistant""): stream = client.chat.completions.create( model=st.session_state[""openai_model""], messages=[ {""role"": m[""role""], ""content"": m[""content""]} for m in st.session_state.messages ], stream=True, ) response = st.write_stream(stream) st.session_state.messages.append({""role"": ""assistant"", ""content"": response}) Above, we've replaced the list of responses with a call to OpenAI().chat.completions.create. We've set stream=True to stream the responses to the frontend. In the API call, we pass the model name we hardcoded in session state and pass the chat history as a list of messages. We also pass the role and content of each message in the chat history. Finally, OpenAI returns a stream of responses (split into chunks of tokens), which we iterate through and display each chunk. Putting it all together, here's the full code for our ChatGPT-like app and the result: View full codeexpand_morefrom openai import OpenAI import streamlit as st st.title(""ChatGPT-like clone"") client = OpenAI(api_key=st.secrets[""OPENAI_API_KEY""]) if ""openai_model"" not in st.session_state: st.session_state[""openai_model""] = ""gpt-3.5-turbo"" if ""messages"" not in st.session_state: st.session_state.messages = [] for message in st.session_state.messages: with st.chat_message(message[""role""]): st.markdown(message[""content""]) if prompt := st.chat_input(""What is up?""): st.session_state.messages.append({""role"": ""user"", ""content"": prompt}) with st.chat_message(""user""): st.markdown(prompt) with st.chat_message(""assistant""): stream = client.chat.completions.create( model=st.session_state[""openai_model""], messages=[ {""role"": m[""role""], ""content"": m[""content""]} for m in st.session_state.messages ], stream=True, ) response = st.write_stream(stream) st.session_state.messages.append({""role"": ""assistant"", ""content"": response}) Built with Streamlit 🎈Fullscreen open_in_new Congratulations! You've built your own ChatGPT-like app in less than 50 lines of code. We're very excited to see what you'll build with Streamlit's chat elements. Experiment with different models and tweak the code to build your own conversational apps. If you build something cool, let us know on the Forum or check out some other Generative AI apps for inspiration. 🎈Previous: Work with LLMsNext: Build an LLM app using LangChainforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy" https://docs.streamlit.io/develop/concepts/architecture/st.cache#example-5-use-caching-to-speed-up-your-app-across-users,"DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsremoveCOREArchitecture & executionremoveRunning your appStreamlit's architectureThe app chromeCachingSession StateFormsFragmentsWidget behaviorMultipage appsaddApp designaddADDITIONALConnections and secretsaddCustom componentsaddConfiguration and themingaddApp testingaddAPI referenceaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Develop/Concepts/Architecture & execution/Optimize performance with st.cachedeleteDeprecation noticest.cache was deprecated in version 1.18.0. Use st.cache_data or st.cache_resource instead. Learn more in Caching. Optimize performance with st.cache Streamlit provides a caching mechanism that allows your app to stay performant even when loading data from the web, manipulating large datasets, or performing expensive computations. This is done with the @st.cache decorator. When you mark a function with the @st.cache decorator, it tells Streamlit that whenever the function is called it needs to check a few things: The input parameters that you called the function with The value of any external variable used in the function The body of the function The body of any function used inside the cached function If this is the first time Streamlit has seen these four components with these exact values and in this exact combination and order, it runs the function and stores the result in a local cache. Then, next time the cached function is called, if none of these components changed, Streamlit will just skip executing the function altogether and, instead, return the output previously stored in the cache. The way Streamlit keeps track of changes in these components is through hashing. Think of the cache as an in-memory key-value store, where the key is a hash of all of the above and the value is the actual output object passed by reference. Finally, @st.cache supports arguments to configure the cache's behavior. You can find more information on those in our API reference. Let's take a look at a few examples that illustrate how caching works in a Streamlit app. Example 1: Basic usage For starters, let's take a look at a sample app that has a function that performs an expensive, long-running computation. Without caching, this function is rerun each time the app is refreshed, leading to a poor user experience. Copy this code into a new app and try it out yourself: import streamlit as st import time def expensive_computation(a, b): time.sleep(2) # 👈 This makes the function take 2s to run return a * b a = 2 b = 21 res = expensive_computation(a, b) st.write(""Result:"", res) Try pressing R to rerun the app, and notice how long it takes for the result to show up. This is because expensive_computation(a, b) is being re-executed every time the app runs. This isn't a great experience. Let's add the @st.cache decorator: import streamlit as st import time @st.cache # 👈 Added this def expensive_computation(a, b): time.sleep(2) # This makes the function take 2s to run return a * b a = 2 b = 21 res = expensive_computation(a, b) st.write(""Result:"", res) Now run the app again and you'll notice that it is much faster every time you press R to rerun. To understand what is happening, let's add an st.write inside the function: import streamlit as st import time @st.cache(suppress_st_warning=True) # 👈 Changed this def expensive_computation(a, b): # 👇 Added this st.write(""Cache miss: expensive_computation("", a, "","", b, "") ran"") time.sleep(2) # This makes the function take 2s to run return a * b a = 2 b = 21 res = expensive_computation(a, b) st.write(""Result:"", res) Now when you rerun the app the text ""Cache miss"" appears on the first run, but not on any subsequent runs. That's because the cached function is only being executed once, and every time after that you're actually hitting the cache. push_pinNoteYou may have noticed that we've added the suppress_st_warning keyword to the @st.cache decorators. That's because the cached function above uses a Streamlit command itself (st.write in this case), and when Streamlit sees that, it shows a warning that your command will only execute when you get a cache miss. More often than not, when you see that warning it's because there's a bug in your code. However, in our case we're using the st.write command to demonstrate when the cache is being missed, so the behavior Streamlit is warning us about is exactly what we want. As a result, we are passing in suppress_st_warning=True to turn that warning off. Example 2: When the function arguments change Without stopping the previous app server, let's change one of the arguments to our cached function: import streamlit as st import time @st.cache(suppress_st_warning=True) def expensive_computation(a, b): st.write(""Cache miss: expensive_computation("", a, "","", b, "") ran"") time.sleep(2) # This makes the function take 2s to run return a * b a = 2 b = 210 # 👈 Changed this res = expensive_computation(a, b) st.write(""Result:"", res) Now the first time you rerun the app it's a cache miss. This is evidenced by the ""Cache miss"" text showing up and the app taking 2s to finish running. After that, if you press R to rerun, it's always a cache hit. That is, no such text shows up and the app is fast again. This is because Streamlit notices whenever the arguments a and b change and determines whether the function should be re-executed and re-cached. Example 3: When the function body changes Without stopping and restarting your Streamlit server, let's remove the widget from our app and modify the function's code by adding a + 1 to the return value. import streamlit as st import time @st.cache(suppress_st_warning=True) def expensive_computation(a, b): st.write(""Cache miss: expensive_computation("", a, "","", b, "") ran"") time.sleep(2) # This makes the function take 2s to run return a * b + 1 # 👈 Added a +1 at the end here a = 2 b = 210 res = expensive_computation(a, b) st.write(""Result:"", res) The first run is a ""Cache miss"", but when you press R each subsequent run is a cache hit. This is because on first run, Streamlit detected that the function body changed, reran the function, and put the result in the cache. starTipIf you change the function back the result will already be in the Streamlit cache from a previous run. Try it out! Example 4: When an inner function changes Let's make our cached function depend on another function internally: import streamlit as st import time def inner_func(a, b): st.write(""inner_func("", a, "","", b, "") ran"") return a * b @st.cache(suppress_st_warning=True) def expensive_computation(a, b): st.write(""Cache miss: expensive_computation("", a, "","", b, "") ran"") time.sleep(2) # This makes the function take 2s to run return inner_func(a, b) + 1 a = 2 b = 210 res = expensive_computation(a, b) st.write(""Result:"", res) What you see is the usual: The first run results in a cache miss. Every subsequent rerun results in a cache hit. But now let's try modifying the inner_func(): import streamlit as st import time def inner_func(a, b): st.write(""inner_func("", a, "","", b, "") ran"") return a ** b # 👈 Changed the * to ** here @st.cache(suppress_st_warning=True) def expensive_computation(a, b): st.write(""Cache miss: expensive_computation("", a, "","", b, "") ran"") time.sleep(2) # This makes the function take 2s to run return inner_func(a, b) + 1 a = 2 b = 21 res = expensive_computation(a, b) st.write(""Result:"", res) Even though inner_func() is not annotated with @st.cache, when we edit its body we cause a ""Cache miss"" in the outer expensive_computation(). That's because Streamlit always traverses your code and its dependencies to verify that the cached values are still valid. This means that while developing your app you can edit your code freely without worrying about the cache. Any change you make to your app, Streamlit should do the right thing! Streamlit is also smart enough to only traverse dependencies that belong to your app, and skip over any dependency that comes from an installed Python library. Example 5: Use caching to speed up your app across users Going back to our original function, let's add a widget to control the value of b: import streamlit as st import time @st.cache(suppress_st_warning=True) def expensive_computation(a, b): st.write(""Cache miss: expensive_computation("", a, "","", b, "") ran"") time.sleep(2) # This makes the function take 2s to run return a * b a = 2 b = st.slider(""Pick a number"", 0, 10) # 👈 Changed this res = expensive_computation(a, b) st.write(""Result:"", res) What you'll see: If you move the slider to a number Streamlit hasn't seen before, you'll have a cache miss again. And every subsequent rerun with the same number will be a cache hit, of course. If you move the slider back to a number Streamlit has seen before, the cache is hit and the app is fast as expected. In computer science terms, what is happening here is that @st.cache is memoizing expensive_computation(a, b). But now let's go one step further! Try the following: Move the slider to a number you haven't tried before, such as 9. Pretend you're another user by opening another browser tab pointing to your Streamlit app (usually at http://localhost:8501) In the new tab, move the slider to 9. Notice how this is actually a cache hit! That is, you don't actually see the ""Cache miss"" text on the second tab even though that second user never moved the slider to 9 at any point prior to this. This happens because the Streamlit cache is global to all users. So everyone contributes to everyone else's performance. Example 6: Mutating cached values As mentioned in the overview section, the Streamlit cache stores items by reference. This allows the Streamlit cache to support structures that aren't memory-managed by Python, such as TensorFlow objects. However, it can also lead to unexpected behavior — which is why Streamlit has a few checks to guide developers in the right direction. Let's look into those checks now. Let's write an app that has a cached function which returns a mutable object, and then let's follow up by mutating that object: import streamlit as st import time @st.cache(suppress_st_warning=True) def expensive_computation(a, b): st.write(""Cache miss: expensive_computation("", a, "","", b, "") ran"") time.sleep(2) # This makes the function take 2s to run return {""output"": a * b} # 👈 Mutable object a = 2 b = 21 res = expensive_computation(a, b) st.write(""Result:"", res) res[""output""] = ""result was manually mutated"" # 👈 Mutated cached value st.write(""Mutated result:"", res) When you run this app for the first time, you should see three messages on the screen: Cache miss: expensive_computation(...) ran Result: {output: 42} Mutated result: {output: ""result was manually mutated""} No surprises here. But now notice what happens when you rerun you app (i.e. press R): Result: {output: ""result was manually mutated""} Mutated result: {output: ""result was manually mutated""} Cached object mutated. (...) So what's up? What's going on here is that Streamlit caches the output res by reference. When you mutated res[""output""] outside the cached function you ended up inadvertently modifying the cache. This means every subsequent call to expensive_computation(2, 21) will return the wrong value! Since this behavior is usually not what you'd expect, Streamlit tries to be helpful and show you a warning, along with some ideas about how to fix your code. In this specific case, the fix is just to not mutate res[""output""] outside the cached function. There was no good reason for us to do that anyway! Another solution would be to clone the result value with res = deepcopy(expensive_computation(2, 21)). Check out the section entitled Fixing caching issues for more information on these approaches and more. Advanced caching In caching, you learned about the Streamlit cache, which is accessed with the @st.cache decorator. In this article you'll see how Streamlit's caching functionality is implemented, so that you can use it to improve the performance of your Streamlit apps. The cache is a key-value store, where the key is a hash of: The input parameters that you called the function with The value of any external variable used in the function The body of the function The body of any function used inside the cached function And the value is a tuple of: The cached output A hash of the cached output (you'll see why soon) For both the key and the output hash, Streamlit uses a specialized hash function that knows how to traverse code, hash special objects, and can have its behavior customized by the user. For example, when the function expensive_computation(a, b), decorated with @st.cache, is executed with a=2 and b=21, Streamlit does the following: Computes the cache key If the key is found in the cache, then: Extracts the previously-cached (output, output_hash) tuple. Performs an Output Mutation Check, where a fresh hash of the output is computed and compared to the stored output_hash. If the two hashes are different, shows a Cached Object Mutated warning. (Note: Setting allow_output_mutation=True disables this step). If the input key is not found in the cache, then: Executes the cached function (i.e. output = expensive_computation(2, 21)). Calculates the output_hash from the function's output. Stores key → (output, output_hash) in the cache. Returns the output. If an error is encountered an exception is raised. If the error occurs while hashing either the key or the output an UnhashableTypeError error is thrown. If you run into any issues, see fixing caching issues. The hash_funcs parameter As described above, Streamlit's caching functionality relies on hashing to calculate the key for cached objects, and to detect unexpected mutations in the cached result. For added expressive power, Streamlit lets you override this hashing process using the hash_funcs argument. Suppose you define a type called FileReference which points to a file in the filesystem: class FileReference: def __init__(self, filename): self.filename = filename @st.cache def func(file_reference): ... By default, Streamlit hashes custom classes like FileReference by recursively navigating their structure. In this case, its hash is the hash of the filename property. As long as the file name doesn't change, the hash will remain constant. However, what if you wanted to have the hasher check for changes to the file's modification time, not just its name? This is possible with @st.cache's hash_funcs parameter: class FileReference: def __init__(self, filename): self.filename = filename def hash_file_reference(file_reference): filename = file_reference.filename return (filename, os.path.getmtime(filename)) @st.cache(hash_funcs={FileReference: hash_file_reference}) def func(file_reference): ... Additionally, you can hash FileReference objects by the file's contents: class FileReference: def __init__(self, filename): self.filename = filename def hash_file_reference(file_reference): with open(file_reference.filename) as f: return f.read() @st.cache(hash_funcs={FileReference: hash_file_reference}) def func(file_reference): ... push_pinNoteBecause Streamlit's hash function works recursively, you don't have to hash the contents inside hash_file_reference Instead, you can return a primitive type, in this case the contents of the file, and Streamlit's internal hasher will compute the actual hash from it. Typical hash functions While it's possible to write custom hash functions, let's take a look at some of the tools that Python provides out of the box. Here's a list of some hash functions and when it makes sense to use them. Python's id function | Example Speed: Fast Use case: If you're hashing a singleton object, like an open database connection or a TensorFlow session. These are objects that will only be instantiated once, no matter how many times your script reruns. lambda _: None | Example Speed: Fast Use case: If you want to turn off hashing of this type. This is useful if you know the object is not going to change. Python's hash() function | Example Speed: Can be slow based the size of the object being cached Use case: If Python already knows how to hash this type correctly. Custom hash function | Example Speed: N/a Use case: If you'd like to override how Streamlit hashes a particular type. Example 1: Pass a database connection around Suppose we want to open a database connection that can be reused across multiple runs of a Streamlit app. For this you can make use of the fact that cached objects are stored by reference to automatically initialize and reuse the connection: @st.cache(allow_output_mutation=True) def get_database_connection(): return db.get_connection() With just 3 lines of code, the database connection is created once and stored in the cache. Then, every subsequent time get_database_connection is called, the already-created connection object is reused automatically. In other words, it becomes a singleton. starTipUse the allow_output_mutation=True flag to suppress the immutability check. This prevents Streamlit from trying to hash the output connection, and also turns off Streamlit's mutation warning in the process. What if you want to write a function that receives a database connection as input? For that, you'll use hash_funcs: @st.cache(hash_funcs={DBConnection: id}) def get_users(connection): # Note: We assume that connection is of type DBConnection. return connection.execute_sql('SELECT * from Users') Here, we use Python's built-in id function, because the connection object is coming from the Streamlit cache via the get_database_connection function. This means that the same connection instance is passed around every time, and therefore it always has the same id. However, if you happened to have a second connection object around that pointed to an entirely different database, it would still be safe to pass it to get_users because its id is guaranteed to be different than the first id. These design patterns apply any time you have an object that points to an external resource, such as a database connection or Tensorflow session. Example 2: Turn off hashing for a specific type You can turn off hashing entirely for a particular type by giving it a custom hash function that returns a constant. One reason that you might do this is to avoid hashing large, slow-to-hash objects that you know are not going to change. For example: @st.cache(hash_funcs={pd.DataFrame: lambda _: None}) def func(huge_constant_dataframe): ... When Streamlit encounters an object of this type, it always converts the object into None, no matter which instance of FooType its looking at. This means all instances are hash to the same value, which effectively cancels out the hashing mechanism. Example 3: Use Python's hash() function Sometimes, you might want to use Python’s default hashing instead of Streamlit's. For example, maybe you've encountered a type that Streamlit is unable to hash, but it's hashable with Python's built-in hash() function: @st.cache(hash_funcs={FooType: hash}) def func(...): ... Previous: CachingNext: Experimental cache primitivesforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy" https://docs.streamlit.io/develop/api-reference/text/st.text#sttext,"DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceremovePAGE ELEMENTSWrite and magicaddText elementsremoveHEADINGS & BODYst.titlest.headerst.subheaderst.markdownFORMATTED TEXTst.captionst.codest.dividerst.echost.latexst.textData elementsaddChart elementsaddInput widgetsaddMedia elementsaddLayouts and containersaddChat elementsaddStatus elementsaddThird-party componentsopen_in_newAPPLICATION LOGICNavigation and pagesaddExecution flowaddCaching and stateaddConnections and secretsaddCustom componentsaddUtilitiesaddConfigurationaddTOOLSApp testingaddCommand lineaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Develop/API reference/Text elements/st.textst.textStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeWrite fixed-width and preformatted text. Function signature[source] st.text(body, *, help=None) Parameters body (str) The string to display. help (str) An optional tooltip that gets displayed next to the text. Example import streamlit as st st.text('This is some text.') Previous: st.latexNext: Data elementsforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy" https://docs.streamlit.io/develop/api-reference/app-testing/testing-element-classes#multiselectset_value,"DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceremovePAGE ELEMENTSWrite and magicaddText elementsaddData elementsaddChart elementsaddInput widgetsaddMedia elementsaddLayouts and containersaddChat elementsaddStatus elementsaddThird-party componentsopen_in_newAPPLICATION LOGICNavigation and pagesaddExecution flowaddCaching and stateaddConnections and secretsaddCustom componentsaddUtilitiesaddConfigurationaddTOOLSApp testingremovest.testing.v1.AppTestTesting element classesCommand lineaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Develop/API reference/App testing/Testing element classesTesting element classes st.testing.v1.element_tree.Block The Block class has the same methods and attributes as AppTest. A Block instance represents a container of elements just as AppTest represents the entire app. For example, Block.button will produce a WidgetList of Button in the same manner as AppTest.button. ChatMessage, Column, and Tab all inherit from Block. For all container classes, parameters of the original element can be obtained as properties. For example, ChatMessage.avatar and Tab.label. st.testing.v1.element_tree.ElementStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeElement base class for testing. This class's methods and attributes are universal for all elements implemented in testing. For example, Caption, Code, Text, and Title inherit from Element. All widget classes also inherit from Element, but have additional methods specific to each widget type. See the AppTest class for the full list of supported elements. For all element classes, parameters of the original element can be obtained as properties. For example, Button.label, Caption.help, and Toast.icon. Class description[source] st.testing.v1.element_tree.Element(proto, root) Methods run(*, timeout=None) Run the AppTest script which contains the element. Attributes value The value or contents of the element. st.testing.v1.element_tree.ButtonStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.button and st.form_submit_button. Class description[source] st.testing.v1.element_tree.Button(proto, root) Methods click() Set the value of the button to True. run(*, timeout=None) Run the AppTest script which contains the element. set_value(v) Set the value of the button. Attributes value The value of the button. (bool) st.testing.v1.element_tree.ChatInputStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.chat_input. Class description[source] st.testing.v1.element_tree.ChatInput(proto, root) Methods run(*, timeout=None) Run the AppTest script which contains the element. set_value(v) Set the value of the widget. Attributes value The value of the widget. (str) st.testing.v1.element_tree.CheckboxStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.checkbox. Class description[source] st.testing.v1.element_tree.Checkbox(proto, root) Methods check() Set the value of the widget to True. run(*, timeout=None) Run the AppTest script which contains the element. set_value(v) Set the value of the widget. uncheck() Set the value of the widget to False. Attributes value The value of the widget. (bool) st.testing.v1.element_tree.ColorPickerStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.color_picker. Class description[source] st.testing.v1.element_tree.ColorPicker(proto, root) Methods pick(v) Set the value of the widget as a hex string. May omit the ""#"" prefix. run(*, timeout=None) Run the AppTest script which contains the element. set_value(v) Set the value of the widget as a hex string. Attributes value The currently selected value as a hex string. (str) st.testing.v1.element_tree.DateInputStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.date_input. Class description[source] st.testing.v1.element_tree.DateInput(proto, root) Methods run(*, timeout=None) Run the AppTest script which contains the element. set_value(v) Set the value of the widget. Attributes value The value of the widget. (date or Tuple of date) st.testing.v1.element_tree.MultiselectStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.multiselect. Class description[source] st.testing.v1.element_tree.Multiselect(proto, root) Methods run(*, timeout=None) Run the AppTest script which contains the element. select(v) Add a selection to the widget. Do nothing if the value is already selected. If testing a multiselect widget with repeated options, use set_value instead. set_value(v) Set the value of the multiselect widget. (list) unselect(v) Remove a selection from the widget. Do nothing if the value is not already selected. If a value is selected multiple times, the first instance is removed. Attributes format_func The widget's formatting function for displaying options. (callable) indices The indices of the currently selected values from the options. (list) value The currently selected values from the options. (list) st.testing.v1.element_tree.NumberInputStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.number_input. Class description[source] st.testing.v1.element_tree.NumberInput(proto, root) Methods decrement() Decrement the st.number_input widget as if the user clicked ""-"". increment() Increment the st.number_input widget as if the user clicked ""+"". run(*, timeout=None) Run the AppTest script which contains the element. set_value(v) Set the value of the st.number_input widget. Attributes value Get the current value of the st.number_input widget. st.testing.v1.element_tree.RadioStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.radio. Class description[source] st.testing.v1.element_tree.Radio(proto, root) Methods run(*, timeout=None) Run the AppTest script which contains the element. set_value(v) Set the selection by value. Attributes format_func The widget's formatting function for displaying options. (callable) index The index of the current selection. (int) value The currently selected value from the options. (Any) st.testing.v1.element_tree.SelectSliderStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.select_slider. Class description[source] st.testing.v1.element_tree.SelectSlider(proto, root) Methods run(*, timeout=None) Run the AppTest script which contains the element. set_range(lower, upper) Set the ranged selection by values. set_value(v) Set the (single) selection by value. Attributes format_func The widget's formatting function for displaying options. (callable) value The currently selected value or range. (Any or Sequence of Any) st.testing.v1.element_tree.SelectboxStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.selectbox. Class description[source] st.testing.v1.element_tree.Selectbox(proto, root) Methods run(*, timeout=None) Run the AppTest script which contains the element. select(v) Set the selection by value. select_index(index) Set the selection by index. set_value(v) Set the selection by value. Attributes format_func The widget's formatting function for displaying options. (callable) index The index of the current selection. (int) value The currently selected value from the options. (Any) st.testing.v1.element_tree.SliderStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.slider. Class description[source] st.testing.v1.element_tree.Slider(proto, root) Methods run(*, timeout=None) Run the AppTest script which contains the element. set_range(lower, upper) Set the ranged value of the slider. set_value(v) Set the (single) value of the slider. Attributes value The currently selected value or range. (Any or Sequence of Any) st.testing.v1.element_tree.TextAreaStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.text_area. Class description[source] st.testing.v1.element_tree.TextArea(proto, root) Methods input(v) Set the value of the widget only if the value does not exceed the maximum allowed characters. run(*, timeout=None) Run the AppTest script which contains the element. set_value(v) Set the value of the widget. Attributes value The current value of the widget. (str) st.testing.v1.element_tree.TextInputStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.text_input. Class description[source] st.testing.v1.element_tree.TextInput(proto, root) Methods input(v) Set the value of the widget only if the value does not exceed the maximum allowed characters. run(*, timeout=None) Run the AppTest script which contains the element. set_value(v) Set the value of the widget. Attributes value The current value of the widget. (str) st.testing.v1.element_tree.TimeInputStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.time_input. Class description[source] st.testing.v1.element_tree.TimeInput(proto, root) Methods decrement() Select the previous available time. increment() Select the next available time. run(*, timeout=None) Run the AppTest script which contains the element. set_value(v) Set the value of the widget. Attributes value The current value of the widget. (time) st.testing.v1.element_tree.ToggleStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.toggle. Class description[source] st.testing.v1.element_tree.Toggle(proto, root) Methods run(*, timeout=None) Run the AppTest script which contains the element. set_value(v) Set the value of the widget. Attributes value The current value of the widget. (bool) Previous: st.testing.v1.AppTestNext: Command lineforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy" https://docs.streamlit.io/develop/concepts/custom-components#how-to-use-a-component,"DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsremoveCOREArchitecture & executionaddMultipage appsaddApp designaddADDITIONALConnections and secretsaddCustom componentsremoveIntro to custom componentsCreate a ComponentPublish a ComponentLimitationsComponent galleryopen_in_newConfiguration and themingaddApp testingaddAPI referenceaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Develop/Concepts/Custom componentsCustom Components Components are third-party Python modules that extend what's possible with Streamlit. How to use a Component Components are super easy to use: Start by finding the Component you'd like to use. Two great resources for this are: The Component gallery This thread, by Fanilo A. from our forums. Install the Component using your favorite Python package manager. This step and all following steps are described in your component's instructions. For example, to use the fantastic AgGrid Component, you first install it with: pip install streamlit-aggrid In your Python code, import the Component as described in its instructions. For AgGrid, this step is: from st_aggrid import AgGrid ...now you're ready to use it! For AgGrid, that's: AgGrid(my_dataframe) Making your own Component If you're interested in making your own component, check out the following resources: Create a Component Publish a Component Components API Blog post for when we launched Components! Alternatively, if you prefer to learn using videos, our engineer Tim Conkling has put together some amazing tutorials: Video tutorial, part 1 Video tutorial, part 2 Previous: Connections and secretsNext: Intro to custom componentsforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy" https://docs.streamlit.io/develop/tutorials/databases/mssql#write-your-streamlit-app,"DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceaddTutorialsremoveExecution flowaddConnect to data sourcesremoveAWS S3BigQueryDeta BaseFirestoreopen_in_newGoogle Cloud StorageMicrosoft SQL ServerMongoDBMySQLNeonPostgreSQLPrivate Google SheetPublic Google SheetSnowflakeSupabaseTableauTiDBTigerGraphMultipage appsaddWork with LLMsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Develop/Tutorials/Connect to data sources/Microsoft SQL ServerConnect Streamlit to Microsoft SQL Server Introduction This guide explains how to securely access a remote Microsoft SQL Server database from Streamlit Community Cloud. It uses the pyodbc library and Streamlit's Secrets management. Create an SQL Server database push_pinNoteIf you already have a remote database that you want to use, feel free to skip to the next step. First, follow the Microsoft documentation to install SQL Server and the sqlcmd Utility. They have detailed installation guides on how to: Install SQL Server on Windows Install on Red Hat Enterprise Linux Install on SUSE Linux Enterprise Server Install on Ubuntu Run on Docker Provision a SQL VM in Azure Once you have SQL Server installed, note down your SQL Server name, username, and password during setup. Connect locally If you are connecting locally, use sqlcmd to connect to your new local SQL Server instance. In your terminal, run the following command: sqlcmd -S localhost -U SA -P '' As you are connecting locally, the SQL Server name is localhost, the username is SA, and the password is the one you provided during the SA account setup. You should see a sqlcmd command prompt 1>, if successful. If you run into a connection failure, review Microsoft's connection troubleshooting recommendations for your OS (Linux & Windows). starTipWhen connecting remotely, the SQL Server name is the machine name or IP address. You might also need to open the SQL Server TCP port (default 1433) on your firewall. Create a SQL Server database By now, you have SQL Server running and have connected to it with sqlcmd! 🥳 Let's put it to use by creating a database containing a table with some example values. From the sqlcmd command prompt, run the following Transact-SQL command to create a test database mydb: CREATE DATABASE mydb To execute the above command, type GO on a new line: GO Insert some data Next create a new table, mytable, in the mydb database with three columns and two rows. Switch to the new mydb database: USE mydb Create a new table with the following schema: CREATE TABLE mytable (name varchar(80), pet varchar(80)) Insert some data into the table: INSERT INTO mytable VALUES ('Mary', 'dog'), ('John', 'cat'), ('Robert', 'bird') Type GO to execute the above commands: GO To end your sqlcmd session, type QUIT on a new line. Add username and password to your local app secrets Your local Streamlit app will read secrets from a file .streamlit/secrets.toml in your app's root directory. Create this file if it doesn't exist yet and add the SQL Server name, database name, username, and password as shown below: # .streamlit/secrets.toml server = ""localhost"" database = ""mydb"" username = ""SA"" password = ""xxx"" priority_highImportantWhen copying your app secrets to Streamlit Community Cloud, be sure to replace the values of server, database, username, and password with those of your remote SQL Server!And add this file to .gitignore and don't commit it to your GitHub repo. Copy your app secrets to Streamlit Community Cloud As the secrets.toml file above is not committed to GitHub, you need to pass its content to your deployed app (on Streamlit Community Cloud) separately. Go to the app dashboard and in the app's dropdown menu, click on Edit Secrets. Copy the content of secrets.toml into the text area. More information is available at Secrets management. Add pyodbc to your requirements file To connect to SQL Server locally with Streamlit, you need to pip install pyodbc, in addition to the Microsoft ODBC driver you installed during the SQL Server installation. On Streamlit Cloud, we have built-in support for SQL Server. On popular demand, we directly added SQL Server tools including the ODBC drivers and the executables sqlcmd and bcp to the container image for Cloud apps, so you don't need to install them. All you need to do is add the pyodbc Python package to your requirements.txt file, and you're ready to go! 🎈 # requirements.txt pyodbc==x.x.x Replace x.x.x ☝️ with the version of pyodbc you want installed on Cloud. push_pinNoteAt this time, Streamlit Community Cloud does not support Azure Active Directory authentication. We will update this tutorial when we add support for Azure Active Directory. Write your Streamlit app Copy the code below to your Streamlit app and run it. Make sure to adapt query to use the name of your table. import streamlit as st import pyodbc # Initialize connection. # Uses st.cache_resource to only run once. @st.cache_resource def init_connection(): return pyodbc.connect( ""DRIVER={ODBC Driver 17 for SQL Server};SERVER="" + st.secrets[""server""] + "";DATABASE="" + st.secrets[""database""] + "";UID="" + st.secrets[""username""] + "";PWD="" + st.secrets[""password""] ) conn = init_connection() # Perform query. # Uses st.cache_data to only rerun when the query changes or after 10 min. @st.cache_data(ttl=600) def run_query(query): with conn.cursor() as cur: cur.execute(query) return cur.fetchall() rows = run_query(""SELECT * from mytable;"") # Print results. for row in rows: st.write(f""{row[0]} has a :{row[1]}:"") See st.cache_data above? Without it, Streamlit would run the query every time the app reruns (e.g. on a widget interaction). With st.cache_data, it only runs when the query changes or after 10 minutes (that's what ttl is for). Watch out: If your database updates more frequently, you should adapt ttl or remove caching so viewers always see the latest data. Learn more in Caching. If everything worked out (and you used the example table we created above), your app should look like this: Previous: Google Cloud StorageNext: MongoDBforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy" https://docs.streamlit.io/knowledge-base/using-streamlit/pydeck-chart-custom-mapbox-styles#how-can-i-make-stpydeck_chart-use-custom-mapbox-styles,"DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Knowledge base/FAQ/How can I make st.pydeck_chart use custom Mapbox styles?How can I make st.pydeck_chart use custom Mapbox styles? If you are supplying a Mapbox token, but the resulting pydeck_chart doesn't show your custom Mapbox styles, please check that you are adding the Mapbox token to the Streamlit config.toml configuration file. Streamlit DOES NOT read Mapbox tokens from inside of a PyDeck specification (i.e. from inside of the Streamlit app). Please see this forum thread for more information.Previous: How to insert elements out of order?Next: How to remove ""· Streamlit"" from the app title?forumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy" https://docs.streamlit.io/develop/concepts/connections/connecting-to-data#a-simple-starting-point---using-a-local-sqlite-database,"DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsremoveCOREArchitecture & executionaddMultipage appsaddApp designaddADDITIONALConnections and secretsremoveConnecting to dataSecrets managementSecurity remindersCustom componentsaddConfiguration and themingaddApp testingaddAPI referenceaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Develop/Concepts/Connections and secrets/Connecting to dataConnecting to data Most Streamlit apps need some kind of data or API access to be useful - either retrieving data to view or saving the results of some user action. This data or API is often part of some remote service, database, or other data source. Anything you can do with Python, including data connections, will generally work in Streamlit. Streamlit's tutorials are a great starting place for many data sources. However: Connecting to data in a Python application is often tedious and annoying. There are specific considerations for connecting to data from streamlit apps, such as caching and secrets management. Streamlit provides st.connection() to more easily connect your Streamlit apps to data and APIs with just a few lines of code. This page provides a basic example of using the feature and then focuses on advanced usage. For a comprehensive overview of this feature, check out this video tutorial by Joshua Carroll, Streamlit's Product Manager for Developer Experience. You'll learn about the feature's utility in creating and managing data connections within your apps by using real-world examples. Basic usage For basic startup and usage examples, read up on the relevant data source tutorial. Streamlit has built-in connections to SQL dialects and Snowflake. We also maintain installable connections for Cloud File Storage and Google Sheets. If you are just starting, the best way to learn is to pick a data source you can access and get a minimal example working from one of the pages above 👆. Here, we will provide an ultra-minimal usage example for using a SQLite database. From there, the rest of this page will focus on advanced usage. A simple starting point - using a local SQLite database A local SQLite database could be useful for your app's semi-persistent data storage. push_pinNoteCommunity Cloud apps do not guarantee the persistence of local file storage, so the platform may delete data stored using this technique at any time. To see the example below running live, check out the interactive demo below: Built with Streamlit 🎈Fullscreen open_in_new Step 1: Install prerequisite library - SQLAlchemy All SQLConnections in Streamlit use SQLAlchemy. For most other SQL dialects, you also need to install the driver. But the SQLite driver ships with python3, so it isn't necessary. pip install SQLAlchemy==1.4.0 Step 2: Set a database URL in your Streamlit secrets.toml file Create a directory and file .streamlit/secrets.toml in the same directory your app will run from. Add the following to the file. # .streamlit/secrets.toml [connections.pets_db] url = ""sqlite:///pets.db"" Step 3: Use the connection in your app The following app creates a connection to the database, uses it to create a table and insert some data, then queries the data back and displays it in a data frame. # streamlit_app.py import streamlit as st # Create the SQL connection to pets_db as specified in your secrets file. conn = st.connection('pets_db', type='sql') # Insert some data with conn.session. with conn.session as s: s.execute('CREATE TABLE IF NOT EXISTS pet_owners (person TEXT, pet TEXT);') s.execute('DELETE FROM pet_owners;') pet_owners = {'jerry': 'fish', 'barbara': 'cat', 'alex': 'puppy'} for k in pet_owners: s.execute( 'INSERT INTO pet_owners (person, pet) VALUES (:owner, :pet);', params=dict(owner=k, pet=pet_owners[k]) ) s.commit() # Query and display the data you inserted pet_owners = conn.query('select * from pet_owners') st.dataframe(pet_owners) In this example, we didn't set a ttl= value on the call to conn.query(), meaning Streamlit caches the result indefinitely as long as the app server runs. Now, on to more advanced topics! 🚀 Advanced topics Global secrets, managing multiple apps and multiple data stores Streamlit supports a global secrets file specified in the user's home directory, such as ~/.streamlit/secrets.toml. If you build or manage multiple apps, we recommend using a global credential or secret file for local development across apps. With this approach, you only need to set up and manage your credentials in one place, and connecting a new app to your existing data sources is effectively a one-liner. It also reduces the risk of accidentally checking in your credentials to git since they don't need to exist in the project repository. For cases where you have multiple similar data sources that you connect to during local development (such as a local vs. staging database), you can define different connection sections in your secrets or credentials file for different environments and then decide which to use at runtime. st.connection supports this with the name=env: syntax. E.g., say I have a local and a staging MySQL database and want to connect my app to either at different times. I could create a global secrets file like this: # ~/.streamlit/secrets.toml [connections.local] url = ""mysql://me:****@localhost:3306/local_db"" [connections.staging] url = ""mysql://jdoe:******@staging.acmecorp.com:3306/staging_db"" Then I can configure my app connection to take its name from a specified environment variable # streamlit_app.py import streamlit as st conn = st.connection(""env:DB_CONN"", ""sql"") df = conn.query(""select * from mytable"") # ... Now I can specify whether to connect to local or staging at runtime by setting the DB_CONN environment variable. # connect to local DB_CONN=local streamlit run streamlit_app.py # connect to staging DB_CONN=staging streamlit run streamlit_app.py Advanced SQLConnection configuration The SQLConnection configuration uses SQLAlchemy create_engine() function. It will take a single URL argument or attempt to construct a URL from several parts (username, database, host, and so on) using SQLAlchemy.engine.URL.create(). Several popular SQLAlchemy dialects, such as Snowflake and Google BigQuery, can be configured using additional arguments to create_engine() besides the URL. These can be passed as **kwargs to the st.connection call directly or specified in an additional secrets section called create_engine_kwargs. E.g. snowflake-sqlalchemy takes an additional connect_args argument as a dictionary for configuration that isn’t supported in the URL. These could be specified as follows: # .streamlit/secrets.toml [connections.snowflake] url = ""snowflake://@/"" [connections.snowflake.create_engine_kwargs.connect_args] authenticator = ""externalbrowser"" warehouse = ""xxx"" role = ""xxx"" # streamlit_app.py import streamlit as st # url and connect_args from secrets.toml above are picked up and used here conn = st.connection(""snowflake"", ""sql"") # ... Alternatively, this could be specified entirely in **kwargs. # streamlit_app.py import streamlit as st # secrets.toml is not needed conn = st.connection( ""snowflake"", ""sql"", url = ""snowflake://@/"", connect_args = dict( authenticator = ""externalbrowser"", warehouse = ""xxx"", role = ""xxx"", ) ) # ... You can also provide both kwargs and secrets.toml values, and they will be merged (typically, kwargs take precedence). Connection considerations in frequently used or long-running apps By default, connection objects are cached without expiration using st.cache_resource. In most cases this is desired. You can do st.connection('myconn', type=MyConnection, ttl=) if you want the connection object to expire after some time. Many connection types are expected to be long-running or completely stateless, so expiration is unnecessary. Suppose a connection becomes stale (such as a cached token expiring or a server-side connection being closed). In that case, every connection has a reset() method, which will invalidate the cached version and cause Streamlit to recreate the connection the next time it is retrieved Convenience methods like query() and read() will typically cache results by default using st.cache_data without an expiration. When an app can run many different read operations with large results, it can cause high memory usage over time and results to become stale in a long-running app, the same as with any other usage of st.cache_data. For production use cases, we recommend setting an appropriate ttl on these read operations, such as conn.read('path/to/file', ttl=""1d""). Refer to Caching for more information. For apps that could get significant concurrent usage, ensure that you understand any thread safety implications of your connection, particularly when using a connection built by a third party. Connections built by Streamlit should provide thread-safe operations by default. Build your own connection Building your own basic connection implementation using an existing driver or SDK is quite straightforward in most cases. However, you can add more complex functionality with further effort. This custom implementation can be a great way to extend support to a new data source and contribute to the Streamlit ecosystem. Maintaining a tailored internal Connection implementation across many apps can be a powerful practice for organizations with frequently used access patterns and data sources. Check out the Build your own Connection page in the st.experimental connection demo app below for a quick tutorial and working implementation. This demo builds a minimal but very functional Connection on top of DuckDB. Built with Streamlit 🎈Fullscreen open_in_new The typical steps are: Declare the Connection class, extending ExperimentalBaseConnection with the type parameter bound to the underlying connection object: from streamlit.connections import ExperimentalBaseConnection import duckdb class DuckDBConnection(ExperimentalBaseConnection[duckdb.DuckDBPyConnection]) Implement the _connect method that reads any kwargs, external config/credential locations, and Streamlit secrets to initialize the underlying connection: def _connect(self, **kwargs) -> duckdb.DuckDBPyConnection: if 'database' in kwargs: db = kwargs.pop('database') else: db = self._secrets['database'] return duckdb.connect(database=db, **kwargs) Add useful helper methods that make sense for your connection (wrapping them in st.cache_data where caching is desired) Connection-building best practices We recommend applying the following best practices to make your Connection consistent with the Connections built into Streamlit and the wider Streamlit ecosystem. These practices are especially important for Connections that you intend to distribute publicly. Extend existing drivers or SDKs, and default to semantics that makes sense for their existing users. You should rarely need to implement complex data access logic from scratch when building a Connection. Use existing popular Python drivers and clients whenever possible. Doing so makes your Connection easier to maintain, more secure, and enables users to get the latest features. E.g. SQLConnection extends SQLAlchemy, FileConnection extends fsspec, GsheetsConnection extends gspread, etc. Consider using access patterns, method/argument naming, and return values that are consistent with the underlying package and familiar to existing users of that package. Intuitive, easy to use read methods. Much of the power of st.connection is providing intuitive, easy-to-use read methods that enable app developers to get started quickly. Most connections should expose at least one read method that is: Named with a simple verb, like read(), query(), or get() Wrapped by st.cache_data by default, with at least ttl= argument supported If the result is in a tabular format, it returns a pandas DataFrame Provides commonly used keyword arguments (such as paging or formatting) with sensible defaults - ideally, the common case requires only 1-2 arguments. Config, secrets, and precedence in _connect method. Every Connection should support commonly used connection parameters provided via Streamlit secrets and keyword arguments. The names should match the ones used when initializing or configuring the underlying package. Additionally, where relevant, Connections should support data source specific configuration through existing standard environment variables or config / credential files. In many cases, the underlying package provides constructors or factory functions that already handle this easily. When you can specify the same connection parameters in multiple places, we recommend using the following precedence order when possible (highest to lowest): Keyword arguments specified in the code Streamlit secrets data source specific configuration (if relevant) Handling thread safety and stale connections. Connections should provide thread-safe operations when practical (which should be most of the time) and clearly document any considerations around this. Most underlying drivers or SDKs should provide thread-safe objects or methods - use these when possible. If the underlying driver or SDK has a risk of stateful connection objects becoming stale or invalid, consider building a low impact health check or reset/retry pattern into the access methods. The SQLConnection built into Streamlit has a good example of this pattern using tenacity and the built-in Connection.reset() method. An alternate approach is to encourage developers to set an appropriate TTL on the st.connection() call to ensure it periodically reinitializes the connection object. Previous: Connections and secretsNext: Secrets managementforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy" https://docs.streamlit.io/develop/tutorials/databases/snowflake#connecting-to-snowflake-from-community-cloud,"DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceaddTutorialsremoveExecution flowaddConnect to data sourcesremoveAWS S3BigQueryDeta BaseFirestoreopen_in_newGoogle Cloud StorageMicrosoft SQL ServerMongoDBMySQLNeonPostgreSQLPrivate Google SheetPublic Google SheetSnowflakeSupabaseTableauTiDBTigerGraphMultipage appsaddWork with LLMsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Develop/Tutorials/Connect to data sources/SnowflakeConnect Streamlit to Snowflake Introduction This guide explains how to securely access a Snowflake database from Streamlit. It uses st.connection, the Snowpark library and Streamlit's Secrets management. The below example code will only work on Streamlit version >= 1.28, when st.connection was added. Create a Snowflake database push_pinNoteIf you already have a database that you want to use, feel free to skip to the next step. First, sign up for Snowflake and log into the Snowflake web interface (note down your username, password, and account identifier!): Enter the following queries into the SQL editor in the Worksheets page to create a database and a table with some example values: CREATE DATABASE PETS; CREATE TABLE MYTABLE ( NAME varchar(80), PET varchar(80) ); INSERT INTO MYTABLE VALUES ('Mary', 'dog'), ('John', 'cat'), ('Robert', 'bird'); SELECT * FROM MYTABLE; Before you execute the queries, first determine which Snowflake UI / web interface you're using. The examples below use Snowsight. You can also use Classic Console Worksheets or any other means of running Snowflake SQL statements. Execute queries in a Worksheet To execute the queries in a Worksheet, highlight or select all the queries with your mouse, and click the play button in the top right corner. priority_highImportantBe sure to highlight or select all the queries (lines 1-10) before clicking the play button. Once you have executed the queries, you should see a preview of the table in the Results panel at the bottom of the page. Additionally, you should see your newly created database and schema by expanding the accordion on the left side of the page. Lastly, the warehouse name is displayed on the button to the left of the Share button. Make sure to note down the name of your warehouse, database, and schema. ☝️ Install snowflake-snowpark-python You can find the instructions and prerequisites for installing snowflake-snowpark-python in the Snowflake Developer Guide. pip install snowflake-snowpark-python Add connection parameters to your local app secrets Your local Streamlit app will read secrets from a file .streamlit/secrets.toml in your app’s root directory. Learn more about Streamlit secrets management here. Create this file if it doesn’t exist yet and add your Snowflake username, password, account identifier, and the name of your warehouse, database, and schema as shown below: # .streamlit/secrets.toml [connections.snowflake] account = ""xxx"" user = ""xxx"" password = ""xxx"" role = ""xxx"" warehouse = ""xxx"" database = ""xxx"" schema = ""xxx"" client_session_keep_alive = true If you created the database from the previous step, the names of your database and schema are PETS and PUBLIC, respectively. Streamlit will also use Snowflake config and credentials from a SnowSQL config file if available. priority_highImportantAdd this file to .gitignore and don't commit it to your GitHub repo! Write your Streamlit app Copy the code below to your Streamlit app and run it. Make sure to adapt the query to use the name of your table. # streamlit_app.py import streamlit as st # Initialize connection. conn = st.connection(""snowflake"") # Perform query. df = conn.query(""SELECT * from mytable;"", ttl=600) # Print results. for row in df.itertuples(): st.write(f""{row.NAME} has a :{row.PET}:"") See st.connection above? This handles secrets retrieval, setup, query caching and retries. By default, query() results are cached without expiring. In this case, we set ttl=600 to ensure the query result is cached for no longer than 10 minutes. You can also set ttl=0 to disable caching. Learn more in Caching. If everything worked out (and you used the example table we created above), your app should look like this: Using a Snowpark Session The same SnowflakeConnection used above also provides access to the Snowpark Session for DataFrame-style operations that run natively inside Snowflake. Using this approach, you can rewrite the app above as follows: # streamlit_app.py import streamlit as st # Initialize connection. conn = st.connection(""snowflake"") # Load the table as a dataframe using the Snowpark Session. @st.cache_data def load_table(): session = conn.session() return session.table(""mytable"").to_pandas() df = load_table() # Print results. for row in df.itertuples(): st.write(f""{row.NAME} has a :{row.PET}:"") If everything worked out (and you used the example table we created above), your app should look the same as the screenshot from the first example above. Connecting to Snowflake from Community Cloud This tutorial assumes a local Streamlit app, however you can also connect to Snowflake from apps hosted in Community Cloud. The main additional steps are: Include information about dependencies using a requirements.txt file with snowflake-snowpark-python and any other dependencies. Add your secrets to your Community Cloud app. Previous: Public Google SheetNext: SupabaseforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy" https://docs.streamlit.io/deploy/streamlit-community-cloud/get-started/explore-your-workspace,"DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudremoveGet startedremoveQuickstartCreate your accountConnect your GitHub accountExplore your workspaceFork and edit a public appTrust and securityDeploy your appaddManage your appaddShare your appaddManage your accountaddTroubleshootingStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Deploy/Streamlit Community Cloud/Get started/Explore your workspaceExplore your workspace If you just created your account, congrats! You are now logged in and ready to go. If you are joining someone else's workspace you may already see apps populated in your workspace. If not, then you need to deploy an app! Check out our next section on how to Deploy your app. If you need an app to deploy, check out our App gallery which includes apps for machine learning, data science, and business use cases. Switching workspaces You may also find that you already have access to multiple Streamlit Community Cloud workspaces. Streamlit Community Cloud automatically groups your apps according to the corresponding GitHub repository's owner or organzation. In the upper-right corner you can see the workspaces you have access to. If apps have already been deployed from any of your repositories, then you will see those apps when you select the associated workspace in the upper-right corner. Learn more about how to Manage your app from your workspace. New app button Your workspace is your base of operations to deploy apps and manage them. You can click on ""New app"" to Deploy your app from a repository where you have administrative privileges. If you want additional options, click the down arrow (expand_more) to begin with a template. ""Use existing repo"" is the default to Deploy your app from a repository where you have administrative privileges. ""Create from sample app template"" will fork and deploy a simple, one-page Streamlit app. ""Create new app with GitHub Codespaces"" will fork and deploy our multipage Streamlit Hello app and create a codespace. To jump quickly into GitHub Codespaces for any of your deployed apps, see Edit your app with GitHub Codespaces instead. Invite other developers to your workspace Inviting other developers is simple, just invite them to your GitHub repository so that you can code on apps together, and then have them log in to share.streamlit.io/signup. Read more about connecting to a GitHub organization in Organization access. Streamlit Community Cloud inherits developer permissions from GitHub so when others sign in, they will automatically see the workspaces they share with you. From there you can all deploy, manage, and share apps together. push_pinNoteOnce a user is added to a repository on GitHub, it will take at most 15 minutes before they can deploy the app on Cloud. If a user is removed from a repository on GitHub, it will take at most 15 minutes before their permissions to manage the app from that repository are revoked. And remember, whenever anyone on the team updates the code on GitHub, the app will also automatically update for you!Previous: Connect your GitHub accountNext: Fork and edit a public appforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy" https://docs.streamlit.io/develop/api-reference/status/st.status,"DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceremovePAGE ELEMENTSWrite and magicaddText elementsaddData elementsaddChart elementsaddInput widgetsaddMedia elementsaddLayouts and containersaddChat elementsaddStatus elementsremoveCALLOUTSst.successst.infost.warningst.errorst.exceptionOTHERst.progressst.spinnerst.statusst.toastst.balloonsst.snowThird-party componentsopen_in_newAPPLICATION LOGICNavigation and pagesaddExecution flowaddCaching and stateaddConnections and secretsaddCustom componentsaddUtilitiesaddConfigurationaddTOOLSApp testingaddCommand lineaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Develop/API reference/Status elements/st.statusst.statusStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeInsert a status container to display output from long-running tasks. Inserts a container into your app that is typically used to show the status and details of a process or task. The container can hold multiple elements and can be expanded or collapsed by the user similar to st.expander. When collapsed, all that is visible is the status icon and label. The label, state, and expanded state can all be updated by calling .update() on the returned object. To add elements to the returned container, you can use with notation (preferred) or just call methods directly on the returned object. By default, st.status() initializes in the ""running"" state. When called using with notation, it automatically updates to the ""complete"" state at the end of the ""with"" block. See examples below for more details. Function signature[source] st.status(label, *, expanded=False, state=""running"") Parameters label (str) The initial label of the status container. The label can optionally contain Markdown and supports the following elements: Bold, Italics, Strikethroughs, Inline Code, Emojis, and Links. This also supports: Emoji shortcodes, such as :+1: and :sunglasses:. For a list of all supported codes, see https://share.streamlit.io/streamlit/emoji-shortcodes. LaTeX expressions, by wrapping them in ""$"" or ""$$"" (the ""$$"" must be on their own lines). Supported LaTeX functions are listed at https://katex.org/docs/supported.html. Colored text and background colors for text, using the syntax :color[text to be colored] and :color-background[text to be colored], respectively. color must be replaced with any of the following supported colors: blue, green, orange, red, violet, gray/grey, rainbow. For example, you can use :orange[your text here] or :blue-background[your text here]. Unsupported elements are unwrapped so only their children (text contents) render. Display unsupported elements as literal characters by backslash-escaping them. E.g. 1\. Not an ordered list. expanded (bool) If True, initializes the status container in ""expanded"" state. Defaults to False (collapsed). state (""running"", ""complete"", or ""error"") The initial state of the status container which determines which icon is shown: running (default): A spinner icon is shown. complete: A checkmark icon is shown. error: An error icon is shown. Returns(StatusContainer) A mutable status container that can hold multiple elements. The label, state, and expanded state can be updated after creation via .update(). Examples You can use the with notation to insert any element into an status container: import time import streamlit as st with st.status(""Downloading data...""): st.write(""Searching for data..."") time.sleep(2) st.write(""Found URL."") time.sleep(1) st.write(""Downloading data..."") time.sleep(1) st.button(""Rerun"") Built with Streamlit 🎈Fullscreen open_in_new You can also use .update() on the container to change the label, state, or expanded state: import time import streamlit as st with st.status(""Downloading data..."", expanded=True) as status: st.write(""Searching for data..."") time.sleep(2) st.write(""Found URL."") time.sleep(1) st.write(""Downloading data..."") time.sleep(1) status.update(label=""Download complete!"", state=""complete"", expanded=False) st.button(""Rerun"") Built with Streamlit 🎈Fullscreen open_in_new StatusContainer.updateStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeUpdate the status container. Only specified arguments are updated. Container contents and unspecified arguments remain unchanged. Function signature[source] StatusContainer.update(*, label=None, expanded=None, state=None) Parameters label (str or None) A new label of the status container. If None, the label is not changed. expanded (bool or None) The new expanded state of the status container. If None, the expanded state is not changed. state (""running"", ""complete"", ""error"", or None) The new state of the status container. This mainly changes the icon. If None, the state is not changed. Previous: st.spinnerNext: st.toastforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy" https://docs.streamlit.io/develop/tutorials/execution-flow/start-and-stop-fragment-auto-reruns#summary,"DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceaddTutorialsremoveExecution flowremoveFRAGMENTSRerun your app from a fragmentCreate a multiple-container fragmentStart and stop a streaming fragmentConnect to data sourcesaddMultipage appsaddWork with LLMsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Develop/Tutorials/Execution flow/Start and stop a streaming fragmentStart and stop a streaming fragment Streamlit lets you turn functions into fragments, which can rerun independently from the full script. Additionally, you can tell Streamlit to rerun a fragment at a set time interval. This is great for streaming data or monitoring processes. You may want the user to start and stop this live streaming. To do this, programmatically set the run_every parameter for your fragment. Applied concepts Use a fragment to stream live data. Start and stop a fragment from automatically rerunning. Prerequisites streamlit>=1.33.0 This tutorial uses fragments, which require Streamlit version 1.33.0 or later. This tutorial assumes you have a clean working directory called your-repository. You should have a basic understanding of fragments. Summary In this example, you'll build an app that streams two data series in a line chart. Your app will gather recent data on the first load of a session and statically display the line chart. Two buttons in the sidebar will allow users to start and stop data streaming to update the chart in real time. You'll use a fragment to manage the frequency and scope of the live updates. Here's a look at what you'll build: Complete codeexpand_moreimport streamlit as st import pandas as pd import numpy as np from datetime import datetime, timedelta def get_recent_data(last_timestamp): """"""Generate and return data from last timestamp to now, at most 60 seconds."""""" now = datetime.now() if now - last_timestamp > timedelta(seconds=60): last_timestamp = now - timedelta(seconds=60) sample_time = timedelta(seconds=0.5) # time between data points next_timestamp = last_timestamp + sample_time timestamps = np.arange(next_timestamp, now, sample_time) sample_values = np.random.randn(len(timestamps), 2) data = pd.DataFrame(sample_values, index=timestamps, columns=[""A"", ""B""]) return data if ""data"" not in st.session_state: st.session_state.data = get_recent_data(datetime.now() - timedelta(seconds=60)) if ""stream"" not in st.session_state: st.session_state.stream = False def toggle_streaming(): st.session_state.stream = not st.session_state.stream st.title(""Data feed"") st.sidebar.slider( ""Check for updates every: (seconds)"", 0.5, 5.0, value=1.0, key=""run_every"" ) st.sidebar.button( ""Start streaming"", disabled=st.session_state.stream, on_click=toggle_streaming ) st.sidebar.button( ""Stop streaming"", disabled=not st.session_state.stream, on_click=toggle_streaming ) if st.session_state.stream is True: run_every = st.session_state.run_every else: run_every = None @st.experimental_fragment(run_every=run_every) def show_latest_data(): last_timestamp = st.session_state.data.index[-1] st.session_state.data = pd.concat( [st.session_state.data, get_recent_data(last_timestamp)] ) st.session_state.data = st.session_state.data[-100:] st.line_chart(st.session_state.data) show_latest_data() Built with Streamlit 🎈Fullscreen open_in_new Build the example Initialize your app In your_repository, create a file named app.py. In a terminal, change directories to your_repository and start your app. streamlit run app.py Your app will be blank since you still need to add code. In app.py, write the following: import streamlit as st import pandas as pd import numpy as np from datetime import datetime, timedelta You'll be using these libraries as follows: You'll work with two data series in a pandas.DataFrame. You'll generate random data with numpy. The data will have datetime.datetime index values. Save your app.py file and view your running app. Click ""Always rerun"" or hit your ""A"" key in your running app. Your running preview will automatically update as you save changes to app.py. Your preview will still be blank. Return to your code. Build a function to generate random, recent data To begin with, you'll define a function to randomly generate some data for two time series, which you'll call ""A"" and ""B."" It's okay to skip this section if you just want to copy the function. Complete function to randomly generate sales dataexpand_moredef get_recent_data(last_timestamp): """"""Generate and return data from last timestamp to now, at most 60 seconds."""""" now = datetime.now() if now - last_timestamp > timedelta(seconds=60): last_timestamp = now - timedelta(seconds=60) sample_time = timedelta(seconds=0.5) # time between data points next_timestamp = last_timestamp + sample_time timestamps = np.arange(next_timestamp, now, sample_time) sample_values = np.random.randn(len(timestamps), 2) data = pd.DataFrame(sample_values, index=timestamps, columns=[""A"", ""B""]) return data Start your function definition. def get_recent_data(last_timestamp): """"""Generate and return data from last timestamp to now, at most 60 seconds."""""" You'll pass the timestamp of your most recent datapoint to your data-generating function. Your function will use this to only return new data. Get the current time and adjust the last timestamp if it is over 60 seconds ago. now = datetime.now() if now - last_timestamp > timedelta(seconds=60): last_timestamp = now - timedelta(seconds=60) By updating the last timestamp, you'll ensure the function never returns more than 60 seconds of data. Declare a new variable, sample_time, to define the time between datapoints. Calculate the timestamp of the first, new datapoint. sample_time = timedelta(seconds=0.5) # time between data points next_timestamp = last_timestamp + sample_time Create a datetime.datetime index and generate two data series of the same length. timestamps = np.arange(next_timestamp, now, sample_time) sample_values = np.random.randn(len(timestamps), 2) Combine the data series with the index into a pandas.DataFrame and return the data. data = pd.DataFrame(sample_values, index=timestamps, columns=[""A"", ""B""]) return data (Optional) Test out your function by calling it and displaying the data. data = get_recent_data(datetime.now() - timedelta(seconds=60)) data Save your app.py file to see the preview. Delete these two lines when finished. Initialize Session State values for your app Since you will dynamically change the run_every parameter of @st.experimental_fragment(), you'll need to initialize the associated variables and Session State values before defining your fragment function. Your fragment function will also read and update values in Session State, so you can define those now to make the fragment function easier to understand. Initialize your data for the first app load in a session. if ""data"" not in st.session_state: st.session_state.data = get_recent_data(datetime.now() - timedelta(seconds=60)) Your app will display this initial data in a static line chart before a user starts streaming data. Initialize ""stream"" in Session State to turn streaming on and off. Set the default to off (False). if ""stream"" not in st.session_state: st.session_state.stream = False Create a callback function to toggle ""stream"" between True and False. def toggle_streaming(): st.session_state.stream = not st.session_state.stream Add a title to your app. st.title(""Data feed"") Add a slider to the sidebar to set how frequently to check for data while streaming. st.sidebar.slider( ""Check for updates every: (seconds)"", 0.5, 5.0, value=1.0, key=""run_every"" ) Add buttons to the sidebar to turn streaming on and off. st.sidebar.button( ""Start streaming"", disabled=st.session_state.stream, on_click=toggle_streaming ) st.sidebar.button( ""Stop streaming"", disabled=not st.session_state.stream, on_click=toggle_streaming ) Both functions use the same callback to toggle ""stream"" in Session State. Use the current value ""stream"" to disable one of the buttons. This ensures the buttons are always consistent with the current state; ""Start streaming"" is only clickable when streaming is off, and ""Stop streaming"" is only clickable when streaming is on. The buttons also provide status to the user by highlighting which action is available to them. Create and set a new variable, run_every, that will determine whether or not the fragment function will rerun automatically (and how fast). if st.session_state.stream is True: run_every = st.session_state.run_every else: run_every = None Build a fragment function to stream data To allow the user to turn data streaming on and off, you must set the run_every parameter in the @st.experimental_fragment() decorator. Complete function to show and stream dataexpand_more@st.experimental_fragment(run_every=run_every) def show_latest_data(): last_timestamp = st.session_state.data.index[-1] st.session_state.data = pd.concat( [st.session_state.data, get_recent_data(last_timestamp)] ) st.session_state.data = st.session_state.data[-100:] st.line_chart(st.session_state.data) Use an @st.experimental_fragment decorator and start your function definition. @st.experimental_fragment(run_every=run_every) def show_latest_data(): Use the run_every variable declared above to set the parameter of the same name. Retrieve the timestamp of the last datapoint in Session State. last_timestamp = st.session_state.data.index[-1] Update the data in Session State and trim to keep only the last 100 timestamps. st.session_state.data = pd.concat( [st.session_state.data, get_recent_data(last_timestamp)] ) st.session_state.data = st.session_state.data[-100:] Show the data in a line chart. st.line_chart(st.session_state.data) Your fragment-function definition is complete. Call and test out your fragment function Call your function at the bottom of your code. show_latest_data() Test out your app by clicking ""Start streaming."" Try adjusting the frequency of updates. Next steps Try adjusting the frequency of data generation or how much data is kept in Session State. Within get_recent_data try setting sample_time with a widget. Try using st.plotly_chart or st.altair_chart to add labels to your chart.Previous: Create a multiple-container fragmentNext: Connect to data sourcesforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy" https://docs.streamlit.io/develop/tutorials/databases/mongodb#add-username-and-password-to-your-local-app-secrets,"DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceaddTutorialsremoveExecution flowaddConnect to data sourcesremoveAWS S3BigQueryDeta BaseFirestoreopen_in_newGoogle Cloud StorageMicrosoft SQL ServerMongoDBMySQLNeonPostgreSQLPrivate Google SheetPublic Google SheetSnowflakeSupabaseTableauTiDBTigerGraphMultipage appsaddWork with LLMsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Develop/Tutorials/Connect to data sources/MongoDBConnect Streamlit to MongoDB Introduction This guide explains how to securely access a remote MongoDB database from Streamlit Community Cloud. It uses the PyMongo library and Streamlit's Secrets management. Create a MongoDB Database push_pinNoteIf you already have a database that you want to use, feel free to skip to the next step. First, follow the official tutorials to install MongoDB, set up authentication (note down the username and password!), and connect to the MongoDB instance. Once you are connected, open the mongo shell and enter the following two commands to create a collection with some example values: use mydb db.mycollection.insertMany([{""name"" : ""Mary"", ""pet"": ""dog""}, {""name"" : ""John"", ""pet"": ""cat""}, {""name"" : ""Robert"", ""pet"": ""bird""}]) Add username and password to your local app secrets Your local Streamlit app will read secrets from a file .streamlit/secrets.toml in your app's root directory. Create this file if it doesn't exist yet and add the database information as shown below: # .streamlit/secrets.toml [mongo] host = ""localhost"" port = 27017 username = ""xxx"" password = ""xxx"" priority_highImportantWhen copying your app secrets to Streamlit Community Cloud, be sure to replace the values of host, port, username, and password with those of your remote MongoDB database!Add this file to .gitignore and don't commit it to your GitHub repo! Copy your app secrets to the cloud As the secrets.toml file above is not committed to GitHub, you need to pass its content to your deployed app (on Streamlit Community Cloud) separately. Go to the app dashboard and in the app's dropdown menu, click on Edit Secrets. Copy the content of secrets.toml into the text area. More information is available at Secrets management. Add PyMongo to your requirements file Add the PyMongo package to your requirements.txt file, preferably pinning its version (replace x.x.x with the version you want installed): # requirements.txt pymongo==x.x.x Write your Streamlit app Copy the code below to your Streamlit app and run it. Make sure to adapt the name of your database and collection. # streamlit_app.py import streamlit as st import pymongo # Initialize connection. # Uses st.cache_resource to only run once. @st.cache_resource def init_connection(): return pymongo.MongoClient(**st.secrets[""mongo""]) client = init_connection() # Pull data from the collection. # Uses st.cache_data to only rerun when the query changes or after 10 min. @st.cache_data(ttl=600) def get_data(): db = client.mydb items = db.mycollection.find() items = list(items) # make hashable for st.cache_data return items items = get_data() # Print results. for item in items: st.write(f""{item['name']} has a :{item['pet']}:"") See st.cache_data above? Without it, Streamlit would run the query every time the app reruns (e.g. on a widget interaction). With st.cache_data, it only runs when the query changes or after 10 minutes (that's what ttl is for). Watch out: If your database updates more frequently, you should adapt ttl or remove caching so viewers always see the latest data. Learn more in Caching. If everything worked out (and you used the example data we created above), your app should look like this: Previous: Microsoft SQL ServerNext: MySQLforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy" https://docs.streamlit.io/develop/quick-reference/cheat-sheet#connect-to-data-sources,"DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceaddTutorialsaddQuick referenceremoveCheat sheetRelease notesPre-release featuresRoadmapopen_in_newweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Develop/Quick reference/Cheat sheetStreamlit API cheat sheet This is a summary of the docs, as of Streamlit v1.34.0. Install & Importpip install streamlit streamlit run first_app.py # Import convention >>> import streamlit as st Pre-release featurespip uninstall streamlit pip install streamlit-nightly --upgrade Learn more about experimental featuresCommand linestreamlit --help streamlit run your_script.py streamlit hello streamlit config show streamlit cache clear streamlit docs streamlit --version Magic commands# Magic commands implicitly # call st.write(). ""_This_ is some **Markdown***"" my_variable ""dataframe:"", my_data_frame Display textst.write(""Most objects"") # df, err, func, keras! st.write([""st"", ""is <"", 3]) # see * st.write_stream(my_generator) st.write_stream(my_llm_stream) st.text(""Fixed width text"") st.markdown(""_Markdown_"") # see * st.latex(r"""""" e^{i\pi} + 1 = 0 """""") st.title(""My title"") st.header(""My header"") st.subheader(""My sub"") st.code(""for i in range(8): foo()"") * optional kwarg unsafe_allow_html = True Display datast.dataframe(my_dataframe) st.table(data.iloc[0:10]) st.json({""foo"":""bar"",""fu"":""ba""}) st.metric(""My metric"", 42, 2) Display mediast.image(""./header.png"") st.audio(data) st.video(data) st.video(data, subtitles=""./subs.vtt"") Display chartsst.area_chart(df) st.bar_chart(df) st.line_chart(df) st.map(df) st.scatter_chart(df) st.altair_chart(chart) st.bokeh_chart(fig) st.graphviz_chart(fig) st.plotly_chart(fig) st.pydeck_chart(chart) st.pyplot(fig) st.vega_lite_chart(df) Add widgets to sidebar# Just add it after st.sidebar: >>> a = st.sidebar.radio(""Select one:"", [1, 2]) # Or use ""with"" notation: >>> with st.sidebar: >>> st.radio(""Select one:"", [1, 2]) Columns# Two equal columns: >>> col1, col2 = st.columns(2) >>> col1.write(""This is column 1"") >>> col2.write(""This is column 2"") # Three different columns: >>> col1, col2, col3 = st.columns([3, 1, 1]) # col1 is larger. # You can also use ""with"" notation: >>> with col1: >>> st.radio(""Select one:"", [1, 2]) Tabs# Insert containers separated into tabs: >>> tab1, tab2 = st.tabs([""Tab 1"", ""Tab2""]) >>> tab1.write(""this is tab 1"") >>> tab2.write(""this is tab 2"") # You can also use ""with"" notation: >>> with tab1: >>> st.radio(""Select one:"", [1, 2]) Expandable containers>>> expand = st.expander(""My label"") >>> expand.write(""Inside the expander."") >>> pop = st.popover(""Button label"") >>> pop.checkbox(""Show all"") # You can also use ""with"" notation: >>> with expand: >>> st.radio(""Select one:"", [1, 2]) Control flow# Stop execution immediately: st.stop() # Rerun script immediately: st.rerun() # Navigate to another page: st.switch_page(""pages/my_page.py"") # Group multiple widgets: >>> with st.form(key=""my_form""): >>> username = st.text_input(""Username"") >>> password = st.text_input(""Password"") >>> st.form_submit_button(""Login"") # Define a dialog function >>> @st.experimental_dialog(""Welcome!"") >>> def modal_dialog(): >>> st.write(""Hello"") >>> >>> modal_dialog() # Define a fragment >>> @st.experimental_fragment >>> def fragment_function(): >>> df = get_data() >>> st.line_chart(df) >>> st.button(""Update"") >>> >>> fragment_function() Display interactive widgetsst.button(""Click me"") st.download_button(""Download file"", data) st.link_button(""Go to gallery"", url) st.page_link(""app.py"", label=""Home"") st.data_editor(""Edit data"", data) st.checkbox(""I agree"") st.toggle(""Enable"") st.radio(""Pick one"", [""cats"", ""dogs""]) st.selectbox(""Pick one"", [""cats"", ""dogs""]) st.multiselect(""Buy"", [""milk"", ""apples"", ""potatoes""]) st.slider(""Pick a number"", 0, 100) st.select_slider(""Pick a size"", [""S"", ""M"", ""L""]) st.text_input(""First name"") st.number_input(""Pick a number"", 0, 10) st.text_area(""Text to translate"") st.date_input(""Your birthday"") st.time_input(""Meeting time"") st.file_uploader(""Upload a CSV"") st.camera_input(""Take a picture"") st.color_picker(""Pick a color"") # Use widgets' returned values in variables: >>> for i in range(int(st.number_input(""Num:""))): >>> foo() >>> if st.sidebar.selectbox(""I:"",[""f""]) == ""f"": >>> b() >>> my_slider_val = st.slider(""Quinn Mallory"", 1, 88) >>> st.write(slider_val) # Disable widgets to remove interactivity: >>> st.slider(""Pick a number"", 0, 100, disabled=True) Build chat-based apps# Insert a chat message container. >>> with st.chat_message(""user""): >>> st.write(""Hello 👋"") >>> st.line_chart(np.random.randn(30, 3)) # Display a chat input widget at the bottom of the app. >>> st.chat_input(""Say something"") # Display a chat input widget inline. >>> with st.container(): >>> st.chat_input(""Say something"") Learn how to Build a basic LLM chat appMutate data# Add rows to a dataframe after # showing it. >>> element = st.dataframe(df1) >>> element.add_rows(df2) # Add rows to a chart after # showing it. >>> element = st.line_chart(df1) >>> element.add_rows(df2) Display code>>> with st.echo(): >>> st.write(""Code will be executed and printed"") Placeholders, help, and options# Replace any single element. >>> element = st.empty() >>> element.line_chart(...) >>> element.text_input(...) # Replaces previous. # Insert out of order. >>> elements = st.container() >>> elements.line_chart(...) >>> st.write(""Hello"") >>> elements.text_input(...) # Appears above ""Hello"". st.help(pandas.DataFrame) st.get_option(key) st.set_option(key, value) st.set_page_config(layout=""wide"") st.query_params[key] st.query_params.from_dict(params_dict) st.query_params.get_all(key) st.query_params.clear() st.html(""

Hi!

"") Connect to data sourcesst.connection(""pets_db"", type=""sql"") conn = st.connection(""sql"") conn = st.connection(""snowflake"") >>> class MyConnection(BaseConnection[myconn.MyConnection]): >>> def _connect(self, **kwargs) -> MyConnection: >>> return myconn.connect(**self._secrets, **kwargs) >>> def query(self, query): >>> return self._instance.query(query) Optimize performanceCache data objects# E.g. Dataframe computation, storing downloaded data, etc. >>> @st.cache_data ... def foo(bar): ... # Do something expensive and return data ... return data # Executes foo >>> d1 = foo(ref1) # Does not execute foo # Returns cached item by value, d1 == d2 >>> d2 = foo(ref1) # Different arg, so function foo executes >>> d3 = foo(ref2) # Clear the cached value for foo(ref1) >>> foo.clear(ref1) # Clear all cached entries for this function >>> foo.clear() # Clear values from *all* in-memory or on-disk cached functions >>> st.cache_data.clear() Cache global resources# E.g. TensorFlow session, database connection, etc. >>> @st.cache_resource ... def foo(bar): ... # Create and return a non-data object ... return session # Executes foo >>> s1 = foo(ref1) # Does not execute foo # Returns cached item by reference, s1 == s2 >>> s2 = foo(ref1) # Different arg, so function foo executes >>> s3 = foo(ref2) # Clear the cached value for foo(ref1) >>> foo.clear(ref1) # Clear all cached entries for this function >>> foo.clear() # Clear all global resources from cache >>> st.cache_resource.clear() Deprecated caching>>> @st.cache ... def foo(bar): ... # Do something expensive in here... ... return data >>> # Executes foo >>> d1 = foo(ref1) >>> # Does not execute foo >>> # Returns cached item by reference, d1 == d2 >>> d2 = foo(ref1) >>> # Different arg, so function foo executes >>> d3 = foo(ref2) Display progress and status# Show a spinner during a process >>> with st.spinner(text=""In progress""): >>> time.sleep(3) >>> st.success(""Done"") # Show and update progress bar >>> bar = st.progress(50) >>> time.sleep(3) >>> bar.progress(100) >>> with st.status(""Authenticating..."") as s: >>> time.sleep(2) >>> st.write(""Some long response."") >>> 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 address. >>> if st.user.email == ""jane@email.com"": >>> display_jane_content() >>> elif st.user.email == ""adam@foocorp.io"": >>> display_adam_content() >>> else: >>> st.write(""Please contact us to get access!"") Previous: Quick referenceNext: Release notesforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy" https://docs.streamlit.io/develop/concepts/architecture,"DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsremoveCOREArchitecture & executionremoveRunning your appStreamlit's architectureThe app chromeCachingSession StateFormsFragmentsWidget behaviorMultipage appsaddApp designaddADDITIONALConnections and secretsaddCustom componentsaddConfiguration and themingaddApp testingaddAPI referenceaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Develop/Concepts/Architecture & executionWorking with Streamlit's execution model Run your appUnderstand how to start your Streamlit app.Streamlit's architectureUnderstand Streamlit's client-server architecture and related considerations.The app chromeEvery Streamlit app has a few widgets in the top right to help you as you develop your app and help your users as they view your app. This is called the app chrome.CachingMake your app performant by caching results to avoid unecessary recomputation with each rerun.Session StateManage your app's statefulness with Session State.FormsUse forms to isolate user input and prevent unnecessary app reruns.Widget behaviorUnderstand how widgets work in detail.Previous: ConceptsNext: Running your appforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy" https://docs.streamlit.io/knowledge-base/dependencies/no-matching-distribution#solution,"DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Knowledge base/Installing dependencies/ERROR No matching distribution found forERROR: No matching distribution found for Problem You receive the error ERROR: No matching distribution found for when you deploy an app on Streamlit Community Cloud. Solution This error occurs when you deploy an app on Streamlit Community Cloud and have one or more of the following issues with your Python dependencies in your requirements file: The package is part of the Python Standard Library. E.g. You will see ERROR: No matching distribution found for base64 if you include base64 in your requirements file, as it is part of the Python Standard Library. The solution is to not include the package in your requirements file. Only include packages in your requirements file that are not distributed with a standard Python installation. The package name in your requirements file is misspelled. Double-check the package name before including it in your requirements file. The package does not support the operating system on which your Streamlit app is running. E.g. You see ERROR: No matching distribution found for pywin32 while deploying to Streamlit Community Cloud. The pywin32 module provides access to many of the Windows APIs from Python. Apps deployed to Streamlit Community Cloud are executed in a Linux environment. As such, pywin32 fails to install on non-Windows systems, including on Streamlit Community Cloud. The solution is to either exclude pywin32 from your requirements file, or deploy your app on a cloud service offering Windows machines. Related forum posts: https://discuss.streamlit.io/t/error-no-matching-distribution-found-for-base64/15758 https://discuss.streamlit.io/t/error-could-not-find-a-version-that-satisfies-the-requirement-pywin32-301-from-versions-none/15343/2 Previous: ModuleNotFoundError No module namedNext: Deployment issuesforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy" https://docs.streamlit.io/library/api-reference/data/st.column_config,"DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceremovePAGE ELEMENTSWrite and magicaddText elementsaddData elementsremovest.dataframest.data_editorst.column_configremoveColumnText columnNumber columnCheckbox columnSelectbox columnDatetime columnDate columnTime columnList columnLink columnImage columnArea chart columnLine chart columnBar chart columnProgress columnst.tablest.metricst.jsonChart elementsaddInput widgetsaddMedia elementsaddLayouts and containersaddChat elementsaddStatus elementsaddThird-party componentsopen_in_newAPPLICATION LOGICNavigation and pagesaddExecution flowaddCaching and stateaddConnections and secretsaddCustom componentsaddUtilitiesaddConfigurationaddTOOLSApp testingaddCommand lineaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Develop/API reference/Data elements/st.column_configColumn configuration When working with data in Streamlit, the st.column_config class is a powerful tool for configuring data display and interaction. Specifically designed for the column_config parameter in st.dataframe and st.data_editor, it provides a suite of methods to tailor your columns to various data types - from simple text and numbers to lists, URLs, images, and more. Whether it's translating temporal data into user-friendly formats or utilizing charts and progress bars for clearer data visualization, column configuration not only provides the user with an enriched data viewing experience but also ensures that you're equipped with the tools to present and interact with your data, just the way you want it. ColumnConfigure a generic column.Column(""Streamlit Widgets"", width=""medium"", help=""Streamlit **widget** commands 🎈"") Text columnConfigure a text column.TextColumn(""Widgets"", max_chars=50, validate=""^st\.[a-z_]+$"") Number columnConfigure a number column.NumberColumn(""Price (in USD)"", min_value=0, format=""$%d"") Checkbox columnConfigure a checkbox column.CheckboxColumn(""Your favorite?"", help=""Select your **favorite** widgets"") Selectbox columnConfigure a selectbox column.SelectboxColumn(""App Category"", options=[""🤖 LLM"", ""📈 Data Viz""]) Datetime columnConfigure a datetime column.DatetimeColumn(""Appointment"", min_value=datetime(2023, 6, 1), format=""D MMM YYYY, h:mm a"") Date columnConfigure a date column.DateColumn(""Birthday"", max_value=date(2005, 1, 1), format=""DD.MM.YYYY"") Time columnConfigure a time column.TimeColumn(""Appointment"", min_value=time(8, 0, 0), format=""hh:mm a"") List columnConfigure a list column.ListColumn(""Sales (last 6 months)"", width=""medium"") Link columnConfigure a link column.LinkColumn(""Trending apps"", max_chars=100, validate=""^https://.*$"") Image columnConfigure an image column.ImageColumn(""Preview Image"", help=""The preview screenshots"") Area chart columnConfigure an area chart column.AreaChartColumn(""Sales (last 6 months)"" y_min=0, y_max=100) Line chart columnConfigure a line chart column.LineChartColumn(""Sales (last 6 months)"" y_min=0, y_max=100) Bar chart columnConfigure a bar chart column.BarChartColumn(""Marketing spend"" y_min=0, y_max=100) Progress columnConfigure a progress column.ProgressColumn(""Sales volume"", min_value=0, max_value=1000, format=""$%f"") Previous: st.data_editorNext: ColumnforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy" https://docs.streamlit.io/en/0.76.0/api.html#utilities-and-user-info,"DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceremovePAGE ELEMENTSWrite and magicaddText elementsaddData elementsaddChart elementsaddInput widgetsaddMedia elementsaddLayouts and containersaddChat elementsaddStatus elementsaddThird-party componentsopen_in_newAPPLICATION LOGICNavigation and pagesaddExecution flowaddCaching and stateaddConnections and secretsaddCustom componentsaddUtilitiesaddConfigurationaddTOOLSApp testingaddCommand lineaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Develop/API referenceAPI reference Streamlit makes it easy for you to visualize, mutate, and share data. The API reference is organized by activity type, like displaying data or optimizing performance. Each section includes methods associated with the activity type, including examples. Browse our API below and click to learn more about any of our available commands! 🎈 Display almost anything Write and magic st.writeWrite arguments to the app.st.write(""Hello **world**!"") st.write(my_data_frame) st.write(my_mpl_figure) st.write_streamWrite generators or streams to the app with a typewriter effect.st.write_stream(my_generator) st.write_stream(my_llm_stream) MagicAny time Streamlit sees either a variable or literal value on its own line, it automatically writes that to your app using st.write""Hello **world**!"" my_data_frame my_mpl_figure Text elements MarkdownDisplay string formatted as Markdown.st.markdown(""Hello **world**!"") TitleDisplay text in title formatting.st.title(""The app title"") HeaderDisplay text in header formatting.st.header(""This is a header"") SubheaderDisplay text in subheader formatting.st.subheader(""This is a subheader"") CaptionDisplay text in small font.st.caption(""This is written small caption text"") Code blockDisplay a code block with optional syntax highlighting.st.code(""a = 1234"") EchoDisplay some code in the app, then execute it. Useful for tutorials.with st.echo(): st.write('This code will be printed') LaTeXDisplay mathematical expressions formatted as LaTeX.st.latex(""\int a x^2 \,dx"") Preformatted textWrite fixed-width and preformatted text.st.text(""Hello world"") DividerDisplay a horizontal rule.st.divider() Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration! PreviousTagsAdd tags to your Streamlit apps. Created by @gagan3012.st_tags(label='# Enter Keywords:', text='Press enter to add more', value=['Zero', 'One', 'Two'], suggestions=['five', 'six', 'seven', 'eight', 'nine', 'three', 'eleven', 'ten', 'four'], maxtags = 4, key='1') NLUApply text mining on a dataframe. Created by @JohnSnowLabs.nlu.load('sentiment').predict('I love NLU! <3') Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.mention(label=""An awesome Streamlit App"", icon=""streamlit"", url=""https://extras.streamlit.app"",) Annotated textDisplay annotated text in Streamlit apps. Created by @tvst.annotated_text(""This "", (""is"", ""verb""), "" some "", (""annotated"", ""adj""), (""text"", ""noun""), "" for those of "", (""you"", ""pronoun""), "" who "", (""like"", ""verb""), "" this sort of "", (""thing"", ""noun""), ""."") Drawable CanvasProvides a sketching canvas using Fabric.js. Created by @andfanilo.st_canvas(fill_color=""rgba(255, 165, 0, 0.3)"", stroke_width=stroke_width, stroke_color=stroke_color, background_color=bg_color, background_image=Image.open(bg_image) if bg_image else None, update_streamlit=realtime_update, height=150, drawing_mode=drawing_mode, point_display_radius=point_display_radius if drawing_mode == 'point' else 0, key=""canvas"",) TagsAdd tags to your Streamlit apps. Created by @gagan3012.st_tags(label='# Enter Keywords:', text='Press enter to add more', value=['Zero', 'One', 'Two'], suggestions=['five', 'six', 'seven', 'eight', 'nine', 'three', 'eleven', 'ten', 'four'], maxtags = 4, key='1') NLUApply text mining on a dataframe. Created by @JohnSnowLabs.nlu.load('sentiment').predict('I love NLU! <3') Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.mention(label=""An awesome Streamlit App"", icon=""streamlit"", url=""https://extras.streamlit.app"",) Annotated textDisplay annotated text in Streamlit apps. Created by @tvst.annotated_text(""This "", (""is"", ""verb""), "" some "", (""annotated"", ""adj""), (""text"", ""noun""), "" for those of "", (""you"", ""pronoun""), "" who "", (""like"", ""verb""), "" this sort of "", (""thing"", ""noun""), ""."") Drawable CanvasProvides a sketching canvas using Fabric.js. Created by @andfanilo.st_canvas(fill_color=""rgba(255, 165, 0, 0.3)"", stroke_width=stroke_width, stroke_color=stroke_color, background_color=bg_color, background_image=Image.open(bg_image) if bg_image else None, update_streamlit=realtime_update, height=150, drawing_mode=drawing_mode, point_display_radius=point_display_radius if drawing_mode == 'point' else 0, key=""canvas"",) TagsAdd tags to your Streamlit apps. Created by @gagan3012.st_tags(label='# Enter Keywords:', text='Press enter to add more', value=['Zero', 'One', 'Two'], suggestions=['five', 'six', 'seven', 'eight', 'nine', 'three', 'eleven', 'ten', 'four'], maxtags = 4, key='1') NLUApply text mining on a dataframe. Created by @JohnSnowLabs.nlu.load('sentiment').predict('I love NLU! <3') Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.mention(label=""An awesome Streamlit App"", icon=""streamlit"", url=""https://extras.streamlit.app"",) Next Data elements DataframesDisplay a dataframe as an interactive table.st.dataframe(my_data_frame) Data editorDisplay a data editor widget.edited = st.data_editor(df, num_rows=""dynamic"") Column configurationConfigure the display and editing behavior of dataframes and data editors.st.column_config.NumberColumn(""Price (in USD)"", min_value=0, format=""$%d"") Static tablesDisplay a static table.st.table(my_data_frame) MetricsDisplay a metric in big bold font, with an optional indicator of how the metric changed.st.metric(""My metric"", 42, 2) Dicts and JSONDisplay object or string as a pretty-printed JSON string.st.json(my_dict) Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration! PreviousImage CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates value = streamlit_image_coordinates(""https://placekitten.com/200/300"") st.write(value) Plotly EventsMake Plotly charts interactive!. Created by @null-jones.from streamlit_plotly_events import plotly_events fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.metric_cards import style_metric_cards col3.metric(label=""No Change"", value=5000, delta=0) style_metric_cards() Streamlit AggridImplementation of Ag-Grid component for Streamlit. Created by @PablocFonseca.df = pd.DataFrame({'col1': [1, 2, 3], 'col2': [4, 5, 6]}) grid_return = AgGrid(df, editable=True) new_df = grid_return['data'] Streamlit FoliumStreamlit Component for rendering Folium maps. Created by @randyzwitch.m = folium.Map(location=[39.949610, -75.150282], zoom_start=16) folium.Marker([39.949610, -75.150282], popup=""Liberty Bell"", tooltip=""Liberty Bell"").add_to(m) st_data = st_folium(m, width=725) Pandas ProfilingPandas profiling component for Streamlit. Created by @okld.df = pd.read_csv(""https://storage.googleapis.com/tf-datasets/titanic/train.csv"") pr = df.profile_report() st_profile_report(pr) Image CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates value = streamlit_image_coordinates(""https://placekitten.com/200/300"") st.write(value) Plotly EventsMake Plotly charts interactive!. Created by @null-jones.from streamlit_plotly_events import plotly_events fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.metric_cards import style_metric_cards col3.metric(label=""No Change"", value=5000, delta=0) style_metric_cards() Streamlit AggridImplementation of Ag-Grid component for Streamlit. Created by @PablocFonseca.df = pd.DataFrame({'col1': [1, 2, 3], 'col2': [4, 5, 6]}) grid_return = AgGrid(df, editable=True) new_df = grid_return['data'] Streamlit FoliumStreamlit Component for rendering Folium maps. Created by @randyzwitch.m = folium.Map(location=[39.949610, -75.150282], zoom_start=16) folium.Marker([39.949610, -75.150282], popup=""Liberty Bell"", tooltip=""Liberty Bell"").add_to(m) st_data = st_folium(m, width=725) Pandas ProfilingPandas profiling component for Streamlit. Created by @okld.df = pd.read_csv(""https://storage.googleapis.com/tf-datasets/titanic/train.csv"") pr = df.profile_report() st_profile_report(pr) Image CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates value = streamlit_image_coordinates(""https://placekitten.com/200/300"") st.write(value) Plotly EventsMake Plotly charts interactive!. Created by @null-jones.from streamlit_plotly_events import plotly_events fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.metric_cards import style_metric_cards col3.metric(label=""No Change"", value=5000, delta=0) style_metric_cards() Next Chart elements Simple area chartsDisplay an area chart.st.area_chart(my_data_frame) Simple bar chartsDisplay a bar chart.st.bar_chart(my_data_frame) Simple line chartsDisplay a line chart.st.line_chart(my_data_frame) Simple scatter chartsDisplay a line chart.st.scatter_chart(my_data_frame) Scatterplots on mapsDisplay a map with points on it.st.map(my_data_frame) MatplotlibDisplay a matplotlib.pyplot figure.st.pyplot(my_mpl_figure) AltairDisplay a chart using the Altair library.st.altair_chart(my_altair_chart) Vega-LiteDisplay a chart using the Vega-Lite library.st.vega_lite_chart(my_vega_lite_chart) PlotlyDisplay an interactive Plotly chart.st.plotly_chart(my_plotly_chart) BokehDisplay an interactive Bokeh chart.st.bokeh_chart(my_bokeh_chart) PyDeckDisplay a chart using the PyDeck library.st.pydeck_chart(my_pydeck_chart) GraphVizDisplay a graph using the dagre-d3 library.st.graphviz_chart(my_graphviz_spec) Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration! PreviousStreamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl(""https://assets5.lottiefiles.com/packages/lf20_V9t630.json"") st_lottie(lottie_hello, key=""hello"") Plotly EventsMake Plotly charts interactive!. Created by @null-jones.fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.chart += get_annotations_chart(annotations=[(""Mar 01, 2008"", ""Pretty good day for GOOG""), (""Dec 01, 2007"", ""Something's going wrong for GOOG & AAPL""), (""Nov 01, 2008"", ""Market starts again thanks to...""), (""Dec 01, 2009"", ""Small crash for GOOG after...""),],) st.altair_chart(chart, use_container_width=True) PlostA deceptively simple plotting library for Streamlit. Created by @tvst.import plost plost.line_chart(my_dataframe, x='time', y='stock_value', color='stock_name',) HiPlotHigh dimensional Interactive Plotting. Created by @facebookresearch.data = [{'dropout':0.1, 'lr': 0.001, 'loss': 10.0, 'optimizer': 'SGD'}, {'dropout':0.15, 'lr': 0.01, 'loss': 3.5, 'optimizer': 'Adam'}, {'dropout':0.3, 'lr': 0.1, 'loss': 4.5, 'optimizer': 'Adam'}] hip.Experiment.from_iterable(data).display() EChartsHigh dimensional Interactive Plotting. Created by @andfanilo.from streamlit_echarts import st_echarts st_echarts(options=options) Streamlit FoliumStreamlit Component for rendering Folium maps. Created by @randyzwitch.m = folium.Map(location=[39.949610, -75.150282], zoom_start=16) st_data = st_folium(m, width=725) Spacy-StreamlitspaCy building blocks and visualizers for Streamlit apps. Created by @explosion.models = [""en_core_web_sm"", ""en_core_web_md""] spacy_streamlit.visualize(models, ""Sundar Pichai is the CEO of Google."") Streamlit AgraphA Streamlit Graph Vis, based on react-grah-vis. Created by @ChrisDelClea.from streamlit_agraph import agraph, Node, Edge, Config agraph(nodes=nodes, edges=edges, config=config) Streamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl(""https://assets5.lottiefiles.com/packages/lf20_V9t630.json"") st_lottie(lottie_hello, key=""hello"") Plotly EventsMake Plotly charts interactive!. Created by @null-jones.fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.chart += get_annotations_chart(annotations=[(""Mar 01, 2008"", ""Pretty good day for GOOG""), (""Dec 01, 2007"", ""Something's going wrong for GOOG & AAPL""), (""Nov 01, 2008"", ""Market starts again thanks to...""), (""Dec 01, 2009"", ""Small crash for GOOG after...""),],) st.altair_chart(chart, use_container_width=True) PlostA deceptively simple plotting library for Streamlit. Created by @tvst.import plost plost.line_chart(my_dataframe, x='time', y='stock_value', color='stock_name',) HiPlotHigh dimensional Interactive Plotting. Created by @facebookresearch.data = [{'dropout':0.1, 'lr': 0.001, 'loss': 10.0, 'optimizer': 'SGD'}, {'dropout':0.15, 'lr': 0.01, 'loss': 3.5, 'optimizer': 'Adam'}, {'dropout':0.3, 'lr': 0.1, 'loss': 4.5, 'optimizer': 'Adam'}] hip.Experiment.from_iterable(data).display() EChartsHigh dimensional Interactive Plotting. Created by @andfanilo.from streamlit_echarts import st_echarts st_echarts(options=options) Streamlit FoliumStreamlit Component for rendering Folium maps. Created by @randyzwitch.m = folium.Map(location=[39.949610, -75.150282], zoom_start=16) st_data = st_folium(m, width=725) Spacy-StreamlitspaCy building blocks and visualizers for Streamlit apps. Created by @explosion.models = [""en_core_web_sm"", ""en_core_web_md""] spacy_streamlit.visualize(models, ""Sundar Pichai is the CEO of Google."") Streamlit AgraphA Streamlit Graph Vis, based on react-grah-vis. Created by @ChrisDelClea.from streamlit_agraph import agraph, Node, Edge, Config agraph(nodes=nodes, edges=edges, config=config) Streamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl(""https://assets5.lottiefiles.com/packages/lf20_V9t630.json"") st_lottie(lottie_hello, key=""hello"") Plotly EventsMake Plotly charts interactive!. Created by @null-jones.fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.chart += get_annotations_chart(annotations=[(""Mar 01, 2008"", ""Pretty good day for GOOG""), (""Dec 01, 2007"", ""Something's going wrong for GOOG & AAPL""), (""Nov 01, 2008"", ""Market starts again thanks to...""), (""Dec 01, 2009"", ""Small crash for GOOG after...""),],) st.altair_chart(chart, use_container_width=True) Next Input widgets ButtonDisplay a button widget.clicked = st.button(""Click me"") Download buttonDisplay a download button widget.st.download_button(""Download file"", file) Form buttonDisplay a form submit button. For use with st.form.st.form_submit_button(""Sign up"") Link buttonDisplay a link button.st.link_button(""Go to gallery"", url) Page linkDisplay a link to another page in a multipage app.st.page_link(""app.py"", label=""Home"", icon=""🏠"") st.page_link(""pages/profile.py"", label=""My profile"") CheckboxDisplay a checkbox widget.selected = st.checkbox(""I agree"") Color pickerDisplay a color picker widget.color = st.color_picker(""Pick a color"") MultiselectDisplay a multiselect widget. The multiselect widget starts as empty.choices = st.multiselect(""Buy"", [""milk"", ""apples"", ""potatoes""]) RadioDisplay a radio button widget.choice = st.radio(""Pick one"", [""cats"", ""dogs""]) SelectboxDisplay a select widget.choice = st.selectbox(""Pick one"", [""cats"", ""dogs""]) Select-sliderDisplay a slider widget to select items from a list.size = st.select_slider(""Pick a size"", [""S"", ""M"", ""L""]) ToggleDisplay a toggle widget.activated = st.toggle(""Activate"") Number inputDisplay a numeric input widget.choice = st.number_input(""Pick a number"", 0, 10) SliderDisplay a slider widget.number = st.slider(""Pick a number"", 0, 100) Date inputDisplay a date input widget.date = st.date_input(""Your birthday"") Time inputDisplay a time input widget.time = st.time_input(""Meeting time"") Chat inputDisplay a chat input widget.prompt = st.chat_input(""Say something"") if prompt: st.write(f""The user has sent: {prompt}"") Text-areaDisplay a multi-line text input widget.text = st.text_area(""Text to translate"") Text inputDisplay a single-line text input widget.name = st.text_input(""First name"") Data editorDisplay a data editor widget.edited = st.experimental_data_editor(df, num_rows=""dynamic"") File UploaderDisplay a file uploader widget.data = st.file_uploader(""Upload a CSV"") Camera inputDisplay a widget that allows users to upload images directly from a camera.image = st.camera_input(""Take a picture"") Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration! PreviousStreamlit ChatStreamlit Component for a Chatbot UI. Created by @AI-Yash.from streamlit_chat import message message(""My message"") message(""Hello bot!"", is_user=True) # align's the message to the right Streamlit Option MenuSelect a single item from a list of options in a menu. Created by @victoryhb.from streamlit_option_menu import option_menu option_menu(""Main Menu"", [""Home"", 'Settings'], icons=['house', 'gear'], menu_icon=""cast"", default_index=1) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.stoggle import stoggle stoggle( ""Click me!"", """"""🥷 Surprise! Here's some additional content"""""",) Streamlit ElementsCreate a draggable and resizable dashboard in Streamlit. Created by @okls.from streamlit_elements import elements, mui, html with elements(""new_element""): mui.Typography(""Hello world"") TagsAdd tags to your Streamlit apps. Created by @gagan3012.from streamlit_tags import st_tags st_tags(label='# Enter Keywords:', text='Press enter to add more', value=['Zero', 'One', 'Two'], suggestions=['five', 'six', 'seven', 'eight', 'nine', 'three', 'eleven', 'ten', 'four'], maxtags = 4, key='1') StqdmThe simplest way to handle a progress bar in streamlit app. Created by @Wirg.from stqdm import stqdm for _ in stqdm(range(50)): sleep(0.5) TimelineDisplay a Timeline in Streamlit apps using TimelineJS. Created by @innerdoc.from streamlit_timeline import timeline with open('example.json', ""r"") as f: timeline(f.read(), height=800) Camera input liveAlternative for st.camera_input which returns the webcam images live. Created by @blackary.from camera_input_live import camera_input_live image = camera_input_live() st.image(value) Streamlit AceAce editor component for Streamlit. Created by @okld.from streamlit_ace import st_ace content = st_ace() content Streamlit ChatStreamlit Component for a Chatbot UI. Created by @AI-Yash.from streamlit_chat import message message(""My message"") message(""Hello bot!"", is_user=True) # align's the message to the right Streamlit Option MenuSelect a single item from a list of options in a menu. Created by @victoryhb.from streamlit_option_menu import option_menu option_menu(""Main Menu"", [""Home"", 'Settings'], icons=['house', 'gear'], menu_icon=""cast"", default_index=1) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.stoggle import stoggle stoggle( ""Click me!"", """"""🥷 Surprise! Here's some additional content"""""",) Streamlit ElementsCreate a draggable and resizable dashboard in Streamlit. Created by @okls.from streamlit_elements import elements, mui, html with elements(""new_element""): mui.Typography(""Hello world"") TagsAdd tags to your Streamlit apps. Created by @gagan3012.from streamlit_tags import st_tags st_tags(label='# Enter Keywords:', text='Press enter to add more', value=['Zero', 'One', 'Two'], suggestions=['five', 'six', 'seven', 'eight', 'nine', 'three', 'eleven', 'ten', 'four'], maxtags = 4, key='1') StqdmThe simplest way to handle a progress bar in streamlit app. Created by @Wirg.from stqdm import stqdm for _ in stqdm(range(50)): sleep(0.5) TimelineDisplay a Timeline in Streamlit apps using TimelineJS. Created by @innerdoc.from streamlit_timeline import timeline with open('example.json', ""r"") as f: timeline(f.read(), height=800) Camera input liveAlternative for st.camera_input which returns the webcam images live. Created by @blackary.from camera_input_live import camera_input_live image = camera_input_live() st.image(value) Streamlit AceAce editor component for Streamlit. Created by @okld.from streamlit_ace import st_ace content = st_ace() content Streamlit ChatStreamlit Component for a Chatbot UI. Created by @AI-Yash.from streamlit_chat import message message(""My message"") message(""Hello bot!"", is_user=True) # align's the message to the right Streamlit Option MenuSelect a single item from a list of options in a menu. Created by @victoryhb.from streamlit_option_menu import option_menu option_menu(""Main Menu"", [""Home"", 'Settings'], icons=['house', 'gear'], menu_icon=""cast"", default_index=1) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.stoggle import stoggle stoggle( ""Click me!"", """"""🥷 Surprise! Here's some additional content"""""",) Next Media elements ImageDisplay an image or list of images.st.image(numpy_array) st.image(image_bytes) st.image(file) st.image(""https://example.com/myimage.jpg"") AudioDisplay an audio player.st.audio(numpy_array) st.audio(audio_bytes) st.audio(file) st.audio(""https://example.com/myaudio.mp3"", format=""audio/mp3"") VideoDisplay a video player.st.video(numpy_array) st.video(video_bytes) st.video(file) st.video(""https://example.com/myvideo.mp4"", format=""video/mp4"") Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration! PreviousStreamlit CropperA simple image cropper for Streamlit. Created by @turner-anderson.from streamlit_cropper import st_cropper st_cropper(img, realtime_update=realtime_update, box_color=box_color, aspect_ratio=aspect_ratio) Image CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates streamlit_image_coordinates(""https://placekitten.com/200/300"") Streamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl(""https://assets5.lottiefiles.com/packages/lf20_V9t630.json"") st_lottie(lottie_hello, key=""hello"") Streamlit WebrtcHandling and transmitting real-time video/audio streams with Streamlit. Created by @whitphx.from streamlit_webrtc import webrtc_streamer webrtc_streamer(key=""sample"") Drawable CanvasProvides a sketching canvas using Fabric.js. Created by @andfanilo.from streamlit_drawable_canvas import st_canvas st_canvas(fill_color=""rgba(255, 165, 0, 0.3)"", stroke_width=stroke_width, stroke_color=stroke_color, background_color=bg_color, background_image=Image.open(bg_image) if bg_image else None, update_streamlit=realtime_update, height=150, drawing_mode=drawing_mode, point_display_radius=point_display_radius if drawing_mode == 'point' else 0, key=""canvas"",) Image ComparisonCompare images with a slider using JuxtaposeJS. Created by @fcakyon.from streamlit_image_comparison import image_comparison image_comparison(img1=""image1.jpg"", img2=""image2.jpg"",) Streamlit CropperA simple image cropper for Streamlit. Created by @turner-anderson.from streamlit_cropper import st_cropper st_cropper(img, realtime_update=realtime_update, box_color=box_color, aspect_ratio=aspect_ratio) Image CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates streamlit_image_coordinates(""https://placekitten.com/200/300"") Streamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl(""https://assets5.lottiefiles.com/packages/lf20_V9t630.json"") st_lottie(lottie_hello, key=""hello"") Streamlit WebrtcHandling and transmitting real-time video/audio streams with Streamlit. Created by @whitphx.from streamlit_webrtc import webrtc_streamer webrtc_streamer(key=""sample"") Drawable CanvasProvides a sketching canvas using Fabric.js. Created by @andfanilo.from streamlit_drawable_canvas import st_canvas st_canvas(fill_color=""rgba(255, 165, 0, 0.3)"", stroke_width=stroke_width, stroke_color=stroke_color, background_color=bg_color, background_image=Image.open(bg_image) if bg_image else None, update_streamlit=realtime_update, height=150, drawing_mode=drawing_mode, point_display_radius=point_display_radius if drawing_mode == 'point' else 0, key=""canvas"",) Image ComparisonCompare images with a slider using JuxtaposeJS. Created by @fcakyon.from streamlit_image_comparison import image_comparison image_comparison(img1=""image1.jpg"", img2=""image2.jpg"",) Streamlit CropperA simple image cropper for Streamlit. Created by @turner-anderson.from streamlit_cropper import st_cropper st_cropper(img, realtime_update=realtime_update, box_color=box_color, aspect_ratio=aspect_ratio) Image CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates streamlit_image_coordinates(""https://placekitten.com/200/300"") Streamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl(""https://assets5.lottiefiles.com/packages/lf20_V9t630.json"") st_lottie(lottie_hello, key=""hello"") Next Layouts and containers ColumnsInsert containers laid out as side-by-side columns.col1, col2 = st.columns(2) col1.write(""this is column 1"") col2.write(""this is column 2"") ContainerInsert a multi-element container.c = st.container() st.write(""This will show last"") c.write(""This will show first"") c.write(""This will show second"") Modal dialogsInsert a modal dialog that can rerun independently from the rest of the script.@st.experimental_dialog(""Sign up"") def email_form(): name = st.text_input(""Name"") email = st.text_input(""Email"") EmptyInsert a single-element container.c = st.empty() st.write(""This will show last"") c.write(""This will be replaced"") c.write(""This will show first"") ExpanderInsert a multi-element container that can be expanded/collapsed.with st.expander(""Open to see more""): st.write(""This is more content"") PopoverInsert a multi-element popover container that can be opened/closed.with st.popover(""Settings""): st.checkbox(""Show completed"") SidebarDisplay items in a sidebar.st.sidebar.write(""This lives in the sidebar"") st.sidebar.button(""Click me!"") TabsInsert containers separated into tabs.tab1, tab2 = st.tabs([""Tab 1"", ""Tab2""]) tab1.write(""this is tab 1"") tab2.write(""this is tab 2"") Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration!Streamlit ElementsCreate a draggable and resizable dashboard in Streamlit. Created by @okls.from streamlit_elements import elements, mui, html with elements(""new_element""): mui.Typography(""Hello world"") PydanticAuto-generate Streamlit UI from Pydantic Models and Dataclasses. Created by @lukasmasuch.import streamlit_pydantic as sp sp.pydantic_form(key=""my_form"", model=ExampleModel) Streamlit PagesAn experimental version of Streamlit Multi-Page Apps. Created by @blackary.from st_pages import Page, show_pages, add_page_title show_pages([ Page(""streamlit_app.py"", ""Home"", ""🏠""), Page(""other_pages/page2.py"", ""Page 2"", "":books:""), ]) Chat elements Streamlit provides a few commands to help you build conversational apps. These chat elements are designed to be used in conjunction with each other, but you can also use them separately. st.chat_message lets you insert a chat message container into the app so you can display messages from the user or the app. Chat containers can contain other Streamlit elements, including charts, tables, text, and more. st.chat_input lets you display a chat input widget so the user can type in a message. Chat inputDisplay a chat input widget.prompt = st.chat_input(""Say something"") if prompt: st.write(f""The user has sent: {prompt}"") Chat messageInsert a chat message container.import numpy as np with st.chat_message(""user""): st.write(""Hello 👋"") st.line_chart(np.random.randn(30, 3)) Status containerDisplay output of long-running tasks in a container.with st.status('Running'): do_something_slow() st.write_streamWrite generators or streams to the app with a typewriter effect.st.write_stream(my_generator) st.write_stream(my_llm_stream) Status elements Progress barDisplay a progress bar.for i in range(101): st.progress(i) do_something_slow() SpinnerTemporarily displays a message while executing a block of code.with st.spinner(""Please wait...""): do_something_slow() Status containerDisplay output of long-running tasks in a container.with st.status('Running'): do_something_slow() ToastBriefly displays a toast message in the bottom-right corner.st.toast('Butter!', icon='🧈') BalloonsDisplay celebratory balloons!do_something() # Celebrate when all done! st.balloons() SnowflakesDisplay celebratory snowflakes!do_something() # Celebrate when all done! st.snow() Success boxDisplay a success message.st.success(""Match found!"") Info boxDisplay an informational message.st.info(""Dataset is updated every day at midnight."") Warning boxDisplay warning message.st.warning(""Unable to fetch image. Skipping..."") Error boxDisplay error message.st.error(""We encountered an error"") Exception outputDisplay an exception.e = RuntimeError(""This is an exception of type RuntimeError"") st.exception(e) Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration!StqdmThe simplest way to handle a progress bar in streamlit app. Created by @Wirg.from stqdm import stqdm for _ in stqdm(range(50)): sleep(0.5) Custom notification boxA custom notification box with the ability to close it out. Created by @Socvest.from streamlit_custom_notification_box import custom_notification_box styles = {'material-icons':{'color': 'red'}, 'text-icon-link-close-container': {'box-shadow': '#3896de 0px 4px'}, 'notification-text': {'':''}, 'close-button':{'':''}, 'link':{'':''}} custom_notification_box(icon='info', textDisplay='We are almost done with your registration...', externalLink='more info', url='#', styles=styles, key=""foo"") Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.let_it_rain import rain rain(emoji=""🎈"", font_size=54, falling_speed=5, animation_length=""infinite"",) App logic and configuration Navigation and pages Switch pageProgrammatically navigates to a specified page.st.switch_page(""pages/my_page.py"") Page linkDisplay a link to another page in a multipage app.st.page_link(""app.py"", label=""Home"", icon=""🏠"") st.page_link(""pages/profile.py"", label=""My profile"") Execution flow Modal dialogsInsert a modal dialog that can rerun independently from the rest of the script.@st.experimental_dialog(""Sign up"") def email_form(): name = st.text_input(""Name"") email = st.text_input(""Email"") FormsCreate a form that batches elements together with a “Submit"" button.with st.form(key='my_form'): name = st.text_input(""Name"") email = st.text_input(""Email"") st.form_submit_button(""Sign up"") Partial rerunsDefine a fragment to rerun independently from the rest of the script.@st.experimental_fragment(run_every=""10s"") def fragment(): df = get_data() st.line_chart(df) Rerun scriptRerun the script immediately.st.rerun() Stop executionStops execution immediately.st.stop() Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration!AutorefreshForce a refresh without tying up a script. Created by @kmcgrady.from streamlit_autorefresh import st_autorefresh st_autorefresh(interval=2000, limit=100, key=""fizzbuzzcounter"") PydanticAuto-generate Streamlit UI from Pydantic Models and Dataclasses. Created by @lukasmasuch.import streamlit_pydantic as sp sp.pydantic_form(key=""my_form"", model=ExampleModel) Streamlit PagesAn experimental version of Streamlit Multi-Page Apps. Created by @blackary.from st_pages import Page, show_pages, add_page_title show_pages([ Page(""streamlit_app.py"", ""Home"", ""🏠""), Page(""other_pages/page2.py"", ""Page 2"", "":books:""), ]) Caching and state Cache dataFunction decorator to cache functions that return data (e.g. dataframe transforms, database queries, ML inference).@st.cache_data def long_function(param1, param2): # Perform expensive computation here or # fetch data from the web here return data Cache resourceFunction decorator to cache functions that return global resources (e.g. database connections, ML models).@st.cache_resource def init_model(): # Return a global resource here return pipeline( ""sentiment-analysis"", model=""distilbert-base-uncased-finetuned-sst-2-english"" ) Session stateSession state is a way to share variables between reruns, for each user session.st.session_state['key'] = value Query parametersGet, set, or clear the query parameters that are shown in the browser's URL bar.st.query_params[key] = value st.query_params.clear() Connections and databases Setup your connection Create a connectionConnect to a data source or APIconn = st.connection('pets_db', type='sql') pet_owners = conn.query('select * from pet_owners') st.dataframe(pet_owners) Built-in connections SnowflakeConnectionA connection to Snowflake.conn = st.connection('snowflake') SQLConnectionA connection to a SQL database using SQLAlchemy.conn = st.connection('sql') Build your own connections Connection base classBuild your own connection with BaseConnection.class MyConnection(BaseConnection[myconn.MyConnection]): def _connect(self, **kwargs) -> MyConnection: return myconn.connect(**self._secrets, **kwargs) def query(self, query): return self._instance.query(query) Secrets management Secrets singletonAccess secrets from a local TOML file.key = st.secrets[""OpenAI_key""] Secrets fileSave your secrets in a per-project or per-profile TOML file.OpenAI_key = """" Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration!AuthenticatorA secure authentication module to validate user credentials. Created by @mkhorasani.import streamlit_authenticator as stauth authenticator = stauth.Authenticate( config['credentials'], config['cookie']['name'], config['cookie']['key'], config['cookie']['expiry_days'], config['preauthorized']) WS localStorageA simple synchronous way of accessing localStorage from your app. Created by @gagangoku.from streamlit_ws_localstorage import injectWebsocketCode ret = conn.setLocalStorageVal(key='k1', val='v1') st.write('ret: ' + ret) Streamlit Auth0The fastest way to provide comprehensive login inside Streamlit. Created by @conradbez.from auth0_component import login_button user_info = login_button(clientId, domain = domain) st.write(user_info) Custom Components Declare a componentCreate and register a custom component.st.components.v1.declare_component( ""custom_slider"", ""/frontend"", ) HTMLDisplay an HTML string in an iframe.st.components.v1.html( ""

Foo bar.

"" ) iframeLoad a remote URL in an iframe.st.components.v1.iframe( ""docs.streamlit.io"" ) Utilities and user info User infost.experimental_user returns information about the logged-in user of private apps on Streamlit Community Cloud.if st.experimental_user.email == ""foo@corp.com"": st.write(""Welcome back, "", st.experimental_user.email) else: st.write(""You are not authorized to view this page."") Get helpDisplay object’s doc string, nicely formatted.st.help(st.write) st.help(pd.DataFrame) Render HTMLRenders HTML strings to your app.css = """""" """""" st.html(css) Configuration Configuration fileConfigures the default settings for your app.your-project/ ├── .streamlit/ │ └── config.toml └── your_app.py Set page title, favicon, and moreConfigures the default settings of the page.st.set_page_config( page_title=""My app"", page_icon="":shark:"", ) Developer tools App testing st.testing.v1.AppTestst.testing.v1.AppTest simulates a running Streamlit app for testing.from streamlit.testing.v1 import AppTest at = AppTest.from_file(""streamlit_app.py"") at.secrets[""WORD""] = ""Foobar"" at.run() assert not at.exception at.text_input(""word"").input(""Bazbat"").run() assert at.warning[0].value == ""Try again."" AppTest.from_filest.testing.v1.AppTest.from_file initializes a simulated app from a file.from streamlit.testing.v1 import AppTest at = AppTest.from_file(""streamlit_app.py"") at.run() AppTest.from_stringst.testing.v1.AppTest.from_string initializes a simulated app from a string.from streamlit.testing.v1 import AppTest at = AppTest.from_string(app_script_as_string) at.run() AppTest.from_functionst.testing.v1.AppTest.from_function initializes a simulated app from a function.from streamlit.testing.v1 import AppTest at = AppTest.from_function(app_script_as_callable) at.run() BlockA representation of container elements, including: st.chat_message st.columns st.sidebar st.tabs The main body of the app. # at.sidebar returns a Block at.sidebar.button[0].click().run() assert not at.exception ElementThe base class for representation of all elements, including: st.title st.header st.markdown st.dataframe # at.title returns a sequence of Title # Title inherits from Element assert at.title[0].value == ""My awesome app"" ButtonA representation of st.button and st.form_submit_button.at.button[0].click().run() ChatInputA representation of st.chat_input.at.chat_input[0].set_value(""What is Streamlit?"").run() CheckboxA representation of st.checkbox.at.checkbox[0].check().run() ColorPickerA representation of st.color_picker.at.color_picker[0].pick(""#FF4B4B"").run() DateInputA representation of st.date_input.release_date = datetime.date(2023, 10, 26) at.date_input[0].set_value(release_date).run() MultiselectA representation of st.multiselect.at.multiselect[0].select(""New York"").run() NumberInputA representation of st.number_input.at.number_input[0].increment().run() RadioA representation of st.radio.at.radio[0].set_value(""New York"").run() SelectSliderA representation of st.select_slider.at.select_slider[0].set_range(""A"",""C"").run() SelectboxA representation of st.selectbox.at.selectbox[0].select(""New York"").run() SliderA representation of st.slider.at.slider[0].set_range(2,5).run() TextAreaA representation of st.text_area.at.text_area[0].input(""Streamlit is awesome!"").run() TextInputA representation of st.text_input.at.text_input[0].input(""Streamlit"").run() TimeInputA representation of st.time_input.at.time_input[0].increment().run() ToggleA representation of st.toggle.at.toggle[0].set_value(""True"").run() Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration!Pandas ProfilingPandas profiling component for Streamlit. Created by @okld.df = pd.read_csv(""https://storage.googleapis.com/tf-datasets/titanic/train.csv"") pr = df.profile_report() st_profile_report(pr) Streamlit AceAce editor component for Streamlit. Created by @okld.from streamlit_ace import st_ace content = st_ace() content Streamlit AnalyticsTrack & visualize user interactions with your streamlit app. Created by @jrieke.import streamlit_analytics with streamlit_analytics.track(): st.text_input(""Write something"") Previous: ConceptsNext: Write and magicforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy" https://docs.streamlit.io/develop/tutorials/execution-flow#fragments,"DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceaddTutorialsremoveExecution flowremoveFRAGMENTSRerun your app from a fragmentCreate a multiple-container fragmentStart and stop a streaming fragmentConnect to data sourcesaddMultipage appsaddWork with LLMsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Develop/Tutorials/Execution flowUse core features to work with Streamlit's execution model Fragments Trigger a full-script rerun from inside a fragmentCall st.rerun from inside a fragment to trigger a full-script rerun when a condition is met.Create a fragment across multiple containersUse a fragment to write to multiple containers across your app.Start and stop a streaming fragmentUse a fragment to live-stream data. Use a button to start and stop the live-streaming.Previous: TutorialsNext: Rerun your app from a fragmentforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy" https://docs.streamlit.io/develop/tutorials/databases/gcs#create-a-google-cloud-storage-bucket-and-add-a-file,"DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceaddTutorialsremoveExecution flowaddConnect to data sourcesremoveAWS S3BigQueryDeta BaseFirestoreopen_in_newGoogle Cloud StorageMicrosoft SQL ServerMongoDBMySQLNeonPostgreSQLPrivate Google SheetPublic Google SheetSnowflakeSupabaseTableauTiDBTigerGraphMultipage appsaddWork with LLMsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Develop/Tutorials/Connect to data sources/Google Cloud StorageConnect Streamlit to Google Cloud Storage Introduction This guide explains how to securely access files on Google Cloud Storage from Streamlit Community Cloud. It uses Streamlit FilesConnection, the gcsfs library and Streamlit's Secrets management. Create a Google Cloud Storage bucket and add a file push_pinNoteIf you already have a bucket that you want to use, feel free to skip to the next step. First, sign up for Google Cloud Platform or log in. Go to the Google Cloud Storage console and create a new bucket. Navigate to the upload section of your new bucket: And upload the following CSV file, which contains some example data: myfile.csv Enable the Google Cloud Storage API The Google Cloud Storage API is enabled by default when you create a project through the Google Cloud Console or CLI. Feel free to skip to the next step. If you do need to enable the API for programmatic access in your project, head over to the APIs & Services dashboard (select or create a project if asked). Search for the Cloud Storage API and enable it. The screenshot below has a blue ""Manage"" button and indicates the ""API is enabled"" which means no further action needs to be taken. This is very likely what you have since the API is enabled by default. However, if that is not what you see and you have an ""Enable"" button, you'll need to enable the API: Create a service account and key file To use the Google Cloud Storage API from Streamlit, you need a Google Cloud Platform service account (a special type for programmatic data access). Go to the Service Accounts page and create an account with Viewer permission. push_pinNoteIf the button CREATE SERVICE ACCOUNT is gray, you don't have the correct permissions. Ask the admin of your Google Cloud project for help. After clicking DONE, you should be back on the service accounts overview. Create a JSON key file for the new account and download it: Add the key to your local app secrets Your local Streamlit app will read secrets from a file .streamlit/secrets.toml in your app's root directory. Create this file if it doesn't exist yet and add the access key to it as shown below: # .streamlit/secrets.toml [connections.gcs] type = ""service_account"" project_id = ""xxx"" private_key_id = ""xxx"" private_key = ""xxx"" client_email = ""xxx"" client_id = ""xxx"" auth_uri = ""https://accounts.google.com/o/oauth2/auth"" token_uri = ""https://oauth2.googleapis.com/token"" auth_provider_x509_cert_url = ""https://www.googleapis.com/oauth2/v1/certs"" client_x509_cert_url = ""xxx"" priority_highImportantAdd this file to .gitignore and don't commit it to your GitHub repo! Copy your app secrets to the cloud As the secrets.toml file above is not committed to GitHub, you need to pass its content to your deployed app (on Streamlit Community Cloud) separately. Go to the app dashboard and in the app's dropdown menu, click on Edit Secrets. Copy the content of secrets.toml into the text area. More information is available at Secrets management. Add FilesConnection and gcsfs to your requirements file Add the FilesConnection and gcsfs packages to your requirements.txt file, preferably pinning the versions (replace x.x.x with the version you want installed): # requirements.txt gcsfs==x.x.x st-files-connection Write your Streamlit app Copy the code below to your Streamlit app and run it. Make sure to adapt the name of your bucket and file. Note that Streamlit automatically turns the access keys from your secrets file into environment variables. # streamlit_app.py import streamlit as st from st_files_connection import FilesConnection # Create connection object and retrieve file contents. # Specify input format is a csv and to cache the result for 600 seconds. conn = st.connection('gcs', type=FilesConnection) df = conn.read(""streamlit-bucket/myfile.csv"", input_format=""csv"", ttl=600) # Print results. for row in df.itertuples(): st.write(f""{row.Owner} has a :{row.Pet}:"") See st.connection above? This handles secrets retrieval, setup, result caching and retries. By default, read() results are cached without expiring. In this case, we set ttl=600 to ensure the file contents is cached for no longer than 10 minutes. You can also set ttl=0 to disable caching. Learn more in Caching. If everything worked out (and you used the example file given above), your app should look like this: Previous: FirestoreNext: Microsoft SQL ServerforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy" https://docs.streamlit.io/develop/api-reference/#chart-elements,"DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceremovePAGE ELEMENTSWrite and magicaddText elementsaddData elementsaddChart elementsaddInput widgetsaddMedia elementsaddLayouts and containersaddChat elementsaddStatus elementsaddThird-party componentsopen_in_newAPPLICATION LOGICNavigation and pagesaddExecution flowaddCaching and stateaddConnections and secretsaddCustom componentsaddUtilitiesaddConfigurationaddTOOLSApp testingaddCommand lineaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Develop/API referenceAPI reference Streamlit makes it easy for you to visualize, mutate, and share data. The API reference is organized by activity type, like displaying data or optimizing performance. Each section includes methods associated with the activity type, including examples. Browse our API below and click to learn more about any of our available commands! 🎈 Display almost anything Write and magic st.writeWrite arguments to the app.st.write(""Hello **world**!"") st.write(my_data_frame) st.write(my_mpl_figure) st.write_streamWrite generators or streams to the app with a typewriter effect.st.write_stream(my_generator) st.write_stream(my_llm_stream) MagicAny time Streamlit sees either a variable or literal value on its own line, it automatically writes that to your app using st.write""Hello **world**!"" my_data_frame my_mpl_figure Text elements MarkdownDisplay string formatted as Markdown.st.markdown(""Hello **world**!"") TitleDisplay text in title formatting.st.title(""The app title"") HeaderDisplay text in header formatting.st.header(""This is a header"") SubheaderDisplay text in subheader formatting.st.subheader(""This is a subheader"") CaptionDisplay text in small font.st.caption(""This is written small caption text"") Code blockDisplay a code block with optional syntax highlighting.st.code(""a = 1234"") EchoDisplay some code in the app, then execute it. Useful for tutorials.with st.echo(): st.write('This code will be printed') LaTeXDisplay mathematical expressions formatted as LaTeX.st.latex(""\int a x^2 \,dx"") Preformatted textWrite fixed-width and preformatted text.st.text(""Hello world"") DividerDisplay a horizontal rule.st.divider() Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration! PreviousTagsAdd tags to your Streamlit apps. Created by @gagan3012.st_tags(label='# Enter Keywords:', text='Press enter to add more', value=['Zero', 'One', 'Two'], suggestions=['five', 'six', 'seven', 'eight', 'nine', 'three', 'eleven', 'ten', 'four'], maxtags = 4, key='1') NLUApply text mining on a dataframe. Created by @JohnSnowLabs.nlu.load('sentiment').predict('I love NLU! <3') Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.mention(label=""An awesome Streamlit App"", icon=""streamlit"", url=""https://extras.streamlit.app"",) Annotated textDisplay annotated text in Streamlit apps. Created by @tvst.annotated_text(""This "", (""is"", ""verb""), "" some "", (""annotated"", ""adj""), (""text"", ""noun""), "" for those of "", (""you"", ""pronoun""), "" who "", (""like"", ""verb""), "" this sort of "", (""thing"", ""noun""), ""."") Drawable CanvasProvides a sketching canvas using Fabric.js. Created by @andfanilo.st_canvas(fill_color=""rgba(255, 165, 0, 0.3)"", stroke_width=stroke_width, stroke_color=stroke_color, background_color=bg_color, background_image=Image.open(bg_image) if bg_image else None, update_streamlit=realtime_update, height=150, drawing_mode=drawing_mode, point_display_radius=point_display_radius if drawing_mode == 'point' else 0, key=""canvas"",) TagsAdd tags to your Streamlit apps. Created by @gagan3012.st_tags(label='# Enter Keywords:', text='Press enter to add more', value=['Zero', 'One', 'Two'], suggestions=['five', 'six', 'seven', 'eight', 'nine', 'three', 'eleven', 'ten', 'four'], maxtags = 4, key='1') NLUApply text mining on a dataframe. Created by @JohnSnowLabs.nlu.load('sentiment').predict('I love NLU! <3') Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.mention(label=""An awesome Streamlit App"", icon=""streamlit"", url=""https://extras.streamlit.app"",) Annotated textDisplay annotated text in Streamlit apps. Created by @tvst.annotated_text(""This "", (""is"", ""verb""), "" some "", (""annotated"", ""adj""), (""text"", ""noun""), "" for those of "", (""you"", ""pronoun""), "" who "", (""like"", ""verb""), "" this sort of "", (""thing"", ""noun""), ""."") Drawable CanvasProvides a sketching canvas using Fabric.js. Created by @andfanilo.st_canvas(fill_color=""rgba(255, 165, 0, 0.3)"", stroke_width=stroke_width, stroke_color=stroke_color, background_color=bg_color, background_image=Image.open(bg_image) if bg_image else None, update_streamlit=realtime_update, height=150, drawing_mode=drawing_mode, point_display_radius=point_display_radius if drawing_mode == 'point' else 0, key=""canvas"",) TagsAdd tags to your Streamlit apps. Created by @gagan3012.st_tags(label='# Enter Keywords:', text='Press enter to add more', value=['Zero', 'One', 'Two'], suggestions=['five', 'six', 'seven', 'eight', 'nine', 'three', 'eleven', 'ten', 'four'], maxtags = 4, key='1') NLUApply text mining on a dataframe. Created by @JohnSnowLabs.nlu.load('sentiment').predict('I love NLU! <3') Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.mention(label=""An awesome Streamlit App"", icon=""streamlit"", url=""https://extras.streamlit.app"",) Next Data elements DataframesDisplay a dataframe as an interactive table.st.dataframe(my_data_frame) Data editorDisplay a data editor widget.edited = st.data_editor(df, num_rows=""dynamic"") Column configurationConfigure the display and editing behavior of dataframes and data editors.st.column_config.NumberColumn(""Price (in USD)"", min_value=0, format=""$%d"") Static tablesDisplay a static table.st.table(my_data_frame) MetricsDisplay a metric in big bold font, with an optional indicator of how the metric changed.st.metric(""My metric"", 42, 2) Dicts and JSONDisplay object or string as a pretty-printed JSON string.st.json(my_dict) Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration! PreviousImage CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates value = streamlit_image_coordinates(""https://placekitten.com/200/300"") st.write(value) Plotly EventsMake Plotly charts interactive!. Created by @null-jones.from streamlit_plotly_events import plotly_events fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.metric_cards import style_metric_cards col3.metric(label=""No Change"", value=5000, delta=0) style_metric_cards() Streamlit AggridImplementation of Ag-Grid component for Streamlit. Created by @PablocFonseca.df = pd.DataFrame({'col1': [1, 2, 3], 'col2': [4, 5, 6]}) grid_return = AgGrid(df, editable=True) new_df = grid_return['data'] Streamlit FoliumStreamlit Component for rendering Folium maps. Created by @randyzwitch.m = folium.Map(location=[39.949610, -75.150282], zoom_start=16) folium.Marker([39.949610, -75.150282], popup=""Liberty Bell"", tooltip=""Liberty Bell"").add_to(m) st_data = st_folium(m, width=725) Pandas ProfilingPandas profiling component for Streamlit. Created by @okld.df = pd.read_csv(""https://storage.googleapis.com/tf-datasets/titanic/train.csv"") pr = df.profile_report() st_profile_report(pr) Image CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates value = streamlit_image_coordinates(""https://placekitten.com/200/300"") st.write(value) Plotly EventsMake Plotly charts interactive!. Created by @null-jones.from streamlit_plotly_events import plotly_events fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.metric_cards import style_metric_cards col3.metric(label=""No Change"", value=5000, delta=0) style_metric_cards() Streamlit AggridImplementation of Ag-Grid component for Streamlit. Created by @PablocFonseca.df = pd.DataFrame({'col1': [1, 2, 3], 'col2': [4, 5, 6]}) grid_return = AgGrid(df, editable=True) new_df = grid_return['data'] Streamlit FoliumStreamlit Component for rendering Folium maps. Created by @randyzwitch.m = folium.Map(location=[39.949610, -75.150282], zoom_start=16) folium.Marker([39.949610, -75.150282], popup=""Liberty Bell"", tooltip=""Liberty Bell"").add_to(m) st_data = st_folium(m, width=725) Pandas ProfilingPandas profiling component for Streamlit. Created by @okld.df = pd.read_csv(""https://storage.googleapis.com/tf-datasets/titanic/train.csv"") pr = df.profile_report() st_profile_report(pr) Image CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates value = streamlit_image_coordinates(""https://placekitten.com/200/300"") st.write(value) Plotly EventsMake Plotly charts interactive!. Created by @null-jones.from streamlit_plotly_events import plotly_events fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.metric_cards import style_metric_cards col3.metric(label=""No Change"", value=5000, delta=0) style_metric_cards() Next Chart elements Simple area chartsDisplay an area chart.st.area_chart(my_data_frame) Simple bar chartsDisplay a bar chart.st.bar_chart(my_data_frame) Simple line chartsDisplay a line chart.st.line_chart(my_data_frame) Simple scatter chartsDisplay a line chart.st.scatter_chart(my_data_frame) Scatterplots on mapsDisplay a map with points on it.st.map(my_data_frame) MatplotlibDisplay a matplotlib.pyplot figure.st.pyplot(my_mpl_figure) AltairDisplay a chart using the Altair library.st.altair_chart(my_altair_chart) Vega-LiteDisplay a chart using the Vega-Lite library.st.vega_lite_chart(my_vega_lite_chart) PlotlyDisplay an interactive Plotly chart.st.plotly_chart(my_plotly_chart) BokehDisplay an interactive Bokeh chart.st.bokeh_chart(my_bokeh_chart) PyDeckDisplay a chart using the PyDeck library.st.pydeck_chart(my_pydeck_chart) GraphVizDisplay a graph using the dagre-d3 library.st.graphviz_chart(my_graphviz_spec) Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration! PreviousStreamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl(""https://assets5.lottiefiles.com/packages/lf20_V9t630.json"") st_lottie(lottie_hello, key=""hello"") Plotly EventsMake Plotly charts interactive!. Created by @null-jones.fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.chart += get_annotations_chart(annotations=[(""Mar 01, 2008"", ""Pretty good day for GOOG""), (""Dec 01, 2007"", ""Something's going wrong for GOOG & AAPL""), (""Nov 01, 2008"", ""Market starts again thanks to...""), (""Dec 01, 2009"", ""Small crash for GOOG after...""),],) st.altair_chart(chart, use_container_width=True) PlostA deceptively simple plotting library for Streamlit. Created by @tvst.import plost plost.line_chart(my_dataframe, x='time', y='stock_value', color='stock_name',) HiPlotHigh dimensional Interactive Plotting. Created by @facebookresearch.data = [{'dropout':0.1, 'lr': 0.001, 'loss': 10.0, 'optimizer': 'SGD'}, {'dropout':0.15, 'lr': 0.01, 'loss': 3.5, 'optimizer': 'Adam'}, {'dropout':0.3, 'lr': 0.1, 'loss': 4.5, 'optimizer': 'Adam'}] hip.Experiment.from_iterable(data).display() EChartsHigh dimensional Interactive Plotting. Created by @andfanilo.from streamlit_echarts import st_echarts st_echarts(options=options) Streamlit FoliumStreamlit Component for rendering Folium maps. Created by @randyzwitch.m = folium.Map(location=[39.949610, -75.150282], zoom_start=16) st_data = st_folium(m, width=725) Spacy-StreamlitspaCy building blocks and visualizers for Streamlit apps. Created by @explosion.models = [""en_core_web_sm"", ""en_core_web_md""] spacy_streamlit.visualize(models, ""Sundar Pichai is the CEO of Google."") Streamlit AgraphA Streamlit Graph Vis, based on react-grah-vis. Created by @ChrisDelClea.from streamlit_agraph import agraph, Node, Edge, Config agraph(nodes=nodes, edges=edges, config=config) Streamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl(""https://assets5.lottiefiles.com/packages/lf20_V9t630.json"") st_lottie(lottie_hello, key=""hello"") Plotly EventsMake Plotly charts interactive!. Created by @null-jones.fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.chart += get_annotations_chart(annotations=[(""Mar 01, 2008"", ""Pretty good day for GOOG""), (""Dec 01, 2007"", ""Something's going wrong for GOOG & AAPL""), (""Nov 01, 2008"", ""Market starts again thanks to...""), (""Dec 01, 2009"", ""Small crash for GOOG after...""),],) st.altair_chart(chart, use_container_width=True) PlostA deceptively simple plotting library for Streamlit. Created by @tvst.import plost plost.line_chart(my_dataframe, x='time', y='stock_value', color='stock_name',) HiPlotHigh dimensional Interactive Plotting. Created by @facebookresearch.data = [{'dropout':0.1, 'lr': 0.001, 'loss': 10.0, 'optimizer': 'SGD'}, {'dropout':0.15, 'lr': 0.01, 'loss': 3.5, 'optimizer': 'Adam'}, {'dropout':0.3, 'lr': 0.1, 'loss': 4.5, 'optimizer': 'Adam'}] hip.Experiment.from_iterable(data).display() EChartsHigh dimensional Interactive Plotting. Created by @andfanilo.from streamlit_echarts import st_echarts st_echarts(options=options) Streamlit FoliumStreamlit Component for rendering Folium maps. Created by @randyzwitch.m = folium.Map(location=[39.949610, -75.150282], zoom_start=16) st_data = st_folium(m, width=725) Spacy-StreamlitspaCy building blocks and visualizers for Streamlit apps. Created by @explosion.models = [""en_core_web_sm"", ""en_core_web_md""] spacy_streamlit.visualize(models, ""Sundar Pichai is the CEO of Google."") Streamlit AgraphA Streamlit Graph Vis, based on react-grah-vis. Created by @ChrisDelClea.from streamlit_agraph import agraph, Node, Edge, Config agraph(nodes=nodes, edges=edges, config=config) Streamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl(""https://assets5.lottiefiles.com/packages/lf20_V9t630.json"") st_lottie(lottie_hello, key=""hello"") Plotly EventsMake Plotly charts interactive!. Created by @null-jones.fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.chart += get_annotations_chart(annotations=[(""Mar 01, 2008"", ""Pretty good day for GOOG""), (""Dec 01, 2007"", ""Something's going wrong for GOOG & AAPL""), (""Nov 01, 2008"", ""Market starts again thanks to...""), (""Dec 01, 2009"", ""Small crash for GOOG after...""),],) st.altair_chart(chart, use_container_width=True) Next Input widgets ButtonDisplay a button widget.clicked = st.button(""Click me"") Download buttonDisplay a download button widget.st.download_button(""Download file"", file) Form buttonDisplay a form submit button. For use with st.form.st.form_submit_button(""Sign up"") Link buttonDisplay a link button.st.link_button(""Go to gallery"", url) Page linkDisplay a link to another page in a multipage app.st.page_link(""app.py"", label=""Home"", icon=""🏠"") st.page_link(""pages/profile.py"", label=""My profile"") CheckboxDisplay a checkbox widget.selected = st.checkbox(""I agree"") Color pickerDisplay a color picker widget.color = st.color_picker(""Pick a color"") MultiselectDisplay a multiselect widget. The multiselect widget starts as empty.choices = st.multiselect(""Buy"", [""milk"", ""apples"", ""potatoes""]) RadioDisplay a radio button widget.choice = st.radio(""Pick one"", [""cats"", ""dogs""]) SelectboxDisplay a select widget.choice = st.selectbox(""Pick one"", [""cats"", ""dogs""]) Select-sliderDisplay a slider widget to select items from a list.size = st.select_slider(""Pick a size"", [""S"", ""M"", ""L""]) ToggleDisplay a toggle widget.activated = st.toggle(""Activate"") Number inputDisplay a numeric input widget.choice = st.number_input(""Pick a number"", 0, 10) SliderDisplay a slider widget.number = st.slider(""Pick a number"", 0, 100) Date inputDisplay a date input widget.date = st.date_input(""Your birthday"") Time inputDisplay a time input widget.time = st.time_input(""Meeting time"") Chat inputDisplay a chat input widget.prompt = st.chat_input(""Say something"") if prompt: st.write(f""The user has sent: {prompt}"") Text-areaDisplay a multi-line text input widget.text = st.text_area(""Text to translate"") Text inputDisplay a single-line text input widget.name = st.text_input(""First name"") Data editorDisplay a data editor widget.edited = st.experimental_data_editor(df, num_rows=""dynamic"") File UploaderDisplay a file uploader widget.data = st.file_uploader(""Upload a CSV"") Camera inputDisplay a widget that allows users to upload images directly from a camera.image = st.camera_input(""Take a picture"") Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration! PreviousStreamlit ChatStreamlit Component for a Chatbot UI. Created by @AI-Yash.from streamlit_chat import message message(""My message"") message(""Hello bot!"", is_user=True) # align's the message to the right Streamlit Option MenuSelect a single item from a list of options in a menu. Created by @victoryhb.from streamlit_option_menu import option_menu option_menu(""Main Menu"", [""Home"", 'Settings'], icons=['house', 'gear'], menu_icon=""cast"", default_index=1) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.stoggle import stoggle stoggle( ""Click me!"", """"""🥷 Surprise! Here's some additional content"""""",) Streamlit ElementsCreate a draggable and resizable dashboard in Streamlit. Created by @okls.from streamlit_elements import elements, mui, html with elements(""new_element""): mui.Typography(""Hello world"") TagsAdd tags to your Streamlit apps. Created by @gagan3012.from streamlit_tags import st_tags st_tags(label='# Enter Keywords:', text='Press enter to add more', value=['Zero', 'One', 'Two'], suggestions=['five', 'six', 'seven', 'eight', 'nine', 'three', 'eleven', 'ten', 'four'], maxtags = 4, key='1') StqdmThe simplest way to handle a progress bar in streamlit app. Created by @Wirg.from stqdm import stqdm for _ in stqdm(range(50)): sleep(0.5) TimelineDisplay a Timeline in Streamlit apps using TimelineJS. Created by @innerdoc.from streamlit_timeline import timeline with open('example.json', ""r"") as f: timeline(f.read(), height=800) Camera input liveAlternative for st.camera_input which returns the webcam images live. Created by @blackary.from camera_input_live import camera_input_live image = camera_input_live() st.image(value) Streamlit AceAce editor component for Streamlit. Created by @okld.from streamlit_ace import st_ace content = st_ace() content Streamlit ChatStreamlit Component for a Chatbot UI. Created by @AI-Yash.from streamlit_chat import message message(""My message"") message(""Hello bot!"", is_user=True) # align's the message to the right Streamlit Option MenuSelect a single item from a list of options in a menu. Created by @victoryhb.from streamlit_option_menu import option_menu option_menu(""Main Menu"", [""Home"", 'Settings'], icons=['house', 'gear'], menu_icon=""cast"", default_index=1) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.stoggle import stoggle stoggle( ""Click me!"", """"""🥷 Surprise! Here's some additional content"""""",) Streamlit ElementsCreate a draggable and resizable dashboard in Streamlit. Created by @okls.from streamlit_elements import elements, mui, html with elements(""new_element""): mui.Typography(""Hello world"") TagsAdd tags to your Streamlit apps. Created by @gagan3012.from streamlit_tags import st_tags st_tags(label='# Enter Keywords:', text='Press enter to add more', value=['Zero', 'One', 'Two'], suggestions=['five', 'six', 'seven', 'eight', 'nine', 'three', 'eleven', 'ten', 'four'], maxtags = 4, key='1') StqdmThe simplest way to handle a progress bar in streamlit app. Created by @Wirg.from stqdm import stqdm for _ in stqdm(range(50)): sleep(0.5) TimelineDisplay a Timeline in Streamlit apps using TimelineJS. Created by @innerdoc.from streamlit_timeline import timeline with open('example.json', ""r"") as f: timeline(f.read(), height=800) Camera input liveAlternative for st.camera_input which returns the webcam images live. Created by @blackary.from camera_input_live import camera_input_live image = camera_input_live() st.image(value) Streamlit AceAce editor component for Streamlit. Created by @okld.from streamlit_ace import st_ace content = st_ace() content Streamlit ChatStreamlit Component for a Chatbot UI. Created by @AI-Yash.from streamlit_chat import message message(""My message"") message(""Hello bot!"", is_user=True) # align's the message to the right Streamlit Option MenuSelect a single item from a list of options in a menu. Created by @victoryhb.from streamlit_option_menu import option_menu option_menu(""Main Menu"", [""Home"", 'Settings'], icons=['house', 'gear'], menu_icon=""cast"", default_index=1) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.stoggle import stoggle stoggle( ""Click me!"", """"""🥷 Surprise! Here's some additional content"""""",) Next Media elements ImageDisplay an image or list of images.st.image(numpy_array) st.image(image_bytes) st.image(file) st.image(""https://example.com/myimage.jpg"") AudioDisplay an audio player.st.audio(numpy_array) st.audio(audio_bytes) st.audio(file) st.audio(""https://example.com/myaudio.mp3"", format=""audio/mp3"") VideoDisplay a video player.st.video(numpy_array) st.video(video_bytes) st.video(file) st.video(""https://example.com/myvideo.mp4"", format=""video/mp4"") Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration! PreviousStreamlit CropperA simple image cropper for Streamlit. Created by @turner-anderson.from streamlit_cropper import st_cropper st_cropper(img, realtime_update=realtime_update, box_color=box_color, aspect_ratio=aspect_ratio) Image CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates streamlit_image_coordinates(""https://placekitten.com/200/300"") Streamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl(""https://assets5.lottiefiles.com/packages/lf20_V9t630.json"") st_lottie(lottie_hello, key=""hello"") Streamlit WebrtcHandling and transmitting real-time video/audio streams with Streamlit. Created by @whitphx.from streamlit_webrtc import webrtc_streamer webrtc_streamer(key=""sample"") Drawable CanvasProvides a sketching canvas using Fabric.js. Created by @andfanilo.from streamlit_drawable_canvas import st_canvas st_canvas(fill_color=""rgba(255, 165, 0, 0.3)"", stroke_width=stroke_width, stroke_color=stroke_color, background_color=bg_color, background_image=Image.open(bg_image) if bg_image else None, update_streamlit=realtime_update, height=150, drawing_mode=drawing_mode, point_display_radius=point_display_radius if drawing_mode == 'point' else 0, key=""canvas"",) Image ComparisonCompare images with a slider using JuxtaposeJS. Created by @fcakyon.from streamlit_image_comparison import image_comparison image_comparison(img1=""image1.jpg"", img2=""image2.jpg"",) Streamlit CropperA simple image cropper for Streamlit. Created by @turner-anderson.from streamlit_cropper import st_cropper st_cropper(img, realtime_update=realtime_update, box_color=box_color, aspect_ratio=aspect_ratio) Image CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates streamlit_image_coordinates(""https://placekitten.com/200/300"") Streamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl(""https://assets5.lottiefiles.com/packages/lf20_V9t630.json"") st_lottie(lottie_hello, key=""hello"") Streamlit WebrtcHandling and transmitting real-time video/audio streams with Streamlit. Created by @whitphx.from streamlit_webrtc import webrtc_streamer webrtc_streamer(key=""sample"") Drawable CanvasProvides a sketching canvas using Fabric.js. Created by @andfanilo.from streamlit_drawable_canvas import st_canvas st_canvas(fill_color=""rgba(255, 165, 0, 0.3)"", stroke_width=stroke_width, stroke_color=stroke_color, background_color=bg_color, background_image=Image.open(bg_image) if bg_image else None, update_streamlit=realtime_update, height=150, drawing_mode=drawing_mode, point_display_radius=point_display_radius if drawing_mode == 'point' else 0, key=""canvas"",) Image ComparisonCompare images with a slider using JuxtaposeJS. Created by @fcakyon.from streamlit_image_comparison import image_comparison image_comparison(img1=""image1.jpg"", img2=""image2.jpg"",) Streamlit CropperA simple image cropper for Streamlit. Created by @turner-anderson.from streamlit_cropper import st_cropper st_cropper(img, realtime_update=realtime_update, box_color=box_color, aspect_ratio=aspect_ratio) Image CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates streamlit_image_coordinates(""https://placekitten.com/200/300"") Streamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl(""https://assets5.lottiefiles.com/packages/lf20_V9t630.json"") st_lottie(lottie_hello, key=""hello"") Next Layouts and containers ColumnsInsert containers laid out as side-by-side columns.col1, col2 = st.columns(2) col1.write(""this is column 1"") col2.write(""this is column 2"") ContainerInsert a multi-element container.c = st.container() st.write(""This will show last"") c.write(""This will show first"") c.write(""This will show second"") Modal dialogsInsert a modal dialog that can rerun independently from the rest of the script.@st.experimental_dialog(""Sign up"") def email_form(): name = st.text_input(""Name"") email = st.text_input(""Email"") EmptyInsert a single-element container.c = st.empty() st.write(""This will show last"") c.write(""This will be replaced"") c.write(""This will show first"") ExpanderInsert a multi-element container that can be expanded/collapsed.with st.expander(""Open to see more""): st.write(""This is more content"") PopoverInsert a multi-element popover container that can be opened/closed.with st.popover(""Settings""): st.checkbox(""Show completed"") SidebarDisplay items in a sidebar.st.sidebar.write(""This lives in the sidebar"") st.sidebar.button(""Click me!"") TabsInsert containers separated into tabs.tab1, tab2 = st.tabs([""Tab 1"", ""Tab2""]) tab1.write(""this is tab 1"") tab2.write(""this is tab 2"") Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration!Streamlit ElementsCreate a draggable and resizable dashboard in Streamlit. Created by @okls.from streamlit_elements import elements, mui, html with elements(""new_element""): mui.Typography(""Hello world"") PydanticAuto-generate Streamlit UI from Pydantic Models and Dataclasses. Created by @lukasmasuch.import streamlit_pydantic as sp sp.pydantic_form(key=""my_form"", model=ExampleModel) Streamlit PagesAn experimental version of Streamlit Multi-Page Apps. Created by @blackary.from st_pages import Page, show_pages, add_page_title show_pages([ Page(""streamlit_app.py"", ""Home"", ""🏠""), Page(""other_pages/page2.py"", ""Page 2"", "":books:""), ]) Chat elements Streamlit provides a few commands to help you build conversational apps. These chat elements are designed to be used in conjunction with each other, but you can also use them separately. st.chat_message lets you insert a chat message container into the app so you can display messages from the user or the app. Chat containers can contain other Streamlit elements, including charts, tables, text, and more. st.chat_input lets you display a chat input widget so the user can type in a message. Chat inputDisplay a chat input widget.prompt = st.chat_input(""Say something"") if prompt: st.write(f""The user has sent: {prompt}"") Chat messageInsert a chat message container.import numpy as np with st.chat_message(""user""): st.write(""Hello 👋"") st.line_chart(np.random.randn(30, 3)) Status containerDisplay output of long-running tasks in a container.with st.status('Running'): do_something_slow() st.write_streamWrite generators or streams to the app with a typewriter effect.st.write_stream(my_generator) st.write_stream(my_llm_stream) Status elements Progress barDisplay a progress bar.for i in range(101): st.progress(i) do_something_slow() SpinnerTemporarily displays a message while executing a block of code.with st.spinner(""Please wait...""): do_something_slow() Status containerDisplay output of long-running tasks in a container.with st.status('Running'): do_something_slow() ToastBriefly displays a toast message in the bottom-right corner.st.toast('Butter!', icon='🧈') BalloonsDisplay celebratory balloons!do_something() # Celebrate when all done! st.balloons() SnowflakesDisplay celebratory snowflakes!do_something() # Celebrate when all done! st.snow() Success boxDisplay a success message.st.success(""Match found!"") Info boxDisplay an informational message.st.info(""Dataset is updated every day at midnight."") Warning boxDisplay warning message.st.warning(""Unable to fetch image. Skipping..."") Error boxDisplay error message.st.error(""We encountered an error"") Exception outputDisplay an exception.e = RuntimeError(""This is an exception of type RuntimeError"") st.exception(e) Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration!StqdmThe simplest way to handle a progress bar in streamlit app. Created by @Wirg.from stqdm import stqdm for _ in stqdm(range(50)): sleep(0.5) Custom notification boxA custom notification box with the ability to close it out. Created by @Socvest.from streamlit_custom_notification_box import custom_notification_box styles = {'material-icons':{'color': 'red'}, 'text-icon-link-close-container': {'box-shadow': '#3896de 0px 4px'}, 'notification-text': {'':''}, 'close-button':{'':''}, 'link':{'':''}} custom_notification_box(icon='info', textDisplay='We are almost done with your registration...', externalLink='more info', url='#', styles=styles, key=""foo"") Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.let_it_rain import rain rain(emoji=""🎈"", font_size=54, falling_speed=5, animation_length=""infinite"",) App logic and configuration Navigation and pages Switch pageProgrammatically navigates to a specified page.st.switch_page(""pages/my_page.py"") Page linkDisplay a link to another page in a multipage app.st.page_link(""app.py"", label=""Home"", icon=""🏠"") st.page_link(""pages/profile.py"", label=""My profile"") Execution flow Modal dialogsInsert a modal dialog that can rerun independently from the rest of the script.@st.experimental_dialog(""Sign up"") def email_form(): name = st.text_input(""Name"") email = st.text_input(""Email"") FormsCreate a form that batches elements together with a “Submit"" button.with st.form(key='my_form'): name = st.text_input(""Name"") email = st.text_input(""Email"") st.form_submit_button(""Sign up"") Partial rerunsDefine a fragment to rerun independently from the rest of the script.@st.experimental_fragment(run_every=""10s"") def fragment(): df = get_data() st.line_chart(df) Rerun scriptRerun the script immediately.st.rerun() Stop executionStops execution immediately.st.stop() Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration!AutorefreshForce a refresh without tying up a script. Created by @kmcgrady.from streamlit_autorefresh import st_autorefresh st_autorefresh(interval=2000, limit=100, key=""fizzbuzzcounter"") PydanticAuto-generate Streamlit UI from Pydantic Models and Dataclasses. Created by @lukasmasuch.import streamlit_pydantic as sp sp.pydantic_form(key=""my_form"", model=ExampleModel) Streamlit PagesAn experimental version of Streamlit Multi-Page Apps. Created by @blackary.from st_pages import Page, show_pages, add_page_title show_pages([ Page(""streamlit_app.py"", ""Home"", ""🏠""), Page(""other_pages/page2.py"", ""Page 2"", "":books:""), ]) Caching and state Cache dataFunction decorator to cache functions that return data (e.g. dataframe transforms, database queries, ML inference).@st.cache_data def long_function(param1, param2): # Perform expensive computation here or # fetch data from the web here return data Cache resourceFunction decorator to cache functions that return global resources (e.g. database connections, ML models).@st.cache_resource def init_model(): # Return a global resource here return pipeline( ""sentiment-analysis"", model=""distilbert-base-uncased-finetuned-sst-2-english"" ) Session stateSession state is a way to share variables between reruns, for each user session.st.session_state['key'] = value Query parametersGet, set, or clear the query parameters that are shown in the browser's URL bar.st.query_params[key] = value st.query_params.clear() Connections and databases Setup your connection Create a connectionConnect to a data source or APIconn = st.connection('pets_db', type='sql') pet_owners = conn.query('select * from pet_owners') st.dataframe(pet_owners) Built-in connections SnowflakeConnectionA connection to Snowflake.conn = st.connection('snowflake') SQLConnectionA connection to a SQL database using SQLAlchemy.conn = st.connection('sql') Build your own connections Connection base classBuild your own connection with BaseConnection.class MyConnection(BaseConnection[myconn.MyConnection]): def _connect(self, **kwargs) -> MyConnection: return myconn.connect(**self._secrets, **kwargs) def query(self, query): return self._instance.query(query) Secrets management Secrets singletonAccess secrets from a local TOML file.key = st.secrets[""OpenAI_key""] Secrets fileSave your secrets in a per-project or per-profile TOML file.OpenAI_key = """" Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration!AuthenticatorA secure authentication module to validate user credentials. Created by @mkhorasani.import streamlit_authenticator as stauth authenticator = stauth.Authenticate( config['credentials'], config['cookie']['name'], config['cookie']['key'], config['cookie']['expiry_days'], config['preauthorized']) WS localStorageA simple synchronous way of accessing localStorage from your app. Created by @gagangoku.from streamlit_ws_localstorage import injectWebsocketCode ret = conn.setLocalStorageVal(key='k1', val='v1') st.write('ret: ' + ret) Streamlit Auth0The fastest way to provide comprehensive login inside Streamlit. Created by @conradbez.from auth0_component import login_button user_info = login_button(clientId, domain = domain) st.write(user_info) Custom Components Declare a componentCreate and register a custom component.st.components.v1.declare_component( ""custom_slider"", ""/frontend"", ) HTMLDisplay an HTML string in an iframe.st.components.v1.html( ""

Foo bar.

"" ) iframeLoad a remote URL in an iframe.st.components.v1.iframe( ""docs.streamlit.io"" ) Utilities and user info User infost.experimental_user returns information about the logged-in user of private apps on Streamlit Community Cloud.if st.experimental_user.email == ""foo@corp.com"": st.write(""Welcome back, "", st.experimental_user.email) else: st.write(""You are not authorized to view this page."") Get helpDisplay object’s doc string, nicely formatted.st.help(st.write) st.help(pd.DataFrame) Render HTMLRenders HTML strings to your app.css = """""" """""" st.html(css) Configuration Configuration fileConfigures the default settings for your app.your-project/ ├── .streamlit/ │ └── config.toml └── your_app.py Set page title, favicon, and moreConfigures the default settings of the page.st.set_page_config( page_title=""My app"", page_icon="":shark:"", ) Developer tools App testing st.testing.v1.AppTestst.testing.v1.AppTest simulates a running Streamlit app for testing.from streamlit.testing.v1 import AppTest at = AppTest.from_file(""streamlit_app.py"") at.secrets[""WORD""] = ""Foobar"" at.run() assert not at.exception at.text_input(""word"").input(""Bazbat"").run() assert at.warning[0].value == ""Try again."" AppTest.from_filest.testing.v1.AppTest.from_file initializes a simulated app from a file.from streamlit.testing.v1 import AppTest at = AppTest.from_file(""streamlit_app.py"") at.run() AppTest.from_stringst.testing.v1.AppTest.from_string initializes a simulated app from a string.from streamlit.testing.v1 import AppTest at = AppTest.from_string(app_script_as_string) at.run() AppTest.from_functionst.testing.v1.AppTest.from_function initializes a simulated app from a function.from streamlit.testing.v1 import AppTest at = AppTest.from_function(app_script_as_callable) at.run() BlockA representation of container elements, including: st.chat_message st.columns st.sidebar st.tabs The main body of the app. # at.sidebar returns a Block at.sidebar.button[0].click().run() assert not at.exception ElementThe base class for representation of all elements, including: st.title st.header st.markdown st.dataframe # at.title returns a sequence of Title # Title inherits from Element assert at.title[0].value == ""My awesome app"" ButtonA representation of st.button and st.form_submit_button.at.button[0].click().run() ChatInputA representation of st.chat_input.at.chat_input[0].set_value(""What is Streamlit?"").run() CheckboxA representation of st.checkbox.at.checkbox[0].check().run() ColorPickerA representation of st.color_picker.at.color_picker[0].pick(""#FF4B4B"").run() DateInputA representation of st.date_input.release_date = datetime.date(2023, 10, 26) at.date_input[0].set_value(release_date).run() MultiselectA representation of st.multiselect.at.multiselect[0].select(""New York"").run() NumberInputA representation of st.number_input.at.number_input[0].increment().run() RadioA representation of st.radio.at.radio[0].set_value(""New York"").run() SelectSliderA representation of st.select_slider.at.select_slider[0].set_range(""A"",""C"").run() SelectboxA representation of st.selectbox.at.selectbox[0].select(""New York"").run() SliderA representation of st.slider.at.slider[0].set_range(2,5).run() TextAreaA representation of st.text_area.at.text_area[0].input(""Streamlit is awesome!"").run() TextInputA representation of st.text_input.at.text_input[0].input(""Streamlit"").run() TimeInputA representation of st.time_input.at.time_input[0].increment().run() ToggleA representation of st.toggle.at.toggle[0].set_value(""True"").run() Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration!Pandas ProfilingPandas profiling component for Streamlit. Created by @okld.df = pd.read_csv(""https://storage.googleapis.com/tf-datasets/titanic/train.csv"") pr = df.profile_report() st_profile_report(pr) Streamlit AceAce editor component for Streamlit. Created by @okld.from streamlit_ace import st_ace content = st_ace() content Streamlit AnalyticsTrack & visualize user interactions with your streamlit app. Created by @jrieke.import streamlit_analytics with streamlit_analytics.track(): st.text_input(""Write something"") Previous: ConceptsNext: Write and magicforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy" https://docs.streamlit.io/develop/concepts/app-testing/automate-tests#streamlit-app-action,"DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsremoveCOREArchitecture & executionaddMultipage appsaddApp designaddADDITIONALConnections and secretsaddCustom componentsaddConfiguration and themingaddApp testingremoveGet startedBeyond the basicsAutomate your testsExampleCheat sheetAPI referenceaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Develop/Concepts/App testing/Automate your testsAutomate your tests with CI One of the key benefits of app testing is that tests can be automated using Continuous Integration (CI). By running tests automatically during development, you can validate that changes to your app don't break existing functionality. You can verify app code as you commit, catch bugs early, and prevent accidental breaks before deployment. There are many popular CI tools, including GitHub Actions, Jenkins, GitLab CI, Azure DevOps, and Circle CI. Streamlit app testing will integrate easily with any of them similar to any other Python tests. GitHub Actions Since many Streamlit apps (and all Community Cloud apps) are built in GitHub, this page uses examples from GitHub Actions. For more information about GitHub Actions, see: Quickstart for GitHub Actions GitHub Actions: About continuous integration GitHub Actions: Build & test Python Streamlit App Action Streamlit App Action provides an easy way to add automated testing to your app repository in GitHub. It also includes basic smoke testing for each page of your app without you writing any test code. To install Streamlit App Action, add a workflow .yml file to your repository's .github/workflows/ folder. For example: # .github/workflows/streamlit-app.yml name: Streamlit app on: push: branches: [""main""] pull_request: branches: [""main""] permissions: contents: read jobs: streamlit: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - uses: actions/setup-python@v5 with: python-version: ""3.11"" - uses: streamlit/streamlit-app-action@v0.0.3 with: app-path: streamlit_app.py Let's take a look in more detail at what this action workflow is doing. Triggering the workflow on: push: branches: [""main""] pull_request: branches: [""main""] This workflow will be triggered and execute tests on pull requests targeting the main branch, as well as any new commits pushed to the main branch. Note that it will also execute the tests on subsequent commits to any open pull requests. See GitHub Actions: Triggering a workflow for more information and examples. Setting up the test environment jobs: streamlit: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - uses: actions/setup-python@v5 with: python-version: ""3.11"" The workflow has a streamlit job that executes a series of steps. The job runs on a Docker container with the ubuntu-latest image. actions/checkout@v4 checks out the current repository code from GitHub and copies the code to the job environment. actions/setup-python@v5 installs Python version 3.11. Running the app tests - uses: streamlit/streamlit-app-action@v0.0.3 with: app-path: streamlit_app.py Streamlit App Action does the following: Install pytest and install any dependencies specified in requirements.txt. Run the built-in app smoke tests. Run any other Python tests found in the repository. starTipIf your app doesn't include requirements.txt in the repository root directory, you will need to add a step to install dependencies with your chosen package manager before running Streamlit App Action. The built-in smoke tests have the following behavior: Run the app specified at app-path as an AppTest. Validate that it completes successfully and does not result in an uncaught exception. Do the same for any additional pages/ of the app relative to app-path. If you want to run Streamlit App Action without the smoke tests, you can set skip-smoke: true. Linting your app code Linting is the automated checking of source code for programmatic and stylistic errors. This is done by using a lint tool (otherwise known as a linter). Linting is important to reduce errors and improve the overall quality of your code, especially for repositories with multiple developers or public repositories. You can add automated linting with Ruff by passing ruff: true to Streamlit App Action. - uses: streamlit/streamlit-app-action@v0.0.3 with: app-path: streamlit_app.py ruff: true starTipYou may want to add a pre-commit hook like ruff-pre-commit in your local development environment to fix linting errors before they get to CI. Viewing results If tests fail, the CI workflow will fail and you will see the results in GitHub. Console logs are available by clicking into the workflow run as described here. For higher-level test results, you can use pytest-results-action. You can combine this with Streamlit App Action as follows: # ... setup as above ... - uses: streamlit/streamlit-app-action@v0.0.3 with: app-path: streamlit_app.py # Add pytest-args to output junit xml pytest-args: -v --junit-xml=test-results.xml - if: always() uses: pmeier/pytest-results-action@v0.6.0 with: path: test-results.xml summary: true display-options: fEX Writing your own actions The above is just provided as an example. Streamlit App Action is a quick way to get started. Once you learn the basics of your CI tool of choice, it's easy to build and customize your own automated workflows. This is a great way to improve your overall productivity as a developer and the quality of your apps. Working example As a final working example example, take a look at our streamlit/llm-examples Actions, defined in this workflow file.Previous: Beyond the basicsNext: ExampleforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy" https://docs.streamlit.io/develop/concepts/architecture/st.cache#example-2-when-the-function-arguments-change,"DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsremoveCOREArchitecture & executionremoveRunning your appStreamlit's architectureThe app chromeCachingSession StateFormsFragmentsWidget behaviorMultipage appsaddApp designaddADDITIONALConnections and secretsaddCustom componentsaddConfiguration and themingaddApp testingaddAPI referenceaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Develop/Concepts/Architecture & execution/Optimize performance with st.cachedeleteDeprecation noticest.cache was deprecated in version 1.18.0. Use st.cache_data or st.cache_resource instead. Learn more in Caching. Optimize performance with st.cache Streamlit provides a caching mechanism that allows your app to stay performant even when loading data from the web, manipulating large datasets, or performing expensive computations. This is done with the @st.cache decorator. When you mark a function with the @st.cache decorator, it tells Streamlit that whenever the function is called it needs to check a few things: The input parameters that you called the function with The value of any external variable used in the function The body of the function The body of any function used inside the cached function If this is the first time Streamlit has seen these four components with these exact values and in this exact combination and order, it runs the function and stores the result in a local cache. Then, next time the cached function is called, if none of these components changed, Streamlit will just skip executing the function altogether and, instead, return the output previously stored in the cache. The way Streamlit keeps track of changes in these components is through hashing. Think of the cache as an in-memory key-value store, where the key is a hash of all of the above and the value is the actual output object passed by reference. Finally, @st.cache supports arguments to configure the cache's behavior. You can find more information on those in our API reference. Let's take a look at a few examples that illustrate how caching works in a Streamlit app. Example 1: Basic usage For starters, let's take a look at a sample app that has a function that performs an expensive, long-running computation. Without caching, this function is rerun each time the app is refreshed, leading to a poor user experience. Copy this code into a new app and try it out yourself: import streamlit as st import time def expensive_computation(a, b): time.sleep(2) # 👈 This makes the function take 2s to run return a * b a = 2 b = 21 res = expensive_computation(a, b) st.write(""Result:"", res) Try pressing R to rerun the app, and notice how long it takes for the result to show up. This is because expensive_computation(a, b) is being re-executed every time the app runs. This isn't a great experience. Let's add the @st.cache decorator: import streamlit as st import time @st.cache # 👈 Added this def expensive_computation(a, b): time.sleep(2) # This makes the function take 2s to run return a * b a = 2 b = 21 res = expensive_computation(a, b) st.write(""Result:"", res) Now run the app again and you'll notice that it is much faster every time you press R to rerun. To understand what is happening, let's add an st.write inside the function: import streamlit as st import time @st.cache(suppress_st_warning=True) # 👈 Changed this def expensive_computation(a, b): # 👇 Added this st.write(""Cache miss: expensive_computation("", a, "","", b, "") ran"") time.sleep(2) # This makes the function take 2s to run return a * b a = 2 b = 21 res = expensive_computation(a, b) st.write(""Result:"", res) Now when you rerun the app the text ""Cache miss"" appears on the first run, but not on any subsequent runs. That's because the cached function is only being executed once, and every time after that you're actually hitting the cache. push_pinNoteYou may have noticed that we've added the suppress_st_warning keyword to the @st.cache decorators. That's because the cached function above uses a Streamlit command itself (st.write in this case), and when Streamlit sees that, it shows a warning that your command will only execute when you get a cache miss. More often than not, when you see that warning it's because there's a bug in your code. However, in our case we're using the st.write command to demonstrate when the cache is being missed, so the behavior Streamlit is warning us about is exactly what we want. As a result, we are passing in suppress_st_warning=True to turn that warning off. Example 2: When the function arguments change Without stopping the previous app server, let's change one of the arguments to our cached function: import streamlit as st import time @st.cache(suppress_st_warning=True) def expensive_computation(a, b): st.write(""Cache miss: expensive_computation("", a, "","", b, "") ran"") time.sleep(2) # This makes the function take 2s to run return a * b a = 2 b = 210 # 👈 Changed this res = expensive_computation(a, b) st.write(""Result:"", res) Now the first time you rerun the app it's a cache miss. This is evidenced by the ""Cache miss"" text showing up and the app taking 2s to finish running. After that, if you press R to rerun, it's always a cache hit. That is, no such text shows up and the app is fast again. This is because Streamlit notices whenever the arguments a and b change and determines whether the function should be re-executed and re-cached. Example 3: When the function body changes Without stopping and restarting your Streamlit server, let's remove the widget from our app and modify the function's code by adding a + 1 to the return value. import streamlit as st import time @st.cache(suppress_st_warning=True) def expensive_computation(a, b): st.write(""Cache miss: expensive_computation("", a, "","", b, "") ran"") time.sleep(2) # This makes the function take 2s to run return a * b + 1 # 👈 Added a +1 at the end here a = 2 b = 210 res = expensive_computation(a, b) st.write(""Result:"", res) The first run is a ""Cache miss"", but when you press R each subsequent run is a cache hit. This is because on first run, Streamlit detected that the function body changed, reran the function, and put the result in the cache. starTipIf you change the function back the result will already be in the Streamlit cache from a previous run. Try it out! Example 4: When an inner function changes Let's make our cached function depend on another function internally: import streamlit as st import time def inner_func(a, b): st.write(""inner_func("", a, "","", b, "") ran"") return a * b @st.cache(suppress_st_warning=True) def expensive_computation(a, b): st.write(""Cache miss: expensive_computation("", a, "","", b, "") ran"") time.sleep(2) # This makes the function take 2s to run return inner_func(a, b) + 1 a = 2 b = 210 res = expensive_computation(a, b) st.write(""Result:"", res) What you see is the usual: The first run results in a cache miss. Every subsequent rerun results in a cache hit. But now let's try modifying the inner_func(): import streamlit as st import time def inner_func(a, b): st.write(""inner_func("", a, "","", b, "") ran"") return a ** b # 👈 Changed the * to ** here @st.cache(suppress_st_warning=True) def expensive_computation(a, b): st.write(""Cache miss: expensive_computation("", a, "","", b, "") ran"") time.sleep(2) # This makes the function take 2s to run return inner_func(a, b) + 1 a = 2 b = 21 res = expensive_computation(a, b) st.write(""Result:"", res) Even though inner_func() is not annotated with @st.cache, when we edit its body we cause a ""Cache miss"" in the outer expensive_computation(). That's because Streamlit always traverses your code and its dependencies to verify that the cached values are still valid. This means that while developing your app you can edit your code freely without worrying about the cache. Any change you make to your app, Streamlit should do the right thing! Streamlit is also smart enough to only traverse dependencies that belong to your app, and skip over any dependency that comes from an installed Python library. Example 5: Use caching to speed up your app across users Going back to our original function, let's add a widget to control the value of b: import streamlit as st import time @st.cache(suppress_st_warning=True) def expensive_computation(a, b): st.write(""Cache miss: expensive_computation("", a, "","", b, "") ran"") time.sleep(2) # This makes the function take 2s to run return a * b a = 2 b = st.slider(""Pick a number"", 0, 10) # 👈 Changed this res = expensive_computation(a, b) st.write(""Result:"", res) What you'll see: If you move the slider to a number Streamlit hasn't seen before, you'll have a cache miss again. And every subsequent rerun with the same number will be a cache hit, of course. If you move the slider back to a number Streamlit has seen before, the cache is hit and the app is fast as expected. In computer science terms, what is happening here is that @st.cache is memoizing expensive_computation(a, b). But now let's go one step further! Try the following: Move the slider to a number you haven't tried before, such as 9. Pretend you're another user by opening another browser tab pointing to your Streamlit app (usually at http://localhost:8501) In the new tab, move the slider to 9. Notice how this is actually a cache hit! That is, you don't actually see the ""Cache miss"" text on the second tab even though that second user never moved the slider to 9 at any point prior to this. This happens because the Streamlit cache is global to all users. So everyone contributes to everyone else's performance. Example 6: Mutating cached values As mentioned in the overview section, the Streamlit cache stores items by reference. This allows the Streamlit cache to support structures that aren't memory-managed by Python, such as TensorFlow objects. However, it can also lead to unexpected behavior — which is why Streamlit has a few checks to guide developers in the right direction. Let's look into those checks now. Let's write an app that has a cached function which returns a mutable object, and then let's follow up by mutating that object: import streamlit as st import time @st.cache(suppress_st_warning=True) def expensive_computation(a, b): st.write(""Cache miss: expensive_computation("", a, "","", b, "") ran"") time.sleep(2) # This makes the function take 2s to run return {""output"": a * b} # 👈 Mutable object a = 2 b = 21 res = expensive_computation(a, b) st.write(""Result:"", res) res[""output""] = ""result was manually mutated"" # 👈 Mutated cached value st.write(""Mutated result:"", res) When you run this app for the first time, you should see three messages on the screen: Cache miss: expensive_computation(...) ran Result: {output: 42} Mutated result: {output: ""result was manually mutated""} No surprises here. But now notice what happens when you rerun you app (i.e. press R): Result: {output: ""result was manually mutated""} Mutated result: {output: ""result was manually mutated""} Cached object mutated. (...) So what's up? What's going on here is that Streamlit caches the output res by reference. When you mutated res[""output""] outside the cached function you ended up inadvertently modifying the cache. This means every subsequent call to expensive_computation(2, 21) will return the wrong value! Since this behavior is usually not what you'd expect, Streamlit tries to be helpful and show you a warning, along with some ideas about how to fix your code. In this specific case, the fix is just to not mutate res[""output""] outside the cached function. There was no good reason for us to do that anyway! Another solution would be to clone the result value with res = deepcopy(expensive_computation(2, 21)). Check out the section entitled Fixing caching issues for more information on these approaches and more. Advanced caching In caching, you learned about the Streamlit cache, which is accessed with the @st.cache decorator. In this article you'll see how Streamlit's caching functionality is implemented, so that you can use it to improve the performance of your Streamlit apps. The cache is a key-value store, where the key is a hash of: The input parameters that you called the function with The value of any external variable used in the function The body of the function The body of any function used inside the cached function And the value is a tuple of: The cached output A hash of the cached output (you'll see why soon) For both the key and the output hash, Streamlit uses a specialized hash function that knows how to traverse code, hash special objects, and can have its behavior customized by the user. For example, when the function expensive_computation(a, b), decorated with @st.cache, is executed with a=2 and b=21, Streamlit does the following: Computes the cache key If the key is found in the cache, then: Extracts the previously-cached (output, output_hash) tuple. Performs an Output Mutation Check, where a fresh hash of the output is computed and compared to the stored output_hash. If the two hashes are different, shows a Cached Object Mutated warning. (Note: Setting allow_output_mutation=True disables this step). If the input key is not found in the cache, then: Executes the cached function (i.e. output = expensive_computation(2, 21)). Calculates the output_hash from the function's output. Stores key → (output, output_hash) in the cache. Returns the output. If an error is encountered an exception is raised. If the error occurs while hashing either the key or the output an UnhashableTypeError error is thrown. If you run into any issues, see fixing caching issues. The hash_funcs parameter As described above, Streamlit's caching functionality relies on hashing to calculate the key for cached objects, and to detect unexpected mutations in the cached result. For added expressive power, Streamlit lets you override this hashing process using the hash_funcs argument. Suppose you define a type called FileReference which points to a file in the filesystem: class FileReference: def __init__(self, filename): self.filename = filename @st.cache def func(file_reference): ... By default, Streamlit hashes custom classes like FileReference by recursively navigating their structure. In this case, its hash is the hash of the filename property. As long as the file name doesn't change, the hash will remain constant. However, what if you wanted to have the hasher check for changes to the file's modification time, not just its name? This is possible with @st.cache's hash_funcs parameter: class FileReference: def __init__(self, filename): self.filename = filename def hash_file_reference(file_reference): filename = file_reference.filename return (filename, os.path.getmtime(filename)) @st.cache(hash_funcs={FileReference: hash_file_reference}) def func(file_reference): ... Additionally, you can hash FileReference objects by the file's contents: class FileReference: def __init__(self, filename): self.filename = filename def hash_file_reference(file_reference): with open(file_reference.filename) as f: return f.read() @st.cache(hash_funcs={FileReference: hash_file_reference}) def func(file_reference): ... push_pinNoteBecause Streamlit's hash function works recursively, you don't have to hash the contents inside hash_file_reference Instead, you can return a primitive type, in this case the contents of the file, and Streamlit's internal hasher will compute the actual hash from it. Typical hash functions While it's possible to write custom hash functions, let's take a look at some of the tools that Python provides out of the box. Here's a list of some hash functions and when it makes sense to use them. Python's id function | Example Speed: Fast Use case: If you're hashing a singleton object, like an open database connection or a TensorFlow session. These are objects that will only be instantiated once, no matter how many times your script reruns. lambda _: None | Example Speed: Fast Use case: If you want to turn off hashing of this type. This is useful if you know the object is not going to change. Python's hash() function | Example Speed: Can be slow based the size of the object being cached Use case: If Python already knows how to hash this type correctly. Custom hash function | Example Speed: N/a Use case: If you'd like to override how Streamlit hashes a particular type. Example 1: Pass a database connection around Suppose we want to open a database connection that can be reused across multiple runs of a Streamlit app. For this you can make use of the fact that cached objects are stored by reference to automatically initialize and reuse the connection: @st.cache(allow_output_mutation=True) def get_database_connection(): return db.get_connection() With just 3 lines of code, the database connection is created once and stored in the cache. Then, every subsequent time get_database_connection is called, the already-created connection object is reused automatically. In other words, it becomes a singleton. starTipUse the allow_output_mutation=True flag to suppress the immutability check. This prevents Streamlit from trying to hash the output connection, and also turns off Streamlit's mutation warning in the process. What if you want to write a function that receives a database connection as input? For that, you'll use hash_funcs: @st.cache(hash_funcs={DBConnection: id}) def get_users(connection): # Note: We assume that connection is of type DBConnection. return connection.execute_sql('SELECT * from Users') Here, we use Python's built-in id function, because the connection object is coming from the Streamlit cache via the get_database_connection function. This means that the same connection instance is passed around every time, and therefore it always has the same id. However, if you happened to have a second connection object around that pointed to an entirely different database, it would still be safe to pass it to get_users because its id is guaranteed to be different than the first id. These design patterns apply any time you have an object that points to an external resource, such as a database connection or Tensorflow session. Example 2: Turn off hashing for a specific type You can turn off hashing entirely for a particular type by giving it a custom hash function that returns a constant. One reason that you might do this is to avoid hashing large, slow-to-hash objects that you know are not going to change. For example: @st.cache(hash_funcs={pd.DataFrame: lambda _: None}) def func(huge_constant_dataframe): ... When Streamlit encounters an object of this type, it always converts the object into None, no matter which instance of FooType its looking at. This means all instances are hash to the same value, which effectively cancels out the hashing mechanism. Example 3: Use Python's hash() function Sometimes, you might want to use Python’s default hashing instead of Streamlit's. For example, maybe you've encountered a type that Streamlit is unable to hash, but it's hashable with Python's built-in hash() function: @st.cache(hash_funcs={FooType: hash}) def func(...): ... Previous: CachingNext: Experimental cache primitivesforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy" https://docs.streamlit.io/en/latest/streamlit_components.html#making-your-own-component,"DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsremoveCOREArchitecture & executionaddMultipage appsaddApp designaddADDITIONALConnections and secretsaddCustom componentsremoveIntro to custom componentsCreate a ComponentPublish a ComponentLimitationsComponent galleryopen_in_newConfiguration and themingaddApp testingaddAPI referenceaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Develop/Concepts/Custom componentsCustom Components Components are third-party Python modules that extend what's possible with Streamlit. How to use a Component Components are super easy to use: Start by finding the Component you'd like to use. Two great resources for this are: The Component gallery This thread, by Fanilo A. from our forums. Install the Component using your favorite Python package manager. This step and all following steps are described in your component's instructions. For example, to use the fantastic AgGrid Component, you first install it with: pip install streamlit-aggrid In your Python code, import the Component as described in its instructions. For AgGrid, this step is: from st_aggrid import AgGrid ...now you're ready to use it! For AgGrid, that's: AgGrid(my_dataframe) Making your own Component If you're interested in making your own component, check out the following resources: Create a Component Publish a Component Components API Blog post for when we launched Components! Alternatively, if you prefer to learn using videos, our engineer Tim Conkling has put together some amazing tutorials: Video tutorial, part 1 Video tutorial, part 2 Previous: Connections and secretsNext: Intro to custom componentsforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy" https://docs.streamlit.io/develop/api-reference/app-testing/testing-element-classes#sttestingv1element_treetoggle,"DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceremovePAGE ELEMENTSWrite and magicaddText elementsaddData elementsaddChart elementsaddInput widgetsaddMedia elementsaddLayouts and containersaddChat elementsaddStatus elementsaddThird-party componentsopen_in_newAPPLICATION LOGICNavigation and pagesaddExecution flowaddCaching and stateaddConnections and secretsaddCustom componentsaddUtilitiesaddConfigurationaddTOOLSApp testingremovest.testing.v1.AppTestTesting element classesCommand lineaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Develop/API reference/App testing/Testing element classesTesting element classes st.testing.v1.element_tree.Block The Block class has the same methods and attributes as AppTest. A Block instance represents a container of elements just as AppTest represents the entire app. For example, Block.button will produce a WidgetList of Button in the same manner as AppTest.button. ChatMessage, Column, and Tab all inherit from Block. For all container classes, parameters of the original element can be obtained as properties. For example, ChatMessage.avatar and Tab.label. st.testing.v1.element_tree.ElementStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeElement base class for testing. This class's methods and attributes are universal for all elements implemented in testing. For example, Caption, Code, Text, and Title inherit from Element. All widget classes also inherit from Element, but have additional methods specific to each widget type. See the AppTest class for the full list of supported elements. For all element classes, parameters of the original element can be obtained as properties. For example, Button.label, Caption.help, and Toast.icon. Class description[source] st.testing.v1.element_tree.Element(proto, root) Methods run(*, timeout=None) Run the AppTest script which contains the element. Attributes value The value or contents of the element. st.testing.v1.element_tree.ButtonStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.button and st.form_submit_button. Class description[source] st.testing.v1.element_tree.Button(proto, root) Methods click() Set the value of the button to True. run(*, timeout=None) Run the AppTest script which contains the element. set_value(v) Set the value of the button. Attributes value The value of the button. (bool) st.testing.v1.element_tree.ChatInputStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.chat_input. Class description[source] st.testing.v1.element_tree.ChatInput(proto, root) Methods run(*, timeout=None) Run the AppTest script which contains the element. set_value(v) Set the value of the widget. Attributes value The value of the widget. (str) st.testing.v1.element_tree.CheckboxStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.checkbox. Class description[source] st.testing.v1.element_tree.Checkbox(proto, root) Methods check() Set the value of the widget to True. run(*, timeout=None) Run the AppTest script which contains the element. set_value(v) Set the value of the widget. uncheck() Set the value of the widget to False. Attributes value The value of the widget. (bool) st.testing.v1.element_tree.ColorPickerStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.color_picker. Class description[source] st.testing.v1.element_tree.ColorPicker(proto, root) Methods pick(v) Set the value of the widget as a hex string. May omit the ""#"" prefix. run(*, timeout=None) Run the AppTest script which contains the element. set_value(v) Set the value of the widget as a hex string. Attributes value The currently selected value as a hex string. (str) st.testing.v1.element_tree.DateInputStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.date_input. Class description[source] st.testing.v1.element_tree.DateInput(proto, root) Methods run(*, timeout=None) Run the AppTest script which contains the element. set_value(v) Set the value of the widget. Attributes value The value of the widget. (date or Tuple of date) st.testing.v1.element_tree.MultiselectStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.multiselect. Class description[source] st.testing.v1.element_tree.Multiselect(proto, root) Methods run(*, timeout=None) Run the AppTest script which contains the element. select(v) Add a selection to the widget. Do nothing if the value is already selected. If testing a multiselect widget with repeated options, use set_value instead. set_value(v) Set the value of the multiselect widget. (list) unselect(v) Remove a selection from the widget. Do nothing if the value is not already selected. If a value is selected multiple times, the first instance is removed. Attributes format_func The widget's formatting function for displaying options. (callable) indices The indices of the currently selected values from the options. (list) value The currently selected values from the options. (list) st.testing.v1.element_tree.NumberInputStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.number_input. Class description[source] st.testing.v1.element_tree.NumberInput(proto, root) Methods decrement() Decrement the st.number_input widget as if the user clicked ""-"". increment() Increment the st.number_input widget as if the user clicked ""+"". run(*, timeout=None) Run the AppTest script which contains the element. set_value(v) Set the value of the st.number_input widget. Attributes value Get the current value of the st.number_input widget. st.testing.v1.element_tree.RadioStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.radio. Class description[source] st.testing.v1.element_tree.Radio(proto, root) Methods run(*, timeout=None) Run the AppTest script which contains the element. set_value(v) Set the selection by value. Attributes format_func The widget's formatting function for displaying options. (callable) index The index of the current selection. (int) value The currently selected value from the options. (Any) st.testing.v1.element_tree.SelectSliderStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.select_slider. Class description[source] st.testing.v1.element_tree.SelectSlider(proto, root) Methods run(*, timeout=None) Run the AppTest script which contains the element. set_range(lower, upper) Set the ranged selection by values. set_value(v) Set the (single) selection by value. Attributes format_func The widget's formatting function for displaying options. (callable) value The currently selected value or range. (Any or Sequence of Any) st.testing.v1.element_tree.SelectboxStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.selectbox. Class description[source] st.testing.v1.element_tree.Selectbox(proto, root) Methods run(*, timeout=None) Run the AppTest script which contains the element. select(v) Set the selection by value. select_index(index) Set the selection by index. set_value(v) Set the selection by value. Attributes format_func The widget's formatting function for displaying options. (callable) index The index of the current selection. (int) value The currently selected value from the options. (Any) st.testing.v1.element_tree.SliderStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.slider. Class description[source] st.testing.v1.element_tree.Slider(proto, root) Methods run(*, timeout=None) Run the AppTest script which contains the element. set_range(lower, upper) Set the ranged value of the slider. set_value(v) Set the (single) value of the slider. Attributes value The currently selected value or range. (Any or Sequence of Any) st.testing.v1.element_tree.TextAreaStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.text_area. Class description[source] st.testing.v1.element_tree.TextArea(proto, root) Methods input(v) Set the value of the widget only if the value does not exceed the maximum allowed characters. run(*, timeout=None) Run the AppTest script which contains the element. set_value(v) Set the value of the widget. Attributes value The current value of the widget. (str) st.testing.v1.element_tree.TextInputStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.text_input. Class description[source] st.testing.v1.element_tree.TextInput(proto, root) Methods input(v) Set the value of the widget only if the value does not exceed the maximum allowed characters. run(*, timeout=None) Run the AppTest script which contains the element. set_value(v) Set the value of the widget. Attributes value The current value of the widget. (str) st.testing.v1.element_tree.TimeInputStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.time_input. Class description[source] st.testing.v1.element_tree.TimeInput(proto, root) Methods decrement() Select the previous available time. increment() Select the next available time. run(*, timeout=None) Run the AppTest script which contains the element. set_value(v) Set the value of the widget. Attributes value The current value of the widget. (time) st.testing.v1.element_tree.ToggleStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.toggle. Class description[source] st.testing.v1.element_tree.Toggle(proto, root) Methods run(*, timeout=None) Run the AppTest script which contains the element. set_value(v) Set the value of the widget. Attributes value The current value of the widget. (bool) Previous: st.testing.v1.AppTestNext: Command lineforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy" https://docs.streamlit.io/develop/concepts/configuration/serving-static-files#details-on-usage,"DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsremoveCOREArchitecture & executionaddMultipage appsaddApp designaddADDITIONALConnections and secretsaddCustom componentsaddConfiguration and themingremoveConfiguration optionsHTTPS supportServing static filesCustomize your themeApp testingaddAPI referenceaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Develop/Concepts/Configuration and theming/Serving static filesStatic file serving Streamlit apps can host and serve small, static media files to support media embedding use cases that won't work with the normal media elements. To enable this feature, set enableStaticServing = true under [server] in your config file, or environment variable STREAMLIT_SERVER_ENABLE_STATIC_SERVING=true. Media stored in the folder ./static/ relative to the running app file is served at path app/static/[filename], such as http://localhost:8501/app/static/cat.png. Details on usage Files with the following extensions will be served normally: "".jpg"", "".jpeg"", "".png"", "".gif"". Any other file will be sent with header Content-Type:text/plain which will cause browsers to render in plain text. This is included for security - other file types that need to render should be hosted outside the app. Streamlit also sets X-Content-Type-Options:nosniff for all files rendered from the static directory. For apps running on Streamlit Community Cloud: Files available in the Github repo will always be served. Any files generated while the app is running, such as based on user interaction (file upload, etc), are not guaranteed to persist across user sessions. Apps which store and serve many files, or large files, may run into resource limits and be shut down. Example usage Put an image cat.png in the folder ./static/ Add enableStaticServing = true under [server] in your .streamlit/config.toml Any media in the ./static/ folder is served at the relative URL like app/static/cat.png # .streamlit/config.toml [server] enableStaticServing = true # app.py import streamlit as st with st.echo(): st.title(""CAT"") st.markdown(""[![Click me](app/static/cat.png)](https://streamlit.io)"") Additional resources: https://docs.streamlit.io/develop/concepts/configuration https://static-file-serving.streamlit.app/ Built with Streamlit 🎈Fullscreen open_in_newPrevious: HTTPS supportNext: Customize your themeforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy" https://docs.streamlit.io/develop/tutorials/databases/mssql#add-username-and-password-to-your-local-app-secrets,"DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceaddTutorialsremoveExecution flowaddConnect to data sourcesremoveAWS S3BigQueryDeta BaseFirestoreopen_in_newGoogle Cloud StorageMicrosoft SQL ServerMongoDBMySQLNeonPostgreSQLPrivate Google SheetPublic Google SheetSnowflakeSupabaseTableauTiDBTigerGraphMultipage appsaddWork with LLMsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Develop/Tutorials/Connect to data sources/Microsoft SQL ServerConnect Streamlit to Microsoft SQL Server Introduction This guide explains how to securely access a remote Microsoft SQL Server database from Streamlit Community Cloud. It uses the pyodbc library and Streamlit's Secrets management. Create an SQL Server database push_pinNoteIf you already have a remote database that you want to use, feel free to skip to the next step. First, follow the Microsoft documentation to install SQL Server and the sqlcmd Utility. They have detailed installation guides on how to: Install SQL Server on Windows Install on Red Hat Enterprise Linux Install on SUSE Linux Enterprise Server Install on Ubuntu Run on Docker Provision a SQL VM in Azure Once you have SQL Server installed, note down your SQL Server name, username, and password during setup. Connect locally If you are connecting locally, use sqlcmd to connect to your new local SQL Server instance. In your terminal, run the following command: sqlcmd -S localhost -U SA -P '' As you are connecting locally, the SQL Server name is localhost, the username is SA, and the password is the one you provided during the SA account setup. You should see a sqlcmd command prompt 1>, if successful. If you run into a connection failure, review Microsoft's connection troubleshooting recommendations for your OS (Linux & Windows). starTipWhen connecting remotely, the SQL Server name is the machine name or IP address. You might also need to open the SQL Server TCP port (default 1433) on your firewall. Create a SQL Server database By now, you have SQL Server running and have connected to it with sqlcmd! 🥳 Let's put it to use by creating a database containing a table with some example values. From the sqlcmd command prompt, run the following Transact-SQL command to create a test database mydb: CREATE DATABASE mydb To execute the above command, type GO on a new line: GO Insert some data Next create a new table, mytable, in the mydb database with three columns and two rows. Switch to the new mydb database: USE mydb Create a new table with the following schema: CREATE TABLE mytable (name varchar(80), pet varchar(80)) Insert some data into the table: INSERT INTO mytable VALUES ('Mary', 'dog'), ('John', 'cat'), ('Robert', 'bird') Type GO to execute the above commands: GO To end your sqlcmd session, type QUIT on a new line. Add username and password to your local app secrets Your local Streamlit app will read secrets from a file .streamlit/secrets.toml in your app's root directory. Create this file if it doesn't exist yet and add the SQL Server name, database name, username, and password as shown below: # .streamlit/secrets.toml server = ""localhost"" database = ""mydb"" username = ""SA"" password = ""xxx"" priority_highImportantWhen copying your app secrets to Streamlit Community Cloud, be sure to replace the values of server, database, username, and password with those of your remote SQL Server!And add this file to .gitignore and don't commit it to your GitHub repo. Copy your app secrets to Streamlit Community Cloud As the secrets.toml file above is not committed to GitHub, you need to pass its content to your deployed app (on Streamlit Community Cloud) separately. Go to the app dashboard and in the app's dropdown menu, click on Edit Secrets. Copy the content of secrets.toml into the text area. More information is available at Secrets management. Add pyodbc to your requirements file To connect to SQL Server locally with Streamlit, you need to pip install pyodbc, in addition to the Microsoft ODBC driver you installed during the SQL Server installation. On Streamlit Cloud, we have built-in support for SQL Server. On popular demand, we directly added SQL Server tools including the ODBC drivers and the executables sqlcmd and bcp to the container image for Cloud apps, so you don't need to install them. All you need to do is add the pyodbc Python package to your requirements.txt file, and you're ready to go! 🎈 # requirements.txt pyodbc==x.x.x Replace x.x.x ☝️ with the version of pyodbc you want installed on Cloud. push_pinNoteAt this time, Streamlit Community Cloud does not support Azure Active Directory authentication. We will update this tutorial when we add support for Azure Active Directory. Write your Streamlit app Copy the code below to your Streamlit app and run it. Make sure to adapt query to use the name of your table. import streamlit as st import pyodbc # Initialize connection. # Uses st.cache_resource to only run once. @st.cache_resource def init_connection(): return pyodbc.connect( ""DRIVER={ODBC Driver 17 for SQL Server};SERVER="" + st.secrets[""server""] + "";DATABASE="" + st.secrets[""database""] + "";UID="" + st.secrets[""username""] + "";PWD="" + st.secrets[""password""] ) conn = init_connection() # Perform query. # Uses st.cache_data to only rerun when the query changes or after 10 min. @st.cache_data(ttl=600) def run_query(query): with conn.cursor() as cur: cur.execute(query) return cur.fetchall() rows = run_query(""SELECT * from mytable;"") # Print results. for row in rows: st.write(f""{row[0]} has a :{row[1]}:"") See st.cache_data above? Without it, Streamlit would run the query every time the app reruns (e.g. on a widget interaction). With st.cache_data, it only runs when the query changes or after 10 minutes (that's what ttl is for). Watch out: If your database updates more frequently, you should adapt ttl or remove caching so viewers always see the latest data. Learn more in Caching. If everything worked out (and you used the example table we created above), your app should look like this: Previous: Google Cloud StorageNext: MongoDBforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy" https://docs.streamlit.io/knowledge-base/deploy/remote-start,"DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Knowledge base/Deployment issues/App is not loading when running remotelyApp is not loading when running remotely Below are a few common errors that occur when users spin up their own solution to host a Streamlit app remotely. To learn about a deceptively simple way to host Streamlit apps that avoids all the issues below, check out Streamlit Community Cloud. Symptom #1: The app never loads When you enter the app's URL in a browser and all you see is a blank page, a ""Page not found"" error, a ""Connection refused"" error, or anything like that, first check that Streamlit is actually running on the remote server. On a Linux server you can SSH into it and then run: ps -Al | grep streamlit If you see Streamlit running, the most likely culprit is the Streamlit port not being exposed. The fix depends on your exact setup. Below are three example fixes: Try port 80: Some hosts expose port 80 by default. To set Streamlit to use that port, start Streamlit with the --server.port option: streamlit run my_app.py --server.port=80 AWS EC2 server: First, click on your instance in the AWS Console. Then scroll down and click on Security Groups → Inbound → Edit. Next, add a Custom TCP rule that allows the Port Range 8501 with Source 0.0.0.0/0. Other types of server: Check the firewall settings. If that still doesn't solve the problem, try running a simple HTTP server instead of Streamlit, and seeing if that works correctly. If it does, then you know the problem lies somewhere in your Streamlit app or configuration (in which case you should ask for help in our forums!) If not, then it's definitely unrelated to Streamlit. How to start a simple HTTP server: python -m http.server [port] Symptom #2: The app says ""Please wait..."" or shows skeleton elements forever This symptom appears differently starting from version 1.29.0. For earlier versions of Streamlit, a loading app shows a blue box in the center of the page with a ""Please wait..."" message. Starting from version 1.29.0, a loading app shows skeleton elements. If this loading screen does not go away, the underlying cause is likely one of the following: Using port 3000 which is reserved for internal development. Misconfigured CORS protection. Server is stripping headers from the Websocket connection, thereby breaking compression. To diagnose the issue, first make sure you are not using port 3000. If in doubt, try port 80 as described above. Next, try temporarily disabling CORS protection by running Streamlit with the --server.enableCORS flag set to false: streamlit run my_app.py --server.enableCORS=false If this fixes your issue, you should re-enable CORS protection and then set browser.serverAddress to the URL of your Streamlit app. If the issue persists, try disabling websocket compression by running Streamlit with the --server.enableWebsocketCompression flag set to false streamlit run my_app.py --server.enableWebsocketCompression=false If this fixes your issue, your server setup is likely stripping the Sec-WebSocket-Extensions HTTP header that is used to negotiate Websocket compression. Compression is not required for Streamlit to work, but it's strongly recommended as it improves performance. If you'd like to turn it back on, you'll need to find which part of your infrastructure is stripping the Sec-WebSocket-Extensions HTTP header and change that behavior. Symptom #3: Unable to upload files when running in multiple replicas If the file uploader widget returns an error with status code 403, this is probably due to a misconfiguration in your app's XSRF protection logic. To diagnose the issue, try temporarily disabling XSRF protection by running Streamlit with the --server.enableXsrfProtection flag set to false: streamlit run my_app.py --server.enableXsrfProtection=false If this fixes your issue, you should re-enable XSRF protection and try one or both of the following: Set browser.serverAddress and browser.serverPort to the URL and port of your Streamlit app. Configure your app to use the same secret across every replica by setting the server.cookieSecret config option to the same hard-to-guess string everywhere. Previous: Organizing your apps with workspaces on Streamlit Community CloudNext: Argh. This app has gone over its resource limitsforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy" https://docs.streamlit.io/develop/api-reference/charts/st.pyplot#stpyplot,"DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceremovePAGE ELEMENTSWrite and magicaddText elementsaddData elementsaddChart elementsremoveSIMPLEst.area_chartst.bar_chartst.line_chartst.mapst.scatter_chartADVANCEDst.altair_chartst.bokeh_chartst.graphviz_chartst.plotly_chartst.pydeck_chartst.pyplotst.vega_lite_chartInput widgetsaddMedia elementsaddLayouts and containersaddChat elementsaddStatus elementsaddThird-party componentsopen_in_newAPPLICATION LOGICNavigation and pagesaddExecution flowaddCaching and stateaddConnections and secretsaddCustom componentsaddUtilitiesaddConfigurationaddTOOLSApp testingaddCommand lineaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Develop/API reference/Chart elements/st.pyplotst.pyplotStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeDisplay a matplotlib.pyplot figure. Function signature[source] st.pyplot(fig=None, clear_figure=None, use_container_width=True, **kwargs) Parameters fig (Matplotlib Figure) The figure to plot. When this argument isn't specified, this function will render the global figure (but this is deprecated, as described below) clear_figure (bool) If True, the figure will be cleared after being rendered. If False, the figure will not be cleared after being rendered. If left unspecified, we pick a default based on the value of fig. If fig is set, defaults to False. If fig is not set, defaults to True. This simulates Jupyter's approach to matplotlib rendering. use_container_width (bool) If True, set the chart width to the column width. Defaults to True. **kwargs (any) Arguments to pass to Matplotlib's savefig function. Example import streamlit as st import matplotlib.pyplot as plt import numpy as np arr = np.random.normal(1, 1, size=100) fig, ax = plt.subplots() ax.hist(arr, bins=20) st.pyplot(fig) Built with Streamlit 🎈Fullscreen open_in_new Notes Note Deprecation warning. After December 1st, 2020, we will remove the ability to specify no arguments in st.pyplot(), as that requires the use of Matplotlib's global figure object, which is not thread-safe. So please always pass a figure object as shown in the example section above. Matplotlib supports several types of ""backends"". If you're getting an error using Matplotlib with Streamlit, try setting your backend to ""TkAgg"": echo ""backend: TkAgg"" >> ~/.matplotlib/matplotlibrc For more information, see https://matplotlib.org/faq/usage_faq.html. Previous: st.pydeck_chartNext: st.vega_lite_chartforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy" https://docs.streamlit.io/#Streamlit-documentation,"DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesStreamlit documentationStreamlit is an open-source Python framework for data scientists and AI/ML engineers to deliver dynamic data apps with only a few lines of code. Build and deploy powerful data apps in minutes. Let's get started!install_desktopSetup and installationGet set up to start working with Streamlit.dvrAPI referenceLearn about our APIs, with actionable explanations of specific functions and features.grid_viewApp galleryTry out awesome apps created by our users, and curated from our forums or Twitter.How to use our docsrocket_launchGet started with Streamlit! Set up your development environment and learn the fundamental concepts, and start coding!descriptionDevelop your Streamlit app! Our API reference explains each Streamlit function with examples. Dive deep into all of our features with conceptual guides. Try out our step-by-step tutorials.cloudDeploy your Streamlit app! Streamlit Community Cloud our free platform for deploying and sharing Streamlit apps. Streamlit in Snowflake is an enterprise-class solution where you can house your data and apps in one, unified, global system. Explore all your options!schoolKnowledge base is a self-serve library of tips, tricks, and articles that answer your questions about creating and deploying Streamlit apps.What's newcrop_7_5Modal dialogsIntroducing st.experimental_dialog to create modal dialogs that can rerun independently from the rest of your app.infoGoogle Material Symbolsst.toast, st.chat_message, and alert messages now support Material Symbols for their icons.highlightMarkdown support for text highlightingYou can set the background color for you text in markdown.videocamMedia autoplayYou can enable autoplay for st.audio andst.video. You can also mute videos.cachedClear specific cached valuesWhen clearing cached values for a function, you can now pass function arguments to clear a specific cached value.question_markst.query_params.from_dict()You can now set all query parameters with a single command.Latest blog postsView all updatesJoin the communityStreamlit is more than just a way to make data apps, it's also a community of creators that share their apps and ideas and help each other make their work better. Please come join us on the community forum. We love to hear your questions, ideas, and help you work through your bugs — stop by today!View forumOther MediaGitHubView the Streamlit source code and issue tracker.YouTubeWatch screencasts made by the Streamlit team and the community.TwitterFollow @streamlit on Twitter to keep up with the latest news.LinkedInFollow @streamlit on the world's largest professional network.NewsletterSign up for communications from Streamlit.Next: Get startedHomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy" https://docs.streamlit.io/deploy/streamlit-community-cloud/share-your-app/indexability#make-sure-your-app-is-public,"DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudremoveGet startedaddDeploy your appaddManage your appaddShare your appremoveEmbed your appSearch indexabilityShare previewsManage your accountaddTroubleshootingStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Deploy/Streamlit Community Cloud/Share your app/Search indexabilitySEO and search indexability When you deploy a public app to Streamlit Community Cloud, it is automatically indexed by search engines like Google and Bing on a weekly basis. 🎈 This means that anyone can find your app by searching for its custom subdomain (e.g. ""traingenerator.streamlit.app"") or by searching for the app's title. Get the most out of app indexability Here are some tips to help you get the most out of app indexability: Make sure your app is public Choose a custom subdomain early Choose a descriptive app title Customize your app's meta description Make sure your app is public All public apps hosted on Streamlit Community Cloud are indexed by search engines. If your app is private, it will not be indexed by search engines. To make your private app public, read Share your app. Choose a custom subdomain early Streamlit Community Cloud automatically generates a random subdomain for your app. However, subdomains are customizable! Custom subdomains modify your app URLs to reflect your app content, personal branding, or whatever you’d like. Read more about custom subdomains in Custom subdomains. By choosing a custom subdomain, you can use it to help people find your app. For example, if you're deploying an app that generates training data, you might choose a subdomain like traingenerator.streamlit.app. This makes it easy for people to find your app by searching for ""training generator"" or ""train generator streamlit app."" We recommend choosing a custom subdomain when you deploy your app. This ensures that your app is indexed by search engines using your custom subdomain, rather than the automatically generated one. If you choose a custom subdomain later, your app may be indexed multiple times—once using the default subdomain and once using your custom subdomain. In this case, your old URL will result in a 404 error which can confuse users who are searching for your app. Choose a descriptive app title The meta title of your app is the text that appears in search engine results. It is also the text that appears in the browser tab when your app is open. By default, the meta title of your app is the same as the title of your app. However, you can customize the meta title of your app by setting the st.set_page_config parameter page_title to a custom string. For example: st.set_page_config(page_title=""Traingenerator"") This will change the meta title of your app to ""Traingenerator."" This makes it easier for people to find your app by searching for ""Traingenerator"" or ""train generator streamlit app"": Google search results for ""train generator streamlit app"" Customize your app's meta description Meta descriptions are the short descriptions that appear in search engine results. Search engines use the meta description to help users understand what your app is about. From our observations, search engines seem to favor the content in both st.header and st.text over st.title. If you put a description at the top of your app under st.header or st.text, there’s a good chance search engines will use this for the meta description. What does my indexed app look like? If you're curious about what your app looks like in search engine results, you can type the following into Google Search: site:.streamlit.app Example: site:traingenerator.streamlit.app Google search results for ""site:traingenerator.streamlit.app"" What if I don't want my app to be indexed? If you don't want your app to be indexed by search engines, you can make it private. Read Share your app to learn more about making your app private. Note: each workspace can only have one private app. If you want to make your app private, you must first delete any other private app in your workspace or make it public. That said, Streamlit Community Cloud is an open and free platform for the community to deploy, discover, and share Streamlit apps and code with each other. As such, we encourage you to make your app public so that it can be indexed by search engines and discovered by other Streamlit users and community members.Previous: Embed your appNext: Share previewsforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy" https://docs.streamlit.io/develop/tutorials/databases/postgresql#copy-your-app-secrets-to-the-cloud,"DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceaddTutorialsremoveExecution flowaddConnect to data sourcesremoveAWS S3BigQueryDeta BaseFirestoreopen_in_newGoogle Cloud StorageMicrosoft SQL ServerMongoDBMySQLNeonPostgreSQLPrivate Google SheetPublic Google SheetSnowflakeSupabaseTableauTiDBTigerGraphMultipage appsaddWork with LLMsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Develop/Tutorials/Connect to data sources/PostgreSQLConnect Streamlit to PostgreSQL Introduction This guide explains how to securely access a remote PostgreSQL database from Streamlit Community Cloud. It uses st.connection and Streamlit's Secrets management. The below example code will only work on Streamlit version >= 1.28, when st.connection was added. Create a PostgreSQL database push_pinNoteIf you already have a database that you want to use, feel free to skip to the next step. First, follow this tutorial to install PostgreSQL and create a database (note down the database name, username, and password!). Open the SQL Shell (psql) and enter the following two commands to create a table with some example values: CREATE TABLE mytable ( name varchar(80), pet varchar(80) ); INSERT INTO mytable VALUES ('Mary', 'dog'), ('John', 'cat'), ('Robert', 'bird'); Add username and password to your local app secrets Your local Streamlit app will read secrets from a file .streamlit/secrets.toml in your app's root directory. Create this file if it doesn't exist yet and add the name, user, and password of your database as shown below: # .streamlit/secrets.toml [connections.postgresql] dialect = ""postgresql"" host = ""localhost"" port = ""5432"" database = ""xxx"" username = ""xxx"" password = ""xxx"" priority_highImportantWhen copying your app secrets to Streamlit Community Cloud, be sure to replace the values of host, port, database, username, and password with those of your remote PostgreSQL database!Add this file to .gitignore and don't commit it to your GitHub repo! Copy your app secrets to the cloud As the secrets.toml file above is not committed to GitHub, you need to pass its content to your deployed app (on Streamlit Community Cloud) separately. Go to the app dashboard and in the app's dropdown menu, click on Edit Secrets. Copy the content of secrets.toml into the text area. More information is available at Secrets management. Add dependencies to your requirements file Add the psycopg2-binary and SQLAlchemy packages to your requirements.txt file, preferably pinning its version (replace x.x.x with the version you want installed): # requirements.txt psycopg2-binary==x.x.x sqlalchemy==x.x.x Write your Streamlit app Copy the code below to your Streamlit app and run it. Make sure to adapt query to use the name of your table. # streamlit_app.py import streamlit as st # Initialize connection. conn = st.connection(""postgresql"", type=""sql"") # Perform query. df = conn.query('SELECT * FROM mytable;', ttl=""10m"") # Print results. for row in df.itertuples(): st.write(f""{row.name} has a :{row.pet}:"") See st.connection above? This handles secrets retrieval, setup, query caching and retries. By default, query() results are cached without expiring. In this case, we set ttl=""10m"" to ensure the query result is cached for no longer than 10 minutes. You can also set ttl=0 to disable caching. Learn more in Caching. If everything worked out (and you used the example table we created above), your app should look like this: Previous: NeonNext: Private Google SheetforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy" https://docs.streamlit.io/deploy/streamlit-community-cloud/deploy-your-app/app-dependencies#other-python-package-managers,"DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudremoveGet startedaddDeploy your appremoveApp dependenciesSecrets managementManage your appaddShare your appaddManage your accountaddTroubleshootingStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Deploy/Streamlit Community Cloud/Deploy your app/App dependenciesApp dependencies The main reason that apps fail to build properly is because Streamlit Community Cloud can't find your dependencies! There are two kinds of dependencies your app might have: Python dependencies and external dependencies. Python dependencies are other Python packages (just like Streamlit!) that you import into you script. External dependencies are less common, but they include any other software your script needs to function properly. Since Streamlit Community Cloud runs on Linux, these will be Linux dependencies installed with apt-get outside the Python environment. For your dependencies to be installed correctly, make sure you: Add a requirements file for Python dependencies. (optional) Add a packages.txt file to manage any external dependencies. push_pinNotePython requirements files should be placed either in the root of your repository or in the same directory as your Streamlit app. Add Python dependencies With each import statement in your script, you are bringing in a Python dependency. You need to tell Streamlit Community Cloud how to install those dependencies through a Python package manager. We recommend using a requirements.txt which is based on pip. You should not include built-in Python libraries like math or random in your requirements.txt file. These are a part of Python and aren't installed separately. Also, Streamlit Community Cloud has streamlit installed by default. You don't strictly need to include streamlit unless you want to pin or restrict the version. If you deploy an app without a requirements.txt file, your app will run in an environment with just streamlit (and its dependencies) installed. If you have a script like the following, no extra dependencies would be needed since pandas and numpy are installed as direct dependencies of streamlit. Similarly, math and random are built into Python. import streamlit as st import pandas as pd import numpy as np import math import random st.write('Hi!') However, a valid requirements.txt file would be: streamlit pandas numpy Alternatively, if you needed to specify certain versions, another valid example would be: streamlit==1.24.1 pandas>2.0 numpy<=1.25.1 In the above example, streamlit is pinned to version 1.24.1, pandas must be strictly greater than version 2.0, and numpy must be at-or-below version 1.25.1. Each line in your requirements.txt file is effectively what you would like to pip install into your cloud environment. push_pinNoteWe recommend that you use the latest version of Streamlit to ensure full Streamlit Community Cloud functionality. Be sure to take note of Streamlit's current requirements for package compatibility when planning your environment, especially protobuf>=3.20,<5. If you pin streamlit below 1.20.0, you may experience unexpected results if you've pinned any dependencies of altair. If streamlit is installed below version 1.20.0, altair<5 will be reinstalled on top of your environment for compatibility reasons. When this happens all of altair's dependencies will be updated. Other Python package managers There are other Python package managers besides pip. If you want to consider alternatives to using a requirements.txt file, Streamlit Community Cloud will look for other Python dependency managers to use in the order below. Streamlit will stop and install the first dependency file found. Recognized FilenamePython Package ManagerPipfilepipenvenvironment.ymlcondarequirements.txtpippyproject.tomlpoetry priority_highWarningYou should only use one requirements file for your app. If you include more than one (e.g. requirements.txt and Pipfile), only the first file encountered will be used as described above. Additionally, Streamlit will first look in the directory of your Streamlit app; however, if no requirements file is found, Streamlit will then look at the root of the repo. apt-get dependencies For many apps, a packages.txt file is not required. However, if your script requires any software to be installed that is not a Python package, then you will need a packages.txt file. Streamlit Community Cloud is built on Debian Linux. Anything you would like to apt-get install needs to go in your packages.txt file. If packages.txt exists in the root directory of your repository we automatically detect it, parse it, and install the listed packages. You can read more about apt-get in Linux documentation. Add apt-get dependencies to packages.txt — one package name per line. For example, mysqlclient is a Python package which requires additional software be installed to function. A valid packages.txt file to enable mysqlclient would be: build-essential pkg-config default-libmysqlclient-dev Previous: Deploy your appNext: Secrets managementforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy" https://docs.streamlit.io/deploy/streamlit-community-cloud/get-started/connect-your-github-account#connect-your-github-account,"DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudremoveGet startedremoveQuickstartCreate your accountConnect your GitHub accountExplore your workspaceFork and edit a public appTrust and securityDeploy your appaddManage your appaddShare your appaddManage your accountaddTroubleshootingStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Deploy/Streamlit Community Cloud/Get started/Connect your GitHub accountConnect your GitHub account Connecting GitHub to your Streamlit Community Cloud account allows you to deploy apps directly from the files you store in your repos. It also lets the system check for updates to those files and automatically update your app. There are two stages to this authorization: the first happens when you connect your account for the first time and the second happens when you deploy your first app. Everyone is prompted to connect GitHub when they create an account. If you need to connect GitHub to an existing primary identity, see Manage your GitHub connection. This page contains additional information about the authorization needed to connect GitHub. If you have just created your account, you are free to skip ahead and Explore your workspace. GitHub's authorization prompts occur automatically as needed. Authorize your GitHub account There are two different authorization prompts to grant access between Streamlit and your GitHub account. The first authorization—""Authorize Streamlit""—happens when you connect your GitHub account to Streamlit. The second authorization—""Streamlit is requesting additional permissions""—happens when you deploy your first app. You must click ""Authorize streamlit"" on both. If you are a member of any GitHub organizations, read below to understand the extras steps to authorize an organization. Questions about GitHub permissions? Read some frequently asked questions about our GitHub integration. priority_highImportantYou must have admin permissions to your repo in order to deploy apps. If you don't have admin access, talk to the repo's owner or reach out to us on the Community forum. Organization access If you are working in a repository that is owned by an organization, authorization must be granted by that organization. If you are an owner or member of a GitHub organization when you connect your GitHub account, your authorization prompts will include an extra section labeled ""Organization access"". Organizations you own For any organization you own, if authorization has not been previously granted or denied you can click ""Grant"" before you click ""Authorize streamlit"". Organizations owned by others For an organization you don't own, if authorization has not been previously granted or denied you can click ""Request"" before you click ""Authorize streamlit"". Previous or pending authorization If someone has already started the process of authorizing Streamlit for your organization, different options and statuses will display accordingly. Approved access If an organization has already granted Streamlit access, a green check is shown. Pending access If a request has been previously sent but not yet approved, a pending status shows. Denied access If a request has been previously sent and denied, no option to grant or request access is shown. In this case, the organization owner will need to authorize Streamlit from GitHub. See GitHub's documentation on OAuth apps and organizations. What's next? Now that you have your account you can Explore your workspace. Or if you're ready to go, jump right in and Deploy your app.Previous: Create your accountNext: Explore your workspaceforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy" https://docs.streamlit.io/develop/api-reference/app-testing/st.testing.v1.apptest#apptestradio,"DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceremovePAGE ELEMENTSWrite and magicaddText elementsaddData elementsaddChart elementsaddInput widgetsaddMedia elementsaddLayouts and containersaddChat elementsaddStatus elementsaddThird-party componentsopen_in_newAPPLICATION LOGICNavigation and pagesaddExecution flowaddCaching and stateaddConnections and secretsaddCustom componentsaddUtilitiesaddConfigurationaddTOOLSApp testingremovest.testing.v1.AppTestTesting element classesCommand lineaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Develop/API reference/App testing/st.testing.v1.AppTest The AppTest class st.testing.v1.AppTestStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA simulated Streamlit app to check the correctness of displayed elements and outputs. An instance of AppTest simulates a running Streamlit app. This class provides methods to set up, manipulate, and inspect the app contents via API instead of a browser UI. It can be used to write automated tests of an app in various scenarios. These can then be run using a tool like pytest. AppTest can be initialized by one of three class methods: st.testing.v1.AppTest.from_file (recommended) st.testing.v1.AppTest.from_string st.testing.v1.AppTest.from_function Once initialized, Session State and widget values can be updated and the script can be run. Unlike an actual live-running Streamlit app, you need to call AppTest.run() explicitly to re-run the app after changing a widget value. Switching pages also requires an explicit, follow-up call to AppTest.run(). AppTest enables developers to build tests on their app as-is, in the familiar python test format, without major refactoring or abstracting out logic to be tested separately from the UI. Tests can run quickly with very low overhead. A typical pattern is to build a suite of tests for an app that ensure consistent functionality as the app evolves, and run the tests locally and/or in a CI environment like Github Actions. Note AppTest only supports testing a single page of an app per instance. For multipage apps, each page will need to be tested separately. No methods exist to programatically switch pages within AppTest. Class description[source] st.testing.v1.AppTest(script_path, *, default_timeout, args=None, kwargs=None) Methods get(element_type) Get elements or widgets of the specified type. run(*, timeout=None) Run the script from the current state. switch_page(page_path) Switch to another page of the app. Attributes secrets (dict[str, Any]) Dictionary of secrets to be used the simulated app. Use dict-like syntax to set secret values for the simulated app. session_state (SafeSessionState) Session State for the simulated app. SafeSessionState object supports read and write operations as usual for Streamlit apps. query_params (dict[str, Any]) Dictionary of query parameters to be used by the simluated app. Use dict-like syntax to set query_params values for the simulated app. button Sequence of all st.button and st.form_submit_button widgets. caption Sequence of all st.caption elements. chat_input Sequence of all st.chat_input widgets. chat_message Sequence of all st.chat_message elements. checkbox Sequence of all st.checkbox widgets. code Sequence of all st.code elements. color_picker Sequence of all st.color_picker widgets. columns Sequence of all columns within st.columns elements. dataframe Sequence of all st.dataframe elements. date_input Sequence of all st.date_input widgets. divider Sequence of all st.divider elements. error Sequence of all st.error elements. exception Sequence of all st.exception elements. expander Sequence of all st.expander elements. header Sequence of all st.header elements. info Sequence of all st.info elements. json Sequence of all st.json elements. latex Sequence of all st.latex elements. main Sequence of elements within the main body of the app. markdown Sequence of all st.markdown elements. metric Sequence of all st.metric elements. multiselect Sequence of all st.multiselect widgets. number_input Sequence of all st.number_input widgets. radio Sequence of all st.radio widgets. select_slider Sequence of all st.select_slider widgets. selectbox Sequence of all st.selectbox widgets. sidebar Sequence of all elements within st.sidebar. slider Sequence of all st.slider widgets. status Sequence of all st.status elements. subheader Sequence of all st.subheader elements. success Sequence of all st.success elements. table Sequence of all st.table elements. tabs Sequence of all tabs within st.tabs elements. text Sequence of all st.text elements. text_area Sequence of all st.text_area widgets. text_input Sequence of all st.text_input widgets. time_input Sequence of all st.time_input widgets. title Sequence of all st.title elements. toast Sequence of all st.toast elements. toggle Sequence of all st.toggle widgets. warning Sequence of all st.warning elements. Initialize a simulated app using AppTest AppTest.from_fileStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeCreate an instance of AppTest to simulate an app page defined within a file. This option is most convenient for CI workflows and testing of published apps. The script must be executable on its own and so must contain all necessary imports. Function signature[source] AppTest.from_file(cls, script_path, *, default_timeout=3) Parameters script_path (str) Path to a script file. The path should be absolute or relative to the file calling .from_file. default_timeout (float) Default time in seconds before a script run is timed out. Can be overridden for individual .run() calls. Returns(AppTest) A simulated Streamlit app for testing. The simulated app can be executed via .run(). AppTest.from_stringStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeCreate an instance of AppTest to simulate an app page defined within a string. This is useful for testing short scripts that fit comfortably as an inline string in the test itself, without having to create a separate file for it. The script must be executable on its own and so must contain all necessary imports. Function signature[source] AppTest.from_string(cls, script, *, default_timeout=3) Parameters script (str) The string contents of the script to be run. default_timeout (float) Default time in seconds before a script run is timed out. Can be overridden for individual .run() calls. Returns(AppTest) A simulated Streamlit app for testing. The simulated app can be executed via .run(). AppTest.from_functionStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeCreate an instance of AppTest to simulate an app page defined within a function. This is similar to AppTest.from_string(), but more convenient to write with IDE assistance. The script must be executable on its own and so must contain all necessary imports. Function signature[source] AppTest.from_function(cls, script, *, default_timeout=3, args=None, kwargs=None) Parameters script (Callable) A function whose body will be used as a script. Must be runnable in isolation, so it must include any necessary imports. default_timeout (float) Default time in seconds before a script run is timed out. Can be overridden for individual .run() calls. args (tuple) An optional tuple of args to pass to the script function. kwargs (dict) An optional dict of kwargs to pass to the script function. Returns(AppTest) A simulated Streamlit app for testing. The simulated app can be executed via .run(). Run an AppTest script AppTest.runStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeRun the script from the current state. This is equivalent to manually rerunning the app or the rerun that occurs upon user interaction. AppTest.run() must be manually called after updating a widget value or switching pages as script reruns do not occur automatically as they do for live-running Streamlit apps. Function signature[source] AppTest.run(*, timeout=None) Parameters timeout (null) The maximum number of seconds to run the script. None means use the default timeout set for the instance of AppTest. Returns(AppTest) self AppTest.switch_pageStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSwitch to another page of the app. This method does not automatically rerun the app. Use a follow-up call to AppTest.run() to obtain the elements on the selected page. Function signature[source] AppTest.switch_page(page_path) Parameters page_path (str) Path of the page to switch to. The path must be relative to the main script's location (e.g. ""pages/my_page.py""). Returns(AppTest) self Get AppTest script elements The main value of AppTest is providing an API to programmatically inspect and interact with the elements and widgets produced by a running Streamlit app. Using the AppTest. properties or AppTest.get() method returns a collection of all the elements or widgets of the specified type that would have been displayed by running the app. Note that you can also retrieve elements within a specific container in the same way - first retrieve the container, then retrieve the elements just in that container. AppTest.getStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeGet elements or widgets of the specified type. This method returns the collection of all elements or widgets of the specified type on the current page. Retrieve a specific element by using its index (order on page) or key lookup. Function signature[source] AppTest.get(element_type) Parameters element_type (str) An element attribute of AppTest. For example, ""button"", ""caption"", or ""chat_input"". Returns(Sequence of Elements) Sequence of elements of the given type. Individual elements can be accessed from a Sequence by index (order on the page). When getting and element_type that is a widget, individual widgets can be accessed by key. For example, at.get(""text"")[0] for the first st.text element or at.get(""slider"")(key=""my_key"") for the st.slider widget with a given key. AppTest.buttonStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.button and st.form_submit_button widgets. Function signature[source] AppTest.button Returns(WidgetList of Button) Sequence of all st.button and st.form_submit_button widgets. Individual widgets can be accessed from a WidgetList by index (order on the page) or key. For example, at.button[0] for the first widget or at.button(key=""my_key"") for a widget with a given key. AppTest.captionStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.caption elements. Function signature[source] AppTest.caption Returns(ElementList of Caption) Sequence of all st.caption elements. Individual elements can be accessed from an ElementList by index (order on the page). For example, at.caption[0] for the first element. Caption is an extension of the Element class. AppTest.chat_inputStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.chat_input widgets. Function signature[source] AppTest.chat_input Returns(WidgetList of ChatInput) Sequence of all st.chat_input widgets. Individual widgets can be accessed from a WidgetList by index (order on the page) or key. For example, at.chat_input[0] for the first widget or at.chat_input(key=""my_key"") for a widget with a given key. AppTest.chat_messageStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.chat_message elements. Function signature[source] AppTest.chat_message Returns(Sequence of ChatMessage) Sequence of all st.chat_message elements. Individual elements can be accessed from an ElementList by index (order on the page). For example, at.chat_message[0] for the first element. ChatMessage is an extension of the Block class. AppTest.checkboxStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.checkbox widgets. Function signature[source] AppTest.checkbox Returns(WidgetList of Checkbox) Sequence of all st.checkbox widgets. Individual widgets can be accessed from a WidgetList by index (order on the page) or key. For example, at.checkbox[0] for the first widget or at.checkbox(key=""my_key"") for a widget with a given key. AppTest.codeStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.code elements. Function signature[source] AppTest.code Returns(ElementList of Code) Sequence of all st.code elements. Individual elements can be accessed from an ElementList by index (order on the page). For example, at.code[0] for the first element. Code is an extension of the Element class. AppTest.color_pickerStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.color_picker widgets. Function signature[source] AppTest.color_picker Returns(WidgetList of ColorPicker) Sequence of all st.color_picker widgets. Individual widgets can be accessed from a WidgetList by index (order on the page) or key. For example, at.color_picker[0] for the first widget or at.color_picker(key=""my_key"") for a widget with a given key. AppTest.columnsStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all columns within st.columns elements. Each column within a single st.columns will be returned as a separate Column in the Sequence. Function signature[source] AppTest.columns Returns(Sequence of Column) Sequence of all columns within st.columns elements. Individual columns can be accessed from an ElementList by index (order on the page). For example, at.columns[0] for the first column. Column is an extension of the Block class. AppTest.dataframeStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.dataframe elements. Function signature[source] AppTest.dataframe Returns(ElementList of Dataframe) Sequence of all st.dataframe elements. Individual elements can be accessed from an ElementList by index (order on the page). For example, at.dataframe[0] for the first element. Dataframe is an extension of the Element class. AppTest.date_inputStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.date_input widgets. Function signature[source] AppTest.date_input Returns(WidgetList of DateInput) Sequence of all st.date_input widgets. Individual widgets can be accessed from a WidgetList by index (order on the page) or key. For example, at.date_input[0] for the first widget or at.date_input(key=""my_key"") for a widget with a given key. AppTest.dividerStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.divider elements. Function signature[source] AppTest.divider Returns(ElementList of Divider) Sequence of all st.divider elements. Individual elements can be accessed from an ElementList by index (order on the page). For example, at.divider[0] for the first element. Divider is an extension of the Element class. AppTest.errorStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.error elements. Function signature[source] AppTest.error Returns(ElementList of Error) Sequence of all st.error elements. Individual elements can be accessed from an ElementList by index (order on the page). For example, at.error[0] for the first element. Error is an extension of the Element class. AppTest.exceptionStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.exception elements. Function signature[source] AppTest.exception Returns(ElementList of Exception) Sequence of all st.exception elements. Individual elements can be accessed from an ElementList by index (order on the page). For example, at.exception[0] for the first element. Exception is an extension of the Element class. AppTest.expanderStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.expander elements. Function signature[source] AppTest.expander Returns(Sequence of Expandable) Sequence of all st.expander elements. Individual elements can be accessed from a Sequence by index (order on the page). For example, at.expander[0] for the first element. Expandable is an extension of the Block class. AppTest.headerStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.header elements. Function signature[source] AppTest.header Returns(ElementList of Header) Sequence of all st.header elements. Individual elements can be accessed from an ElementList by index (order on the page). For example, at.header[0] for the first element. Header is an extension of the Element class. AppTest.infoStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.info elements. Function signature[source] AppTest.info Returns(ElementList of Info) Sequence of all st.info elements. Individual elements can be accessed from an ElementList by index (order on the page). For example, at.info[0] for the first element. Info is an extension of the Element class. AppTest.jsonStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.json elements. Function signature[source] AppTest.json Returns(ElementList of Json) Sequence of all st.json elements. Individual elements can be accessed from an ElementList by index (order on the page). For example, at.json[0] for the first element. Json is an extension of the Element class. AppTest.latexStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.latex elements. Function signature[source] AppTest.latex Returns(ElementList of Latex) Sequence of all st.latex elements. Individual elements can be accessed from an ElementList by index (order on the page). For example, at.latex[0] for the first element. Latex is an extension of the Element class. AppTest.mainStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of elements within the main body of the app. Function signature[source] AppTest.main Returns(Block) A container of elements. Block can be queried for elements in the same manner as AppTest. For example, Block.checkbox will return all st.checkbox within the associated container. AppTest.markdownStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.markdown elements. Function signature[source] AppTest.markdown Returns(ElementList of Markdown) Sequence of all st.markdown elements. Individual elements can be accessed from an ElementList by index (order on the page). For example, at.markdown[0] for the first element. Markdown is an extension of the Element class. AppTest.metricStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.metric elements. Function signature[source] AppTest.metric Returns(ElementList of Metric) Sequence of all st.metric elements. Individual elements can be accessed from an ElementList by index (order on the page). For example, at.metric[0] for the first element. Metric is an extension of the Element class. AppTest.multiselectStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.multiselect widgets. Function signature[source] AppTest.multiselect Returns(WidgetList of Multiselect) Sequence of all st.multiselect widgets. Individual widgets can be accessed from a WidgetList by index (order on the page) or key. For example, at.multiselect[0] for the first widget or at.multiselect(key=""my_key"") for a widget with a given key. AppTest.number_inputStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.number_input widgets. Function signature[source] AppTest.number_input Returns(WidgetList of NumberInput) Sequence of all st.number_input widgets. Individual widgets can be accessed from a WidgetList by index (order on the page) or key. For example, at.number_input[0] for the first widget or at.number_input(key=""my_key"") for a widget with a given key. AppTest.radioStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.radio widgets. Function signature[source] AppTest.radio Returns(WidgetList of Radio) Sequence of all st.radio widgets. Individual widgets can be accessed from a WidgetList by index (order on the page) or key. For example, at.radio[0] for the first widget or at.radio(key=""my_key"") for a widget with a given key. AppTest.select_sliderStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.select_slider widgets. Function signature[source] AppTest.select_slider Returns(WidgetList of SelectSlider) Sequence of all st.select_slider widgets. Individual widgets can be accessed from a WidgetList by index (order on the page) or key. For example, at.select_slider[0] for the first widget or at.select_slider(key=""my_key"") for a widget with a given key. AppTest.selectboxStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.selectbox widgets. Function signature[source] AppTest.selectbox Returns(WidgetList of Selectbox) Sequence of all st.selectbox widgets. Individual widgets can be accessed from a WidgetList by index (order on the page) or key. For example, at.selectbox[0] for the first widget or at.selectbox(key=""my_key"") for a widget with a given key. AppTest.sidebarStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all elements within st.sidebar. Function signature[source] AppTest.sidebar Returns(Block) A container of elements. Block can be queried for elements in the same manner as AppTest. For example, Block.checkbox will return all st.checkbox within the associated container. AppTest.sliderStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.slider widgets. Function signature[source] AppTest.slider Returns(WidgetList of Slider) Sequence of all st.slider widgets. Individual widgets can be accessed from a WidgetList by index (order on the page) or key. For example, at.slider[0] for the first widget or at.slider(key=""my_key"") for a widget with a given key. AppTest.subheaderStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.subheader elements. Function signature[source] AppTest.subheader Returns(ElementList of Subheader) Sequence of all st.subheader elements. Individual elements can be accessed from an ElementList by index (order on the page). For example, at.subheader[0] for the first element. Subheader is an extension of the Element class. AppTest.successStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.success elements. Function signature[source] AppTest.success Returns(ElementList of Success) Sequence of all st.success elements. Individual elements can be accessed from an ElementList by index (order on the page). For example, at.success[0] for the first element. Success is an extension of the Element class. AppTest.statusStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.status elements. Function signature[source] AppTest.status Returns(Sequence of Status) Sequence of all st.status elements. Individual elements can be accessed from a Sequence by index (order on the page). For example, at.status[0] for the first element. Status is an extension of the Block class. AppTest.tableStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.table elements. Function signature[source] AppTest.table Returns(ElementList of Table) Sequence of all st.table elements. Individual elements can be accessed from an ElementList by index (order on the page). For example, at.table[0] for the first element. Table is an extension of the Element class. AppTest.tabsStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all tabs within st.tabs elements. Each tab within a single st.tabs will be returned as a separate Tab in the Sequence. Additionally, the tab labels are forwarded to each Tab element as a property. For example, st.tabs(""A"",""B"") will yield two Tab objects, with Tab.label returning ""A"" and ""B"", respectively. Function signature[source] AppTest.tabs Returns(Sequence of Tab) Sequence of all tabs within st.tabs elements. Individual tabs can be accessed from an ElementList by index (order on the page). For example, at.tabs[0] for the first tab. Tab is an extension of the Block class. AppTest.textStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.text elements. Function signature[source] AppTest.text Returns(ElementList of Text) Sequence of all st.text elements. Individual elements can be accessed from an ElementList by index (order on the page). For example, at.text[0] for the first element. Text is an extension of the Element class. AppTest.text_areaStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.text_area widgets. Function signature[source] AppTest.text_area Returns(WidgetList of TextArea) Sequence of all st.text_area widgets. Individual widgets can be accessed from a WidgetList by index (order on the page) or key. For example, at.text_area[0] for the first widget or at.text_area(key=""my_key"") for a widget with a given key. AppTest.text_inputStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.text_input widgets. Function signature[source] AppTest.text_input Returns(WidgetList of TextInput) Sequence of all st.text_input widgets. Individual widgets can be accessed from a WidgetList by index (order on the page) or key. For example, at.text_input[0] for the first widget or at.text_input(key=""my_key"") for a widget with a given key. AppTest.time_inputStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.time_input widgets. Function signature[source] AppTest.time_input Returns(WidgetList of TimeInput) Sequence of all st.time_input widgets. Individual widgets can be accessed from a WidgetList by index (order on the page) or key. For example, at.time_input[0] for the first widget or at.time_input(key=""my_key"") for a widget with a given key. AppTest.titleStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.title elements. Function signature[source] AppTest.title Returns(ElementList of Title) Sequence of all st.title elements. Individual elements can be accessed from an ElementList by index (order on the page). For example, at.title[0] for the first element. Title is an extension of the Element class. AppTest.toastStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.toast elements. Function signature[source] AppTest.toast Returns(ElementList of Toast) Sequence of all st.toast elements. Individual elements can be accessed from an ElementList by index (order on the page). For example, at.toast[0] for the first element. Toast is an extension of the Element class. AppTest.toggleStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.toggle widgets. Function signature[source] AppTest.toggle Returns(WidgetList of Toggle) Sequence of all st.toggle widgets. Individual widgets can be accessed from a WidgetList by index (order on the page) or key. For example, at.toggle[0] for the first widget or at.toggle(key=""my_key"") for a widget with a given key. AppTest.warningStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.warning elements. Function signature[source] AppTest.warning Returns(ElementList of Warning) Sequence of all st.warning elements. Individual elements can be accessed from an ElementList by index (order on the page). For example, at.warning[0] for the first element. Warning is an extension of the Element class. Previous: App testingNext: Testing element classesforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy" https://docs.streamlit.io/deploy/tutorials/kubernetes,"DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsremoveDockerKubernetesschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Deploy/Other platforms/KubernetesDeploy Streamlit using Kubernetes Introduction So you have an amazing app and you want to start sharing it with other people, what do you do? You have a few options. First, where do you want to run your Streamlit app, and how do you want to access it? On your corporate network - Most corporate networks are closed to the outside world. You typically use a VPN to log onto your corporate network and access resources there. You could run your Streamlit app on a server in your corporate network for security reasons, to ensure that only folks internal to your company can access it. On the cloud - If you'd like to access your Streamlit app from outside of a corporate network, or share your app with folks outside of your home network or laptop, you might choose this option. In this case, it'll depend on your hosting provider. We have community-submitted guides from Heroku, AWS, and other providers. Wherever you decide to deploy your app, you will first need to containerize it. This guide walks you through using Kubernetes to deploy your app. If you prefer Docker see Deploy Streamlit using Docker. Prerequisites Install Docker Engine Install the gcloud CLI Install Docker Engine If you haven't already done so, install Docker on your server. Docker provides .deb and .rpm packages from many Linux distributions, including: Debian Ubuntu Verify that Docker Engine is installed correctly by running the hello-world Docker image: sudo docker run hello-world starTipFollow Docker's official post-installation steps for Linux to run Docker as a non-root user, so that you don't have to preface the docker command with sudo. Install the gcloud CLI In this guide, we will orchestrate Docker containers with Kubernetes and host docker images on the Google Container Registry (GCR). As GCR is a Google-supported Docker registry, we need to register gcloud as the Docker credential helper. Follow the official documentation to Install the gcloud CLI and initialize it. Create a Docker container We need to create a docker container which contains all the dependencies and the application code. Below you can see the entrypoint, i.e. the command run when the container starts, and the Dockerfile definition. Create an entrypoint script Create a run.sh script containing the following: #!/bin/bash APP_PID= stopRunningProcess() { # Based on https://linuxconfig.org/how-to-propagate-a-signal-to-child-processes-from-a-bash-script if test ! ""${APP_PID}"" = '' && ps -p ${APP_PID} > /dev/null ; then > /proc/1/fd/1 echo ""Stopping ${COMMAND_PATH} which is running with process ID ${APP_PID}"" kill -TERM ${APP_PID} > /proc/1/fd/1 echo ""Waiting for ${COMMAND_PATH} to process SIGTERM signal"" wait ${APP_PID} > /proc/1/fd/1 echo ""All processes have stopped running"" else > /proc/1/fd/1 echo ""${COMMAND_PATH} was not started when the signal was sent or it has already been stopped"" fi } trap stopRunningProcess EXIT TERM source ${VIRTUAL_ENV}/bin/activate streamlit run ${HOME}/app/streamlit_app.py & APP_ID=${!} wait ${APP_ID} Create a Dockerfile Docker builds images by reading the instructions from a Dockerfile. A Dockerfile is a text document that contains all the commands a user could call on the command line to assemble an image. Learn more in the Dockerfile reference. The docker build command builds an image from a Dockerfile. The docker run command first creates a container over the specified image, and then starts it using the specified command. Here's an example Dockerfile that you can add to the root of your directory. FROM python:3.8-slim RUN groupadd --gid 1000 appuser \ && useradd --uid 1000 --gid 1000 -ms /bin/bash appuser RUN pip3 install --no-cache-dir --upgrade \ pip \ virtualenv RUN apt-get update && apt-get install -y \ build-essential \ software-properties-common \ git USER appuser WORKDIR /home/appuser RUN git clone https://github.com/streamlit/streamlit-example.git app ENV VIRTUAL_ENV=/home/appuser/venv RUN virtualenv ${VIRTUAL_ENV} RUN . ${VIRTUAL_ENV}/bin/activate && pip install -r app/requirements.txt EXPOSE 8501 COPY run.sh /home/appuser ENTRYPOINT [""./run.sh""] priority_highImportantAs mentioned in Development flow, for Streamlit version 1.10.0 and higher, Streamlit apps cannot be run from the root directory of Linux distributions. Your main script should live in a directory other than the root directory. If you try to run a Streamlit app from the root directory, Streamlit will throw a FileNotFoundError: [Errno 2] No such file or directory error. For more information, see GitHub issue #5239.If you are using Streamlit version 1.10.0 or higher, you must set the WORKDIR to a directory other than the root directory. For example, you can set the WORKDIR to /home/appuser as shown in the example Dockerfile above. Build a Docker image Put the above files (run.sh and Dockerfile) in the same folder and build the docker image: docker build --platform linux/amd64 -t gcr.io/$GCP_PROJECT_ID/k8s-streamlit:test . priority_highImportantReplace $GCP_PROJECT_ID in the above command with the name of your Google Cloud project. Upload the Docker image to a container registry The next step is to upload the Docker image to a container registry. In this example, we will use the Google Container Registry (GCR). Start by enabling the Container Registry API. Sign in to Google Cloud and navigate to your project’s Container Registry and click Enable. We can now build the Docker image from the previous step and push it to our project’s GCR. Be sure to replace $GCP_PROJECT_ID in the docker push command with the name of your project: gcloud auth configure-docker docker push gcr.io/$GCP_PROJECT_ID/k8s-streamlit:test Create a Kubernetes deployment For this step you will need a: Running Kubernetes service Custom domain for which you can generate a TLS certificate DNS service where you can configure your custom domain to point to the application IP As the image was uploaded to the container registry in the previous step, we can run it in Kubernetes using the below configurations. Install and run Kubernetes Make sure your Kubernetes client, kubectl, is installed and running on your machine. Configure a Google OAuth Client and oauth2-proxy For configuring the Google OAuth Client, please see Google Auth Provider. Configure oauth2-proxy to use the desired OAuth Provider Configuration and update the oath2-proxy config in the config map. The below configuration contains a ouath2-proxy sidecar container which handles the authentication with Google. You can learn more from the oauth2-proxy repository. Create a Kubernetes configuration file Create a YAML configuration file named k8s-streamlit.yaml: apiVersion: v1 kind: ConfigMap metadata: name: streamlit-configmap data: oauth2-proxy.cfg: |- http_address = ""0.0.0.0:4180"" upstreams = [""http://127.0.0.1:8501/""] email_domains = [""*""] client_id = """" client_secret = """" cookie_secret = ""<16, 24, or 32 bytes>"" redirect_url = --- apiVersion: apps/v1 kind: Deployment metadata: name: streamlit-deployment labels: app: streamlit spec: replicas: 1 selector: matchLabels: app: streamlit template: metadata: labels: app: streamlit spec: containers: - name: oauth2-proxy image: quay.io/oauth2-proxy/oauth2-proxy:v7.2.0 args: [""--config"", ""/etc/oauth2-proxy/oauth2-proxy.cfg""] ports: - containerPort: 4180 livenessProbe: httpGet: path: /ping port: 4180 scheme: HTTP readinessProbe: httpGet: path: /ping port: 4180 scheme: HTTP volumeMounts: - mountPath: ""/etc/oauth2-proxy"" name: oauth2-config - name: streamlit image: gcr.io/GCP_PROJECT_ID/k8s-streamlit:test imagePullPolicy: Always ports: - containerPort: 8501 livenessProbe: httpGet: path: /_stcore/health port: 8501 scheme: HTTP timeoutSeconds: 1 readinessProbe: httpGet: path: /_stcore/health port: 8501 scheme: HTTP timeoutSeconds: 1 resources: limits: cpu: 1 memory: 2Gi requests: cpu: 100m memory: 745Mi volumes: - name: oauth2-config configMap: name: streamlit-configmap --- apiVersion: v1 kind: Service metadata: name: streamlit-service spec: type: LoadBalancer selector: app: streamlit ports: - name: streamlit-port protocol: TCP port: 80 targetPort: 4180 priority_highImportantWhile the above configurations can be copied verbatim, you will have to configure the oauth2-proxy yourself and use the correct GOOGLE_CLIENT_ID, GOOGLE_CLIENT_ID, GCP_PROJECT_ID, and REDIRECT_URL. Now create the configuration from the file in Kubernetes with the kubectl create command: kubctl create -f k8s-streamlit.yaml Set up TLS support Since you are using the Google authentication, you will need to set up TLS support. Find out how in TLS Configuration. Verify the deployment Once the deployment and the service are created, we need to wait a couple of minutes for the public IP address to become available. We can check when that is ready by running: kubectl get service streamlit-service -o jsonpath='{.status.loadBalancer.ingress[0].ip}' After the public IP is assigned, you will need to configure in your DNS service an A record pointing to the above IP address.Previous: DockerNext: Knowledge baseforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy" https://docs.streamlit.io/develop/api-reference/charts/st.map#elementadd_rows,"DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceremovePAGE ELEMENTSWrite and magicaddText elementsaddData elementsaddChart elementsremoveSIMPLEst.area_chartst.bar_chartst.line_chartst.mapst.scatter_chartADVANCEDst.altair_chartst.bokeh_chartst.graphviz_chartst.plotly_chartst.pydeck_chartst.pyplotst.vega_lite_chartInput widgetsaddMedia elementsaddLayouts and containersaddChat elementsaddStatus elementsaddThird-party componentsopen_in_newAPPLICATION LOGICNavigation and pagesaddExecution flowaddCaching and stateaddConnections and secretsaddCustom componentsaddUtilitiesaddConfigurationaddTOOLSApp testingaddCommand lineaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Develop/API reference/Chart elements/st.mapst.mapStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeDisplay a map with a scatterplot overlaid onto it. This is a wrapper around st.pydeck_chart to quickly create scatterplot charts on top of a map, with auto-centering and auto-zoom. When using this command, Mapbox provides the map tiles to render map content. Note that Mapbox is a third-party product and Streamlit accepts no responsibility or liability of any kind for Mapbox or for any content or information made available by Mapbox. Mapbox requires users to register and provide a token before users can request map tiles. Currently, Streamlit provides this token for you, but this could change at any time. We strongly recommend all users create and use their own personal Mapbox token to avoid any disruptions to their experience. You can do this with the mapbox.token config option. The use of Mapbox is governed by Mapbox's Terms of Use. To get a token for yourself, create an account at https://mapbox.com. For more info on how to set config options, see https://docs.streamlit.io/library/advanced-features/configuration Function signature[source] st.map(data=None, *, latitude=None, longitude=None, color=None, size=None, zoom=None, use_container_width=True) Parameters data (pandas.DataFrame, pandas.Styler, pyarrow.Table, pyspark.sql.DataFrame, snowflake.snowpark.dataframe.DataFrame, snowflake.snowpark.table.Table, Iterable, dict, or None) The data to be plotted. latitude (str or None) The name of the column containing the latitude coordinates of the datapoints in the chart. If None, the latitude data will come from any column named 'lat', 'latitude', 'LAT', or 'LATITUDE'. longitude (str or None) The name of the column containing the longitude coordinates of the datapoints in the chart. If None, the longitude data will come from any column named 'lon', 'longitude', 'LON', or 'LONGITUDE'. color (str or tuple or None) The color of the circles representing each datapoint. Can be: None, to use the default color. A hex string like ""#ffaa00"" or ""#ffaa0088"". An RGB or RGBA tuple with the red, green, blue, and alpha components specified as ints from 0 to 255 or floats from 0.0 to 1.0. The name of the column to use for the color. Cells in this column should contain colors represented as a hex string or color tuple, as described above. size (str or float or None) The size of the circles representing each point, in meters. This can be: None, to use the default size. A number like 100, to specify a single size to use for all datapoints. The name of the column to use for the size. This allows each datapoint to be represented by a circle of a different size. zoom (int) Zoom level as specified in https://wiki.openstreetmap.org/wiki/Zoom_levels. use_container_width (bool) If True, set the chart width to the column width. This takes precedence over the width argument. Examples import streamlit as st import pandas as pd import numpy as np df = pd.DataFrame( np.random.randn(1000, 2) / [50, 50] + [37.76, -122.4], columns=['lat', 'lon']) st.map(df) Built with Streamlit 🎈Fullscreen open_in_new You can also customize the size and color of the datapoints: st.map(df, size=20, color='#0044ff') And finally, you can choose different columns to use for the latitude and longitude components, as well as set size and color of each datapoint dynamically based on other columns: import streamlit as st import pandas as pd import numpy as np df = pd.DataFrame({ ""col1"": np.random.randn(1000) / 50 + 37.76, ""col2"": np.random.randn(1000) / 50 + -122.4, ""col3"": np.random.randn(1000) * 100, ""col4"": np.random.rand(1000, 4).tolist(), }) st.map(df, latitude='col1', longitude='col2', size='col3', color='col4') Built with Streamlit 🎈Fullscreen open_in_new element.add_rowsStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeConcatenate a dataframe to the bottom of the current one. Function signature[source] element.add_rows(data=None, **kwargs) Parameters data (pandas.DataFrame, pandas.Styler, pyarrow.Table, numpy.ndarray, pyspark.sql.DataFrame, snowflake.snowpark.dataframe.DataFrame, Iterable, dict, or None) Table to concat. Optional. **kwargs (pandas.DataFrame, numpy.ndarray, Iterable, dict, or None) The named dataset to concat. Optional. You can only pass in 1 dataset (including the one in the data parameter). Example import streamlit as st import pandas as pd import numpy as np df1 = pd.DataFrame(np.random.randn(50, 20), columns=(""col %d"" % i for i in range(20))) my_table = st.table(df1) df2 = pd.DataFrame(np.random.randn(50, 20), columns=(""col %d"" % i for i in range(20))) my_table.add_rows(df2) # Now the table shown in the Streamlit app contains the data for # df1 followed by the data for df2. You can do the same thing with plots. For example, if you want to add more data to a line chart: # Assuming df1 and df2 from the example above still exist... my_chart = st.line_chart(df1) my_chart.add_rows(df2) # Now the chart shown in the Streamlit app contains the data for # df1 followed by the data for df2. And for plots whose datasets are named, you can pass the data with a keyword argument where the key is the name: my_chart = st.vega_lite_chart({ 'mark': 'line', 'encoding': {'x': 'a', 'y': 'b'}, 'datasets': { 'some_fancy_name': df1, # <-- named dataset }, 'data': {'name': 'some_fancy_name'}, }), my_chart.add_rows(some_fancy_name=df2) # <-- name used as keyword Previous: st.line_chartNext: st.scatter_chartforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy" https://docs.streamlit.io/deploy/streamlit-community-cloud/get-started/create-your-account#sign-up,"DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudremoveGet startedremoveQuickstartCreate your accountConnect your GitHub accountExplore your workspaceFork and edit a public appTrust and securityDeploy your appaddManage your appaddShare your appaddManage your accountaddTroubleshootingStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Deploy/Streamlit Community Cloud/Get started/Create your accountCreate your account Before you can start deploying apps for the world to see, you need to sign up for your Streamlit Community Cloud account. Streamlit Community Cloud accounts have two underlying identities: primary and source control. Your primary identity is used for viewing analytics as well as viewing permissions. Your source-control identity is used for deploying and managing apps. Sign up Although you can begin the sign-up process with GitHub, we recommend starting with Google or email in order to have a complete account from the start. Step 1: Primary identity (Google or email) Step 2: Source control (GitHub) Step 3: Set up your account Step 1: Primary identity Your primary identity is associated to an email. You can sign in through Google or through single-use, emailed links which are valid for 15 minutes once requested. If you're sharing a private app, you will assign viewing permission by email. Therefore, your app's users will need to sign in with either Google or emailed links. Primary identity option 1: Google Go to share.streamlit.io/signup. Click ""Continue with Google"". Enter your Google credentials and click ""Next"". If you will be deploying or managing any apps, click ""Connect GitHub account"" and proceed to Step 2: Source Control. If you are only going to be viewing apps and will not be using GitHub, you can click ""Skip this step"" and proceed to Step 3: Set up your account. Primary identity option 2: email Go to share.streamlit.io/signup. Enter your email address and click ""Continue with email"". A confirmation screen will display, telling you to check your email. Check your inbox for an email with the subject ""Sign in to Streamlit Cloud"". Click the link to sign in. If you will be deploying or managing any apps, click ""Connect GitHub account"" and proceed to Step 2: Source control. If you are only going to be viewing apps and will not be using GitHub, you can click ""Skip this step"" and proceed to Step 3: Set up your account. Step 2: Source control Streamlit Community Cloud is integrated with GitHub for source control. If you begin your sign-up process with GitHub, you will not be directly prompted to create a primary identity. However, you can attach a Google account later. There are two different authorization requests to completely Connect your GitHub account. You will encounter the first authorization request when you begin connecting your GitHub account. A second authorization is needed the first time you deploy an app. If you will be deploying or managing any apps from a GitHub organization, your authorization requests will include additional options to allow Organization access. After completing Step 1: Primary identity or after clicking ""Continue with GitHub"" from the sign-up page, enter your GitHub credentials and click ""Sign in"". Click ""Authorize streamlit"". Continue to Step 3: Set up your account Step 3: Set up your account As a final step to account creation, please tell us about yourself and your experience with Streamlit. This is also when you can read and acknowledge our Terms of use and Privacy notice. The email you provide in this survey is not used as your account email. Fill in your information and click ""Continue"" at the bottom of the screen. You will be taken to your workspace. Finish up Congratulations on creating your Streamlit Community Cloud account! A warning icon (warning) next to ""Settings"" in the upper-right corner is expected; this indicates one of three things: You created a primary identity and skipped connecting GitHub. You started with GitHub and did not create a primary identity. You created both a primary identity and connected GitHub, but the second authorization for GitHub is still pending. You will be prompted with the second authorization when you deploy your first app. What's next? Now that you have your account you can Explore your workspace. Or if you're ready to go, jump right in and Deploy your app.Previous: QuickstartNext: Connect your GitHub accountforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy" https://docs.streamlit.io/develop/api-reference/caching-and-state/st.experimental_singleton#supported-widgets,"DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceremovePAGE ELEMENTSWrite and magicaddText elementsaddData elementsaddChart elementsaddInput widgetsaddMedia elementsaddLayouts and containersaddChat elementsaddStatus elementsaddThird-party componentsopen_in_newAPPLICATION LOGICNavigation and pagesaddExecution flowaddCaching and stateremovest.cache_datast.cache_resourcest.cachedeletest.session_statest.query_paramsst.experimental_get_query_paramsdeletest.experimental_set_query_paramsdeleteConnections and secretsaddCustom componentsaddUtilitiesaddConfigurationaddTOOLSApp testingaddCommand lineaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Develop/API reference/Caching and state/st.experimental_singletonpriority_highImportantThis is an experimental feature. Experimental features and their APIs may change or be removed at any time. To learn more, click here. st.experimental_singletonStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakedeleteDeprecation noticest.experimental_singleton was deprecated in version 1.18.0. Use st.cache_resource instead. Learn more in Caching.Decorator to cache functions that return global resources (e.g. database connections, ML models). Cached objects are shared across all users, sessions, and reruns. They must be thread-safe because they can be accessed from multiple threads concurrently. If thread safety is an issue, consider using st.session_state to store resources per session instead. You can clear a function's cache with func.clear() or clear the entire cache with st.cache_resource.clear(). To cache data, use st.cache_data instead. Learn more about caching at https://docs.streamlit.io/library/advanced-features/caching. Function signature[source] st.experimental_singleton(func, *, ttl, max_entries, show_spinner, validate, experimental_allow_widgets, hash_funcs=None) Parameters func (callable) The function that creates the cached resource. Streamlit hashes the function's source code. ttl (float, timedelta, str, or None) The maximum time to keep an entry in the cache. Can be one of: None if cache entries should never expire (default). A number specifying the time in seconds. A string specifying the time in a format supported by Pandas's Timedelta constructor, e.g. ""1d"", ""1.5 days"", or ""1h23s"". A timedelta object from Python's built-in datetime library, e.g. timedelta(days=1). max_entries (int or None) The maximum number of entries to keep in the cache, or None for an unbounded cache. When a new entry is added to a full cache, the oldest cached entry will be removed. Defaults to None. show_spinner (bool or str) Enable the spinner. Default is True to show a spinner when there is a ""cache miss"" and the cached resource is being created. If string, value of show_spinner param will be used for spinner text. validate (callable or None) An optional validation function for cached data. validate is called each time the cached value is accessed. It receives the cached value as its only parameter and it must return a boolean. If validate returns False, the current cached value is discarded, and the decorated function is called to compute a new value. This is useful e.g. to check the health of database connections. experimental_allow_widgets (bool) Allow widgets to be used in the cached function. Defaults to False. Support for widgets in cached functions is currently experimental. Setting this parameter to True may lead to excessive memory use since the widget value is treated as an additional input parameter to the cache. We may remove support for this option at any time without notice. hash_funcs (dict or None) Mapping of types or fully qualified names to hash functions. This is used to override the behavior of the hasher inside Streamlit's caching mechanism: when the hasher encounters an object, it will first check to see if its type matches a key in this dict and, if so, will use the provided function to generate a hash for it. See below for an example of how this can be used. Example import streamlit as st @st.cache_resource def get_database_session(url): # Create a database session object that points to the URL. return session s1 = get_database_session(SESSION_URL_1) # Actually executes the function, since this is the first time it was # encountered. s2 = get_database_session(SESSION_URL_1) # Does not execute the function. Instead, returns its previously computed # value. This means that now the connection object in s1 is the same as in s2. s3 = get_database_session(SESSION_URL_2) # This is a different URL, so the function executes. By default, all parameters to a cache_resource function must be hashable. Any parameter whose name begins with _ will not be hashed. You can use this as an ""escape hatch"" for parameters that are not hashable: import streamlit as st @st.cache_resource def get_database_session(_sessionmaker, url): # Create a database connection object that points to the URL. return connection s1 = get_database_session(create_sessionmaker(), DATA_URL_1) # Actually executes the function, since this is the first time it was # encountered. s2 = get_database_session(create_sessionmaker(), DATA_URL_1) # Does not execute the function. Instead, returns its previously computed # value - even though the _sessionmaker parameter was different # in both calls. A cache_resource function's cache can be procedurally cleared: import streamlit as st @st.cache_resource def get_database_session(_sessionmaker, url): # Create a database connection object that points to the URL. return connection fetch_and_clean_data.clear(_sessionmaker, ""https://streamlit.io/"") # Clear the cached entry for the arguments provided. get_database_session.clear() # Clear all cached entries for this function. To override the default hashing behavior, pass a custom hash function. You can do that by mapping a type (e.g. Person) to a hash function (str) like this: import streamlit as st from pydantic import BaseModel class Person(BaseModel): name: str @st.cache_resource(hash_funcs={Person: str}) def get_person_name(person: Person): return person.name Alternatively, you can map the type's fully-qualified name (e.g. ""__main__.Person"") to the hash function instead: import streamlit as st from pydantic import BaseModel class Person(BaseModel): name: str @st.cache_resource(hash_funcs={""__main__.Person"": str}) def get_person_name(person: Person): return person.name st.experimental_singleton.clearStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakedeleteDeprecation noticest.experimental_singleton.clear was deprecated in version 1.18.0. Use st.cache_resource.clear instead. Learn more in Caching.Clear all cache_resource caches. Function signature[source] st.experimental_singleton.clear() Example In the example below, pressing the ""Clear All"" button will clear all singleton caches. i.e. Clears cached singleton objects from all functions decorated with @st.experimental_singleton. import streamlit as st from transformers import BertModel @st.experimental_singleton def get_database_session(url): # Create a database session object that points to the URL. return session @st.experimental_singleton def get_model(model_type): # Create a model of the specified type. return BertModel.from_pretrained(model_type) if st.button(""Clear All""): # Clears all singleton caches: st.experimental_singleton.clear() Validating the cache The @st.experimental_singleton decorator is used to cache the output of a function, so that it only needs to be executed once. This can improve performance in certain situations, such as when a function takes a long time to execute or makes a network request. However, in some cases, the cached output may become invalid over time, such as when a database connection times out. To handle this, the @st.experimental_singleton decorator supports an optional validate parameter, which accepts a validation function that is called each time the cached output is accessed. If the validation function returns False, the cached output is discarded and the decorated function is executed again. Best Practices Use the validate parameter when the cached output may become invalid over time, such as when a database connection or an API key expires. Use the validate parameter judiciously, as it will add an additional overhead of calling the validation function each time the cached output is accessed. Make sure that the validation function is as fast as possible, as it will be called each time the cached output is accessed. Consider to validate cached data periodically, instead of each time it is accessed, to mitigate the performance impact. Handle errors that may occur during validation and provide a fallback mechanism if the validation fails. Replay static st elements in cache-decorated functions Functions decorated with @st.experimental_singleton can contain static st elements. When a cache-decorated function is executed, we record the element and block messages produced, so the elements will appear in the app even when execution of the function is skipped because the result was cached. In the example below, the @st.experimental_singleton decorator is used to cache the execution of the get_model function, that returns a 🤗 Hugging Face Transformers model. Notice the cached function also contains a st.bar_chart command, which will be replayed when the function is skipped because the result was cached. import numpy as np import pandas as pd import streamlit as st from transformers import AutoModel @st.experimental_singleton def get_model(model_type): # Contains a static element st.bar_chart st.bar_chart( np.random.rand(10, 1) ) # This will be recorded and displayed even when the function is skipped # Create a model of the specified type return AutoModel.from_pretrained(model_type) bert_model = get_model(""distilbert-base-uncased"") st.help(bert_model) # Display the model's docstring Supported static st elements in cache-decorated functions include: st.alert st.altair_chart st.area_chart st.audio st.bar_chart st.ballons st.bokeh_chart st.caption st.code st.components.v1.html st.components.v1.iframe st.container st.dataframe st.echo st.empty st.error st.exception st.expander st.experimental_get_query_params st.experimental_set_query_params st.form st.form_submit_button st.graphviz_chart st.help st.image st.info st.json st.latex st.line_chart st.markdown st.metric st.plotly_chart st.progress st.pydeck_chart st.snow st.spinner st.success st.table st.text st.vega_lite_chart st.video st.warning Replay input widgets in cache-decorated functions In addition to static elements, functions decorated with @st.experimental_singleton can also contain input widgets! Replaying input widgets is disabled by default. To enable it, you can set the experimental_allow_widgets parameter for @st.experimental_singleton to True. The example below enables widget replaying, and shows the use of a checkbox widget within a cache-decorated function. import streamlit as st # Enable widget replay @st.experimental_singleton(experimental_allow_widgets=True) def func(): # Contains an input widget st.checkbox(""Works!"") func() If the cache decorated function contains input widgets, but experimental_allow_widgets is set to False or unset, Streamlit will throw a CachedStFunctionWarning, like the one below: import streamlit as st # Widget replay is disabled by default @st.experimental_singleton def func(): # Streamlit will throw a CachedStFunctionWarning st.checkbox(""Doesn't work"") func() How widget replay works Let's demystify how widget replay in cache-decorated functions works and gain a conceptual understanding. Widget values are treated as additional inputs to the function, and are used to determine whether the function should be executed or not. Consider the following example: import streamlit as st @st.experimental_singleton(experimental_allow_widgets=True) def plus_one(x): y = x + 1 if st.checkbox(""Nuke the value 💥""): st.write(""Value was nuked, returning 0"") y = 0 return y st.write(plus_one(2)) The plus_one function takes an integer x as input, and returns x + 1. The function also contains a checkbox widget, which is used to ""nuke"" the value of x. i.e. the return value of plus_one depends on the state of the checkbox: if it is checked, the function returns 0, otherwise it returns 3. In order to know which value the cache should return (in case of a cache hit), Streamlit treats the checkbox state (checked / unchecked) as an additional input to the function plus_one (just like x). If the user checks the checkbox (thereby changing its state), we look up the cache for the same value of x (2) and the same checkbox state (checked). If the cache contains a value for this combination of inputs, we return it. Otherwise, we execute the function and store the result in the cache. Let's now understand how enabling and disabling widget replay changes the behavior of the function. Widget replay disabled Widgets in cached functions throw a CachedStFunctionWarning and are ignored. Other static elements in cached functions replay as expected. Widget replay enabled Widgets in cached functions don't lead to a warning, and are replayed as expected. Interacting with a widget in a cached function will cause the function to be executed again, and the cache to be updated. Widgets in cached functions retain their state across reruns. Each unique combination of widget values is treated as a separate input to the function, and is used to determine whether the function should be executed or not. i.e. Each unique combination of widget values has its own cache entry; the cached function runs the first time and the saved value is used afterwards. Calling a cached function multiple times in one script run with the same arguments triggers a DuplicateWidgetID error. If the arguments to a cached function change, widgets from that function that render again retain their state. Changing the source code of a cached function invalidates the cache. Both st.experimental_singleton and st.experimental_memo support widget replay. Fundamentally, the behavior of a function with (supported) widgets in it doesn't change when it is decorated with @st.experimental_singleton or @st.experimental_memo. The only difference is that the function is only executed when we detect a cache ""miss"". Supported widgets All input widgets are supported in cache-decorated functions. The following is an exhaustive list of supported widgets: st.button st.camera_input st.checkbox st.color_picker st.date_input st.download_button st.file_uploader st.multiselect st.number_input st.radio st.selectbox st.select_slider st.slider st.text_area st.text_input st.time_input Previous: st.experimental_memoNext: st.session_stateforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy" https://docs.streamlit.io/develop/api-reference/#api-reference,"DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceremovePAGE ELEMENTSWrite and magicaddText elementsaddData elementsaddChart elementsaddInput widgetsaddMedia elementsaddLayouts and containersaddChat elementsaddStatus elementsaddThird-party componentsopen_in_newAPPLICATION LOGICNavigation and pagesaddExecution flowaddCaching and stateaddConnections and secretsaddCustom componentsaddUtilitiesaddConfigurationaddTOOLSApp testingaddCommand lineaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Develop/API referenceAPI reference Streamlit makes it easy for you to visualize, mutate, and share data. The API reference is organized by activity type, like displaying data or optimizing performance. Each section includes methods associated with the activity type, including examples. Browse our API below and click to learn more about any of our available commands! 🎈 Display almost anything Write and magic st.writeWrite arguments to the app.st.write(""Hello **world**!"") st.write(my_data_frame) st.write(my_mpl_figure) st.write_streamWrite generators or streams to the app with a typewriter effect.st.write_stream(my_generator) st.write_stream(my_llm_stream) MagicAny time Streamlit sees either a variable or literal value on its own line, it automatically writes that to your app using st.write""Hello **world**!"" my_data_frame my_mpl_figure Text elements MarkdownDisplay string formatted as Markdown.st.markdown(""Hello **world**!"") TitleDisplay text in title formatting.st.title(""The app title"") HeaderDisplay text in header formatting.st.header(""This is a header"") SubheaderDisplay text in subheader formatting.st.subheader(""This is a subheader"") CaptionDisplay text in small font.st.caption(""This is written small caption text"") Code blockDisplay a code block with optional syntax highlighting.st.code(""a = 1234"") EchoDisplay some code in the app, then execute it. Useful for tutorials.with st.echo(): st.write('This code will be printed') LaTeXDisplay mathematical expressions formatted as LaTeX.st.latex(""\int a x^2 \,dx"") Preformatted textWrite fixed-width and preformatted text.st.text(""Hello world"") DividerDisplay a horizontal rule.st.divider() Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration! PreviousTagsAdd tags to your Streamlit apps. Created by @gagan3012.st_tags(label='# Enter Keywords:', text='Press enter to add more', value=['Zero', 'One', 'Two'], suggestions=['five', 'six', 'seven', 'eight', 'nine', 'three', 'eleven', 'ten', 'four'], maxtags = 4, key='1') NLUApply text mining on a dataframe. Created by @JohnSnowLabs.nlu.load('sentiment').predict('I love NLU! <3') Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.mention(label=""An awesome Streamlit App"", icon=""streamlit"", url=""https://extras.streamlit.app"",) Annotated textDisplay annotated text in Streamlit apps. Created by @tvst.annotated_text(""This "", (""is"", ""verb""), "" some "", (""annotated"", ""adj""), (""text"", ""noun""), "" for those of "", (""you"", ""pronoun""), "" who "", (""like"", ""verb""), "" this sort of "", (""thing"", ""noun""), ""."") Drawable CanvasProvides a sketching canvas using Fabric.js. Created by @andfanilo.st_canvas(fill_color=""rgba(255, 165, 0, 0.3)"", stroke_width=stroke_width, stroke_color=stroke_color, background_color=bg_color, background_image=Image.open(bg_image) if bg_image else None, update_streamlit=realtime_update, height=150, drawing_mode=drawing_mode, point_display_radius=point_display_radius if drawing_mode == 'point' else 0, key=""canvas"",) TagsAdd tags to your Streamlit apps. Created by @gagan3012.st_tags(label='# Enter Keywords:', text='Press enter to add more', value=['Zero', 'One', 'Two'], suggestions=['five', 'six', 'seven', 'eight', 'nine', 'three', 'eleven', 'ten', 'four'], maxtags = 4, key='1') NLUApply text mining on a dataframe. Created by @JohnSnowLabs.nlu.load('sentiment').predict('I love NLU! <3') Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.mention(label=""An awesome Streamlit App"", icon=""streamlit"", url=""https://extras.streamlit.app"",) Annotated textDisplay annotated text in Streamlit apps. Created by @tvst.annotated_text(""This "", (""is"", ""verb""), "" some "", (""annotated"", ""adj""), (""text"", ""noun""), "" for those of "", (""you"", ""pronoun""), "" who "", (""like"", ""verb""), "" this sort of "", (""thing"", ""noun""), ""."") Drawable CanvasProvides a sketching canvas using Fabric.js. Created by @andfanilo.st_canvas(fill_color=""rgba(255, 165, 0, 0.3)"", stroke_width=stroke_width, stroke_color=stroke_color, background_color=bg_color, background_image=Image.open(bg_image) if bg_image else None, update_streamlit=realtime_update, height=150, drawing_mode=drawing_mode, point_display_radius=point_display_radius if drawing_mode == 'point' else 0, key=""canvas"",) TagsAdd tags to your Streamlit apps. Created by @gagan3012.st_tags(label='# Enter Keywords:', text='Press enter to add more', value=['Zero', 'One', 'Two'], suggestions=['five', 'six', 'seven', 'eight', 'nine', 'three', 'eleven', 'ten', 'four'], maxtags = 4, key='1') NLUApply text mining on a dataframe. Created by @JohnSnowLabs.nlu.load('sentiment').predict('I love NLU! <3') Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.mention(label=""An awesome Streamlit App"", icon=""streamlit"", url=""https://extras.streamlit.app"",) Next Data elements DataframesDisplay a dataframe as an interactive table.st.dataframe(my_data_frame) Data editorDisplay a data editor widget.edited = st.data_editor(df, num_rows=""dynamic"") Column configurationConfigure the display and editing behavior of dataframes and data editors.st.column_config.NumberColumn(""Price (in USD)"", min_value=0, format=""$%d"") Static tablesDisplay a static table.st.table(my_data_frame) MetricsDisplay a metric in big bold font, with an optional indicator of how the metric changed.st.metric(""My metric"", 42, 2) Dicts and JSONDisplay object or string as a pretty-printed JSON string.st.json(my_dict) Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration! PreviousImage CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates value = streamlit_image_coordinates(""https://placekitten.com/200/300"") st.write(value) Plotly EventsMake Plotly charts interactive!. Created by @null-jones.from streamlit_plotly_events import plotly_events fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.metric_cards import style_metric_cards col3.metric(label=""No Change"", value=5000, delta=0) style_metric_cards() Streamlit AggridImplementation of Ag-Grid component for Streamlit. Created by @PablocFonseca.df = pd.DataFrame({'col1': [1, 2, 3], 'col2': [4, 5, 6]}) grid_return = AgGrid(df, editable=True) new_df = grid_return['data'] Streamlit FoliumStreamlit Component for rendering Folium maps. Created by @randyzwitch.m = folium.Map(location=[39.949610, -75.150282], zoom_start=16) folium.Marker([39.949610, -75.150282], popup=""Liberty Bell"", tooltip=""Liberty Bell"").add_to(m) st_data = st_folium(m, width=725) Pandas ProfilingPandas profiling component for Streamlit. Created by @okld.df = pd.read_csv(""https://storage.googleapis.com/tf-datasets/titanic/train.csv"") pr = df.profile_report() st_profile_report(pr) Image CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates value = streamlit_image_coordinates(""https://placekitten.com/200/300"") st.write(value) Plotly EventsMake Plotly charts interactive!. Created by @null-jones.from streamlit_plotly_events import plotly_events fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.metric_cards import style_metric_cards col3.metric(label=""No Change"", value=5000, delta=0) style_metric_cards() Streamlit AggridImplementation of Ag-Grid component for Streamlit. Created by @PablocFonseca.df = pd.DataFrame({'col1': [1, 2, 3], 'col2': [4, 5, 6]}) grid_return = AgGrid(df, editable=True) new_df = grid_return['data'] Streamlit FoliumStreamlit Component for rendering Folium maps. Created by @randyzwitch.m = folium.Map(location=[39.949610, -75.150282], zoom_start=16) folium.Marker([39.949610, -75.150282], popup=""Liberty Bell"", tooltip=""Liberty Bell"").add_to(m) st_data = st_folium(m, width=725) Pandas ProfilingPandas profiling component for Streamlit. Created by @okld.df = pd.read_csv(""https://storage.googleapis.com/tf-datasets/titanic/train.csv"") pr = df.profile_report() st_profile_report(pr) Image CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates value = streamlit_image_coordinates(""https://placekitten.com/200/300"") st.write(value) Plotly EventsMake Plotly charts interactive!. Created by @null-jones.from streamlit_plotly_events import plotly_events fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.metric_cards import style_metric_cards col3.metric(label=""No Change"", value=5000, delta=0) style_metric_cards() Next Chart elements Simple area chartsDisplay an area chart.st.area_chart(my_data_frame) Simple bar chartsDisplay a bar chart.st.bar_chart(my_data_frame) Simple line chartsDisplay a line chart.st.line_chart(my_data_frame) Simple scatter chartsDisplay a line chart.st.scatter_chart(my_data_frame) Scatterplots on mapsDisplay a map with points on it.st.map(my_data_frame) MatplotlibDisplay a matplotlib.pyplot figure.st.pyplot(my_mpl_figure) AltairDisplay a chart using the Altair library.st.altair_chart(my_altair_chart) Vega-LiteDisplay a chart using the Vega-Lite library.st.vega_lite_chart(my_vega_lite_chart) PlotlyDisplay an interactive Plotly chart.st.plotly_chart(my_plotly_chart) BokehDisplay an interactive Bokeh chart.st.bokeh_chart(my_bokeh_chart) PyDeckDisplay a chart using the PyDeck library.st.pydeck_chart(my_pydeck_chart) GraphVizDisplay a graph using the dagre-d3 library.st.graphviz_chart(my_graphviz_spec) Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration! PreviousStreamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl(""https://assets5.lottiefiles.com/packages/lf20_V9t630.json"") st_lottie(lottie_hello, key=""hello"") Plotly EventsMake Plotly charts interactive!. Created by @null-jones.fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.chart += get_annotations_chart(annotations=[(""Mar 01, 2008"", ""Pretty good day for GOOG""), (""Dec 01, 2007"", ""Something's going wrong for GOOG & AAPL""), (""Nov 01, 2008"", ""Market starts again thanks to...""), (""Dec 01, 2009"", ""Small crash for GOOG after...""),],) st.altair_chart(chart, use_container_width=True) PlostA deceptively simple plotting library for Streamlit. Created by @tvst.import plost plost.line_chart(my_dataframe, x='time', y='stock_value', color='stock_name',) HiPlotHigh dimensional Interactive Plotting. Created by @facebookresearch.data = [{'dropout':0.1, 'lr': 0.001, 'loss': 10.0, 'optimizer': 'SGD'}, {'dropout':0.15, 'lr': 0.01, 'loss': 3.5, 'optimizer': 'Adam'}, {'dropout':0.3, 'lr': 0.1, 'loss': 4.5, 'optimizer': 'Adam'}] hip.Experiment.from_iterable(data).display() EChartsHigh dimensional Interactive Plotting. Created by @andfanilo.from streamlit_echarts import st_echarts st_echarts(options=options) Streamlit FoliumStreamlit Component for rendering Folium maps. Created by @randyzwitch.m = folium.Map(location=[39.949610, -75.150282], zoom_start=16) st_data = st_folium(m, width=725) Spacy-StreamlitspaCy building blocks and visualizers for Streamlit apps. Created by @explosion.models = [""en_core_web_sm"", ""en_core_web_md""] spacy_streamlit.visualize(models, ""Sundar Pichai is the CEO of Google."") Streamlit AgraphA Streamlit Graph Vis, based on react-grah-vis. Created by @ChrisDelClea.from streamlit_agraph import agraph, Node, Edge, Config agraph(nodes=nodes, edges=edges, config=config) Streamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl(""https://assets5.lottiefiles.com/packages/lf20_V9t630.json"") st_lottie(lottie_hello, key=""hello"") Plotly EventsMake Plotly charts interactive!. Created by @null-jones.fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.chart += get_annotations_chart(annotations=[(""Mar 01, 2008"", ""Pretty good day for GOOG""), (""Dec 01, 2007"", ""Something's going wrong for GOOG & AAPL""), (""Nov 01, 2008"", ""Market starts again thanks to...""), (""Dec 01, 2009"", ""Small crash for GOOG after...""),],) st.altair_chart(chart, use_container_width=True) PlostA deceptively simple plotting library for Streamlit. Created by @tvst.import plost plost.line_chart(my_dataframe, x='time', y='stock_value', color='stock_name',) HiPlotHigh dimensional Interactive Plotting. Created by @facebookresearch.data = [{'dropout':0.1, 'lr': 0.001, 'loss': 10.0, 'optimizer': 'SGD'}, {'dropout':0.15, 'lr': 0.01, 'loss': 3.5, 'optimizer': 'Adam'}, {'dropout':0.3, 'lr': 0.1, 'loss': 4.5, 'optimizer': 'Adam'}] hip.Experiment.from_iterable(data).display() EChartsHigh dimensional Interactive Plotting. Created by @andfanilo.from streamlit_echarts import st_echarts st_echarts(options=options) Streamlit FoliumStreamlit Component for rendering Folium maps. Created by @randyzwitch.m = folium.Map(location=[39.949610, -75.150282], zoom_start=16) st_data = st_folium(m, width=725) Spacy-StreamlitspaCy building blocks and visualizers for Streamlit apps. Created by @explosion.models = [""en_core_web_sm"", ""en_core_web_md""] spacy_streamlit.visualize(models, ""Sundar Pichai is the CEO of Google."") Streamlit AgraphA Streamlit Graph Vis, based on react-grah-vis. Created by @ChrisDelClea.from streamlit_agraph import agraph, Node, Edge, Config agraph(nodes=nodes, edges=edges, config=config) Streamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl(""https://assets5.lottiefiles.com/packages/lf20_V9t630.json"") st_lottie(lottie_hello, key=""hello"") Plotly EventsMake Plotly charts interactive!. Created by @null-jones.fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.chart += get_annotations_chart(annotations=[(""Mar 01, 2008"", ""Pretty good day for GOOG""), (""Dec 01, 2007"", ""Something's going wrong for GOOG & AAPL""), (""Nov 01, 2008"", ""Market starts again thanks to...""), (""Dec 01, 2009"", ""Small crash for GOOG after...""),],) st.altair_chart(chart, use_container_width=True) Next Input widgets ButtonDisplay a button widget.clicked = st.button(""Click me"") Download buttonDisplay a download button widget.st.download_button(""Download file"", file) Form buttonDisplay a form submit button. For use with st.form.st.form_submit_button(""Sign up"") Link buttonDisplay a link button.st.link_button(""Go to gallery"", url) Page linkDisplay a link to another page in a multipage app.st.page_link(""app.py"", label=""Home"", icon=""🏠"") st.page_link(""pages/profile.py"", label=""My profile"") CheckboxDisplay a checkbox widget.selected = st.checkbox(""I agree"") Color pickerDisplay a color picker widget.color = st.color_picker(""Pick a color"") MultiselectDisplay a multiselect widget. The multiselect widget starts as empty.choices = st.multiselect(""Buy"", [""milk"", ""apples"", ""potatoes""]) RadioDisplay a radio button widget.choice = st.radio(""Pick one"", [""cats"", ""dogs""]) SelectboxDisplay a select widget.choice = st.selectbox(""Pick one"", [""cats"", ""dogs""]) Select-sliderDisplay a slider widget to select items from a list.size = st.select_slider(""Pick a size"", [""S"", ""M"", ""L""]) ToggleDisplay a toggle widget.activated = st.toggle(""Activate"") Number inputDisplay a numeric input widget.choice = st.number_input(""Pick a number"", 0, 10) SliderDisplay a slider widget.number = st.slider(""Pick a number"", 0, 100) Date inputDisplay a date input widget.date = st.date_input(""Your birthday"") Time inputDisplay a time input widget.time = st.time_input(""Meeting time"") Chat inputDisplay a chat input widget.prompt = st.chat_input(""Say something"") if prompt: st.write(f""The user has sent: {prompt}"") Text-areaDisplay a multi-line text input widget.text = st.text_area(""Text to translate"") Text inputDisplay a single-line text input widget.name = st.text_input(""First name"") Data editorDisplay a data editor widget.edited = st.experimental_data_editor(df, num_rows=""dynamic"") File UploaderDisplay a file uploader widget.data = st.file_uploader(""Upload a CSV"") Camera inputDisplay a widget that allows users to upload images directly from a camera.image = st.camera_input(""Take a picture"") Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration! PreviousStreamlit ChatStreamlit Component for a Chatbot UI. Created by @AI-Yash.from streamlit_chat import message message(""My message"") message(""Hello bot!"", is_user=True) # align's the message to the right Streamlit Option MenuSelect a single item from a list of options in a menu. Created by @victoryhb.from streamlit_option_menu import option_menu option_menu(""Main Menu"", [""Home"", 'Settings'], icons=['house', 'gear'], menu_icon=""cast"", default_index=1) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.stoggle import stoggle stoggle( ""Click me!"", """"""🥷 Surprise! Here's some additional content"""""",) Streamlit ElementsCreate a draggable and resizable dashboard in Streamlit. Created by @okls.from streamlit_elements import elements, mui, html with elements(""new_element""): mui.Typography(""Hello world"") TagsAdd tags to your Streamlit apps. Created by @gagan3012.from streamlit_tags import st_tags st_tags(label='# Enter Keywords:', text='Press enter to add more', value=['Zero', 'One', 'Two'], suggestions=['five', 'six', 'seven', 'eight', 'nine', 'three', 'eleven', 'ten', 'four'], maxtags = 4, key='1') StqdmThe simplest way to handle a progress bar in streamlit app. Created by @Wirg.from stqdm import stqdm for _ in stqdm(range(50)): sleep(0.5) TimelineDisplay a Timeline in Streamlit apps using TimelineJS. Created by @innerdoc.from streamlit_timeline import timeline with open('example.json', ""r"") as f: timeline(f.read(), height=800) Camera input liveAlternative for st.camera_input which returns the webcam images live. Created by @blackary.from camera_input_live import camera_input_live image = camera_input_live() st.image(value) Streamlit AceAce editor component for Streamlit. Created by @okld.from streamlit_ace import st_ace content = st_ace() content Streamlit ChatStreamlit Component for a Chatbot UI. Created by @AI-Yash.from streamlit_chat import message message(""My message"") message(""Hello bot!"", is_user=True) # align's the message to the right Streamlit Option MenuSelect a single item from a list of options in a menu. Created by @victoryhb.from streamlit_option_menu import option_menu option_menu(""Main Menu"", [""Home"", 'Settings'], icons=['house', 'gear'], menu_icon=""cast"", default_index=1) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.stoggle import stoggle stoggle( ""Click me!"", """"""🥷 Surprise! Here's some additional content"""""",) Streamlit ElementsCreate a draggable and resizable dashboard in Streamlit. Created by @okls.from streamlit_elements import elements, mui, html with elements(""new_element""): mui.Typography(""Hello world"") TagsAdd tags to your Streamlit apps. Created by @gagan3012.from streamlit_tags import st_tags st_tags(label='# Enter Keywords:', text='Press enter to add more', value=['Zero', 'One', 'Two'], suggestions=['five', 'six', 'seven', 'eight', 'nine', 'three', 'eleven', 'ten', 'four'], maxtags = 4, key='1') StqdmThe simplest way to handle a progress bar in streamlit app. Created by @Wirg.from stqdm import stqdm for _ in stqdm(range(50)): sleep(0.5) TimelineDisplay a Timeline in Streamlit apps using TimelineJS. Created by @innerdoc.from streamlit_timeline import timeline with open('example.json', ""r"") as f: timeline(f.read(), height=800) Camera input liveAlternative for st.camera_input which returns the webcam images live. Created by @blackary.from camera_input_live import camera_input_live image = camera_input_live() st.image(value) Streamlit AceAce editor component for Streamlit. Created by @okld.from streamlit_ace import st_ace content = st_ace() content Streamlit ChatStreamlit Component for a Chatbot UI. Created by @AI-Yash.from streamlit_chat import message message(""My message"") message(""Hello bot!"", is_user=True) # align's the message to the right Streamlit Option MenuSelect a single item from a list of options in a menu. Created by @victoryhb.from streamlit_option_menu import option_menu option_menu(""Main Menu"", [""Home"", 'Settings'], icons=['house', 'gear'], menu_icon=""cast"", default_index=1) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.stoggle import stoggle stoggle( ""Click me!"", """"""🥷 Surprise! Here's some additional content"""""",) Next Media elements ImageDisplay an image or list of images.st.image(numpy_array) st.image(image_bytes) st.image(file) st.image(""https://example.com/myimage.jpg"") AudioDisplay an audio player.st.audio(numpy_array) st.audio(audio_bytes) st.audio(file) st.audio(""https://example.com/myaudio.mp3"", format=""audio/mp3"") VideoDisplay a video player.st.video(numpy_array) st.video(video_bytes) st.video(file) st.video(""https://example.com/myvideo.mp4"", format=""video/mp4"") Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration! PreviousStreamlit CropperA simple image cropper for Streamlit. Created by @turner-anderson.from streamlit_cropper import st_cropper st_cropper(img, realtime_update=realtime_update, box_color=box_color, aspect_ratio=aspect_ratio) Image CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates streamlit_image_coordinates(""https://placekitten.com/200/300"") Streamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl(""https://assets5.lottiefiles.com/packages/lf20_V9t630.json"") st_lottie(lottie_hello, key=""hello"") Streamlit WebrtcHandling and transmitting real-time video/audio streams with Streamlit. Created by @whitphx.from streamlit_webrtc import webrtc_streamer webrtc_streamer(key=""sample"") Drawable CanvasProvides a sketching canvas using Fabric.js. Created by @andfanilo.from streamlit_drawable_canvas import st_canvas st_canvas(fill_color=""rgba(255, 165, 0, 0.3)"", stroke_width=stroke_width, stroke_color=stroke_color, background_color=bg_color, background_image=Image.open(bg_image) if bg_image else None, update_streamlit=realtime_update, height=150, drawing_mode=drawing_mode, point_display_radius=point_display_radius if drawing_mode == 'point' else 0, key=""canvas"",) Image ComparisonCompare images with a slider using JuxtaposeJS. Created by @fcakyon.from streamlit_image_comparison import image_comparison image_comparison(img1=""image1.jpg"", img2=""image2.jpg"",) Streamlit CropperA simple image cropper for Streamlit. Created by @turner-anderson.from streamlit_cropper import st_cropper st_cropper(img, realtime_update=realtime_update, box_color=box_color, aspect_ratio=aspect_ratio) Image CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates streamlit_image_coordinates(""https://placekitten.com/200/300"") Streamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl(""https://assets5.lottiefiles.com/packages/lf20_V9t630.json"") st_lottie(lottie_hello, key=""hello"") Streamlit WebrtcHandling and transmitting real-time video/audio streams with Streamlit. Created by @whitphx.from streamlit_webrtc import webrtc_streamer webrtc_streamer(key=""sample"") Drawable CanvasProvides a sketching canvas using Fabric.js. Created by @andfanilo.from streamlit_drawable_canvas import st_canvas st_canvas(fill_color=""rgba(255, 165, 0, 0.3)"", stroke_width=stroke_width, stroke_color=stroke_color, background_color=bg_color, background_image=Image.open(bg_image) if bg_image else None, update_streamlit=realtime_update, height=150, drawing_mode=drawing_mode, point_display_radius=point_display_radius if drawing_mode == 'point' else 0, key=""canvas"",) Image ComparisonCompare images with a slider using JuxtaposeJS. Created by @fcakyon.from streamlit_image_comparison import image_comparison image_comparison(img1=""image1.jpg"", img2=""image2.jpg"",) Streamlit CropperA simple image cropper for Streamlit. Created by @turner-anderson.from streamlit_cropper import st_cropper st_cropper(img, realtime_update=realtime_update, box_color=box_color, aspect_ratio=aspect_ratio) Image CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates streamlit_image_coordinates(""https://placekitten.com/200/300"") Streamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl(""https://assets5.lottiefiles.com/packages/lf20_V9t630.json"") st_lottie(lottie_hello, key=""hello"") Next Layouts and containers ColumnsInsert containers laid out as side-by-side columns.col1, col2 = st.columns(2) col1.write(""this is column 1"") col2.write(""this is column 2"") ContainerInsert a multi-element container.c = st.container() st.write(""This will show last"") c.write(""This will show first"") c.write(""This will show second"") Modal dialogsInsert a modal dialog that can rerun independently from the rest of the script.@st.experimental_dialog(""Sign up"") def email_form(): name = st.text_input(""Name"") email = st.text_input(""Email"") EmptyInsert a single-element container.c = st.empty() st.write(""This will show last"") c.write(""This will be replaced"") c.write(""This will show first"") ExpanderInsert a multi-element container that can be expanded/collapsed.with st.expander(""Open to see more""): st.write(""This is more content"") PopoverInsert a multi-element popover container that can be opened/closed.with st.popover(""Settings""): st.checkbox(""Show completed"") SidebarDisplay items in a sidebar.st.sidebar.write(""This lives in the sidebar"") st.sidebar.button(""Click me!"") TabsInsert containers separated into tabs.tab1, tab2 = st.tabs([""Tab 1"", ""Tab2""]) tab1.write(""this is tab 1"") tab2.write(""this is tab 2"") Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration!Streamlit ElementsCreate a draggable and resizable dashboard in Streamlit. Created by @okls.from streamlit_elements import elements, mui, html with elements(""new_element""): mui.Typography(""Hello world"") PydanticAuto-generate Streamlit UI from Pydantic Models and Dataclasses. Created by @lukasmasuch.import streamlit_pydantic as sp sp.pydantic_form(key=""my_form"", model=ExampleModel) Streamlit PagesAn experimental version of Streamlit Multi-Page Apps. Created by @blackary.from st_pages import Page, show_pages, add_page_title show_pages([ Page(""streamlit_app.py"", ""Home"", ""🏠""), Page(""other_pages/page2.py"", ""Page 2"", "":books:""), ]) Chat elements Streamlit provides a few commands to help you build conversational apps. These chat elements are designed to be used in conjunction with each other, but you can also use them separately. st.chat_message lets you insert a chat message container into the app so you can display messages from the user or the app. Chat containers can contain other Streamlit elements, including charts, tables, text, and more. st.chat_input lets you display a chat input widget so the user can type in a message. Chat inputDisplay a chat input widget.prompt = st.chat_input(""Say something"") if prompt: st.write(f""The user has sent: {prompt}"") Chat messageInsert a chat message container.import numpy as np with st.chat_message(""user""): st.write(""Hello 👋"") st.line_chart(np.random.randn(30, 3)) Status containerDisplay output of long-running tasks in a container.with st.status('Running'): do_something_slow() st.write_streamWrite generators or streams to the app with a typewriter effect.st.write_stream(my_generator) st.write_stream(my_llm_stream) Status elements Progress barDisplay a progress bar.for i in range(101): st.progress(i) do_something_slow() SpinnerTemporarily displays a message while executing a block of code.with st.spinner(""Please wait...""): do_something_slow() Status containerDisplay output of long-running tasks in a container.with st.status('Running'): do_something_slow() ToastBriefly displays a toast message in the bottom-right corner.st.toast('Butter!', icon='🧈') BalloonsDisplay celebratory balloons!do_something() # Celebrate when all done! st.balloons() SnowflakesDisplay celebratory snowflakes!do_something() # Celebrate when all done! st.snow() Success boxDisplay a success message.st.success(""Match found!"") Info boxDisplay an informational message.st.info(""Dataset is updated every day at midnight."") Warning boxDisplay warning message.st.warning(""Unable to fetch image. Skipping..."") Error boxDisplay error message.st.error(""We encountered an error"") Exception outputDisplay an exception.e = RuntimeError(""This is an exception of type RuntimeError"") st.exception(e) Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration!StqdmThe simplest way to handle a progress bar in streamlit app. Created by @Wirg.from stqdm import stqdm for _ in stqdm(range(50)): sleep(0.5) Custom notification boxA custom notification box with the ability to close it out. Created by @Socvest.from streamlit_custom_notification_box import custom_notification_box styles = {'material-icons':{'color': 'red'}, 'text-icon-link-close-container': {'box-shadow': '#3896de 0px 4px'}, 'notification-text': {'':''}, 'close-button':{'':''}, 'link':{'':''}} custom_notification_box(icon='info', textDisplay='We are almost done with your registration...', externalLink='more info', url='#', styles=styles, key=""foo"") Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.let_it_rain import rain rain(emoji=""🎈"", font_size=54, falling_speed=5, animation_length=""infinite"",) App logic and configuration Navigation and pages Switch pageProgrammatically navigates to a specified page.st.switch_page(""pages/my_page.py"") Page linkDisplay a link to another page in a multipage app.st.page_link(""app.py"", label=""Home"", icon=""🏠"") st.page_link(""pages/profile.py"", label=""My profile"") Execution flow Modal dialogsInsert a modal dialog that can rerun independently from the rest of the script.@st.experimental_dialog(""Sign up"") def email_form(): name = st.text_input(""Name"") email = st.text_input(""Email"") FormsCreate a form that batches elements together with a “Submit"" button.with st.form(key='my_form'): name = st.text_input(""Name"") email = st.text_input(""Email"") st.form_submit_button(""Sign up"") Partial rerunsDefine a fragment to rerun independently from the rest of the script.@st.experimental_fragment(run_every=""10s"") def fragment(): df = get_data() st.line_chart(df) Rerun scriptRerun the script immediately.st.rerun() Stop executionStops execution immediately.st.stop() Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration!AutorefreshForce a refresh without tying up a script. Created by @kmcgrady.from streamlit_autorefresh import st_autorefresh st_autorefresh(interval=2000, limit=100, key=""fizzbuzzcounter"") PydanticAuto-generate Streamlit UI from Pydantic Models and Dataclasses. Created by @lukasmasuch.import streamlit_pydantic as sp sp.pydantic_form(key=""my_form"", model=ExampleModel) Streamlit PagesAn experimental version of Streamlit Multi-Page Apps. Created by @blackary.from st_pages import Page, show_pages, add_page_title show_pages([ Page(""streamlit_app.py"", ""Home"", ""🏠""), Page(""other_pages/page2.py"", ""Page 2"", "":books:""), ]) Caching and state Cache dataFunction decorator to cache functions that return data (e.g. dataframe transforms, database queries, ML inference).@st.cache_data def long_function(param1, param2): # Perform expensive computation here or # fetch data from the web here return data Cache resourceFunction decorator to cache functions that return global resources (e.g. database connections, ML models).@st.cache_resource def init_model(): # Return a global resource here return pipeline( ""sentiment-analysis"", model=""distilbert-base-uncased-finetuned-sst-2-english"" ) Session stateSession state is a way to share variables between reruns, for each user session.st.session_state['key'] = value Query parametersGet, set, or clear the query parameters that are shown in the browser's URL bar.st.query_params[key] = value st.query_params.clear() Connections and databases Setup your connection Create a connectionConnect to a data source or APIconn = st.connection('pets_db', type='sql') pet_owners = conn.query('select * from pet_owners') st.dataframe(pet_owners) Built-in connections SnowflakeConnectionA connection to Snowflake.conn = st.connection('snowflake') SQLConnectionA connection to a SQL database using SQLAlchemy.conn = st.connection('sql') Build your own connections Connection base classBuild your own connection with BaseConnection.class MyConnection(BaseConnection[myconn.MyConnection]): def _connect(self, **kwargs) -> MyConnection: return myconn.connect(**self._secrets, **kwargs) def query(self, query): return self._instance.query(query) Secrets management Secrets singletonAccess secrets from a local TOML file.key = st.secrets[""OpenAI_key""] Secrets fileSave your secrets in a per-project or per-profile TOML file.OpenAI_key = """" Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration!AuthenticatorA secure authentication module to validate user credentials. Created by @mkhorasani.import streamlit_authenticator as stauth authenticator = stauth.Authenticate( config['credentials'], config['cookie']['name'], config['cookie']['key'], config['cookie']['expiry_days'], config['preauthorized']) WS localStorageA simple synchronous way of accessing localStorage from your app. Created by @gagangoku.from streamlit_ws_localstorage import injectWebsocketCode ret = conn.setLocalStorageVal(key='k1', val='v1') st.write('ret: ' + ret) Streamlit Auth0The fastest way to provide comprehensive login inside Streamlit. Created by @conradbez.from auth0_component import login_button user_info = login_button(clientId, domain = domain) st.write(user_info) Custom Components Declare a componentCreate and register a custom component.st.components.v1.declare_component( ""custom_slider"", ""/frontend"", ) HTMLDisplay an HTML string in an iframe.st.components.v1.html( ""

Foo bar.

"" ) iframeLoad a remote URL in an iframe.st.components.v1.iframe( ""docs.streamlit.io"" ) Utilities and user info User infost.experimental_user returns information about the logged-in user of private apps on Streamlit Community Cloud.if st.experimental_user.email == ""foo@corp.com"": st.write(""Welcome back, "", st.experimental_user.email) else: st.write(""You are not authorized to view this page."") Get helpDisplay object’s doc string, nicely formatted.st.help(st.write) st.help(pd.DataFrame) Render HTMLRenders HTML strings to your app.css = """""" """""" st.html(css) Configuration Configuration fileConfigures the default settings for your app.your-project/ ├── .streamlit/ │ └── config.toml └── your_app.py Set page title, favicon, and moreConfigures the default settings of the page.st.set_page_config( page_title=""My app"", page_icon="":shark:"", ) Developer tools App testing st.testing.v1.AppTestst.testing.v1.AppTest simulates a running Streamlit app for testing.from streamlit.testing.v1 import AppTest at = AppTest.from_file(""streamlit_app.py"") at.secrets[""WORD""] = ""Foobar"" at.run() assert not at.exception at.text_input(""word"").input(""Bazbat"").run() assert at.warning[0].value == ""Try again."" AppTest.from_filest.testing.v1.AppTest.from_file initializes a simulated app from a file.from streamlit.testing.v1 import AppTest at = AppTest.from_file(""streamlit_app.py"") at.run() AppTest.from_stringst.testing.v1.AppTest.from_string initializes a simulated app from a string.from streamlit.testing.v1 import AppTest at = AppTest.from_string(app_script_as_string) at.run() AppTest.from_functionst.testing.v1.AppTest.from_function initializes a simulated app from a function.from streamlit.testing.v1 import AppTest at = AppTest.from_function(app_script_as_callable) at.run() BlockA representation of container elements, including: st.chat_message st.columns st.sidebar st.tabs The main body of the app. # at.sidebar returns a Block at.sidebar.button[0].click().run() assert not at.exception ElementThe base class for representation of all elements, including: st.title st.header st.markdown st.dataframe # at.title returns a sequence of Title # Title inherits from Element assert at.title[0].value == ""My awesome app"" ButtonA representation of st.button and st.form_submit_button.at.button[0].click().run() ChatInputA representation of st.chat_input.at.chat_input[0].set_value(""What is Streamlit?"").run() CheckboxA representation of st.checkbox.at.checkbox[0].check().run() ColorPickerA representation of st.color_picker.at.color_picker[0].pick(""#FF4B4B"").run() DateInputA representation of st.date_input.release_date = datetime.date(2023, 10, 26) at.date_input[0].set_value(release_date).run() MultiselectA representation of st.multiselect.at.multiselect[0].select(""New York"").run() NumberInputA representation of st.number_input.at.number_input[0].increment().run() RadioA representation of st.radio.at.radio[0].set_value(""New York"").run() SelectSliderA representation of st.select_slider.at.select_slider[0].set_range(""A"",""C"").run() SelectboxA representation of st.selectbox.at.selectbox[0].select(""New York"").run() SliderA representation of st.slider.at.slider[0].set_range(2,5).run() TextAreaA representation of st.text_area.at.text_area[0].input(""Streamlit is awesome!"").run() TextInputA representation of st.text_input.at.text_input[0].input(""Streamlit"").run() TimeInputA representation of st.time_input.at.time_input[0].increment().run() ToggleA representation of st.toggle.at.toggle[0].set_value(""True"").run() Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration!Pandas ProfilingPandas profiling component for Streamlit. Created by @okld.df = pd.read_csv(""https://storage.googleapis.com/tf-datasets/titanic/train.csv"") pr = df.profile_report() st_profile_report(pr) Streamlit AceAce editor component for Streamlit. Created by @okld.from streamlit_ace import st_ace content = st_ace() content Streamlit AnalyticsTrack & visualize user interactions with your streamlit app. Created by @jrieke.import streamlit_analytics with streamlit_analytics.track(): st.text_input(""Write something"") Previous: ConceptsNext: Write and magicforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy" https://docs.streamlit.io/develop/concepts/architecture/widget-behavior#updating-a-slider-with-a-default-value,"DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsremoveCOREArchitecture & executionremoveRunning your appStreamlit's architectureThe app chromeCachingSession StateFormsFragmentsWidget behaviorMultipage appsaddApp designaddADDITIONALConnections and secretsaddCustom componentsaddConfiguration and themingaddApp testingaddAPI referenceaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Develop/Concepts/Architecture & execution/Widget behaviorUnderstanding widget behavior Widgets (like st.button, st.selectbox, and st.text_input) are at the heart of Streamlit apps. They are the interactive elements of Streamlit that pass information from your users into your Python code. Widgets are magical and often work how you want, but they can have surprising behavior in some situations. Understanding the different parts of a widget and the precise order in which events occur helps you achieve your desired results. This guide covers advanced concepts about widgets. Generally, it begins with simpler concepts and increases in complexity. For most beginning users, these details won't be important to know right away. When you want to dynamically change widgets or preserve widget information between pages, these concepts will be important to understand. We recommend having a basic understanding of Session State before reading this guide. 🎈 TL;DRexpand_more The actions of one user do not affect the widgets of any other user. A widget function call returns the widget's current value, which is a simple Python type. (e.g. st.button returns a boolean value.) Widgets return their default values on their first call before a user interacts with them. A widget's identity depends on the arguments passed to the widget function. Changing a widget's label, min or max value, default value, placeholder text, help text, or key will cause it to reset. If you don't call a widget function in a script run, Streamlit will delete the widget's information—including its key-value pair in Session State. If you call the same widget function later, Streamlit treats it as a new widget. The last two points (widget identity and widget deletion) are the most relevant when dynamically changing widgets or working with multi-page applications. This is covered in detail later in this guide: Statefulness of widgets and Widget life cycle. Anatomy of a widget There are four parts to keep in mind when using widgets: The frontend component as seen by the user. The backend value or value as seen through st.session_state. The key of the widget used to access its value via st.session_state. The return value given by the widget's function. Widgets are session dependent Widget states are dependent on a particular session (browser connection). The actions of one user do not affect the widgets of any other user. Furthermore, if a user opens up multiple tabs to access an app, each tab will be a unique session. Changing a widget in one tab will not affect the same widget in another tab. Widgets return simple Python data types The value of a widget as seen through st.session_state and returned by the widget function are of simple Python types. For example, st.button returns a boolean value and will have the same boolean value saved in st.session_state if using a key. The first time a widget function is called (before a user interacts with it), it will return its default value. (e.g. st.selectbox returns the first option by default.) Default values are configurable for all widgets with a few special exceptions like st.button and st.file_uploader. Keys help distinguish widgets and access their values Widget keys serve two purposes: Distinguishing two otherwise identical widgets. Creating a means to access and manipulate the widget's value through st.session_state. Whenever possible, Streamlit updates widgets incrementally on the frontend instead of rebuilding them with each rerun. This means Streamlit assigns an ID to each widget from the arguments passed to the widget function. A widget's ID is based on parameters such as label, min or max value, default value, placeholder text, help text, and key. The page where the widget appears also factors into a widget's ID. If you have two widgets of the same type with the same arguments on the same page, you will get a DuplicateWidgetID error. In this case, assign unique keys to the two widgets. Streamlit can't understand two identical widgets on the same page # This will cause a DuplicateWidgetID error. st.button(""OK"") st.button(""OK"") Use keys to distinguish otherwise identical widgets st.button(""OK"", key=""privacy"") st.button(""OK"", key=""terms"") Order of operations When a user interacts with a widget, the order of logic is: Its value in st.session_state is updated. The callback function (if any) is executed. The page reruns with the widget function returning its new value. If the callback function writes anything to the screen, that content will appear above the rest of the page. A callback function runs as a prefix to the script rerunning. Consequently, that means anything written via a callback function will disappear as soon as the user performs their next action. Other widgets should generally not be created within a callback function. push_pinNoteIf a callback function is passed any args or kwargs, those arguments will be established when the widget is rendered. In particular, if you want to use a widget's new value in its own callback function, you cannot pass that value to the callback function via the args parameter; you will have to assign a key to the widget and look up its new value using a call to st.session_state within the callback function. Using callback functions with forms Using a callback function with a form requires consideration of this order of operations. import streamlit as st if ""attendance"" not in st.session_state: st.session_state.attendance = set() def take_attendance(): if st.session_state.name in st.session_state.attendance: st.info(f""{st.session_state.name} has already been counted."") else: st.session_state.attendance.add(st.session_state.name) with st.form(key=""my_form""): st.text_input(""Name"", key=""name"") st.form_submit_button(""I'm here!"", on_click=take_attendance) Built with Streamlit 🎈Fullscreen open_in_new Statefulness of widgets As long as the defining parameters of a widget remain the same and that widget is continuously rendered on the frontend, then it will be stateful and remember user input. Changing parameters of a widget will reset it If any of the defining parameters of a widget change, Streamlit will see it as a new widget and it will reset. The use of manually assigned keys and default values is particularly important in this case. Note that callback functions, callback args and kwargs, label visibility, and disabling a widget do not affect a widget's identity. In this example, we have a slider whose min and max values are changed. Try interacting with each slider to change its value then change the min or max setting to see what happens. import streamlit as st cols = st.columns([2, 1, 2]) minimum = cols[0].number_input(""Minimum"", 1, 5) maximum = cols[2].number_input(""Maximum"", 6, 10, 10) st.slider(""No default, no key"", minimum, maximum) st.slider(""No default, with key"", minimum, maximum, key=""a"") st.slider(""With default, no key"", minimum, maximum, value=5) st.slider(""With default, with key"", minimum, maximum, value=5, key=""b"") Built with Streamlit 🎈Fullscreen open_in_new Updating a slider with no default value For the first two sliders above, as soon as the min or max value is changed, the sliders reset to the min value. The changing of the min or max value makes them ""new"" widgets from Streamlit's perspective and so they are recreated from scratch when the app reruns with the changed parameters. Since no default value is defined, each widget will reset to its min value. This is the same with or without a key since it's seen as a new widget either way. There is a subtle point to understand about pre-existing keys connecting to widgets. This will be explained further down in Widget life cycle. Updating a slider with a default value For the last two sliders above, a change to the min or max value will result in the widgets being seen as ""new"" and thus recreated like before. Since a default value of 5 is defined, each widget will reset to 5 whenever the min or max is changed. This is again the same (with or without a key). A solution to Retain statefulness when changing a widget's parameters is provided further on. Widgets do not persist when not continually rendered If a widget's function is not called during a script run, then none of its parts will be retained, including its value in st.session_state. If a widget has a key and you navigate away from that widget, its key and associated value in st.session_state will be deleted. Even temporarily hiding a widget will cause it to reset when it reappears; Streamlit will treat it like a new widget. You can either interrupt the Widget clean-up process (described at the end of this page) or save the value to another key. Save widget values in Session State to preserve them between pages If you want to navigate away from a widget and return to it while keeping its value, use a separate key in st.session_state to save the information independently from the widget. In this example, a temporary key is used with a widget. The temporary key uses an underscore prefix. Hence, ""_my_key"" is used as the widget key, but the data is copied to ""my_key"" to preserve it between pages. import streamlit as st def store_value(): # Copy the value to the permanent key st.session_state[""my_key""] = st.session_state[""_my_key""] # Copy the saved value to the temporary key st.session_state[""_my_key""] = st.session_state[""my_key""] st.number_input(""Number of filters"", key=""_my_key"", on_change=store_value) If this is functionalized to work with multiple widgets, it could look something like this: import streamlit as st def store_value(key): st.session_state[key] = st.session_state[""_""+key] def load_value(key): st.session_state[""_""+key] = st.session_state[key] load_value(""my_key"") st.number_input(""Number of filters"", key=""_my_key"", on_change=store_value, args=[""my_key""]) Widget life cycle When a widget function is called, Streamlit will check if it already has a widget with the same parameters. Streamlit will reconnect if it thinks the widget already exists. Otherwise, it will make a new one. As mentioned earlier, Streamlit determines a widget's ID based on parameters such as label, min or max value, default value, placeholder text, help text, and key. The page name also factors into a widget's ID. On the other hand, callback functions, callback args and kwargs, label visibility, and disabling a widget do not affect a widget's identity. Calling a widget function when the widget doesn't already exist If your script rerun calls a widget function with changed parameters or calls a widget function that wasn't used on the last script run: Streamlit will build the frontend and backend parts of the widget. If the widget has been assigned a key, Streamlit will check if that key already exists in Session State. a. If it exists and is not currently associated with another widget, Streamlit will attach to that key and take on its value for the widget. b. Otherwise, it will assign the default value to the key in st.session_state (creating a new key-value pair or overwriting an existing one). If there are args or kwargs for a callback function, they are computed and saved at this point in time. The default value is then returned by the function. Step 2 can be tricky. If you have a widget: st.number_input(""Alpha"",key=""A"") and you change it on a page rerun to: st.number_input(""Beta"",key=""A"") Streamlit will see that as a new widget because of the label change. The key ""A"" will be considered part of the widget labeled ""Alpha"" and will not be attached as-is to the new widget labeled ""Beta"". Streamlit will destroy st.session_state.A and recreate it with the default value. If a widget attaches to a pre-existing key when created and is also manually assigned a default value, you will get a warning if there is a disparity. If you want to control a widget's value through st.session_state, initialize the widget's value through st.session_state and avoid the default value argument to prevent conflict. Calling a widget function when the widget already exists When rerunning a script without changing a widget's parameters: Streamlit will connect to the existing frontend and backend parts. If the widget has a key that was deleted from st.session_state, then Streamlit will recreate the key using the current frontend value. (e.g Deleting a key will not revert the widget to a default value.) It will return the current value of the widget. Widget clean-up process When Streamlit gets to the end of a script run, it will delete the data for any widgets it has in memory that were not rendered on the screen. Most importantly, that means Streamlit will delete all key-value pairs in st.session_state associated with a widget not currently on screen. Additional examples As promised, let's address how to retain the statefulness of widgets when changing pages or modifying their parameters. There are two ways to do this. Use dummy keys to duplicate widget values in st.session_state and protect the data from being deleted along with the widget. Interrupt the widget clean-up process. The first method was shown above in Save widget values in Session State to preserve them between pages Interrupting the widget clean-up process To retain information for a widget with key=""my_key"", just add this to the top of every page: st.session_state.my_key = st.session_state.my_key When you manually save data to a key in st.session_state, it will become detached from any widget as far as the clean-up process is concerned. If you navigate away from a widget with some key ""my_key"" and save data to st.session_state.my_key on the new page, you will interrupt the widget clean-up process and prevent the key-value pair from being deleted or overwritten if another widget with the same key exists. Retain statefulness when changing a widget's parameters Here is a solution to our earlier example of changing a slider's min and max values. This solution interrupts the clean-up process as described above. import streamlit as st # Set default value if ""a"" not in st.session_state: st.session_state.a = 5 cols = st.columns(2) minimum = cols[0].number_input(""Min"", 1, 5, key=""min"") maximum = cols[1].number_input(""Max"", 6, 10, 10, key=""max"") def update_value(): # Helper function to ensure consistency between widget parameters and value st.session_state.a = min(st.session_state.a, maximum) st.session_state.a = max(st.session_state.a, minimum) # Validate the slider value before rendering update_value() st.slider(""A"", minimum, maximum, key=""a"") Built with Streamlit 🎈Fullscreen open_in_new The update_value() helper function is actually doing two things. On the surface, it's making sure there are no inconsistent changes to the parameters values as described. Importantly, it's also interrupting the widget clean-up process. When the min or max value of the widget changes, Streamlit sees it as a new widget on rerun. Without saving a value to st.session_state.a, the value would be thrown out and replaced by the ""new"" widget's default value.Previous: FragmentsNext: Multipage appsforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy" https://docs.streamlit.io/develop/concepts/custom-components/intro#working-with-themes,"DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsremoveCOREArchitecture & executionaddMultipage appsaddApp designaddADDITIONALConnections and secretsaddCustom componentsremoveIntro to custom componentsCreate a ComponentPublish a ComponentLimitationsComponent galleryopen_in_newConfiguration and themingaddApp testingaddAPI referenceaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Develop/Concepts/Custom components/Intro to custom componentsIntro to custom components The first step in developing a Streamlit Component is deciding whether to create a static component (i.e. rendered once, controlled by Python) or to create a bi-directional component that can communicate from Python to JavaScript and back. Create a static component If your goal in creating a Streamlit Component is solely to display HTML code or render a chart from a Python visualization library, Streamlit provides two methods that greatly simplify the process: components.html() and components.iframe(). If you are unsure whether you need bi-directional communication, start here first! Render an HTML string While st.text, st.markdown and st.write make it easy to write text to a Streamlit app, sometimes you'd rather implement a custom piece of HTML. Similarly, while Streamlit natively supports many charting libraries, you may want to implement a specific HTML/JavaScript template for a new charting library. components.html works by giving you the ability to embed an iframe inside of a Streamlit app that contains your desired output. Example import streamlit as st import streamlit.components.v1 as components # bootstrap 4 collapse example components.html( """"""
Collapsible Group Item #1 content
Collapsible Group Item #2 content
"""""", height=600, ) Render an iframe URL components.iframe is similar in features to components.html, with the difference being that components.iframe takes a URL as its input. This is used for situations where you want to include an entire page within a Streamlit app. Example import streamlit as st import streamlit.components.v1 as components # embed streamlit docs in a streamlit app components.iframe(""https://example.com"", height=500) Create a bi-directional component A bi-directional Streamlit Component has two parts: A frontend, which is built out of HTML and any other web tech you like (JavaScript, React, Vue, etc.), and gets rendered in Streamlit apps via an iframe tag. A Python API, which Streamlit apps use to instantiate and talk to that frontend To make the process of creating bi-directional Streamlit Components easier, we've created a React template and a TypeScript-only template in the Streamlit Component-template GitHub repo. We also provide some example Components in the same repo. Development Environment Setup To build a Streamlit Component, you need the following installed in your development environment: Python 3.8 - Python 3.12 Streamlit 1.11.1 or higher nodejs npm or yarn Clone the component-template GitHub repo, then decide whether you want to use the React.js (""template"") or plain TypeScript (""template-reactless"") template. Initialize and build the component template frontend from the terminal: # React template template/my_component/frontend npm install # Initialize the project and install npm dependencies npm run start # Start the Webpack dev server # or # TypeScript-only template template-reactless/my_component/frontend npm install # Initialize the project and install npm dependencies npm run start # Start the Webpack dev server From a separate terminal, run the Streamlit app (Python) that declares and uses the component: # React template cd template . venv/bin/activate # or similar to activate the venv/conda environment where Streamlit is installed pip install -e . # install template as editable package streamlit run my_component/example.py # run the example # or # TypeScript-only template cd template-reactless . venv/bin/activate # or similar to activate the venv/conda environment where Streamlit is installed pip install -e . # install template as editable package streamlit run my_component/example.py # run the example After running the steps above, you should see a Streamlit app in your browser that looks like this: The example app from the template shows how bi-directional communication is implemented. The Streamlit Component displays a button (Python → JavaScript), and the end-user can click the button. Each time the button is clicked, the JavaScript front-end increments the counter value and passes it back to Python (JavaScript → Python), which is then displayed by Streamlit (Python → JavaScript). Frontend Because each Streamlit Component is its own webpage that gets rendered into an iframe, you can use just about any web tech you'd like to create that web page. We provide two templates to get started with in the Streamlit Components-template GitHub repo; one of those templates uses React and the other does not. push_pinNoteEven if you're not already familiar with React, you may still want to check out the React-based template. It handles most of the boilerplate required to send and receive data from Streamlit, and you can learn the bits of React you need as you go.If you'd rather not use React, please read this section anyway! It explains the fundamentals of Streamlit ↔ Component communication. React The React-based template is in template/my_component/frontend/src/MyComponent.tsx. MyComponent.render() is called automatically when the component needs to be re-rendered (just like in any React app) Arguments passed from the Python script are available via the this.props.args dictionary: # Send arguments in Python: result = my_component(greeting=""Hello"", name=""Streamlit"") // Receive arguments in frontend: let greeting = this.props.args[""greeting""]; // greeting = ""Hello"" let name = this.props.args[""name""]; // name = ""Streamlit"" Use Streamlit.setComponentValue() to return data from the component to the Python script: // Set value in frontend: Streamlit.setComponentValue(3.14); # Access value in Python: result = my_component(greeting=""Hello"", name=""Streamlit"") st.write(""result = "", result) # result = 3.14 When you call Streamlit.setComponentValue(new_value), that new value is sent to Streamlit, which then re-executes the Python script from top to bottom. When the script is re-executed, the call to my_component(...) will return the new value. From a code flow perspective, it appears that you're transmitting data synchronously with the frontend: Python sends the arguments to JavaScript, and JavaScript returns a value to Python, all in a single function call! But in reality this is all happening asynchronously, and it's the re-execution of the Python script that achieves the sleight of hand. Use Streamlit.setFrameHeight() to control the height of your component. By default, the React template calls this automatically (see StreamlitComponentBase.componentDidUpdate()). You can override this behavior if you need more control. There's a tiny bit of magic in the last line of the file: export default withStreamlitConnection(MyComponent) - this does some handshaking with Streamlit, and sets up the mechanisms for bi-directional data communication. TypeScript-only The TypeScript-only template is in template-reactless/my_component/frontend/src/MyComponent.tsx. This template has much more code than its React sibling, in that all the mechanics of handshaking, setting up event listeners, and updating the component's frame height are done manually. The React version of the template handles most of these details automatically. Towards the bottom of the source file, the template calls Streamlit.setComponentReady() to tell Streamlit it's ready to start receiving data. (You'll generally want to do this after creating and loading everything that the Component relies on.) It subscribes to Streamlit.RENDER_EVENT to be notified of when to redraw. (This event won't be fired until setComponentReady is called) Within its onRender event handler, it accesses the arguments passed in the Python script via event.detail.args It sends data back to the Python script in the same way that the React template does—clicking on the ""Click Me!"" button calls Streamlit.setComponentValue() It informs Streamlit when its height may have changed via Streamlit.setFrameHeight() Working with Themes push_pinNoteCustom component theme support requires streamlit-component-lib version 1.2.0 or higher. Along with sending an args object to your component, Streamlit also sends a theme object defining the active theme so that your component can adjust its styling in a compatible way. This object is sent in the same message as args, so it can be accessed via this.props.theme (when using the React template) or event.detail.theme (when using the plain TypeScript template). The theme object has the following shape: { ""base"": ""lightORdark"", ""primaryColor"": ""someColor1"", ""backgroundColor"": ""someColor2"", ""secondaryBackgroundColor"": ""someColor3"", ""textColor"": ""someColor4"", ""font"": ""someFont"" } The base option allows you to specify a preset Streamlit theme that your custom theme inherits from. Any theme config options not defined in your theme settings have their values set to those of the base theme. Valid values for base are ""light"" and ""dark"". Note that the theme object has fields with the same names and semantics as the options in the ""theme"" section of the config options printed with the command streamlit config show. When using the React template, the following CSS variables are also set automatically. --base --primary-color --background-color --secondary-background-color --text-color --font If you're not familiar with CSS variables, the TLDR version is that you can use them like this: .mySelector { color: var(--text-color); } These variables match the fields defined in the theme object above, and whether to use CSS variables or the theme object in your component is a matter of personal preference. Other frontend details Because you're hosting your component from a dev server (via npm run start), any changes you make should be automatically reflected in the Streamlit app when you save. If you want to add more packages to your component, run npm add to add them from within your component's frontend/ directory. npm add baseui To build a static version of your component, run npm run export. See Prepare your Component for more information Python API components.declare_component() is all that's required to create your Component's Python API: import streamlit.components.v1 as components my_component = components.declare_component( ""my_component"", url=""http://localhost:3001"" ) You can then use the returned my_component function to send and receive data with your frontend code: # Send data to the frontend using named arguments. return_value = my_component(name=""Blackbeard"", ship=""Queen Anne's Revenge"") # `my_component`'s return value is the data returned from the frontend. st.write(""Value = "", return_value) While the above is all you need to define from the Python side to have a working Component, we recommend creating a ""wrapper"" function with named arguments and default values, input validation and so on. This will make it easier for end-users to understand what data values your function accepts and allows for defining helpful docstrings. Please see this example from the Components-template for an example of creating a wrapper function. Data serialization Python → Frontend You send data from Python to the frontend by passing keyword args to your Component's invoke function (that is, the function returned from declare_component). You can send the following types of data from Python to the frontend: Any JSON-serializable data numpy.array pandas.DataFrame Any JSON-serializable data gets serialized to a JSON string, and deserialized to its JavaScript equivalent. numpy.array and pandas.DataFrame get serialized using Apache Arrow and are deserialized as instances of ArrowTable, which is a custom type that wraps Arrow structures and provides a convenient API on top of them. Check out the CustomDataframe and SelectableDataTable Component example code for more context on how to use ArrowTable. Frontend → Python You send data from the frontend to Python via the Streamlit.setComponentValue() API (which is part of the template code). Unlike arg-passing from Python → frontend, this API takes a single value. If you want to return multiple values, you'll need to wrap them in an Array or Object. Custom Components can send JSON-serializable data from the frontend to Python, as well as Apache Arrow ArrowTables to represent dataframes.Previous: Custom componentsNext: Create a ComponentforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy" https://docs.streamlit.io/develop/api-reference/connections/st.connections.sqlconnection#basic-usage,"DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceremovePAGE ELEMENTSWrite and magicaddText elementsaddData elementsaddChart elementsaddInput widgetsaddMedia elementsaddLayouts and containersaddChat elementsaddStatus elementsaddThird-party componentsopen_in_newAPPLICATION LOGICNavigation and pagesaddExecution flowaddCaching and stateaddConnections and secretsremoveSECRETSst.secretssecrets.tomlCONNECTIONSst.connectionSnowflakeConnectionSQLConnectionBaseConnectionSnowparkConnectiondeleteCustom componentsaddUtilitiesaddConfigurationaddTOOLSApp testingaddCommand lineaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Develop/API reference/Connections and secrets/SQLConnectionstarTipThis page only contains the st.connections.SQLConnection class. For a deeper dive into creating and managing data connections within Streamlit apps, read Connecting to data. st.connections.SQLConnectionStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA connection to a SQL database using a SQLAlchemy Engine. Initialize using st.connection("""", type=""sql""). SQLConnection provides the query() convenience method, which can be used to run simple read-only queries with both caching and simple error handling/retries. More complex DB interactions can be performed by using the .session property to receive a regular SQLAlchemy Session. SQLConnections should always be created using st.connection(), not initialized directly. Connection parameters for a SQLConnection can be specified using either st.secrets or **kwargs. Some frequently used parameters include: url or arguments for sqlalchemy.engine.URL.create(). Most commonly it includes a dialect, host, database, username and password. create_engine_kwargs can be passed via st.secrets, such as for snowflake-sqlalchemy or Google BigQuery. These can also be passed directly as **kwargs to connection(). autocommit=True to run with isolation level AUTOCOMMIT. Default is False. Class description[source] st.connections.SQLConnection(connection_name, **kwargs) Methods connect() Call .connect() on the underlying SQLAlchemy Engine, returning a new sqlalchemy.engine.Connection object. query(sql, *, show_spinner=""Running `sql.query(...)`."", ttl=None, index_col=None, chunksize=None, params=None, **kwargs) Run a read-only query. reset() Reset this connection so that it gets reinitialized the next time it's used. Attributes driver The name of the driver used by the underlying SQLAlchemy Engine. engine The underlying SQLAlchemy Engine. session Return a SQLAlchemy Session. Example import streamlit as st conn = st.connection(""sql"") df = conn.query(""select * from pet_owners"") st.dataframe(df) Basic usage: SQLAlchemy and any required drivers must be installed to use this connection. import streamlit as st conn = st.connection(""sql"") df = conn.query(""select * from pet_owners"") st.dataframe(df) In case you want to pass a connection URL (or other parameters) directly, it also works: conn = st.connection( ""local_db"", type=""sql"", url=""mysql://user:pass@localhost:3306/mydb"" ) Or specify parameters in secrets: # .streamlit/secrets.toml [connections.mydb] dialect = ""mysql"" username = ""myuser"" password = ""password"" host = ""localhost"" database = ""mydb"" # streamlit_app.py conn = st.connection(""mydb"", type=""sql"", autocommit=True) As described above, some cloud databases use extra **kwargs to specify credentials. These can be passed via secrets using the create_engine_kwargs section: # .streamlit/secrets.toml [connections.snowflake] url = ""snowflake://@/"" [connections.snowflake.create_engine_kwargs.connect_args] authenticator = ""externalbrowser"" role = ""..."" # ... SQLConnection.connectStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeCall .connect() on the underlying SQLAlchemy Engine, returning a new sqlalchemy.engine.Connection object. Calling this method is equivalent to calling self._instance.connect(). NOTE: This method should not be confused with the internal _connect method used to implement a Streamlit Connection. Function signature[source] SQLConnection.connect() SQLConnection.queryStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeRun a read-only query. This method implements both query result caching (with caching behavior identical to that of using @st.cache_data) as well as simple error handling/retries. Note Queries that are run without a specified ttl are cached indefinitely. Aside from the ttl kwarg, all kwargs passed to this function are passed down to pandas.read_sql and have the behavior described in the pandas documentation. Function signature[source] SQLConnection.query(sql, *, show_spinner=""Running `sql.query(...)`."", ttl=None, index_col=None, chunksize=None, params=None, **kwargs) Parameters sql (str) The read-only SQL query to execute. show_spinner (boolean or string) Enable the spinner. The default is to show a spinner when there is a ""cache miss"" and the cached resource is being created. If a string, the value of the show_spinner param will be used for the spinner text. ttl (float, int, timedelta or None) The maximum number of seconds to keep results in the cache, or None if cached results should not expire. The default is None. index_col (str, list of str, or None) Column(s) to set as index(MultiIndex). Default is None. chunksize (int or None) If specified, return an iterator where chunksize is the number of rows to include in each chunk. Default is None. params (list, tuple, dict or None) List of parameters to pass to the execute method. The syntax used to pass parameters is database driver dependent. Check your database driver documentation for which of the five syntax styles, described in PEP 249 paramstyle, is supported. Default is None. **kwargs (dict) Additional keyword arguments are passed to pandas.read_sql. Returns(pandas.DataFrame) The result of running the query, formatted as a pandas DataFrame. Example import streamlit as st conn = st.connection(""sql"") df = conn.query(""select * from pet_owners where owner = :owner"", ttl=3600, params={""owner"":""barbara""}) st.dataframe(df) SQLConnection.resetStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeReset this connection so that it gets reinitialized the next time it's used. This method can be useful when a connection has become stale, an auth token has expired, or in similar scenarios where a broken connection might be fixed by reinitializing it. Note that some connection methods may already use reset() in their error handling code. Function signature[source] SQLConnection.reset() Example import streamlit as st conn = st.connection(""my_conn"") # Reset the connection before using it if it isn't healthy # Note: is_healthy() isn't a real method and is just shown for example here. if not conn.is_healthy(): conn.reset() # Do stuff with conn... SQLConnection.driverStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeThe name of the driver used by the underlying SQLAlchemy Engine. This is equivalent to accessing self._instance.driver. Function signature[source] SQLConnection.driver SQLConnection.engineStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeThe underlying SQLAlchemy Engine. This is equivalent to accessing self._instance. Function signature[source] SQLConnection.engine SQLConnection.sessionStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeReturn a SQLAlchemy Session. Users of this connection should use the contextmanager pattern for writes, transactions, and anything more complex than simple read queries. See the usage example below, which assumes we have a table numbers with a single integer column val. The SQLAlchemy docs also contain much more information on the usage of sessions. Function signature[source] SQLConnection.session Example import streamlit as st conn = st.connection(""sql"") n = st.slider(""Pick a number"") if st.button(""Add the number!""): with conn.session as session: session.execute(""INSERT INTO numbers (val) VALUES (:n);"", {""n"": n}) session.commit() Previous: SnowflakeConnectionNext: BaseConnectionforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy" https://docs.streamlit.io/develop/api-reference/app-testing/testing-element-classes#textinputinput,"DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceremovePAGE ELEMENTSWrite and magicaddText elementsaddData elementsaddChart elementsaddInput widgetsaddMedia elementsaddLayouts and containersaddChat elementsaddStatus elementsaddThird-party componentsopen_in_newAPPLICATION LOGICNavigation and pagesaddExecution flowaddCaching and stateaddConnections and secretsaddCustom componentsaddUtilitiesaddConfigurationaddTOOLSApp testingremovest.testing.v1.AppTestTesting element classesCommand lineaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Develop/API reference/App testing/Testing element classesTesting element classes st.testing.v1.element_tree.Block The Block class has the same methods and attributes as AppTest. A Block instance represents a container of elements just as AppTest represents the entire app. For example, Block.button will produce a WidgetList of Button in the same manner as AppTest.button. ChatMessage, Column, and Tab all inherit from Block. For all container classes, parameters of the original element can be obtained as properties. For example, ChatMessage.avatar and Tab.label. st.testing.v1.element_tree.ElementStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeElement base class for testing. This class's methods and attributes are universal for all elements implemented in testing. For example, Caption, Code, Text, and Title inherit from Element. All widget classes also inherit from Element, but have additional methods specific to each widget type. See the AppTest class for the full list of supported elements. For all element classes, parameters of the original element can be obtained as properties. For example, Button.label, Caption.help, and Toast.icon. Class description[source] st.testing.v1.element_tree.Element(proto, root) Methods run(*, timeout=None) Run the AppTest script which contains the element. Attributes value The value or contents of the element. st.testing.v1.element_tree.ButtonStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.button and st.form_submit_button. Class description[source] st.testing.v1.element_tree.Button(proto, root) Methods click() Set the value of the button to True. run(*, timeout=None) Run the AppTest script which contains the element. set_value(v) Set the value of the button. Attributes value The value of the button. (bool) st.testing.v1.element_tree.ChatInputStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.chat_input. Class description[source] st.testing.v1.element_tree.ChatInput(proto, root) Methods run(*, timeout=None) Run the AppTest script which contains the element. set_value(v) Set the value of the widget. Attributes value The value of the widget. (str) st.testing.v1.element_tree.CheckboxStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.checkbox. Class description[source] st.testing.v1.element_tree.Checkbox(proto, root) Methods check() Set the value of the widget to True. run(*, timeout=None) Run the AppTest script which contains the element. set_value(v) Set the value of the widget. uncheck() Set the value of the widget to False. Attributes value The value of the widget. (bool) st.testing.v1.element_tree.ColorPickerStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.color_picker. Class description[source] st.testing.v1.element_tree.ColorPicker(proto, root) Methods pick(v) Set the value of the widget as a hex string. May omit the ""#"" prefix. run(*, timeout=None) Run the AppTest script which contains the element. set_value(v) Set the value of the widget as a hex string. Attributes value The currently selected value as a hex string. (str) st.testing.v1.element_tree.DateInputStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.date_input. Class description[source] st.testing.v1.element_tree.DateInput(proto, root) Methods run(*, timeout=None) Run the AppTest script which contains the element. set_value(v) Set the value of the widget. Attributes value The value of the widget. (date or Tuple of date) st.testing.v1.element_tree.MultiselectStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.multiselect. Class description[source] st.testing.v1.element_tree.Multiselect(proto, root) Methods run(*, timeout=None) Run the AppTest script which contains the element. select(v) Add a selection to the widget. Do nothing if the value is already selected. If testing a multiselect widget with repeated options, use set_value instead. set_value(v) Set the value of the multiselect widget. (list) unselect(v) Remove a selection from the widget. Do nothing if the value is not already selected. If a value is selected multiple times, the first instance is removed. Attributes format_func The widget's formatting function for displaying options. (callable) indices The indices of the currently selected values from the options. (list) value The currently selected values from the options. (list) st.testing.v1.element_tree.NumberInputStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.number_input. Class description[source] st.testing.v1.element_tree.NumberInput(proto, root) Methods decrement() Decrement the st.number_input widget as if the user clicked ""-"". increment() Increment the st.number_input widget as if the user clicked ""+"". run(*, timeout=None) Run the AppTest script which contains the element. set_value(v) Set the value of the st.number_input widget. Attributes value Get the current value of the st.number_input widget. st.testing.v1.element_tree.RadioStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.radio. Class description[source] st.testing.v1.element_tree.Radio(proto, root) Methods run(*, timeout=None) Run the AppTest script which contains the element. set_value(v) Set the selection by value. Attributes format_func The widget's formatting function for displaying options. (callable) index The index of the current selection. (int) value The currently selected value from the options. (Any) st.testing.v1.element_tree.SelectSliderStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.select_slider. Class description[source] st.testing.v1.element_tree.SelectSlider(proto, root) Methods run(*, timeout=None) Run the AppTest script which contains the element. set_range(lower, upper) Set the ranged selection by values. set_value(v) Set the (single) selection by value. Attributes format_func The widget's formatting function for displaying options. (callable) value The currently selected value or range. (Any or Sequence of Any) st.testing.v1.element_tree.SelectboxStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.selectbox. Class description[source] st.testing.v1.element_tree.Selectbox(proto, root) Methods run(*, timeout=None) Run the AppTest script which contains the element. select(v) Set the selection by value. select_index(index) Set the selection by index. set_value(v) Set the selection by value. Attributes format_func The widget's formatting function for displaying options. (callable) index The index of the current selection. (int) value The currently selected value from the options. (Any) st.testing.v1.element_tree.SliderStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.slider. Class description[source] st.testing.v1.element_tree.Slider(proto, root) Methods run(*, timeout=None) Run the AppTest script which contains the element. set_range(lower, upper) Set the ranged value of the slider. set_value(v) Set the (single) value of the slider. Attributes value The currently selected value or range. (Any or Sequence of Any) st.testing.v1.element_tree.TextAreaStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.text_area. Class description[source] st.testing.v1.element_tree.TextArea(proto, root) Methods input(v) Set the value of the widget only if the value does not exceed the maximum allowed characters. run(*, timeout=None) Run the AppTest script which contains the element. set_value(v) Set the value of the widget. Attributes value The current value of the widget. (str) st.testing.v1.element_tree.TextInputStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.text_input. Class description[source] st.testing.v1.element_tree.TextInput(proto, root) Methods input(v) Set the value of the widget only if the value does not exceed the maximum allowed characters. run(*, timeout=None) Run the AppTest script which contains the element. set_value(v) Set the value of the widget. Attributes value The current value of the widget. (str) st.testing.v1.element_tree.TimeInputStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.time_input. Class description[source] st.testing.v1.element_tree.TimeInput(proto, root) Methods decrement() Select the previous available time. increment() Select the next available time. run(*, timeout=None) Run the AppTest script which contains the element. set_value(v) Set the value of the widget. Attributes value The current value of the widget. (time) st.testing.v1.element_tree.ToggleStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.toggle. Class description[source] st.testing.v1.element_tree.Toggle(proto, root) Methods run(*, timeout=None) Run the AppTest script which contains the element. set_value(v) Set the value of the widget. Attributes value The current value of the widget. (bool) Previous: st.testing.v1.AppTestNext: Command lineforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy" https://docs.streamlit.io/develop/api-reference/app-testing/st.testing.v1.apptest#apptesttext_input,"DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceremovePAGE ELEMENTSWrite and magicaddText elementsaddData elementsaddChart elementsaddInput widgetsaddMedia elementsaddLayouts and containersaddChat elementsaddStatus elementsaddThird-party componentsopen_in_newAPPLICATION LOGICNavigation and pagesaddExecution flowaddCaching and stateaddConnections and secretsaddCustom componentsaddUtilitiesaddConfigurationaddTOOLSApp testingremovest.testing.v1.AppTestTesting element classesCommand lineaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Develop/API reference/App testing/st.testing.v1.AppTest The AppTest class st.testing.v1.AppTestStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA simulated Streamlit app to check the correctness of displayed elements and outputs. An instance of AppTest simulates a running Streamlit app. This class provides methods to set up, manipulate, and inspect the app contents via API instead of a browser UI. It can be used to write automated tests of an app in various scenarios. These can then be run using a tool like pytest. AppTest can be initialized by one of three class methods: st.testing.v1.AppTest.from_file (recommended) st.testing.v1.AppTest.from_string st.testing.v1.AppTest.from_function Once initialized, Session State and widget values can be updated and the script can be run. Unlike an actual live-running Streamlit app, you need to call AppTest.run() explicitly to re-run the app after changing a widget value. Switching pages also requires an explicit, follow-up call to AppTest.run(). AppTest enables developers to build tests on their app as-is, in the familiar python test format, without major refactoring or abstracting out logic to be tested separately from the UI. Tests can run quickly with very low overhead. A typical pattern is to build a suite of tests for an app that ensure consistent functionality as the app evolves, and run the tests locally and/or in a CI environment like Github Actions. Note AppTest only supports testing a single page of an app per instance. For multipage apps, each page will need to be tested separately. No methods exist to programatically switch pages within AppTest. Class description[source] st.testing.v1.AppTest(script_path, *, default_timeout, args=None, kwargs=None) Methods get(element_type) Get elements or widgets of the specified type. run(*, timeout=None) Run the script from the current state. switch_page(page_path) Switch to another page of the app. Attributes secrets (dict[str, Any]) Dictionary of secrets to be used the simulated app. Use dict-like syntax to set secret values for the simulated app. session_state (SafeSessionState) Session State for the simulated app. SafeSessionState object supports read and write operations as usual for Streamlit apps. query_params (dict[str, Any]) Dictionary of query parameters to be used by the simluated app. Use dict-like syntax to set query_params values for the simulated app. button Sequence of all st.button and st.form_submit_button widgets. caption Sequence of all st.caption elements. chat_input Sequence of all st.chat_input widgets. chat_message Sequence of all st.chat_message elements. checkbox Sequence of all st.checkbox widgets. code Sequence of all st.code elements. color_picker Sequence of all st.color_picker widgets. columns Sequence of all columns within st.columns elements. dataframe Sequence of all st.dataframe elements. date_input Sequence of all st.date_input widgets. divider Sequence of all st.divider elements. error Sequence of all st.error elements. exception Sequence of all st.exception elements. expander Sequence of all st.expander elements. header Sequence of all st.header elements. info Sequence of all st.info elements. json Sequence of all st.json elements. latex Sequence of all st.latex elements. main Sequence of elements within the main body of the app. markdown Sequence of all st.markdown elements. metric Sequence of all st.metric elements. multiselect Sequence of all st.multiselect widgets. number_input Sequence of all st.number_input widgets. radio Sequence of all st.radio widgets. select_slider Sequence of all st.select_slider widgets. selectbox Sequence of all st.selectbox widgets. sidebar Sequence of all elements within st.sidebar. slider Sequence of all st.slider widgets. status Sequence of all st.status elements. subheader Sequence of all st.subheader elements. success Sequence of all st.success elements. table Sequence of all st.table elements. tabs Sequence of all tabs within st.tabs elements. text Sequence of all st.text elements. text_area Sequence of all st.text_area widgets. text_input Sequence of all st.text_input widgets. time_input Sequence of all st.time_input widgets. title Sequence of all st.title elements. toast Sequence of all st.toast elements. toggle Sequence of all st.toggle widgets. warning Sequence of all st.warning elements. Initialize a simulated app using AppTest AppTest.from_fileStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeCreate an instance of AppTest to simulate an app page defined within a file. This option is most convenient for CI workflows and testing of published apps. The script must be executable on its own and so must contain all necessary imports. Function signature[source] AppTest.from_file(cls, script_path, *, default_timeout=3) Parameters script_path (str) Path to a script file. The path should be absolute or relative to the file calling .from_file. default_timeout (float) Default time in seconds before a script run is timed out. Can be overridden for individual .run() calls. Returns(AppTest) A simulated Streamlit app for testing. The simulated app can be executed via .run(). AppTest.from_stringStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeCreate an instance of AppTest to simulate an app page defined within a string. This is useful for testing short scripts that fit comfortably as an inline string in the test itself, without having to create a separate file for it. The script must be executable on its own and so must contain all necessary imports. Function signature[source] AppTest.from_string(cls, script, *, default_timeout=3) Parameters script (str) The string contents of the script to be run. default_timeout (float) Default time in seconds before a script run is timed out. Can be overridden for individual .run() calls. Returns(AppTest) A simulated Streamlit app for testing. The simulated app can be executed via .run(). AppTest.from_functionStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeCreate an instance of AppTest to simulate an app page defined within a function. This is similar to AppTest.from_string(), but more convenient to write with IDE assistance. The script must be executable on its own and so must contain all necessary imports. Function signature[source] AppTest.from_function(cls, script, *, default_timeout=3, args=None, kwargs=None) Parameters script (Callable) A function whose body will be used as a script. Must be runnable in isolation, so it must include any necessary imports. default_timeout (float) Default time in seconds before a script run is timed out. Can be overridden for individual .run() calls. args (tuple) An optional tuple of args to pass to the script function. kwargs (dict) An optional dict of kwargs to pass to the script function. Returns(AppTest) A simulated Streamlit app for testing. The simulated app can be executed via .run(). Run an AppTest script AppTest.runStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeRun the script from the current state. This is equivalent to manually rerunning the app or the rerun that occurs upon user interaction. AppTest.run() must be manually called after updating a widget value or switching pages as script reruns do not occur automatically as they do for live-running Streamlit apps. Function signature[source] AppTest.run(*, timeout=None) Parameters timeout (null) The maximum number of seconds to run the script. None means use the default timeout set for the instance of AppTest. Returns(AppTest) self AppTest.switch_pageStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSwitch to another page of the app. This method does not automatically rerun the app. Use a follow-up call to AppTest.run() to obtain the elements on the selected page. Function signature[source] AppTest.switch_page(page_path) Parameters page_path (str) Path of the page to switch to. The path must be relative to the main script's location (e.g. ""pages/my_page.py""). Returns(AppTest) self Get AppTest script elements The main value of AppTest is providing an API to programmatically inspect and interact with the elements and widgets produced by a running Streamlit app. Using the AppTest. properties or AppTest.get() method returns a collection of all the elements or widgets of the specified type that would have been displayed by running the app. Note that you can also retrieve elements within a specific container in the same way - first retrieve the container, then retrieve the elements just in that container. AppTest.getStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeGet elements or widgets of the specified type. This method returns the collection of all elements or widgets of the specified type on the current page. Retrieve a specific element by using its index (order on page) or key lookup. Function signature[source] AppTest.get(element_type) Parameters element_type (str) An element attribute of AppTest. For example, ""button"", ""caption"", or ""chat_input"". Returns(Sequence of Elements) Sequence of elements of the given type. Individual elements can be accessed from a Sequence by index (order on the page). When getting and element_type that is a widget, individual widgets can be accessed by key. For example, at.get(""text"")[0] for the first st.text element or at.get(""slider"")(key=""my_key"") for the st.slider widget with a given key. AppTest.buttonStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.button and st.form_submit_button widgets. Function signature[source] AppTest.button Returns(WidgetList of Button) Sequence of all st.button and st.form_submit_button widgets. Individual widgets can be accessed from a WidgetList by index (order on the page) or key. For example, at.button[0] for the first widget or at.button(key=""my_key"") for a widget with a given key. AppTest.captionStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.caption elements. Function signature[source] AppTest.caption Returns(ElementList of Caption) Sequence of all st.caption elements. Individual elements can be accessed from an ElementList by index (order on the page). For example, at.caption[0] for the first element. Caption is an extension of the Element class. AppTest.chat_inputStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.chat_input widgets. Function signature[source] AppTest.chat_input Returns(WidgetList of ChatInput) Sequence of all st.chat_input widgets. Individual widgets can be accessed from a WidgetList by index (order on the page) or key. For example, at.chat_input[0] for the first widget or at.chat_input(key=""my_key"") for a widget with a given key. AppTest.chat_messageStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.chat_message elements. Function signature[source] AppTest.chat_message Returns(Sequence of ChatMessage) Sequence of all st.chat_message elements. Individual elements can be accessed from an ElementList by index (order on the page). For example, at.chat_message[0] for the first element. ChatMessage is an extension of the Block class. AppTest.checkboxStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.checkbox widgets. Function signature[source] AppTest.checkbox Returns(WidgetList of Checkbox) Sequence of all st.checkbox widgets. Individual widgets can be accessed from a WidgetList by index (order on the page) or key. For example, at.checkbox[0] for the first widget or at.checkbox(key=""my_key"") for a widget with a given key. AppTest.codeStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.code elements. Function signature[source] AppTest.code Returns(ElementList of Code) Sequence of all st.code elements. Individual elements can be accessed from an ElementList by index (order on the page). For example, at.code[0] for the first element. Code is an extension of the Element class. AppTest.color_pickerStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.color_picker widgets. Function signature[source] AppTest.color_picker Returns(WidgetList of ColorPicker) Sequence of all st.color_picker widgets. Individual widgets can be accessed from a WidgetList by index (order on the page) or key. For example, at.color_picker[0] for the first widget or at.color_picker(key=""my_key"") for a widget with a given key. AppTest.columnsStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all columns within st.columns elements. Each column within a single st.columns will be returned as a separate Column in the Sequence. Function signature[source] AppTest.columns Returns(Sequence of Column) Sequence of all columns within st.columns elements. Individual columns can be accessed from an ElementList by index (order on the page). For example, at.columns[0] for the first column. Column is an extension of the Block class. AppTest.dataframeStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.dataframe elements. Function signature[source] AppTest.dataframe Returns(ElementList of Dataframe) Sequence of all st.dataframe elements. Individual elements can be accessed from an ElementList by index (order on the page). For example, at.dataframe[0] for the first element. Dataframe is an extension of the Element class. AppTest.date_inputStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.date_input widgets. Function signature[source] AppTest.date_input Returns(WidgetList of DateInput) Sequence of all st.date_input widgets. Individual widgets can be accessed from a WidgetList by index (order on the page) or key. For example, at.date_input[0] for the first widget or at.date_input(key=""my_key"") for a widget with a given key. AppTest.dividerStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.divider elements. Function signature[source] AppTest.divider Returns(ElementList of Divider) Sequence of all st.divider elements. Individual elements can be accessed from an ElementList by index (order on the page). For example, at.divider[0] for the first element. Divider is an extension of the Element class. AppTest.errorStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.error elements. Function signature[source] AppTest.error Returns(ElementList of Error) Sequence of all st.error elements. Individual elements can be accessed from an ElementList by index (order on the page). For example, at.error[0] for the first element. Error is an extension of the Element class. AppTest.exceptionStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.exception elements. Function signature[source] AppTest.exception Returns(ElementList of Exception) Sequence of all st.exception elements. Individual elements can be accessed from an ElementList by index (order on the page). For example, at.exception[0] for the first element. Exception is an extension of the Element class. AppTest.expanderStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.expander elements. Function signature[source] AppTest.expander Returns(Sequence of Expandable) Sequence of all st.expander elements. Individual elements can be accessed from a Sequence by index (order on the page). For example, at.expander[0] for the first element. Expandable is an extension of the Block class. AppTest.headerStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.header elements. Function signature[source] AppTest.header Returns(ElementList of Header) Sequence of all st.header elements. Individual elements can be accessed from an ElementList by index (order on the page). For example, at.header[0] for the first element. Header is an extension of the Element class. AppTest.infoStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.info elements. Function signature[source] AppTest.info Returns(ElementList of Info) Sequence of all st.info elements. Individual elements can be accessed from an ElementList by index (order on the page). For example, at.info[0] for the first element. Info is an extension of the Element class. AppTest.jsonStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.json elements. Function signature[source] AppTest.json Returns(ElementList of Json) Sequence of all st.json elements. Individual elements can be accessed from an ElementList by index (order on the page). For example, at.json[0] for the first element. Json is an extension of the Element class. AppTest.latexStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.latex elements. Function signature[source] AppTest.latex Returns(ElementList of Latex) Sequence of all st.latex elements. Individual elements can be accessed from an ElementList by index (order on the page). For example, at.latex[0] for the first element. Latex is an extension of the Element class. AppTest.mainStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of elements within the main body of the app. Function signature[source] AppTest.main Returns(Block) A container of elements. Block can be queried for elements in the same manner as AppTest. For example, Block.checkbox will return all st.checkbox within the associated container. AppTest.markdownStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.markdown elements. Function signature[source] AppTest.markdown Returns(ElementList of Markdown) Sequence of all st.markdown elements. Individual elements can be accessed from an ElementList by index (order on the page). For example, at.markdown[0] for the first element. Markdown is an extension of the Element class. AppTest.metricStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.metric elements. Function signature[source] AppTest.metric Returns(ElementList of Metric) Sequence of all st.metric elements. Individual elements can be accessed from an ElementList by index (order on the page). For example, at.metric[0] for the first element. Metric is an extension of the Element class. AppTest.multiselectStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.multiselect widgets. Function signature[source] AppTest.multiselect Returns(WidgetList of Multiselect) Sequence of all st.multiselect widgets. Individual widgets can be accessed from a WidgetList by index (order on the page) or key. For example, at.multiselect[0] for the first widget or at.multiselect(key=""my_key"") for a widget with a given key. AppTest.number_inputStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.number_input widgets. Function signature[source] AppTest.number_input Returns(WidgetList of NumberInput) Sequence of all st.number_input widgets. Individual widgets can be accessed from a WidgetList by index (order on the page) or key. For example, at.number_input[0] for the first widget or at.number_input(key=""my_key"") for a widget with a given key. AppTest.radioStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.radio widgets. Function signature[source] AppTest.radio Returns(WidgetList of Radio) Sequence of all st.radio widgets. Individual widgets can be accessed from a WidgetList by index (order on the page) or key. For example, at.radio[0] for the first widget or at.radio(key=""my_key"") for a widget with a given key. AppTest.select_sliderStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.select_slider widgets. Function signature[source] AppTest.select_slider Returns(WidgetList of SelectSlider) Sequence of all st.select_slider widgets. Individual widgets can be accessed from a WidgetList by index (order on the page) or key. For example, at.select_slider[0] for the first widget or at.select_slider(key=""my_key"") for a widget with a given key. AppTest.selectboxStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.selectbox widgets. Function signature[source] AppTest.selectbox Returns(WidgetList of Selectbox) Sequence of all st.selectbox widgets. Individual widgets can be accessed from a WidgetList by index (order on the page) or key. For example, at.selectbox[0] for the first widget or at.selectbox(key=""my_key"") for a widget with a given key. AppTest.sidebarStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all elements within st.sidebar. Function signature[source] AppTest.sidebar Returns(Block) A container of elements. Block can be queried for elements in the same manner as AppTest. For example, Block.checkbox will return all st.checkbox within the associated container. AppTest.sliderStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.slider widgets. Function signature[source] AppTest.slider Returns(WidgetList of Slider) Sequence of all st.slider widgets. Individual widgets can be accessed from a WidgetList by index (order on the page) or key. For example, at.slider[0] for the first widget or at.slider(key=""my_key"") for a widget with a given key. AppTest.subheaderStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.subheader elements. Function signature[source] AppTest.subheader Returns(ElementList of Subheader) Sequence of all st.subheader elements. Individual elements can be accessed from an ElementList by index (order on the page). For example, at.subheader[0] for the first element. Subheader is an extension of the Element class. AppTest.successStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.success elements. Function signature[source] AppTest.success Returns(ElementList of Success) Sequence of all st.success elements. Individual elements can be accessed from an ElementList by index (order on the page). For example, at.success[0] for the first element. Success is an extension of the Element class. AppTest.statusStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.status elements. Function signature[source] AppTest.status Returns(Sequence of Status) Sequence of all st.status elements. Individual elements can be accessed from a Sequence by index (order on the page). For example, at.status[0] for the first element. Status is an extension of the Block class. AppTest.tableStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.table elements. Function signature[source] AppTest.table Returns(ElementList of Table) Sequence of all st.table elements. Individual elements can be accessed from an ElementList by index (order on the page). For example, at.table[0] for the first element. Table is an extension of the Element class. AppTest.tabsStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all tabs within st.tabs elements. Each tab within a single st.tabs will be returned as a separate Tab in the Sequence. Additionally, the tab labels are forwarded to each Tab element as a property. For example, st.tabs(""A"",""B"") will yield two Tab objects, with Tab.label returning ""A"" and ""B"", respectively. Function signature[source] AppTest.tabs Returns(Sequence of Tab) Sequence of all tabs within st.tabs elements. Individual tabs can be accessed from an ElementList by index (order on the page). For example, at.tabs[0] for the first tab. Tab is an extension of the Block class. AppTest.textStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.text elements. Function signature[source] AppTest.text Returns(ElementList of Text) Sequence of all st.text elements. Individual elements can be accessed from an ElementList by index (order on the page). For example, at.text[0] for the first element. Text is an extension of the Element class. AppTest.text_areaStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.text_area widgets. Function signature[source] AppTest.text_area Returns(WidgetList of TextArea) Sequence of all st.text_area widgets. Individual widgets can be accessed from a WidgetList by index (order on the page) or key. For example, at.text_area[0] for the first widget or at.text_area(key=""my_key"") for a widget with a given key. AppTest.text_inputStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.text_input widgets. Function signature[source] AppTest.text_input Returns(WidgetList of TextInput) Sequence of all st.text_input widgets. Individual widgets can be accessed from a WidgetList by index (order on the page) or key. For example, at.text_input[0] for the first widget or at.text_input(key=""my_key"") for a widget with a given key. AppTest.time_inputStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.time_input widgets. Function signature[source] AppTest.time_input Returns(WidgetList of TimeInput) Sequence of all st.time_input widgets. Individual widgets can be accessed from a WidgetList by index (order on the page) or key. For example, at.time_input[0] for the first widget or at.time_input(key=""my_key"") for a widget with a given key. AppTest.titleStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.title elements. Function signature[source] AppTest.title Returns(ElementList of Title) Sequence of all st.title elements. Individual elements can be accessed from an ElementList by index (order on the page). For example, at.title[0] for the first element. Title is an extension of the Element class. AppTest.toastStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.toast elements. Function signature[source] AppTest.toast Returns(ElementList of Toast) Sequence of all st.toast elements. Individual elements can be accessed from an ElementList by index (order on the page). For example, at.toast[0] for the first element. Toast is an extension of the Element class. AppTest.toggleStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.toggle widgets. Function signature[source] AppTest.toggle Returns(WidgetList of Toggle) Sequence of all st.toggle widgets. Individual widgets can be accessed from a WidgetList by index (order on the page) or key. For example, at.toggle[0] for the first widget or at.toggle(key=""my_key"") for a widget with a given key. AppTest.warningStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.warning elements. Function signature[source] AppTest.warning Returns(ElementList of Warning) Sequence of all st.warning elements. Individual elements can be accessed from an ElementList by index (order on the page). For example, at.warning[0] for the first element. Warning is an extension of the Element class. Previous: App testingNext: Testing element classesforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy" https://docs.streamlit.io/deploy/streamlit-community-cloud/troubleshooting#what-happens-when-a-users-permissions-change-on-github,"DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudremoveGet startedaddDeploy your appaddManage your appaddShare your appaddManage your accountaddTroubleshootingStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Deploy/Streamlit Community Cloud/TroubleshootingTroubleshooting Sorry to hear you're having issues! Please take a look at some frequently asked questions and issues below. If you cannot find an answer to your issue, please post on our Community forum so that our engineers or community members can help you. Table of contents General help Deploying apps Sharing and accessing apps Data and app security GitHub integration Limitations and known issues General help How can I get help with my app? If you have any questions, feedback, run into any issues, or need to reach us, you can ask on our Community forum. This is best suited for any questions related to the open source library and Community Cloud - debugging code, deployment, resource limits, etc. Deploying apps My repo isn't showing on the Deploy page It's possible it just isn't showing up even though it is already there. Try typing it in. If we don't recognize it, you'll see the message below with a link to click and give access. If for some reason that doesn't work, please try logging out and back in again to make sure the change took effect. And if that doesn't work - please let us know and we'll get you sorted! It won't let me deploy the app To deploy an app for the first time you must have admin-level access to the repo in GitHub. Please check with your administrator to make sure you have that access. If not, please ask them to deploy for the first time (we need this in order to establish webhooks for continuous integration) and from there you can then push updates to the app. I need to set a specific Python version for my app When deploying an app, under advanced settings, you can choose which version of Python you wish your app to use. How do I store files locally? If you want to store your data locally as opposed to in a database, you can store the file in your GitHub repository. Streamlit is just python, so you can read the file using: pandas.read_csv(""data.csv"") or open(""data.csv"") starTipIf you have really big or binary data that you change frequently, and git is feeling slow, you might want to check out Git Large File Store (LFS) as a better way to store large files in GitHub. You don't need to make any changes to your app to start using it. If your GitHub repo uses LFS, it will now just work with Streamlit. My app is running into issues while deploying Check your Cloud logs by clicking on the ""Manage app"" expander in the bottom right corner of your screen. Often the trouble is due to a dependency not being declared. See here for more information on dependency management. If that's not the issue, then please send the logs and warning you are seeing to our Community forum and we'll help get you sorted! My app is hitting resource limits / my app is running very slowly If your app is running slowly or you're hitting the 'Argh' page, we first highly recommend going through and implementing the suggestions in the following blog posts to prevent your app from hitting the resource limits and to detect if your Streamlit app leaks memory: Common app problems: Resource limits 3 steps to fix app memory leaks If you're still having issues, click here to learn more about resource limits. Can I get a custom URL for my app? Yes! You can find instructions for setting a custom subdomain here. Sharing and accessing apps Don't have SSO? No problem! You can sign in to Streamlit with your email address. Click here for step-by-step instructions on how to sign in with email. */} How do I add viewers to my Streamlit apps? Viewer auth allows you to restrict the viewers of your private app. To access your app, users have to authenticate using an email-based passwordless login or Google OAuth. To learn more about how to share your public and private apps with viewers, click here. Do viewers need access to the GitHub repo? Nope! You only need access to the GitHub repo if you want to push changes to the app. What will unauthorized/logged out viewers see when they view my app? A 404 error is displayed to unauthorized viewers to avoid providing any unnecessary information about your app to unintended viewers. Users who satisfy any of the following conditions will see a 404 error when attempting to view your app after you have configured viewer auth: User is not logged in with their primary identity. User is not included in the list of allowed viewers provided in the app settings. User lacks read access to your app's GitHub repo. User has read access to your app's GitHub repo but is not enrolled in Streamlit Community Cloud. I've added someone to the viewer list but they still see a 404 error when attempting to view the app If a user is still seeing a 404 error after their email address has been added to the viewer list, we recommend that you: Check that the user did not log into a different Google account via Single Sign-On (if you have added their work email address to the viewer list, ask the user to check that they are not logged into their personal Google account, and vice versa). Check that the user has navigated to the correct URL. Check that the user's email address has been entered correctly in the viewer list. Reach out on our Community forum and we will be happy to help. Data and app security How will Streamlit secure my data? Streamlit takes a number of industry best-practice measures to ensure your code, data, and apps are all secure. Read more in our Trust and Security memo. How do I set up SSO for my organization? Community Cloud uses Google OAuth, by default. If you use Google for authentication you're all set. Billing and administration The Community Cloud is a free service. You don't have to worry about setting up billing or being charged. GitHub integration Why does Streamlit require additional OAuth scope? In order to deploy your app, Streamlit requires access to your app's source code in GitHub and also the ability to manage the public keys associated with the repositories. The default GitHub OAuth scopes are sufficient to work with apps in public GitHub repositories. However, in order to work with apps in private GitHub repositories, Streamlit requires the additional repo OAuth scope from GitHub. We recognize that this scope provides Streamlit with extra permissions that we do not really need, and which, as people who prize security, we'd rather not even be granted. Alas, we need to work with the APIs we are provided by GitHub. After deploying my private-repo app, I received an email from GitHub saying a new public key was added to my repo. Is this expected? This is the expected behavior. When you try to deploy an app that lives in a private repo, Streamlit Community Cloud needs to get access to that repo somehow. For this, we create a read-only GitHub Deploy Key then access your repo using a public SSH key. When we set this up, GitHub notifies admins of the repo that the key was created as a security measure. What happens when a user's permissions change on GitHub? Once a user is added to a repository on GitHub, it will take at most 15 minutes before they can deploy the app on Cloud. If a user is removed from a repository on GitHub, it will take at most 15 minutes before their permissions to manage the app from that repository are revoked. Limitations and known issues Here are some limitations and known issues that we're actively working to resolve. When you print something to the Cloud logs, you may need to do a sys.stdout.flush() before it shows up. Matplotlib doesn't work well with threads. So if you're using Matplotlib you should wrap your code with locks as shown in the snippet below. This Matplotlib bug is more prominent when you share your app apps since you're more likely to get more concurrent users then. from matplotlib.backends.backend_agg import RendererAgg _lock = RendererAgg.lock with _lock: fig.title('This is a figure)') fig.plot([1,20,3,40]) st.pyplot(fig) All apps are hosted in the United States. This is currently not configurable. Previous: Manage your accountNext: Streamlit in SnowflakeforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy" https://docs.streamlit.io/deploy/streamlit-community-cloud/manage-your-app/delete-your-app#delete-your-app-from-your-workspace,"DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudremoveGet startedaddDeploy your appaddManage your appremoveApp analyticsApp settingsDelete your appEdit your appFavorite your appReboot your appShare your appaddManage your accountaddTroubleshootingStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Deploy/Streamlit Community Cloud/Manage your app/Delete your appDelete your app If you need to delete your app, it's simple and easy. There are several cases where you may need to delete your app: You have finished playing around with an example app. You want to deploy from a private repository but already have a private app. You want to change the Python version for your app or otherwise redeploy your app. If you delete your app and intend to immediately redploy it, your custom subdomain should be immediately available for reuse. Read more about data deletion in Streamlit trust and security. You can delete your app: From your workspace. From your Cloud logs. Delete your app from your workspace From your workspace at share.streamlit.io, click the overflow icon (more_vert) next to your app. Click ""Delete"". A confirmation will display. Enter the required confirmation string and click ""Delete"". Delete your app from your Cloud logs From your app at .streamlit.app, click ""Manage app"" in the lower-right corner. Click the overflow menu icon (more_vert) and click ""Delete app"". A confirmation will display. Enter the required confirmation string and click ""Delete"". Previous: App settingsNext: Edit your appforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy" https://docs.streamlit.io/knowledge-base/deploy/share-apps-with-viewers-outside-organization#share-your-app,"DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudremoveGet startedaddDeploy your appaddManage your appaddShare your appremoveEmbed your appSearch indexabilityShare previewsManage your accountaddTroubleshootingStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Deploy/Streamlit Community Cloud/Share your appShare your app Now that your app is deployed you can easily share it and collaborate on it. But first, let's take a moment and do a little joy dance for getting that app deployed! 🕺💃 Your app is now live at a fixed URL, so go wild and share it with whomever you want. Your app will inherit permissions from your GitHub repo, meaning that if your repo is private your app will be private and if your repo is public your app will be public. If you want to change that you can simply do so from the app settings menu. You are only allowed one private app at a time. If you've deployed from a private repository, you will have to make that app public or delete it before you can deploy another app from a private repository. Only developers can change your app between public and private. Make your app public or private Share your public app Share your private app Make your app public or private If you deployed your app from a public repository, your app will be public by default. If you deployed your app from a private repository, you will need to make the app public if you want to freely share it with the community at large. Set privacy from your app settings Access your App settings and go to the ""Sharing"" section. Set your app's privacy under ""Who can view this app."" Select ""This app is public and searchable"" to make your app public. Select ""Only specific people can view this app"" to make your app private. Set privacy from the share button From your app at .streamlit.app, click ""Share"" in the upper-right corner. Toggle your app between public and private by clicking ""Make this app public"". Share your public app Once your app is public, just give anyone your app's URL and they view it! Streamlit Community Cloud has several convenient shortcuts for sharing your app. Share your app on social media From your app at .streamlit.app, click ""Share"" in the upper-right corner. Click ""Social"" to access convenient social media share buttons. starTipUse the social media sharing buttons to post your app on our forum! We'd love to see what you make and perhaps feature your app as our app of the month. 💖 Invite viewers by email Whether your app is public or private, you can send an email invite to your app directly from Streamlit Community Cloud. This grants the viewer access to analytics for all your public apps and the ability to invite other viewers to your workspace. Developers and invited viewers are identified by their email in analytics instead of appearing anonymously (if they view any of your apps while logged in). Read more about viewers in App analytics. From your app at .streamlit.app, click ""Share"" in the upper-right corner. Enter an email address and click ""Invite"". Invited users will get a direct link to your app in their inbox. Copy your app's URL You can convenitiently copy your app's URL from the share menu or from your workspace. From your app click ""Share"" in the upper-right corner then click ""Copy link"". From your workspace click the overflow menu icon (more_vert) then click ""Copy URL"". Add a badge to your GitHub repository To help others find and play with your Streamlit app, you can add Streamlit's GitHub badge to your repo. Below is an enlarged example of what the badge looks like. Clicking on the badge takes you to—in this case—Streamlit's Roadmap. Once you deploy your app, you can embed this badge right into your GitHub README.md by adding the following Markdown: [![Streamlit App](https://static.streamlit.io/badges/streamlit_badge_black_white.svg)](https://.streamlit.app) push_pinNoteBe sure to replace https://.streamlit.app with the URL of your deployed app! Share your private app By default an app deployed from a private repository will be private to the developers in the workspace. A private app will not be visible to anyone else unless you grant them explicit permission. You can grant permission by adding them as a developer on GitHub or by adding them as a viewer on Streamlit Community Cloud. Once you have added someone's email address to your app's viewer list, that person will be able to sign in and view your private app. If their email is associated to a Google account, they will be able to sign in with Google OAuth. Otherwise, they will be able to sign in with single-use, emailed links. Streamlit sends an email invitation with a link to your app every time you invite someone. priority_highImportantWhen you add a viewer to any app in your workspace, they are granted access to analytics for that app as well as analytics for all your public apps. They can also pass these permissions to others by inviting more viewers. All viewers and developers in your workspace are identified by their email in analytics. Furthermore, their emails show in analytics for every app in your workspace and not just apps they are explicitly invited to. Read more about viewers in App analytics Invite viewers from the share button From your app at .streamlit.app, click ""Share"" in the upper-right corner. Enter the email to send an invitation to and click ""Invite"". Invited users appear in the list below. Invited users will get a direct link to your app in their inbox. To remove a viewer, simply access the share menu as above and click the close next to their name. Invite viewers from your app settings Access your App settings and go to the ""Sharing"" section. Add or remove users from the list of viewers. Click ""Save"". Previous: Manage your appNext: Embed your appforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy" https://docs.streamlit.io/knowledge-base/using-streamlit/insert-elements-out-of-order,"DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Knowledge base/FAQ/How to insert elements out of order?How to insert elements out of order? You can use the st.empty method as a placeholder, to ""save"" a slot in your app that you can use later. st.text('This will appear first') # Appends some text to the app. my_slot1 = st.empty() # Appends an empty slot to the app. We'll use this later. my_slot2 = st.empty() # Appends another empty slot. st.text('This will appear last') # Appends some more text to the app. my_slot1.text('This will appear second') # Replaces the first empty slot with a text string. my_slot2.line_chart(np.random.randn(20, 2)) # Replaces the second empty slot with a chart. Previous: How do I upgrade to the latest version of Streamlit?Next: How can I make st.pydeck_chart use custom Mapbox styles?forumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy" https://docs.streamlit.io/deploy/streamlit-community-cloud/manage-your-account#access-your-workspace-settings,"DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudremoveGet startedaddDeploy your appaddManage your appaddShare your appaddManage your accountremoveSign in & sign outWorkspace settingsManage your GitHub connectionUpdate your emailDelete your accountTroubleshootingStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Deploy/Streamlit Community Cloud/Manage your accountManage your account You can Update your email or Delete your account entirely through Workspace settings. When using Streamlit Community Cloud, you have two identities behind your account: a primary identity (Google or email) and source control (GitHub). Your primary identity allows other users to share private apps with you and grant you access to their analytics. Your source control identity allows you to deploy apps from GitHub repositories and manage them through your Streamlit Community Cloud workspace. Access your workspace settings To manage your account, sign in to share.streamlit.io and click ""Settings"" in the top right corner to access your workspace settings. Learn more about how to Update your email and Delete your account.Previous: Share your appNext: Sign in & sign outforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy" https://docs.streamlit.io/develop/api-reference/charts/st.bar_chart#elementadd_rows,"DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceremovePAGE ELEMENTSWrite and magicaddText elementsaddData elementsaddChart elementsremoveSIMPLEst.area_chartst.bar_chartst.line_chartst.mapst.scatter_chartADVANCEDst.altair_chartst.bokeh_chartst.graphviz_chartst.plotly_chartst.pydeck_chartst.pyplotst.vega_lite_chartInput widgetsaddMedia elementsaddLayouts and containersaddChat elementsaddStatus elementsaddThird-party componentsopen_in_newAPPLICATION LOGICNavigation and pagesaddExecution flowaddCaching and stateaddConnections and secretsaddCustom componentsaddUtilitiesaddConfigurationaddTOOLSApp testingaddCommand lineaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Develop/API reference/Chart elements/st.bar_chartst.bar_chartStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeDisplay a bar chart. This is syntax-sugar around st.altair_chart. The main difference is this command uses the data's own column and indices to figure out the chart's spec. As a result this is easier to use for many ""just plot this"" scenarios, while being less customizable. If st.bar_chart does not guess the data specification correctly, try specifying your desired chart using st.altair_chart. Function signature[source] st.bar_chart(data=None, *, x=None, y=None, color=None, width=0, height=0, use_container_width=True) Parameters data (pandas.DataFrame, pandas.Styler, pyarrow.Table, numpy.ndarray, pyspark.sql.DataFrame, snowflake.snowpark.dataframe.DataFrame, snowflake.snowpark.table.Table, Iterable, or dict) Data to be plotted. x (str or None) Column name to use for the x-axis. If None, uses the data index for the x-axis. y (str, Sequence of str, or None) Column name(s) to use for the y-axis. If a Sequence of strings, draws several series on the same chart by melting your wide-format table into a long-format table behind the scenes. If None, draws the data of all remaining columns as data series. color (str, tuple, Sequence of str, Sequence of tuple, or None) The color to use for different series in this chart. For a bar chart with just one series, this can be: None, to use the default color. A hex string like ""#ffaa00"" or ""#ffaa0088"". An RGB or RGBA tuple with the red, green, blue, and alpha components specified as ints from 0 to 255 or floats from 0.0 to 1.0. For a bar chart with multiple series, where the dataframe is in long format (that is, y is None or just one column), this can be: None, to use the default colors. The name of a column in the dataset. Data points will be grouped into series of the same color based on the value of this column. In addition, if the values in this column match one of the color formats above (hex string or color tuple), then that color will be used. For example: if the dataset has 1000 rows, but this column only contains the values ""adult"", ""child"", and ""baby"", then those 1000 datapoints will be grouped into three series whose colors will be automatically selected from the default palette. But, if for the same 1000-row dataset, this column contained the values ""#ffaa00"", ""#f0f"", ""#0000ff"", then then those 1000 datapoints would still be grouped into 3 series, but their colors would be ""#ffaa00"", ""#f0f"", ""#0000ff"" this time around. For a bar chart with multiple series, where the dataframe is in wide format (that is, y is a Sequence of columns), this can be: None, to use the default colors. A list of string colors or color tuples to be used for each of the series in the chart. This list should have the same length as the number of y values (e.g. color=[""#fd0"", ""#f0f"", ""#04f""] for three lines). width (int) The chart width in pixels. If 0, selects the width automatically. height (int) The chart height in pixels. If 0, selects the height automatically. use_container_width (bool) If True, set the chart width to the column width. This takes precedence over the width argument. Examples import streamlit as st import pandas as pd import numpy as np chart_data = pd.DataFrame(np.random.randn(20, 3), columns=[""a"", ""b"", ""c""]) st.bar_chart(chart_data) Built with Streamlit 🎈Fullscreen open_in_new You can also choose different columns to use for x and y, as well as set the color dynamically based on a 3rd column (assuming your dataframe is in long format): import streamlit as st import pandas as pd import numpy as np chart_data = pd.DataFrame( { ""col1"": list(range(20)) * 3, ""col2"": np.random.randn(60), ""col3"": [""A""] * 20 + [""B""] * 20 + [""C""] * 20, } ) st.bar_chart(chart_data, x=""col1"", y=""col2"", color=""col3"") Built with Streamlit 🎈Fullscreen open_in_new Finally, if your dataframe is in wide format, you can group multiple columns under the y argument to show multiple series with different colors: import streamlit as st import pandas as pd import numpy as np chart_data = pd.DataFrame( {""col1"": list(range(20)), ""col2"": np.random.randn(20), ""col3"": np.random.randn(20)} ) st.bar_chart( chart_data, x=""col1"", y=[""col2"", ""col3""], color=[""#FF0000"", ""#0000FF""] # Optional ) Built with Streamlit 🎈Fullscreen open_in_new element.add_rowsStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeConcatenate a dataframe to the bottom of the current one. Function signature[source] element.add_rows(data=None, **kwargs) Parameters data (pandas.DataFrame, pandas.Styler, pyarrow.Table, numpy.ndarray, pyspark.sql.DataFrame, snowflake.snowpark.dataframe.DataFrame, Iterable, dict, or None) Table to concat. Optional. **kwargs (pandas.DataFrame, numpy.ndarray, Iterable, dict, or None) The named dataset to concat. Optional. You can only pass in 1 dataset (including the one in the data parameter). Example import streamlit as st import pandas as pd import numpy as np df1 = pd.DataFrame(np.random.randn(50, 20), columns=(""col %d"" % i for i in range(20))) my_table = st.table(df1) df2 = pd.DataFrame(np.random.randn(50, 20), columns=(""col %d"" % i for i in range(20))) my_table.add_rows(df2) # Now the table shown in the Streamlit app contains the data for # df1 followed by the data for df2. You can do the same thing with plots. For example, if you want to add more data to a line chart: # Assuming df1 and df2 from the example above still exist... my_chart = st.line_chart(df1) my_chart.add_rows(df2) # Now the chart shown in the Streamlit app contains the data for # df1 followed by the data for df2. And for plots whose datasets are named, you can pass the data with a keyword argument where the key is the name: my_chart = st.vega_lite_chart({ 'mark': 'line', 'encoding': {'x': 'a', 'y': 'b'}, 'datasets': { 'some_fancy_name': df1, # <-- named dataset }, 'data': {'name': 'some_fancy_name'}, }), my_chart.add_rows(some_fancy_name=df2) # <-- name used as keyword Previous: st.area_chartNext: st.line_chartforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy" https://docs.streamlit.io/develop/concepts/design/dataframes#stdataframe-ui-features,"DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsremoveCOREArchitecture & executionaddMultipage appsaddApp designremoveAnimate & update elementsButton behavior and examplesDataframesUsing custom classesWorking with timezonesADDITIONALConnections and secretsaddCustom componentsaddConfiguration and themingaddApp testingaddAPI referenceaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Develop/Concepts/App design/DataframesDataframes Dataframes are a great way to display and edit data in a tabular format. Working with Pandas DataFrames and other tabular data structures is key to data science workflows. If developers and data scientists want to display this data in Streamlit, they have multiple options: st.dataframe and st.data_editor. If you want to solely display data in a table-like UI, st.dataframe is the way to go. If you want to interactively edit data, use st.data_editor. We explore the use cases and advantages of each option in the following sections. Display dataframes with st.dataframe Streamlit can display dataframes in a table-like UI via st.dataframe : import streamlit as st import pandas as pd df = pd.DataFrame( [ {""command"": ""st.selectbox"", ""rating"": 4, ""is_widget"": True}, {""command"": ""st.balloons"", ""rating"": 5, ""is_widget"": False}, {""command"": ""st.time_input"", ""rating"": 3, ""is_widget"": True}, ] ) st.dataframe(df, use_container_width=True) Built with Streamlit 🎈Fullscreen open_in_new st.dataframe UI features st.dataframe provides additional functionality by using glide-data-grid under the hood: Column sorting: Sort columns by clicking on their headers. Column resizing: Resize columns by dragging and dropping column header borders. Table resizing: Resize tables by dragging and dropping the bottom right corner. Fullscreen view: Enlarge tables to fullscreen by clicking the fullscreen icon (fullscreen) in the toolbar. Search: Click the search icon (search) in the toolbar or use hotkeys (⌘+F or Ctrl+F) to search through the data. Download: Click the download icon in the toolbar to download the data as a CSV file. Copy to clipboard: Select one or multiple cells, copy them to the clipboard (⌘+C or Ctrl+C), and paste them into your favorite spreadsheet software. Try out all the UI features using the embedded app from the prior section. In addition to Pandas DataFrames, st.dataframe also supports other common Python types, e.g., list, dict, or numpy array. It also supports Snowpark and PySpark DataFrames, which allow you to lazily evaluate and pull data from databases. This can be useful for working with large datasets. Edit data with st.data_editor Streamlit supports editable dataframes via the st.data_editor command. Check out its API in st.data_editor. It shows the dataframe in a table, similar to st.dataframe. But in contrast to st.dataframe, this table isn't static! The user can click on cells and edit them. The edited data is then returned on the Python side. Here's an example: df = pd.DataFrame( [ {""command"": ""st.selectbox"", ""rating"": 4, ""is_widget"": True}, {""command"": ""st.balloons"", ""rating"": 5, ""is_widget"": False}, {""command"": ""st.time_input"", ""rating"": 3, ""is_widget"": True}, ] ) edited_df = st.data_editor(df) # 👈 An editable dataframe favorite_command = edited_df.loc[edited_df[""rating""].idxmax()][""command""] st.markdown(f""Your favorite command is **{favorite_command}** 🎈"") Built with Streamlit 🎈Fullscreen open_in_new Try it out by double-clicking on any cell. You'll notice you can edit all cell values. Try editing the values in the rating column and observe how the text output at the bottom changes: st.data_editor UI features st.data_editor also supports a few additional things: Add and delete rows: You can do this by setting num_rows= ""dynamic"" when calling st.data_editor. This will allow users to add and delete rows as needed. Copy and paste support: Copy and paste both between st.data_editor and spreadsheet software like Google Sheets and Excel. Access edited data: Access only the individual edits instead of the entire edited data structure via Session State. Bulk edits: Similar to Excel, just drag a handle to edit neighboring cells. Automatic input validation: Column Configuration provides strong data type support and other configurable options. For example, there's no way to enter letters into a number cell. Number cells can have a designated min and max. Edit common data structures: st.data_editor supports lists, dicts, NumPy ndarray, and more! Add and delete rows With st.data_editor, viewers can add or delete rows via the table UI. This mode can be activated by setting the num_rows parameter to ""dynamic"": edited_df = st.data_editor(df, num_rows=""dynamic"") To add new rows, click the plus icon (add) in the toolbar. Alternatively, click inside a shaded cell below the bottom row of the table. To delete rows, select one or more rows using the checkboxes on the left. Click the delete icon (delete) or press the delete key on your keyboard. Built with Streamlit 🎈Fullscreen open_in_new Copy and paste support The data editor supports pasting in tabular data from Google Sheets, Excel, Notion, and many other similar tools. You can also copy-paste data between st.data_editor instances. This functionality, powered by the Clipboard API, can be a huge time saver for users who need to work with data across multiple platforms. To try it out: Copy data from this Google Sheets document to your clipboard. Single click any cell in the name column in the app above. Paste it in using hotkeys (⌘+V or Ctrl+V). push_pinNoteEvery cell of the pasted data will be evaluated individually and inserted into the cells if the data is compatible with the column type. For example, pasting in non-numerical text data into a number column will be ignored. starTipIf you embed your apps with iframes, you'll need to allow the iframe to access the clipboard if you want to use the copy-paste functionality. To do so, give the iframe clipboard-write and clipboard-read permissions. E.g. As developers, ensure the app is served with a valid, trusted certificate when using TLS. If users encounter issues with copying and pasting data, direct them to check if their browser has activated clipboard access permissions for the Streamlit application, either when prompted or through the browser's site settings. Access edited data Sometimes, it is more convenient to know which cells have been changed rather than getting the entire edited dataframe back. Streamlit makes this easy through the use of Session State. If a key parameter is set, Streamlit will store any changes made to the dataframe in Session State. This snippet shows how you can access changed data using Session State: st.data_editor(df, key=""my_key"", num_rows=""dynamic"") # 👈 Set a key st.write(""Here's the value in Session State:"") st.write(st.session_state[""my_key""]) # 👈 Show the value in Session State In this code snippet, the key parameter is set to ""my_key"". After the data editor is created, the value associated to ""my_key"" in Session State is displayed in the app using st.write. This shows the additions, edits, and deletions that were made. This can be useful when working with large dataframes and you only need to know which cells have changed, rather than access the entire edited dataframe. Built with Streamlit 🎈Fullscreen open_in_new Use all we've learned so far and apply them to the above embedded app. Try editing cells, adding new rows, and deleting rows. Notice how edits to the table are reflected in Session State. When you make any edits, a rerun is triggered which sends the edits to the backend. The widget's state is a JSON object containing three properties: edited_rows, added_rows, and deleted rows:. priority_highWarningWhen going from st.experimental_data_editor to st.data_editor in 1.23.0, the data editor's representation in st.session_state was changed. The edited_cells dictionary is now called edited_rows and uses a different format ({0: {""column name"": ""edited value""}} instead of {""0:1"": ""edited value""}). You may need to adjust your code if your app uses st.experimental_data_editor in combination with st.session_state."" edited_rows is a dictionary containing all edits. Keys are zero-based row indices and values are dictionaries that map column names to edits (e.g. {0: {""col1"": ..., ""col2"": ...}}). added_rows is a list of newly added rows. Each value is a dictionary with the same format as above (e.g. [{""col1"": ..., ""col2"": ...}]). deleted_rows is a list of row numbers that have been deleted from the table (e.g. [0, 2]). st.data_editor does not support reordering rows, so added rows will always be appended to the end of the dataframe with any edits and deletions applicable to the original rows. Bulk edits The data editor includes a feature that allows for bulk editing of cells. Similar to Excel, you can drag a handle across a selection of cells to edit their values in bulk. You can even apply commonly used keyboard shortcuts in spreadsheet software. This is useful when you need to make the same change across multiple cells, rather than editing each cell individually. Edit common data structures Editing doesn't just work for Pandas DataFrames! You can also edit lists, tuples, sets, dictionaries, NumPy arrays, or Snowpark & PySpark DataFrames. Most data types will be returned in their original format. But some types (e.g. Snowpark and PySpark) are converted to Pandas DataFrames. To learn about all the supported types, read the st.data_editor API. For example, you can easily let the user add items to a list: edited_list = st.data_editor([""red"", ""green"", ""blue""], num_rows= ""dynamic"") st.write(""Here are all the colors you entered:"") st.write(edited_list) Or numpy arrays: import numpy as np st.data_editor(np.array([ [""st.text_area"", ""widget"", 4.92], [""st.markdown"", ""element"", 47.22] ])) Or lists of records: st.data_editor([ {""name"": ""st.text_area"", ""type"": ""widget""}, {""name"": ""st.markdown"", ""type"": ""element""}, ]) Or dictionaries and many more types! st.data_editor({ ""st.text_area"": ""widget"", ""st.markdown"": ""element"" }) Automatic input validation The data editor includes automatic input validation to help prevent errors when editing cells. For example, if you have a column that contains numerical data, the input field will automatically restrict the user to only entering numerical data. This helps to prevent errors that could occur if the user were to accidentally enter a non-numerical value. Additional input validation can be configured through the Column configuration API. Keep reading below for an overview of column configuration, including validation options. Configuring columns You can configure the display and editing behavior of columns in st.dataframe and st.data_editor via the Column configuration API. We have developed the API to let you add images, charts, and clickable URLs in dataframe and data editor columns. Additionally, you can make individual columns editable, set columns as categorical and specify which options they can take, hide the index of the dataframe, and much more. Column configuration includes the following column types: Text, Number, Checkbox, Selectbox, Date, Time, Datetime, List, Link, Image, Line chart, Bar chart, and Progress. There is also a generic Column option. See the embedded app below to view these different column types. Each column type is individually previewed in the Column configuration API documentation. Built with Streamlit 🎈Fullscreen open_in_new Format values A format parameter is available in column configuration for Text, Date, Time, and Datetime columns. Chart-like columns can also be formatted. Line chart and Bar chart columns have a y_min and y_max parameters to set the vertical bounds. For a Progress column, you can declare the horizontal bounds with min_value and max_value. Validate input When specifying a column configuration, you can declare not only the data type of the column but also value restrictions. All column configuration elements allow you to make a column required with the keyword parameter required=True. For Text and Link columns, you can specify the maximum number of characters with max_chars or use regular expressions to validate entries through validate. Numerical columns, including Number, Date, Time, and Datetime have min_value and max_value parameters. Selectbox columns have a configurable list of options. The data type for Number columns is float by default. Passing a value of type int to any of min_value, max_value, step, or default will set the type for the column as int. Configure an empty dataframe You can use st.data_editor to collect tabular input from a user. When starting from an empty dataframe, default column types are text. Use column configuration to specify the data types you want to collect from users. import streamlit as st import pandas as pd df = pd.DataFrame(columns=['name','age','color']) colors = ['red', 'orange', 'yellow', 'green', 'blue', 'indigo', 'violet'] config = { 'name' : st.column_config.TextColumn('Full Name (required)', width='large', required=True), 'age' : st.column_config.NumberColumn('Age (years)', min_value=0, max_value=122), 'color' : st.column_config.SelectboxColumn('Favorite Color', options=colors) } result = st.data_editor(df, column_config = config, num_rows='dynamic') if st.button('Get results'): st.write(result) Built with Streamlit 🎈Fullscreen open_in_new Additional formatting options In addition to column configuration, st.dataframe and st.data_editor have a few more parameters to customize the display of your dataframe. hide_index : Set to True to hide the dataframe's index. column_order : Pass a list of column labels to specify the order of display. disabled : Pass a list of column labels to disable them from editing. This let's you avoid disabling them individually. Handling large datasets st.dataframe and st.data_editor have been designed to theoretically handle tables with millions of rows thanks to their highly performant implementation using the glide-data-grid library and HTML canvas. However, the maximum amount of data that an app can realistically handle will depend on several other factors, including: The maximum size of WebSocket messages: Streamlit's WebSocket messages are configurable via the server.maxMessageSize config option, which limits the amount of data that can be transferred via the WebSocket connection at once. The server memory: The amount of data that your app can handle will also depend on the amount of memory available on your server. If the server's memory is exceeded, the app may become slow or unresponsive. The user's browser memory: Since all the data needs to be transferred to the user's browser for rendering, the amount of memory available on the user's device can also affect the app's performance. If the browser's memory is exceeded, it may crash or become unresponsive. In addition to these factors, a slow network connection can also significantly slow down apps that handle large datasets. When handling large datasets with more than 150,000 rows, Streamlit applies additional optimizations and disables column sorting. This can help to reduce the amount of data that needs to be processed at once and improve the app's performance. Limitations Streamlit casts all column names to strings internally, so st.data_editor will return a DataFrame where all column names are strings. The dataframe toolbar is not currently configurable. While Streamlit's data editing capabilities offer a lot of functionality, editing is enabled for a limited set of column types (TextColumn, NumberColumn, LinkColumn, CheckboxColumn, SelectboxColumn, DateColumn, TimeColumn, and DatetimeColumn). We are actively working on supporting editing for other column types as well, such as images, lists, and charts. Almost all editable datatypes are supported for index editing. However, pandas.CategoricalIndex and pandas.MultiIndex are not supported for editing. Sorting is not supported for st.data_editor when num_rows=""dynamic"". Sorting is deactivated to optimize performance on large datasets with more than 150,000 rows. We are continually working to improve Streamlit's handling of DataFrame and add functionality to data editing, so keep an eye out for updates.Previous: Button behavior and examplesNext: Using custom classesforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy" https://docs.streamlit.io/knowledge-base/deploy/authentication-without-sso#step-1-add-the-password-to-your-local-app-secrets,"DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Knowledge base/Deployment issues/Authentication without SSOAuthentication without SSO Introduction Want to secure your Streamlit app with passwords, but cannot implement single sign-on? We got you covered! This guide shows you two simple techniques for adding basic authentication to your Streamlit app, using Secrets management. priority_highWarningWhile this technique adds some level of security, it is NOT comparable to proper authentication with an SSO provider. Option 1: One global password for all users This is the easiest option! Your app will ask for a password that's shared between all users. It will be stored in the app secrets using Secrets management. If you want to change this password or revoke a user's access, you will need to change it for everyone. If you want to have one password per user instead, jump to Option 2 below. Step 1: Add the password to your local app secrets Your local Streamlit app will read secrets from a file .streamlit/secrets.toml in your app's root dir. Create this file if it doesn't exist yet and add your password to it as shown below: # .streamlit/secrets.toml password = ""streamlit123"" priority_highImportantBe sure to add this file to your .gitignore so you don't commit your secrets! Step 2: Copy your app secrets to the cloud As the secrets.toml file above is not committed to GitHub, you need to pass its content to your deployed app (on Streamlit Community Cloud) separately. Go to the app dashboard and in the app's dropdown menu, click on Edit Secrets. Copy the content of secrets.toml into the text area. More information is available at Secrets management. Step 3: Ask for the password in your Streamlit app Copy the code below to your Streamlit app, insert your normal app code below the check_password() function call at the bottom, and run it: # streamlit_app.py import hmac import streamlit as st def check_password(): """"""Returns `True` if the user had the correct password."""""" def password_entered(): """"""Checks whether a password entered by the user is correct."""""" if hmac.compare_digest(st.session_state[""password""], st.secrets[""password""]): st.session_state[""password_correct""] = True del st.session_state[""password""] # Don't store the password. else: st.session_state[""password_correct""] = False # Return True if the password is validated. if st.session_state.get(""password_correct"", False): return True # Show input for password. st.text_input( ""Password"", type=""password"", on_change=password_entered, key=""password"" ) if ""password_correct"" in st.session_state: st.error(""😕 Password incorrect"") return False if not check_password(): st.stop() # Do not continue if check_password is not True. # Main Streamlit app starts here st.write(""Here goes your normal Streamlit app..."") st.button(""Click me"") If everything worked out, your app should look like this: Option 2: Individual password for each user This option allows you to set a username and password for each user of your app. Like in Option 1, both values will be stored in the app secrets using Secrets management. Step 1: Add usernames & passwords to your local app secrets Your local Streamlit app will read secrets from a file .streamlit/secrets.toml in your app's root dir. Create this file if it doesn't exist yet and add the usernames & password to it as shown below: # .streamlit/secrets.toml [passwords] # Follow the rule: username = ""password"" alice_foo = ""streamlit123"" bob_bar = ""mycrazypw"" priority_highImportantBe sure to add this file to your .gitignore so you don't commit your secrets! Alternatively, you could set up and manage usernames & passwords via a spreadsheet or database. To use secrets to securely connect to Google Sheets, AWS, and other data providers, read our tutorials on how to Connect Streamlit to data sources. Step 2: Copy your app secrets to the cloud As the secrets.toml file above is not committed to GitHub, you need to pass its content to your deployed app (on Streamlit Community Cloud) separately. Go to the app dashboard and in the app's dropdown menu, click on Edit Secrets. Copy the content of secrets.toml into the text area. More information is available at Secrets management. Step 3: Ask for username & password in your Streamlit app Copy the code below to your Streamlit app, insert your normal app code below the check_password() function call at the bottom, and run it: # streamlit_app.py import hmac import streamlit as st def check_password(): """"""Returns `True` if the user had a correct password."""""" def login_form(): """"""Form with widgets to collect user information"""""" with st.form(""Credentials""): st.text_input(""Username"", key=""username"") st.text_input(""Password"", type=""password"", key=""password"") st.form_submit_button(""Log in"", on_click=password_entered) def password_entered(): """"""Checks whether a password entered by the user is correct."""""" if st.session_state[""username""] in st.secrets[ ""passwords"" ] and hmac.compare_digest( st.session_state[""password""], st.secrets.passwords[st.session_state[""username""]], ): st.session_state[""password_correct""] = True del st.session_state[""password""] # Don't store the username or password. del st.session_state[""username""] else: st.session_state[""password_correct""] = False # Return True if the username + password is validated. if st.session_state.get(""password_correct"", False): return True # Show inputs for username + password. login_form() if ""password_correct"" in st.session_state: st.error(""😕 User not known or password incorrect"") return False if not check_password(): st.stop() # Main Streamlit app starts here st.write(""Here goes your normal Streamlit app..."") st.button(""Click me"") If everything worked out, your app should look like this: Previous: Deployment issuesNext: How can I deploy multiple Streamlit apps on different subdomains?forumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy" https://docs.streamlit.io/en/0.76.0/api.html#write-and-magic,"DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceremovePAGE ELEMENTSWrite and magicaddText elementsaddData elementsaddChart elementsaddInput widgetsaddMedia elementsaddLayouts and containersaddChat elementsaddStatus elementsaddThird-party componentsopen_in_newAPPLICATION LOGICNavigation and pagesaddExecution flowaddCaching and stateaddConnections and secretsaddCustom componentsaddUtilitiesaddConfigurationaddTOOLSApp testingaddCommand lineaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Develop/API referenceAPI reference Streamlit makes it easy for you to visualize, mutate, and share data. The API reference is organized by activity type, like displaying data or optimizing performance. Each section includes methods associated with the activity type, including examples. Browse our API below and click to learn more about any of our available commands! 🎈 Display almost anything Write and magic st.writeWrite arguments to the app.st.write(""Hello **world**!"") st.write(my_data_frame) st.write(my_mpl_figure) st.write_streamWrite generators or streams to the app with a typewriter effect.st.write_stream(my_generator) st.write_stream(my_llm_stream) MagicAny time Streamlit sees either a variable or literal value on its own line, it automatically writes that to your app using st.write""Hello **world**!"" my_data_frame my_mpl_figure Text elements MarkdownDisplay string formatted as Markdown.st.markdown(""Hello **world**!"") TitleDisplay text in title formatting.st.title(""The app title"") HeaderDisplay text in header formatting.st.header(""This is a header"") SubheaderDisplay text in subheader formatting.st.subheader(""This is a subheader"") CaptionDisplay text in small font.st.caption(""This is written small caption text"") Code blockDisplay a code block with optional syntax highlighting.st.code(""a = 1234"") EchoDisplay some code in the app, then execute it. Useful for tutorials.with st.echo(): st.write('This code will be printed') LaTeXDisplay mathematical expressions formatted as LaTeX.st.latex(""\int a x^2 \,dx"") Preformatted textWrite fixed-width and preformatted text.st.text(""Hello world"") DividerDisplay a horizontal rule.st.divider() Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration! PreviousTagsAdd tags to your Streamlit apps. Created by @gagan3012.st_tags(label='# Enter Keywords:', text='Press enter to add more', value=['Zero', 'One', 'Two'], suggestions=['five', 'six', 'seven', 'eight', 'nine', 'three', 'eleven', 'ten', 'four'], maxtags = 4, key='1') NLUApply text mining on a dataframe. Created by @JohnSnowLabs.nlu.load('sentiment').predict('I love NLU! <3') Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.mention(label=""An awesome Streamlit App"", icon=""streamlit"", url=""https://extras.streamlit.app"",) Annotated textDisplay annotated text in Streamlit apps. Created by @tvst.annotated_text(""This "", (""is"", ""verb""), "" some "", (""annotated"", ""adj""), (""text"", ""noun""), "" for those of "", (""you"", ""pronoun""), "" who "", (""like"", ""verb""), "" this sort of "", (""thing"", ""noun""), ""."") Drawable CanvasProvides a sketching canvas using Fabric.js. Created by @andfanilo.st_canvas(fill_color=""rgba(255, 165, 0, 0.3)"", stroke_width=stroke_width, stroke_color=stroke_color, background_color=bg_color, background_image=Image.open(bg_image) if bg_image else None, update_streamlit=realtime_update, height=150, drawing_mode=drawing_mode, point_display_radius=point_display_radius if drawing_mode == 'point' else 0, key=""canvas"",) TagsAdd tags to your Streamlit apps. Created by @gagan3012.st_tags(label='# Enter Keywords:', text='Press enter to add more', value=['Zero', 'One', 'Two'], suggestions=['five', 'six', 'seven', 'eight', 'nine', 'three', 'eleven', 'ten', 'four'], maxtags = 4, key='1') NLUApply text mining on a dataframe. Created by @JohnSnowLabs.nlu.load('sentiment').predict('I love NLU! <3') Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.mention(label=""An awesome Streamlit App"", icon=""streamlit"", url=""https://extras.streamlit.app"",) Annotated textDisplay annotated text in Streamlit apps. Created by @tvst.annotated_text(""This "", (""is"", ""verb""), "" some "", (""annotated"", ""adj""), (""text"", ""noun""), "" for those of "", (""you"", ""pronoun""), "" who "", (""like"", ""verb""), "" this sort of "", (""thing"", ""noun""), ""."") Drawable CanvasProvides a sketching canvas using Fabric.js. Created by @andfanilo.st_canvas(fill_color=""rgba(255, 165, 0, 0.3)"", stroke_width=stroke_width, stroke_color=stroke_color, background_color=bg_color, background_image=Image.open(bg_image) if bg_image else None, update_streamlit=realtime_update, height=150, drawing_mode=drawing_mode, point_display_radius=point_display_radius if drawing_mode == 'point' else 0, key=""canvas"",) TagsAdd tags to your Streamlit apps. Created by @gagan3012.st_tags(label='# Enter Keywords:', text='Press enter to add more', value=['Zero', 'One', 'Two'], suggestions=['five', 'six', 'seven', 'eight', 'nine', 'three', 'eleven', 'ten', 'four'], maxtags = 4, key='1') NLUApply text mining on a dataframe. Created by @JohnSnowLabs.nlu.load('sentiment').predict('I love NLU! <3') Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.mention(label=""An awesome Streamlit App"", icon=""streamlit"", url=""https://extras.streamlit.app"",) Next Data elements DataframesDisplay a dataframe as an interactive table.st.dataframe(my_data_frame) Data editorDisplay a data editor widget.edited = st.data_editor(df, num_rows=""dynamic"") Column configurationConfigure the display and editing behavior of dataframes and data editors.st.column_config.NumberColumn(""Price (in USD)"", min_value=0, format=""$%d"") Static tablesDisplay a static table.st.table(my_data_frame) MetricsDisplay a metric in big bold font, with an optional indicator of how the metric changed.st.metric(""My metric"", 42, 2) Dicts and JSONDisplay object or string as a pretty-printed JSON string.st.json(my_dict) Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration! PreviousImage CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates value = streamlit_image_coordinates(""https://placekitten.com/200/300"") st.write(value) Plotly EventsMake Plotly charts interactive!. Created by @null-jones.from streamlit_plotly_events import plotly_events fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.metric_cards import style_metric_cards col3.metric(label=""No Change"", value=5000, delta=0) style_metric_cards() Streamlit AggridImplementation of Ag-Grid component for Streamlit. Created by @PablocFonseca.df = pd.DataFrame({'col1': [1, 2, 3], 'col2': [4, 5, 6]}) grid_return = AgGrid(df, editable=True) new_df = grid_return['data'] Streamlit FoliumStreamlit Component for rendering Folium maps. Created by @randyzwitch.m = folium.Map(location=[39.949610, -75.150282], zoom_start=16) folium.Marker([39.949610, -75.150282], popup=""Liberty Bell"", tooltip=""Liberty Bell"").add_to(m) st_data = st_folium(m, width=725) Pandas ProfilingPandas profiling component for Streamlit. Created by @okld.df = pd.read_csv(""https://storage.googleapis.com/tf-datasets/titanic/train.csv"") pr = df.profile_report() st_profile_report(pr) Image CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates value = streamlit_image_coordinates(""https://placekitten.com/200/300"") st.write(value) Plotly EventsMake Plotly charts interactive!. Created by @null-jones.from streamlit_plotly_events import plotly_events fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.metric_cards import style_metric_cards col3.metric(label=""No Change"", value=5000, delta=0) style_metric_cards() Streamlit AggridImplementation of Ag-Grid component for Streamlit. Created by @PablocFonseca.df = pd.DataFrame({'col1': [1, 2, 3], 'col2': [4, 5, 6]}) grid_return = AgGrid(df, editable=True) new_df = grid_return['data'] Streamlit FoliumStreamlit Component for rendering Folium maps. Created by @randyzwitch.m = folium.Map(location=[39.949610, -75.150282], zoom_start=16) folium.Marker([39.949610, -75.150282], popup=""Liberty Bell"", tooltip=""Liberty Bell"").add_to(m) st_data = st_folium(m, width=725) Pandas ProfilingPandas profiling component for Streamlit. Created by @okld.df = pd.read_csv(""https://storage.googleapis.com/tf-datasets/titanic/train.csv"") pr = df.profile_report() st_profile_report(pr) Image CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates value = streamlit_image_coordinates(""https://placekitten.com/200/300"") st.write(value) Plotly EventsMake Plotly charts interactive!. Created by @null-jones.from streamlit_plotly_events import plotly_events fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.metric_cards import style_metric_cards col3.metric(label=""No Change"", value=5000, delta=0) style_metric_cards() Next Chart elements Simple area chartsDisplay an area chart.st.area_chart(my_data_frame) Simple bar chartsDisplay a bar chart.st.bar_chart(my_data_frame) Simple line chartsDisplay a line chart.st.line_chart(my_data_frame) Simple scatter chartsDisplay a line chart.st.scatter_chart(my_data_frame) Scatterplots on mapsDisplay a map with points on it.st.map(my_data_frame) MatplotlibDisplay a matplotlib.pyplot figure.st.pyplot(my_mpl_figure) AltairDisplay a chart using the Altair library.st.altair_chart(my_altair_chart) Vega-LiteDisplay a chart using the Vega-Lite library.st.vega_lite_chart(my_vega_lite_chart) PlotlyDisplay an interactive Plotly chart.st.plotly_chart(my_plotly_chart) BokehDisplay an interactive Bokeh chart.st.bokeh_chart(my_bokeh_chart) PyDeckDisplay a chart using the PyDeck library.st.pydeck_chart(my_pydeck_chart) GraphVizDisplay a graph using the dagre-d3 library.st.graphviz_chart(my_graphviz_spec) Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration! PreviousStreamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl(""https://assets5.lottiefiles.com/packages/lf20_V9t630.json"") st_lottie(lottie_hello, key=""hello"") Plotly EventsMake Plotly charts interactive!. Created by @null-jones.fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.chart += get_annotations_chart(annotations=[(""Mar 01, 2008"", ""Pretty good day for GOOG""), (""Dec 01, 2007"", ""Something's going wrong for GOOG & AAPL""), (""Nov 01, 2008"", ""Market starts again thanks to...""), (""Dec 01, 2009"", ""Small crash for GOOG after...""),],) st.altair_chart(chart, use_container_width=True) PlostA deceptively simple plotting library for Streamlit. Created by @tvst.import plost plost.line_chart(my_dataframe, x='time', y='stock_value', color='stock_name',) HiPlotHigh dimensional Interactive Plotting. Created by @facebookresearch.data = [{'dropout':0.1, 'lr': 0.001, 'loss': 10.0, 'optimizer': 'SGD'}, {'dropout':0.15, 'lr': 0.01, 'loss': 3.5, 'optimizer': 'Adam'}, {'dropout':0.3, 'lr': 0.1, 'loss': 4.5, 'optimizer': 'Adam'}] hip.Experiment.from_iterable(data).display() EChartsHigh dimensional Interactive Plotting. Created by @andfanilo.from streamlit_echarts import st_echarts st_echarts(options=options) Streamlit FoliumStreamlit Component for rendering Folium maps. Created by @randyzwitch.m = folium.Map(location=[39.949610, -75.150282], zoom_start=16) st_data = st_folium(m, width=725) Spacy-StreamlitspaCy building blocks and visualizers for Streamlit apps. Created by @explosion.models = [""en_core_web_sm"", ""en_core_web_md""] spacy_streamlit.visualize(models, ""Sundar Pichai is the CEO of Google."") Streamlit AgraphA Streamlit Graph Vis, based on react-grah-vis. Created by @ChrisDelClea.from streamlit_agraph import agraph, Node, Edge, Config agraph(nodes=nodes, edges=edges, config=config) Streamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl(""https://assets5.lottiefiles.com/packages/lf20_V9t630.json"") st_lottie(lottie_hello, key=""hello"") Plotly EventsMake Plotly charts interactive!. Created by @null-jones.fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.chart += get_annotations_chart(annotations=[(""Mar 01, 2008"", ""Pretty good day for GOOG""), (""Dec 01, 2007"", ""Something's going wrong for GOOG & AAPL""), (""Nov 01, 2008"", ""Market starts again thanks to...""), (""Dec 01, 2009"", ""Small crash for GOOG after...""),],) st.altair_chart(chart, use_container_width=True) PlostA deceptively simple plotting library for Streamlit. Created by @tvst.import plost plost.line_chart(my_dataframe, x='time', y='stock_value', color='stock_name',) HiPlotHigh dimensional Interactive Plotting. Created by @facebookresearch.data = [{'dropout':0.1, 'lr': 0.001, 'loss': 10.0, 'optimizer': 'SGD'}, {'dropout':0.15, 'lr': 0.01, 'loss': 3.5, 'optimizer': 'Adam'}, {'dropout':0.3, 'lr': 0.1, 'loss': 4.5, 'optimizer': 'Adam'}] hip.Experiment.from_iterable(data).display() EChartsHigh dimensional Interactive Plotting. Created by @andfanilo.from streamlit_echarts import st_echarts st_echarts(options=options) Streamlit FoliumStreamlit Component for rendering Folium maps. Created by @randyzwitch.m = folium.Map(location=[39.949610, -75.150282], zoom_start=16) st_data = st_folium(m, width=725) Spacy-StreamlitspaCy building blocks and visualizers for Streamlit apps. Created by @explosion.models = [""en_core_web_sm"", ""en_core_web_md""] spacy_streamlit.visualize(models, ""Sundar Pichai is the CEO of Google."") Streamlit AgraphA Streamlit Graph Vis, based on react-grah-vis. Created by @ChrisDelClea.from streamlit_agraph import agraph, Node, Edge, Config agraph(nodes=nodes, edges=edges, config=config) Streamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl(""https://assets5.lottiefiles.com/packages/lf20_V9t630.json"") st_lottie(lottie_hello, key=""hello"") Plotly EventsMake Plotly charts interactive!. Created by @null-jones.fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.chart += get_annotations_chart(annotations=[(""Mar 01, 2008"", ""Pretty good day for GOOG""), (""Dec 01, 2007"", ""Something's going wrong for GOOG & AAPL""), (""Nov 01, 2008"", ""Market starts again thanks to...""), (""Dec 01, 2009"", ""Small crash for GOOG after...""),],) st.altair_chart(chart, use_container_width=True) Next Input widgets ButtonDisplay a button widget.clicked = st.button(""Click me"") Download buttonDisplay a download button widget.st.download_button(""Download file"", file) Form buttonDisplay a form submit button. For use with st.form.st.form_submit_button(""Sign up"") Link buttonDisplay a link button.st.link_button(""Go to gallery"", url) Page linkDisplay a link to another page in a multipage app.st.page_link(""app.py"", label=""Home"", icon=""🏠"") st.page_link(""pages/profile.py"", label=""My profile"") CheckboxDisplay a checkbox widget.selected = st.checkbox(""I agree"") Color pickerDisplay a color picker widget.color = st.color_picker(""Pick a color"") MultiselectDisplay a multiselect widget. The multiselect widget starts as empty.choices = st.multiselect(""Buy"", [""milk"", ""apples"", ""potatoes""]) RadioDisplay a radio button widget.choice = st.radio(""Pick one"", [""cats"", ""dogs""]) SelectboxDisplay a select widget.choice = st.selectbox(""Pick one"", [""cats"", ""dogs""]) Select-sliderDisplay a slider widget to select items from a list.size = st.select_slider(""Pick a size"", [""S"", ""M"", ""L""]) ToggleDisplay a toggle widget.activated = st.toggle(""Activate"") Number inputDisplay a numeric input widget.choice = st.number_input(""Pick a number"", 0, 10) SliderDisplay a slider widget.number = st.slider(""Pick a number"", 0, 100) Date inputDisplay a date input widget.date = st.date_input(""Your birthday"") Time inputDisplay a time input widget.time = st.time_input(""Meeting time"") Chat inputDisplay a chat input widget.prompt = st.chat_input(""Say something"") if prompt: st.write(f""The user has sent: {prompt}"") Text-areaDisplay a multi-line text input widget.text = st.text_area(""Text to translate"") Text inputDisplay a single-line text input widget.name = st.text_input(""First name"") Data editorDisplay a data editor widget.edited = st.experimental_data_editor(df, num_rows=""dynamic"") File UploaderDisplay a file uploader widget.data = st.file_uploader(""Upload a CSV"") Camera inputDisplay a widget that allows users to upload images directly from a camera.image = st.camera_input(""Take a picture"") Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration! PreviousStreamlit ChatStreamlit Component for a Chatbot UI. Created by @AI-Yash.from streamlit_chat import message message(""My message"") message(""Hello bot!"", is_user=True) # align's the message to the right Streamlit Option MenuSelect a single item from a list of options in a menu. Created by @victoryhb.from streamlit_option_menu import option_menu option_menu(""Main Menu"", [""Home"", 'Settings'], icons=['house', 'gear'], menu_icon=""cast"", default_index=1) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.stoggle import stoggle stoggle( ""Click me!"", """"""🥷 Surprise! Here's some additional content"""""",) Streamlit ElementsCreate a draggable and resizable dashboard in Streamlit. Created by @okls.from streamlit_elements import elements, mui, html with elements(""new_element""): mui.Typography(""Hello world"") TagsAdd tags to your Streamlit apps. Created by @gagan3012.from streamlit_tags import st_tags st_tags(label='# Enter Keywords:', text='Press enter to add more', value=['Zero', 'One', 'Two'], suggestions=['five', 'six', 'seven', 'eight', 'nine', 'three', 'eleven', 'ten', 'four'], maxtags = 4, key='1') StqdmThe simplest way to handle a progress bar in streamlit app. Created by @Wirg.from stqdm import stqdm for _ in stqdm(range(50)): sleep(0.5) TimelineDisplay a Timeline in Streamlit apps using TimelineJS. Created by @innerdoc.from streamlit_timeline import timeline with open('example.json', ""r"") as f: timeline(f.read(), height=800) Camera input liveAlternative for st.camera_input which returns the webcam images live. Created by @blackary.from camera_input_live import camera_input_live image = camera_input_live() st.image(value) Streamlit AceAce editor component for Streamlit. Created by @okld.from streamlit_ace import st_ace content = st_ace() content Streamlit ChatStreamlit Component for a Chatbot UI. Created by @AI-Yash.from streamlit_chat import message message(""My message"") message(""Hello bot!"", is_user=True) # align's the message to the right Streamlit Option MenuSelect a single item from a list of options in a menu. Created by @victoryhb.from streamlit_option_menu import option_menu option_menu(""Main Menu"", [""Home"", 'Settings'], icons=['house', 'gear'], menu_icon=""cast"", default_index=1) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.stoggle import stoggle stoggle( ""Click me!"", """"""🥷 Surprise! Here's some additional content"""""",) Streamlit ElementsCreate a draggable and resizable dashboard in Streamlit. Created by @okls.from streamlit_elements import elements, mui, html with elements(""new_element""): mui.Typography(""Hello world"") TagsAdd tags to your Streamlit apps. Created by @gagan3012.from streamlit_tags import st_tags st_tags(label='# Enter Keywords:', text='Press enter to add more', value=['Zero', 'One', 'Two'], suggestions=['five', 'six', 'seven', 'eight', 'nine', 'three', 'eleven', 'ten', 'four'], maxtags = 4, key='1') StqdmThe simplest way to handle a progress bar in streamlit app. Created by @Wirg.from stqdm import stqdm for _ in stqdm(range(50)): sleep(0.5) TimelineDisplay a Timeline in Streamlit apps using TimelineJS. Created by @innerdoc.from streamlit_timeline import timeline with open('example.json', ""r"") as f: timeline(f.read(), height=800) Camera input liveAlternative for st.camera_input which returns the webcam images live. Created by @blackary.from camera_input_live import camera_input_live image = camera_input_live() st.image(value) Streamlit AceAce editor component for Streamlit. Created by @okld.from streamlit_ace import st_ace content = st_ace() content Streamlit ChatStreamlit Component for a Chatbot UI. Created by @AI-Yash.from streamlit_chat import message message(""My message"") message(""Hello bot!"", is_user=True) # align's the message to the right Streamlit Option MenuSelect a single item from a list of options in a menu. Created by @victoryhb.from streamlit_option_menu import option_menu option_menu(""Main Menu"", [""Home"", 'Settings'], icons=['house', 'gear'], menu_icon=""cast"", default_index=1) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.stoggle import stoggle stoggle( ""Click me!"", """"""🥷 Surprise! Here's some additional content"""""",) Next Media elements ImageDisplay an image or list of images.st.image(numpy_array) st.image(image_bytes) st.image(file) st.image(""https://example.com/myimage.jpg"") AudioDisplay an audio player.st.audio(numpy_array) st.audio(audio_bytes) st.audio(file) st.audio(""https://example.com/myaudio.mp3"", format=""audio/mp3"") VideoDisplay a video player.st.video(numpy_array) st.video(video_bytes) st.video(file) st.video(""https://example.com/myvideo.mp4"", format=""video/mp4"") Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration! PreviousStreamlit CropperA simple image cropper for Streamlit. Created by @turner-anderson.from streamlit_cropper import st_cropper st_cropper(img, realtime_update=realtime_update, box_color=box_color, aspect_ratio=aspect_ratio) Image CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates streamlit_image_coordinates(""https://placekitten.com/200/300"") Streamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl(""https://assets5.lottiefiles.com/packages/lf20_V9t630.json"") st_lottie(lottie_hello, key=""hello"") Streamlit WebrtcHandling and transmitting real-time video/audio streams with Streamlit. Created by @whitphx.from streamlit_webrtc import webrtc_streamer webrtc_streamer(key=""sample"") Drawable CanvasProvides a sketching canvas using Fabric.js. Created by @andfanilo.from streamlit_drawable_canvas import st_canvas st_canvas(fill_color=""rgba(255, 165, 0, 0.3)"", stroke_width=stroke_width, stroke_color=stroke_color, background_color=bg_color, background_image=Image.open(bg_image) if bg_image else None, update_streamlit=realtime_update, height=150, drawing_mode=drawing_mode, point_display_radius=point_display_radius if drawing_mode == 'point' else 0, key=""canvas"",) Image ComparisonCompare images with a slider using JuxtaposeJS. Created by @fcakyon.from streamlit_image_comparison import image_comparison image_comparison(img1=""image1.jpg"", img2=""image2.jpg"",) Streamlit CropperA simple image cropper for Streamlit. Created by @turner-anderson.from streamlit_cropper import st_cropper st_cropper(img, realtime_update=realtime_update, box_color=box_color, aspect_ratio=aspect_ratio) Image CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates streamlit_image_coordinates(""https://placekitten.com/200/300"") Streamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl(""https://assets5.lottiefiles.com/packages/lf20_V9t630.json"") st_lottie(lottie_hello, key=""hello"") Streamlit WebrtcHandling and transmitting real-time video/audio streams with Streamlit. Created by @whitphx.from streamlit_webrtc import webrtc_streamer webrtc_streamer(key=""sample"") Drawable CanvasProvides a sketching canvas using Fabric.js. Created by @andfanilo.from streamlit_drawable_canvas import st_canvas st_canvas(fill_color=""rgba(255, 165, 0, 0.3)"", stroke_width=stroke_width, stroke_color=stroke_color, background_color=bg_color, background_image=Image.open(bg_image) if bg_image else None, update_streamlit=realtime_update, height=150, drawing_mode=drawing_mode, point_display_radius=point_display_radius if drawing_mode == 'point' else 0, key=""canvas"",) Image ComparisonCompare images with a slider using JuxtaposeJS. Created by @fcakyon.from streamlit_image_comparison import image_comparison image_comparison(img1=""image1.jpg"", img2=""image2.jpg"",) Streamlit CropperA simple image cropper for Streamlit. Created by @turner-anderson.from streamlit_cropper import st_cropper st_cropper(img, realtime_update=realtime_update, box_color=box_color, aspect_ratio=aspect_ratio) Image CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates streamlit_image_coordinates(""https://placekitten.com/200/300"") Streamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl(""https://assets5.lottiefiles.com/packages/lf20_V9t630.json"") st_lottie(lottie_hello, key=""hello"") Next Layouts and containers ColumnsInsert containers laid out as side-by-side columns.col1, col2 = st.columns(2) col1.write(""this is column 1"") col2.write(""this is column 2"") ContainerInsert a multi-element container.c = st.container() st.write(""This will show last"") c.write(""This will show first"") c.write(""This will show second"") Modal dialogsInsert a modal dialog that can rerun independently from the rest of the script.@st.experimental_dialog(""Sign up"") def email_form(): name = st.text_input(""Name"") email = st.text_input(""Email"") EmptyInsert a single-element container.c = st.empty() st.write(""This will show last"") c.write(""This will be replaced"") c.write(""This will show first"") ExpanderInsert a multi-element container that can be expanded/collapsed.with st.expander(""Open to see more""): st.write(""This is more content"") PopoverInsert a multi-element popover container that can be opened/closed.with st.popover(""Settings""): st.checkbox(""Show completed"") SidebarDisplay items in a sidebar.st.sidebar.write(""This lives in the sidebar"") st.sidebar.button(""Click me!"") TabsInsert containers separated into tabs.tab1, tab2 = st.tabs([""Tab 1"", ""Tab2""]) tab1.write(""this is tab 1"") tab2.write(""this is tab 2"") Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration!Streamlit ElementsCreate a draggable and resizable dashboard in Streamlit. Created by @okls.from streamlit_elements import elements, mui, html with elements(""new_element""): mui.Typography(""Hello world"") PydanticAuto-generate Streamlit UI from Pydantic Models and Dataclasses. Created by @lukasmasuch.import streamlit_pydantic as sp sp.pydantic_form(key=""my_form"", model=ExampleModel) Streamlit PagesAn experimental version of Streamlit Multi-Page Apps. Created by @blackary.from st_pages import Page, show_pages, add_page_title show_pages([ Page(""streamlit_app.py"", ""Home"", ""🏠""), Page(""other_pages/page2.py"", ""Page 2"", "":books:""), ]) Chat elements Streamlit provides a few commands to help you build conversational apps. These chat elements are designed to be used in conjunction with each other, but you can also use them separately. st.chat_message lets you insert a chat message container into the app so you can display messages from the user or the app. Chat containers can contain other Streamlit elements, including charts, tables, text, and more. st.chat_input lets you display a chat input widget so the user can type in a message. Chat inputDisplay a chat input widget.prompt = st.chat_input(""Say something"") if prompt: st.write(f""The user has sent: {prompt}"") Chat messageInsert a chat message container.import numpy as np with st.chat_message(""user""): st.write(""Hello 👋"") st.line_chart(np.random.randn(30, 3)) Status containerDisplay output of long-running tasks in a container.with st.status('Running'): do_something_slow() st.write_streamWrite generators or streams to the app with a typewriter effect.st.write_stream(my_generator) st.write_stream(my_llm_stream) Status elements Progress barDisplay a progress bar.for i in range(101): st.progress(i) do_something_slow() SpinnerTemporarily displays a message while executing a block of code.with st.spinner(""Please wait...""): do_something_slow() Status containerDisplay output of long-running tasks in a container.with st.status('Running'): do_something_slow() ToastBriefly displays a toast message in the bottom-right corner.st.toast('Butter!', icon='🧈') BalloonsDisplay celebratory balloons!do_something() # Celebrate when all done! st.balloons() SnowflakesDisplay celebratory snowflakes!do_something() # Celebrate when all done! st.snow() Success boxDisplay a success message.st.success(""Match found!"") Info boxDisplay an informational message.st.info(""Dataset is updated every day at midnight."") Warning boxDisplay warning message.st.warning(""Unable to fetch image. Skipping..."") Error boxDisplay error message.st.error(""We encountered an error"") Exception outputDisplay an exception.e = RuntimeError(""This is an exception of type RuntimeError"") st.exception(e) Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration!StqdmThe simplest way to handle a progress bar in streamlit app. Created by @Wirg.from stqdm import stqdm for _ in stqdm(range(50)): sleep(0.5) Custom notification boxA custom notification box with the ability to close it out. Created by @Socvest.from streamlit_custom_notification_box import custom_notification_box styles = {'material-icons':{'color': 'red'}, 'text-icon-link-close-container': {'box-shadow': '#3896de 0px 4px'}, 'notification-text': {'':''}, 'close-button':{'':''}, 'link':{'':''}} custom_notification_box(icon='info', textDisplay='We are almost done with your registration...', externalLink='more info', url='#', styles=styles, key=""foo"") Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.let_it_rain import rain rain(emoji=""🎈"", font_size=54, falling_speed=5, animation_length=""infinite"",) App logic and configuration Navigation and pages Switch pageProgrammatically navigates to a specified page.st.switch_page(""pages/my_page.py"") Page linkDisplay a link to another page in a multipage app.st.page_link(""app.py"", label=""Home"", icon=""🏠"") st.page_link(""pages/profile.py"", label=""My profile"") Execution flow Modal dialogsInsert a modal dialog that can rerun independently from the rest of the script.@st.experimental_dialog(""Sign up"") def email_form(): name = st.text_input(""Name"") email = st.text_input(""Email"") FormsCreate a form that batches elements together with a “Submit"" button.with st.form(key='my_form'): name = st.text_input(""Name"") email = st.text_input(""Email"") st.form_submit_button(""Sign up"") Partial rerunsDefine a fragment to rerun independently from the rest of the script.@st.experimental_fragment(run_every=""10s"") def fragment(): df = get_data() st.line_chart(df) Rerun scriptRerun the script immediately.st.rerun() Stop executionStops execution immediately.st.stop() Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration!AutorefreshForce a refresh without tying up a script. Created by @kmcgrady.from streamlit_autorefresh import st_autorefresh st_autorefresh(interval=2000, limit=100, key=""fizzbuzzcounter"") PydanticAuto-generate Streamlit UI from Pydantic Models and Dataclasses. Created by @lukasmasuch.import streamlit_pydantic as sp sp.pydantic_form(key=""my_form"", model=ExampleModel) Streamlit PagesAn experimental version of Streamlit Multi-Page Apps. Created by @blackary.from st_pages import Page, show_pages, add_page_title show_pages([ Page(""streamlit_app.py"", ""Home"", ""🏠""), Page(""other_pages/page2.py"", ""Page 2"", "":books:""), ]) Caching and state Cache dataFunction decorator to cache functions that return data (e.g. dataframe transforms, database queries, ML inference).@st.cache_data def long_function(param1, param2): # Perform expensive computation here or # fetch data from the web here return data Cache resourceFunction decorator to cache functions that return global resources (e.g. database connections, ML models).@st.cache_resource def init_model(): # Return a global resource here return pipeline( ""sentiment-analysis"", model=""distilbert-base-uncased-finetuned-sst-2-english"" ) Session stateSession state is a way to share variables between reruns, for each user session.st.session_state['key'] = value Query parametersGet, set, or clear the query parameters that are shown in the browser's URL bar.st.query_params[key] = value st.query_params.clear() Connections and databases Setup your connection Create a connectionConnect to a data source or APIconn = st.connection('pets_db', type='sql') pet_owners = conn.query('select * from pet_owners') st.dataframe(pet_owners) Built-in connections SnowflakeConnectionA connection to Snowflake.conn = st.connection('snowflake') SQLConnectionA connection to a SQL database using SQLAlchemy.conn = st.connection('sql') Build your own connections Connection base classBuild your own connection with BaseConnection.class MyConnection(BaseConnection[myconn.MyConnection]): def _connect(self, **kwargs) -> MyConnection: return myconn.connect(**self._secrets, **kwargs) def query(self, query): return self._instance.query(query) Secrets management Secrets singletonAccess secrets from a local TOML file.key = st.secrets[""OpenAI_key""] Secrets fileSave your secrets in a per-project or per-profile TOML file.OpenAI_key = """" Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration!AuthenticatorA secure authentication module to validate user credentials. Created by @mkhorasani.import streamlit_authenticator as stauth authenticator = stauth.Authenticate( config['credentials'], config['cookie']['name'], config['cookie']['key'], config['cookie']['expiry_days'], config['preauthorized']) WS localStorageA simple synchronous way of accessing localStorage from your app. Created by @gagangoku.from streamlit_ws_localstorage import injectWebsocketCode ret = conn.setLocalStorageVal(key='k1', val='v1') st.write('ret: ' + ret) Streamlit Auth0The fastest way to provide comprehensive login inside Streamlit. Created by @conradbez.from auth0_component import login_button user_info = login_button(clientId, domain = domain) st.write(user_info) Custom Components Declare a componentCreate and register a custom component.st.components.v1.declare_component( ""custom_slider"", ""/frontend"", ) HTMLDisplay an HTML string in an iframe.st.components.v1.html( ""

Foo bar.

"" ) iframeLoad a remote URL in an iframe.st.components.v1.iframe( ""docs.streamlit.io"" ) Utilities and user info User infost.experimental_user returns information about the logged-in user of private apps on Streamlit Community Cloud.if st.experimental_user.email == ""foo@corp.com"": st.write(""Welcome back, "", st.experimental_user.email) else: st.write(""You are not authorized to view this page."") Get helpDisplay object’s doc string, nicely formatted.st.help(st.write) st.help(pd.DataFrame) Render HTMLRenders HTML strings to your app.css = """""" """""" st.html(css) Configuration Configuration fileConfigures the default settings for your app.your-project/ ├── .streamlit/ │ └── config.toml └── your_app.py Set page title, favicon, and moreConfigures the default settings of the page.st.set_page_config( page_title=""My app"", page_icon="":shark:"", ) Developer tools App testing st.testing.v1.AppTestst.testing.v1.AppTest simulates a running Streamlit app for testing.from streamlit.testing.v1 import AppTest at = AppTest.from_file(""streamlit_app.py"") at.secrets[""WORD""] = ""Foobar"" at.run() assert not at.exception at.text_input(""word"").input(""Bazbat"").run() assert at.warning[0].value == ""Try again."" AppTest.from_filest.testing.v1.AppTest.from_file initializes a simulated app from a file.from streamlit.testing.v1 import AppTest at = AppTest.from_file(""streamlit_app.py"") at.run() AppTest.from_stringst.testing.v1.AppTest.from_string initializes a simulated app from a string.from streamlit.testing.v1 import AppTest at = AppTest.from_string(app_script_as_string) at.run() AppTest.from_functionst.testing.v1.AppTest.from_function initializes a simulated app from a function.from streamlit.testing.v1 import AppTest at = AppTest.from_function(app_script_as_callable) at.run() BlockA representation of container elements, including: st.chat_message st.columns st.sidebar st.tabs The main body of the app. # at.sidebar returns a Block at.sidebar.button[0].click().run() assert not at.exception ElementThe base class for representation of all elements, including: st.title st.header st.markdown st.dataframe # at.title returns a sequence of Title # Title inherits from Element assert at.title[0].value == ""My awesome app"" ButtonA representation of st.button and st.form_submit_button.at.button[0].click().run() ChatInputA representation of st.chat_input.at.chat_input[0].set_value(""What is Streamlit?"").run() CheckboxA representation of st.checkbox.at.checkbox[0].check().run() ColorPickerA representation of st.color_picker.at.color_picker[0].pick(""#FF4B4B"").run() DateInputA representation of st.date_input.release_date = datetime.date(2023, 10, 26) at.date_input[0].set_value(release_date).run() MultiselectA representation of st.multiselect.at.multiselect[0].select(""New York"").run() NumberInputA representation of st.number_input.at.number_input[0].increment().run() RadioA representation of st.radio.at.radio[0].set_value(""New York"").run() SelectSliderA representation of st.select_slider.at.select_slider[0].set_range(""A"",""C"").run() SelectboxA representation of st.selectbox.at.selectbox[0].select(""New York"").run() SliderA representation of st.slider.at.slider[0].set_range(2,5).run() TextAreaA representation of st.text_area.at.text_area[0].input(""Streamlit is awesome!"").run() TextInputA representation of st.text_input.at.text_input[0].input(""Streamlit"").run() TimeInputA representation of st.time_input.at.time_input[0].increment().run() ToggleA representation of st.toggle.at.toggle[0].set_value(""True"").run() Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration!Pandas ProfilingPandas profiling component for Streamlit. Created by @okld.df = pd.read_csv(""https://storage.googleapis.com/tf-datasets/titanic/train.csv"") pr = df.profile_report() st_profile_report(pr) Streamlit AceAce editor component for Streamlit. Created by @okld.from streamlit_ace import st_ace content = st_ace() content Streamlit AnalyticsTrack & visualize user interactions with your streamlit app. Created by @jrieke.import streamlit_analytics with streamlit_analytics.track(): st.text_input(""Write something"") Previous: ConceptsNext: Write and magicforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy" https://docs.streamlit.io/develop/concepts/design/custom-classes#patterns-to-define-your-custom-classes,"DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsremoveCOREArchitecture & executionaddMultipage appsaddApp designremoveAnimate & update elementsButton behavior and examplesDataframesUsing custom classesWorking with timezonesADDITIONALConnections and secretsaddCustom componentsaddConfiguration and themingaddApp testingaddAPI referenceaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Develop/Concepts/App design/Using custom classesUsing custom Python classes in your Streamlit app If you are building a complex Streamlit app or working with existing code, you may have custom Python classes defined in your script. Common examples include the following: Defining a @dataclass to store related data within your app. Defining an Enum class to represent a fixed set of options or values. Defining custom interfaces to external services or databases not covered by st.connection. Because Streamlit reruns your script after every user interaction, custom classes may be redefined multiple times within the same Streamlit session. This may result in unwanted effects, especially with class and instance comparisons. Read on to understand this common pitfall and how to avoid it. We begin by covering some general-purpose patterns you can use for different types of custom classes, and follow with a few more technical details explaining why this matters. Finally, we go into more detail about Using Enum classes specifically, and describe a configuration option which can make them more convenient. Patterns to define your custom classes Pattern 1: Define your class in a separate module This is the recommended, general solution. If possible, move class definitions into their own module file and import them into your app script. As long as you are not editing the file where your class is defined, Streamlit will not re-import it with each rerun. Therefore, if a class is defined in an external file and imported into your script, the class will not be redefined during the session. Example: Move your class definition Try running the following Streamlit app where MyClass is defined within the page's script. isinstance() will return True on the first script run then return False on each rerun thereafter. # app.py import streamlit as st # MyClass gets redefined every time app.py reruns class MyClass: def __init__(self, var1, var2): self.var1 = var1 self.var2 = var2 if ""my_instance"" not in st.session_state: st.session_state.my_instance = MyClass(""foo"", ""bar"") # Displays True on the first run then False on every rerun st.write(isinstance(st.session_state.my_instance, MyClass)) st.button(""Rerun"") If you move the class definition out of app.py into another file, you can make isinstance() consistently return True. Consider the following file structure: myproject/ ├── my_class.py └── app.py # my_class.py class MyClass: def __init__(self, var1, var2): self.var1 = var1 self.var2 = var2 # app.py import streamlit as st from my_class import MyClass # MyClass doesn't get redefined with each rerun if ""my_instance"" not in st.session_state: st.session_state.my_instance = MyClass(""foo"", ""bar"") # Displays True on every rerun st.write(isinstance(st.session_state.my_instance, MyClass)) st.button(""Rerun"") Streamlit only reloads code in imported modules when it detects the code has changed. Thus, if you are actively editing the file where your class is defined, you may need to stop and restart your Streamlit server to avoid an undesirable class redefinition mid-session. Pattern 2: Force your class to compare internal values For classes that store data (like dataclasses), you may be more interested in comparing the internally stored values rather than the class itself. If you define a custom __eq__ method, you can force comparisons to be made on the internally stored values. Example: Define __eq__ Try running the following Streamlit app and observe how the comparison is True on the first run then False on every rerun thereafter. import streamlit as st from dataclasses import dataclass @dataclass class MyDataclass: var1: int var2: float if ""my_dataclass"" not in st.session_state: st.session_state.my_dataclass = MyDataclass(1, 5.5) # Displays True on the first run the False on every rerun st.session_state.my_dataclass == MyDataclass(1, 5.5) st.button(""Rerun"") Since MyDataclass gets redefined with each rerun, the instance stored in Session State will not be equal to any instance defined in a later script run. You can fix this by forcing a comparison of internal values as follows: import streamlit as st from dataclasses import dataclass @dataclass class MyDataclass: var1: int var2: float def __eq__(self, other): # An instance of MyDataclass is equal to another object if the object # contains the same fields with the same values return (self.var1, self.var2) == (other.var1, other.var2) if ""my_dataclass"" not in st.session_state: st.session_state.my_dataclass = MyDataclass(1, 5.5) # Displays True on every rerun st.session_state.my_dataclass == MyDataclass(1, 5.5) st.button(""Rerun"") The default Python __eq__ implementation for a regular class or @dataclass depends on the in-memory ID of the class or class instance. To avoid problems in Streamlit, your custom __eq__ method should not depend the type() of self and other. Pattern 3: Store your class as serialized data Another option for classes that store data is to define serialization and deserialization methods like to_str and from_str for your class. You can use these to store class instance data in st.session_state rather than storing the class instance itself. Similar to pattern 2, this is a way to force comparison of the internal data and bypass the changing in-memory IDs. Example: Save your class instance as a string Using the same example from pattern 2, this can be done as follows: import streamlit as st from dataclasses import dataclass @dataclass class MyDataclass: var1: int var2: float def to_str(self): return f""{self.var1},{self.var2}"" @classmethod def from_str(cls, serial_str): values = serial_str.split("","") var1 = int(values[0]) var2 = float(values[1]) return cls(var1, var2) if ""my_dataclass"" not in st.session_state: st.session_state.my_dataclass = MyDataclass(1, 5.5).to_str() # Displays True on every rerun MyDataclass.from_str(st.session_state.my_dataclass) == MyDataclass(1, 5.5) st.button(""Rerun"") Pattern 4: Use caching to preserve your class For classes that are used as resources (database connections, state managers, APIs), consider using the cached singleton pattern. Use @st.cache_resource to decorate a @staticmethod of your class to generate a single, cached instance of the class. For example: import streamlit as st class MyResource: def __init__(self, api_url: str): self._url = api_url @st.cache_resource(ttl=300) @staticmethod def get_resource_manager(api_url: str): return MyResource(api_url) # This is cached until Session State is cleared or 5 minutes has elapsed. resource_manager = MyResource.get_resource_manager(""http://example.com/api/"") When you use one of Streamlit's caching decorators on a function, Streamlit doesn't use the function object to look up cached values. Instead, Streamlit's caching decorators index return values using the function's qualified name and module. So, even though Streamlit redefines MyResource with each script run, st.cache_resource is unaffected by this. get_resource_manager() will return its cached value with each rerun, until the value expires. Understanding how Python defines and compares classes So what's really happening here? We'll consider a simple example to illustrate why this is a pitfall. Feel free to skip this section if you don't want to deal more details. You can jump ahead to learn about Using Enum classes. Example: What happens when you define the same class twice? Set aside Streamlit for a moment and think about this simple Python script: from dataclasses import dataclass @dataclass class Student: student_id: int name: str Marshall_A = Student(1, ""Marshall"") Marshall_B = Student(1, ""Marshall"") # This is True (because a dataclass will compare two of its instances by value) Marshall_A == Marshall_B # Redefine the class @dataclass class Student: student_id: int name: str Marshall_C = Student(1, ""Marshall"") # This is False Marshall_A == Marshall_C In this example, the dataclass Student is defined twice. All three Marshalls have the same internal values. If you compare Marshall_A and Marshall_B they will be equal because they were both created from the first definition of Student. However, if you compare Marshall_A and Marshall_C they will not be equal because Marshall_C was created from the second definition of Student. Even though both Student dataclasses are defined exactly the same, they have differnt in-memory IDs and are therefore different. What's happening in Streamlit? In Streamlit, you probably don't have the same class written twice in your page script. However, the rerun logic of Streamlit creates the same effect. Let's use the above example for an analogy. If you define a class in one script run and save an instance in Session State, then a later rerun will redefine the class and you may end up comparing a Mashall_C in your rerun to a Marshall_A in Session State. Since widgets rely on Session State under the hood, this is where things can get confusing. How Streamlit widgets store options Several Streamlit UI elements, such as st.selectbox or st.radio, accept multiple-choice options via an options argument. The user of your application can typically select one or more of these options. The selected value is returned by the widget function. For example: number = st.selectbox(""Pick a number, any number"", options=[1, 2, 3]) # number == whatever value the user has selected from the UI. When you call a function like st.selectbox and pass an Iterable to options, the Iterable and current selection are saved into a hidden portion of Session State called the Widget Metadata. When the user of your application interacts with the st.selectbox widget, the broswer sends the index of their selection to your Streamlit server. This index is used to determine which values from the original options list, saved in the Widget Metadata from the previous page execution, are returned to your application. The key detail is that the value returned by st.selectbox (or similar widget function) is from an Iterable saved in Session State during a previous execution of the page, NOT the values passed to options on the current execution. There are a number of architectural reasons why Streamlit is designed this way, which we won't go into here. However, this is how we end up comparing instances of different classes when we think we are comparing instances of the same class. A pathological example The above explanation might be a bit confusing, so here's a pathological example to illustrate the idea. import streamlit as st from dataclasses import dataclass @dataclass class Student: student_id: int name: str Marshall_A = Student(1, ""Marshall"") if ""B"" not in st.session_state: st.session_state.B = Student(1, ""Marshall"") Marshall_B = st.session_state.B options = [Marshall_A,Marshall_B] selected = st.selectbox(""Pick"", options) # This comparison does not return expected results: selected == Marshall_A # This comparison evaluates as expected: selected == Marshall_B As a final note, we used @dataclass in the example for this section to illustrate a point, but in fact it is possible to encounter these same problems with classes, in general. Any class which checks class identity inside of a comparison operator—such as __eq__ or __gt__—can exhibit these issues. Using Enum classes in Streamlit The Enum class from the Python standard library is a powerful way to define custom symbolic names that can be used as options for st.multiselect or st.selectbox in place of str values. For example, you might add the following to your streamlit page: from enum import Enum import streamlit as st # class syntax class Color(Enum): RED = 1 GREEN = 2 BLUE = 3 selected_colors = set(st.multiselect(""Pick colors"", options=Color)) if selected_colors == {Color.RED, Color.GREEN}: st.write(""Hooray, you found the color YELLOW!"") If you're using the latest version of Streamlit, this Streamlit page will work as it appears it should. When a user picks both Color.RED and Color.GREEN, they are shown the special message. However, if you've read the rest of this page you might notice something tricky going on. Specifically, the Enum class Color gets redefined every time this script is run. In Python, if you define two Enum classes with the same class name, members, and values, the classes and their members are still considered unique from each other. This should cause the above if condition to always evaluate to False. In any script rerun, the Color values returned by st.multiselect would be of a different class than the Color defined in that script run. If you run the snippet above with Streamlit version 1.28.0 or less, you will not be able see the special message. Thankfully, as of version 1.29.0, Streamlit introduced a configuration option to greatly simplify the problem. That's where the enabled-by-default enumCoercion configuration option comes in. Understanding the enumCoercion configuration option When enumCoercion is enabled, Streamlit tries to recognize when you are using an element like st.multiselect or st.selectbox with a set of Enum members as options. If Streamlit detects this, it will convert the widget's returned values to members of the Enum class defined in the latest script run. This is something we call automatic Enum coercion. This behavior is configurable via the enumCoercion setting in your Streamlit config.toml file. It is enabled by default, and may be disabled or set to a stricter set of matching criteria. If you find that you still encounter issues with enumCoercion enabled, consider using the custom class patterns described above, such as moving your Enum class definition to a separate module file.Previous: DataframesNext: Working with timezonesforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy" https://docs.streamlit.io/develop/tutorials/databases/mssql#connect-locally,"DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceaddTutorialsremoveExecution flowaddConnect to data sourcesremoveAWS S3BigQueryDeta BaseFirestoreopen_in_newGoogle Cloud StorageMicrosoft SQL ServerMongoDBMySQLNeonPostgreSQLPrivate Google SheetPublic Google SheetSnowflakeSupabaseTableauTiDBTigerGraphMultipage appsaddWork with LLMsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Develop/Tutorials/Connect to data sources/Microsoft SQL ServerConnect Streamlit to Microsoft SQL Server Introduction This guide explains how to securely access a remote Microsoft SQL Server database from Streamlit Community Cloud. It uses the pyodbc library and Streamlit's Secrets management. Create an SQL Server database push_pinNoteIf you already have a remote database that you want to use, feel free to skip to the next step. First, follow the Microsoft documentation to install SQL Server and the sqlcmd Utility. They have detailed installation guides on how to: Install SQL Server on Windows Install on Red Hat Enterprise Linux Install on SUSE Linux Enterprise Server Install on Ubuntu Run on Docker Provision a SQL VM in Azure Once you have SQL Server installed, note down your SQL Server name, username, and password during setup. Connect locally If you are connecting locally, use sqlcmd to connect to your new local SQL Server instance. In your terminal, run the following command: sqlcmd -S localhost -U SA -P '' As you are connecting locally, the SQL Server name is localhost, the username is SA, and the password is the one you provided during the SA account setup. You should see a sqlcmd command prompt 1>, if successful. If you run into a connection failure, review Microsoft's connection troubleshooting recommendations for your OS (Linux & Windows). starTipWhen connecting remotely, the SQL Server name is the machine name or IP address. You might also need to open the SQL Server TCP port (default 1433) on your firewall. Create a SQL Server database By now, you have SQL Server running and have connected to it with sqlcmd! 🥳 Let's put it to use by creating a database containing a table with some example values. From the sqlcmd command prompt, run the following Transact-SQL command to create a test database mydb: CREATE DATABASE mydb To execute the above command, type GO on a new line: GO Insert some data Next create a new table, mytable, in the mydb database with three columns and two rows. Switch to the new mydb database: USE mydb Create a new table with the following schema: CREATE TABLE mytable (name varchar(80), pet varchar(80)) Insert some data into the table: INSERT INTO mytable VALUES ('Mary', 'dog'), ('John', 'cat'), ('Robert', 'bird') Type GO to execute the above commands: GO To end your sqlcmd session, type QUIT on a new line. Add username and password to your local app secrets Your local Streamlit app will read secrets from a file .streamlit/secrets.toml in your app's root directory. Create this file if it doesn't exist yet and add the SQL Server name, database name, username, and password as shown below: # .streamlit/secrets.toml server = ""localhost"" database = ""mydb"" username = ""SA"" password = ""xxx"" priority_highImportantWhen copying your app secrets to Streamlit Community Cloud, be sure to replace the values of server, database, username, and password with those of your remote SQL Server!And add this file to .gitignore and don't commit it to your GitHub repo. Copy your app secrets to Streamlit Community Cloud As the secrets.toml file above is not committed to GitHub, you need to pass its content to your deployed app (on Streamlit Community Cloud) separately. Go to the app dashboard and in the app's dropdown menu, click on Edit Secrets. Copy the content of secrets.toml into the text area. More information is available at Secrets management. Add pyodbc to your requirements file To connect to SQL Server locally with Streamlit, you need to pip install pyodbc, in addition to the Microsoft ODBC driver you installed during the SQL Server installation. On Streamlit Cloud, we have built-in support for SQL Server. On popular demand, we directly added SQL Server tools including the ODBC drivers and the executables sqlcmd and bcp to the container image for Cloud apps, so you don't need to install them. All you need to do is add the pyodbc Python package to your requirements.txt file, and you're ready to go! 🎈 # requirements.txt pyodbc==x.x.x Replace x.x.x ☝️ with the version of pyodbc you want installed on Cloud. push_pinNoteAt this time, Streamlit Community Cloud does not support Azure Active Directory authentication. We will update this tutorial when we add support for Azure Active Directory. Write your Streamlit app Copy the code below to your Streamlit app and run it. Make sure to adapt query to use the name of your table. import streamlit as st import pyodbc # Initialize connection. # Uses st.cache_resource to only run once. @st.cache_resource def init_connection(): return pyodbc.connect( ""DRIVER={ODBC Driver 17 for SQL Server};SERVER="" + st.secrets[""server""] + "";DATABASE="" + st.secrets[""database""] + "";UID="" + st.secrets[""username""] + "";PWD="" + st.secrets[""password""] ) conn = init_connection() # Perform query. # Uses st.cache_data to only rerun when the query changes or after 10 min. @st.cache_data(ttl=600) def run_query(query): with conn.cursor() as cur: cur.execute(query) return cur.fetchall() rows = run_query(""SELECT * from mytable;"") # Print results. for row in rows: st.write(f""{row[0]} has a :{row[1]}:"") See st.cache_data above? Without it, Streamlit would run the query every time the app reruns (e.g. on a widget interaction). With st.cache_data, it only runs when the query changes or after 10 minutes (that's what ttl is for). Watch out: If your database updates more frequently, you should adapt ttl or remove caching so viewers always see the latest data. Learn more in Caching. If everything worked out (and you used the example table we created above), your app should look like this: Previous: Google Cloud StorageNext: MongoDBforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy" https://docs.streamlit.io/develop/concepts/custom-components/intro#frontend,"DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsremoveCOREArchitecture & executionaddMultipage appsaddApp designaddADDITIONALConnections and secretsaddCustom componentsremoveIntro to custom componentsCreate a ComponentPublish a ComponentLimitationsComponent galleryopen_in_newConfiguration and themingaddApp testingaddAPI referenceaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Develop/Concepts/Custom components/Intro to custom componentsIntro to custom components The first step in developing a Streamlit Component is deciding whether to create a static component (i.e. rendered once, controlled by Python) or to create a bi-directional component that can communicate from Python to JavaScript and back. Create a static component If your goal in creating a Streamlit Component is solely to display HTML code or render a chart from a Python visualization library, Streamlit provides two methods that greatly simplify the process: components.html() and components.iframe(). If you are unsure whether you need bi-directional communication, start here first! Render an HTML string While st.text, st.markdown and st.write make it easy to write text to a Streamlit app, sometimes you'd rather implement a custom piece of HTML. Similarly, while Streamlit natively supports many charting libraries, you may want to implement a specific HTML/JavaScript template for a new charting library. components.html works by giving you the ability to embed an iframe inside of a Streamlit app that contains your desired output. Example import streamlit as st import streamlit.components.v1 as components # bootstrap 4 collapse example components.html( """"""
Collapsible Group Item #1 content
Collapsible Group Item #2 content
"""""", height=600, ) Render an iframe URL components.iframe is similar in features to components.html, with the difference being that components.iframe takes a URL as its input. This is used for situations where you want to include an entire page within a Streamlit app. Example import streamlit as st import streamlit.components.v1 as components # embed streamlit docs in a streamlit app components.iframe(""https://example.com"", height=500) Create a bi-directional component A bi-directional Streamlit Component has two parts: A frontend, which is built out of HTML and any other web tech you like (JavaScript, React, Vue, etc.), and gets rendered in Streamlit apps via an iframe tag. A Python API, which Streamlit apps use to instantiate and talk to that frontend To make the process of creating bi-directional Streamlit Components easier, we've created a React template and a TypeScript-only template in the Streamlit Component-template GitHub repo. We also provide some example Components in the same repo. Development Environment Setup To build a Streamlit Component, you need the following installed in your development environment: Python 3.8 - Python 3.12 Streamlit 1.11.1 or higher nodejs npm or yarn Clone the component-template GitHub repo, then decide whether you want to use the React.js (""template"") or plain TypeScript (""template-reactless"") template. Initialize and build the component template frontend from the terminal: # React template template/my_component/frontend npm install # Initialize the project and install npm dependencies npm run start # Start the Webpack dev server # or # TypeScript-only template template-reactless/my_component/frontend npm install # Initialize the project and install npm dependencies npm run start # Start the Webpack dev server From a separate terminal, run the Streamlit app (Python) that declares and uses the component: # React template cd template . venv/bin/activate # or similar to activate the venv/conda environment where Streamlit is installed pip install -e . # install template as editable package streamlit run my_component/example.py # run the example # or # TypeScript-only template cd template-reactless . venv/bin/activate # or similar to activate the venv/conda environment where Streamlit is installed pip install -e . # install template as editable package streamlit run my_component/example.py # run the example After running the steps above, you should see a Streamlit app in your browser that looks like this: The example app from the template shows how bi-directional communication is implemented. The Streamlit Component displays a button (Python → JavaScript), and the end-user can click the button. Each time the button is clicked, the JavaScript front-end increments the counter value and passes it back to Python (JavaScript → Python), which is then displayed by Streamlit (Python → JavaScript). Frontend Because each Streamlit Component is its own webpage that gets rendered into an iframe, you can use just about any web tech you'd like to create that web page. We provide two templates to get started with in the Streamlit Components-template GitHub repo; one of those templates uses React and the other does not. push_pinNoteEven if you're not already familiar with React, you may still want to check out the React-based template. It handles most of the boilerplate required to send and receive data from Streamlit, and you can learn the bits of React you need as you go.If you'd rather not use React, please read this section anyway! It explains the fundamentals of Streamlit ↔ Component communication. React The React-based template is in template/my_component/frontend/src/MyComponent.tsx. MyComponent.render() is called automatically when the component needs to be re-rendered (just like in any React app) Arguments passed from the Python script are available via the this.props.args dictionary: # Send arguments in Python: result = my_component(greeting=""Hello"", name=""Streamlit"") // Receive arguments in frontend: let greeting = this.props.args[""greeting""]; // greeting = ""Hello"" let name = this.props.args[""name""]; // name = ""Streamlit"" Use Streamlit.setComponentValue() to return data from the component to the Python script: // Set value in frontend: Streamlit.setComponentValue(3.14); # Access value in Python: result = my_component(greeting=""Hello"", name=""Streamlit"") st.write(""result = "", result) # result = 3.14 When you call Streamlit.setComponentValue(new_value), that new value is sent to Streamlit, which then re-executes the Python script from top to bottom. When the script is re-executed, the call to my_component(...) will return the new value. From a code flow perspective, it appears that you're transmitting data synchronously with the frontend: Python sends the arguments to JavaScript, and JavaScript returns a value to Python, all in a single function call! But in reality this is all happening asynchronously, and it's the re-execution of the Python script that achieves the sleight of hand. Use Streamlit.setFrameHeight() to control the height of your component. By default, the React template calls this automatically (see StreamlitComponentBase.componentDidUpdate()). You can override this behavior if you need more control. There's a tiny bit of magic in the last line of the file: export default withStreamlitConnection(MyComponent) - this does some handshaking with Streamlit, and sets up the mechanisms for bi-directional data communication. TypeScript-only The TypeScript-only template is in template-reactless/my_component/frontend/src/MyComponent.tsx. This template has much more code than its React sibling, in that all the mechanics of handshaking, setting up event listeners, and updating the component's frame height are done manually. The React version of the template handles most of these details automatically. Towards the bottom of the source file, the template calls Streamlit.setComponentReady() to tell Streamlit it's ready to start receiving data. (You'll generally want to do this after creating and loading everything that the Component relies on.) It subscribes to Streamlit.RENDER_EVENT to be notified of when to redraw. (This event won't be fired until setComponentReady is called) Within its onRender event handler, it accesses the arguments passed in the Python script via event.detail.args It sends data back to the Python script in the same way that the React template does—clicking on the ""Click Me!"" button calls Streamlit.setComponentValue() It informs Streamlit when its height may have changed via Streamlit.setFrameHeight() Working with Themes push_pinNoteCustom component theme support requires streamlit-component-lib version 1.2.0 or higher. Along with sending an args object to your component, Streamlit also sends a theme object defining the active theme so that your component can adjust its styling in a compatible way. This object is sent in the same message as args, so it can be accessed via this.props.theme (when using the React template) or event.detail.theme (when using the plain TypeScript template). The theme object has the following shape: { ""base"": ""lightORdark"", ""primaryColor"": ""someColor1"", ""backgroundColor"": ""someColor2"", ""secondaryBackgroundColor"": ""someColor3"", ""textColor"": ""someColor4"", ""font"": ""someFont"" } The base option allows you to specify a preset Streamlit theme that your custom theme inherits from. Any theme config options not defined in your theme settings have their values set to those of the base theme. Valid values for base are ""light"" and ""dark"". Note that the theme object has fields with the same names and semantics as the options in the ""theme"" section of the config options printed with the command streamlit config show. When using the React template, the following CSS variables are also set automatically. --base --primary-color --background-color --secondary-background-color --text-color --font If you're not familiar with CSS variables, the TLDR version is that you can use them like this: .mySelector { color: var(--text-color); } These variables match the fields defined in the theme object above, and whether to use CSS variables or the theme object in your component is a matter of personal preference. Other frontend details Because you're hosting your component from a dev server (via npm run start), any changes you make should be automatically reflected in the Streamlit app when you save. If you want to add more packages to your component, run npm add to add them from within your component's frontend/ directory. npm add baseui To build a static version of your component, run npm run export. See Prepare your Component for more information Python API components.declare_component() is all that's required to create your Component's Python API: import streamlit.components.v1 as components my_component = components.declare_component( ""my_component"", url=""http://localhost:3001"" ) You can then use the returned my_component function to send and receive data with your frontend code: # Send data to the frontend using named arguments. return_value = my_component(name=""Blackbeard"", ship=""Queen Anne's Revenge"") # `my_component`'s return value is the data returned from the frontend. st.write(""Value = "", return_value) While the above is all you need to define from the Python side to have a working Component, we recommend creating a ""wrapper"" function with named arguments and default values, input validation and so on. This will make it easier for end-users to understand what data values your function accepts and allows for defining helpful docstrings. Please see this example from the Components-template for an example of creating a wrapper function. Data serialization Python → Frontend You send data from Python to the frontend by passing keyword args to your Component's invoke function (that is, the function returned from declare_component). You can send the following types of data from Python to the frontend: Any JSON-serializable data numpy.array pandas.DataFrame Any JSON-serializable data gets serialized to a JSON string, and deserialized to its JavaScript equivalent. numpy.array and pandas.DataFrame get serialized using Apache Arrow and are deserialized as instances of ArrowTable, which is a custom type that wraps Arrow structures and provides a convenient API on top of them. Check out the CustomDataframe and SelectableDataTable Component example code for more context on how to use ArrowTable. Frontend → Python You send data from the frontend to Python via the Streamlit.setComponentValue() API (which is part of the template code). Unlike arg-passing from Python → frontend, this API takes a single value. If you want to return multiple values, you'll need to wrap them in an Array or Object. Custom Components can send JSON-serializable data from the frontend to Python, as well as Apache Arrow ArrowTables to represent dataframes.Previous: Custom componentsNext: Create a ComponentforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy" https://docs.streamlit.io/develop/tutorials/databases/bigquery#enable-the-bigquery-api,"DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceaddTutorialsremoveExecution flowaddConnect to data sourcesremoveAWS S3BigQueryDeta BaseFirestoreopen_in_newGoogle Cloud StorageMicrosoft SQL ServerMongoDBMySQLNeonPostgreSQLPrivate Google SheetPublic Google SheetSnowflakeSupabaseTableauTiDBTigerGraphMultipage appsaddWork with LLMsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Develop/Tutorials/Connect to data sources/BigQueryConnect Streamlit to Google BigQuery Introduction This guide explains how to securely access a BigQuery database from Streamlit Community Cloud. It uses the google-cloud-bigquery library and Streamlit's Secrets management. Create a BigQuery database push_pinNoteIf you already have a database that you want to use, feel free to skip to the next step. For this example, we will use one of the sample datasets from BigQuery (namely the shakespeare table). If you want to create a new dataset instead, follow Google's quickstart guide. Enable the BigQuery API Programmatic access to BigQuery is controlled through Google Cloud Platform. Create an account or sign in and head over to the APIs & Services dashboard (select or create a project if asked). As shown below, search for the BigQuery API and enable it: Create a service account & key file To use the BigQuery API from Streamlit Community Cloud, you need a Google Cloud Platform service account (a special account type for programmatic data access). Go to the Service Accounts page and create an account with the Viewer permission (this will let the account access data but not change it): push_pinNoteIf the button CREATE SERVICE ACCOUNT is gray, you don't have the correct permissions. Ask the admin of your Google Cloud project for help. After clicking DONE, you should be back on the service accounts overview. Create a JSON key file for the new account and download it: Add the key file to your local app secrets Your local Streamlit app will read secrets from a file .streamlit/secrets.toml in your app's root directory. Create this file if it doesn't exist yet and add the content of the key file you just downloaded to it as shown below: # .streamlit/secrets.toml [gcp_service_account] type = ""service_account"" project_id = ""xxx"" private_key_id = ""xxx"" private_key = ""xxx"" client_email = ""xxx"" client_id = ""xxx"" auth_uri = ""https://accounts.google.com/o/oauth2/auth"" token_uri = ""https://oauth2.googleapis.com/token"" auth_provider_x509_cert_url = ""https://www.googleapis.com/oauth2/v1/certs"" client_x509_cert_url = ""xxx"" priority_highImportantAdd this file to .gitignore and don't commit it to your GitHub repo! Copy your app secrets to the cloud As the secrets.toml file above is not committed to GitHub, you need to pass its content to your deployed app (on Streamlit Community Cloud) separately. Go to the app dashboard and in the app's dropdown menu, click on Edit Secrets. Copy the content of secrets.toml into the text area. More information is available at Secrets management. Add google-cloud-bigquery to your requirements file Add the google-cloud-bigquery package to your requirements.txt file, preferably pinning its version (replace x.x.x with the version want installed): # requirements.txt google-cloud-bigquery==x.x.x Write your Streamlit app Copy the code below to your Streamlit app and run it. Make sure to adapt the query if you don't use the sample table. # streamlit_app.py import streamlit as st from google.oauth2 import service_account from google.cloud import bigquery # Create API client. credentials = service_account.Credentials.from_service_account_info( st.secrets[""gcp_service_account""] ) client = bigquery.Client(credentials=credentials) # Perform query. # Uses st.cache_data to only rerun when the query changes or after 10 min. @st.cache_data(ttl=600) def run_query(query): query_job = client.query(query) rows_raw = query_job.result() # Convert to list of dicts. Required for st.cache_data to hash the return value. rows = [dict(row) for row in rows_raw] return rows rows = run_query(""SELECT word FROM `bigquery-public-data.samples.shakespeare` LIMIT 10"") # Print results. st.write(""Some wise words from Shakespeare:"") for row in rows: st.write(""✍️ "" + row['word']) See st.cache_data above? Without it, Streamlit would run the query every time the app reruns (e.g. on a widget interaction). With st.cache_data, it only runs when the query changes or after 10 minutes (that's what ttl is for). Watch out: If your database updates more frequently, you should adapt ttl or remove caching so viewers always see the latest data. Learn more in Caching. Alternatively, you can use pandas to read from BigQuery right into a dataframe! Follow all the above steps, install the pandas-gbq library (don't forget to add it to requirements.txt!), and call pandas.read_gbq(query, credentials=credentials). More info in the pandas docs. If everything worked out (and you used the sample table), your app should look like this: Previous: AWS S3Next: Deta BaseforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy" https://docs.streamlit.io/develop/api-reference/connections/st.connections.snowflakeconnection#using-streamlit-secrets,"DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceremovePAGE ELEMENTSWrite and magicaddText elementsaddData elementsaddChart elementsaddInput widgetsaddMedia elementsaddLayouts and containersaddChat elementsaddStatus elementsaddThird-party componentsopen_in_newAPPLICATION LOGICNavigation and pagesaddExecution flowaddCaching and stateaddConnections and secretsremoveSECRETSst.secretssecrets.tomlCONNECTIONSst.connectionSnowflakeConnectionSQLConnectionBaseConnectionSnowparkConnectiondeleteCustom componentsaddUtilitiesaddConfigurationaddTOOLSApp testingaddCommand lineaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Develop/API reference/Connections and secrets/SnowflakeConnectionstarTipThis page only contains the st.connections.SnowflakeConnection class. For a deeper dive into creating and managing data connections within Streamlit apps, read Connecting to data. st.connections.SnowflakeConnectionStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA connection to Snowflake using the Snowflake Python Connector. Initialize using st.connection("""", type=""snowflake""). SnowflakeConnection supports direct SQL querying using .query(""...""), access to the underlying Snowflake Python Connector object with .raw_connection, and other convenience functions. See the methods below for more information. SnowflakeConnections should always be created using st.connection(), not initialized directly. Class description[source] st.connections.SnowflakeConnection(connection_name, **kwargs) Methods cursor() Return a PEP 249-compliant cursor object. query(sql, *, ttl=None, show_spinner=""Running `snowflake.query(...)`."", params=None, **kwargs) Run a read-only SQL query. reset() Reset this connection so that it gets reinitialized the next time it's used. session() Create a new Snowpark Session from this connection. write_pandas(df, table_name, database=None, schema=None, chunk_size=None, **kwargs) Call snowflake.connector.pandas_tools.write_pandas with this connection. Attributes raw_connection Access the underlying Snowflake Python connector object. Configuration st.connection(""snowflake"") can be configured using Streamlit secrets or keyword args just like any other connection. It can also use existing Snowflake connection configuration when available. Note that snowflake-snowpark-python must be installed to use this connection. Using Streamlit secrets For example, if your Snowflake account supports SSO, you can set up a quick local connection for development using browser-based SSO and secrets.toml as follows: # .streamlit/secrets.toml [connections.snowflake] account = """" user = """" authenticator = ""EXTERNALBROWSER"" Learn more about account indentifier here. You could also specify the full configuration and credentials in your secrets file, as in the example here. Using existing Snowflake configuration Snowflake's python driver also supports a connection configuration file, which is well integrated with Streamlit SnowflakeConnection. If you already have one or more connections configured, all you need to do is pass Streamlit the name of the connection to use. This can be done in several ways: Set connection_name in your app code, such as st.connnection("""", type=""snowflake""). Set connection_name = """" in the [connections.snowflake] section of your Streamlit secrets. Set the environment variable SNOWFLAKE_DEFAULT_CONNECTION_NAME=. Set a default connection in your Snowflake configuration. When available in Streamlit in Snowflake, st.connection(""snowflake"") will connect automatically using the app owner role and does not require any configuration. Learn more about setting up connections in the Connecting Streamlit to Snowflake tutorial and Connecting to data. SnowflakeConnection.cursorStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeReturn a PEP 249-compliant cursor object. For more information, see the Snowflake Python Connector documentation. Function signature[source] SnowflakeConnection.cursor() SnowflakeConnection.queryStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeRun a read-only SQL query. This method implements both query result caching (with caching behavior identical to that of using @st.cache_data) as well as simple error handling/retries. Note Queries that are run without a specified ttl are cached indefinitely. Function signature[source] SnowflakeConnection.query(sql, *, ttl=None, show_spinner=""Running `snowflake.query(...)`."", params=None, **kwargs) Parameters sql (str) The read-only SQL query to execute. ttl (float, int, timedelta or None) The maximum number of seconds to keep results in the cache, or None if cached results should not expire. The default is None. show_spinner (boolean or string) Enable the spinner. The default is to show a spinner when there is a ""cache miss"" and the cached resource is being created. If a string, the value of the show_spinner param will be used for the spinner text. params (list, tuple, dict or None) List of parameters to pass to the execute method. This connector supports binding data to a SQL statement using qmark bindings. For more information and examples, see the Snowflake Python Connector documentation. Default is None. Returns(pandas.DataFrame) The result of running the query, formatted as a pandas DataFrame. Example import streamlit as st conn = st.connection(""snowflake"") df = conn.query(""select * from pet_owners"") st.dataframe(df) SnowflakeConnection.raw_connectionStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeAccess the underlying Snowflake Python connector object. Information on how to use the Snowflake Python Connector can be found in the Snowflake Python Connector documentation. Function signature[source] SnowflakeConnection.raw_connection SnowflakeConnection.resetStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeReset this connection so that it gets reinitialized the next time it's used. This method can be useful when a connection has become stale, an auth token has expired, or in similar scenarios where a broken connection might be fixed by reinitializing it. Note that some connection methods may already use reset() in their error handling code. Function signature[source] SnowflakeConnection.reset() Example import streamlit as st conn = st.connection(""my_conn"") # Reset the connection before using it if it isn't healthy # Note: is_healthy() isn't a real method and is just shown for example here. if not conn.is_healthy(): conn.reset() # Do stuff with conn... SnowflakeConnection.sessionStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeCreate a new Snowpark Session from this connection. Information on how to use Snowpark sessions can be found in the Snowpark documentation. Function signature[source] SnowflakeConnection.session() SnowflakeConnection.write_pandasStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeCall snowflake.connector.pandas_tools.write_pandas with this connection. This convenience method is simply a thin wrapper around the write_pandas function of the same name from snowflake.connector.pandas_tools. For more information, see the Snowflake Python Connector documentation. Function signature[source] SnowflakeConnection.write_pandas(df, table_name, database=None, schema=None, chunk_size=None, **kwargs) Returns(tuple[bool, int, int]) A tuple containing three values: A bool that is True if the write was successful. An int giving the number of chunks of data that were copied. An int giving the number of rows that were inserted. Previous: st.connectionNext: SQLConnectionforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy" https://docs.streamlit.io/develop/api-reference/widgets/st.download_button#stdownload_button,"DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceremovePAGE ELEMENTSWrite and magicaddText elementsaddData elementsaddChart elementsaddInput widgetsremoveBUTTONSst.buttonst.download_buttonst.form_submit_buttonlinkst.link_buttonst.page_linkSELECTIONSst.checkboxst.color_pickerst.multiselectst.radiost.selectboxst.select_sliderst.toggleNUMERICst.number_inputst.sliderDATE & TIMEst.date_inputst.time_inputTEXTst.chat_inputlinkst.text_areast.text_inputMEDIA & FILESst.camera_inputst.data_editorlinkst.file_uploaderMedia elementsaddLayouts and containersaddChat elementsaddStatus elementsaddThird-party componentsopen_in_newAPPLICATION LOGICNavigation and pagesaddExecution flowaddCaching and stateaddConnections and secretsaddCustom componentsaddUtilitiesaddConfigurationaddTOOLSApp testingaddCommand lineaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Develop/API reference/Input widgets/st.download_buttonst.download_buttonStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeDisplay a download button widget. This is useful when you would like to provide a way for your users to download a file directly from your app. Note that the data to be downloaded is stored in-memory while the user is connected, so it's a good idea to keep file sizes under a couple hundred megabytes to conserve memory. Function signature[source] st.download_button(label, data, file_name=None, mime=None, key=None, help=None, on_click=None, args=None, kwargs=None, *, type=""secondary"", disabled=False, use_container_width=False) Parameters label (str) A short label explaining to the user what this button is for. The label can optionally contain Markdown and supports the following elements: Bold, Italics, Strikethroughs, Inline Code, and Emojis. This also supports: Emoji shortcodes, such as :+1: and :sunglasses:. For a list of all supported codes, see https://share.streamlit.io/streamlit/emoji-shortcodes. LaTeX expressions, by wrapping them in ""$"" or ""$$"" (the ""$$"" must be on their own lines). Supported LaTeX functions are listed at https://katex.org/docs/supported.html. Colored text and background colors for text, using the syntax :color[text to be colored] and :color-background[text to be colored], respectively. color must be replaced with any of the following supported colors: blue, green, orange, red, violet, gray/grey, rainbow. For example, you can use :orange[your text here] or :blue-background[your text here]. Unsupported elements are unwrapped so only their children (text contents) render. Display unsupported elements as literal characters by backslash-escaping them. E.g. 1\. Not an ordered list. data (str or bytes or file) The contents of the file to be downloaded. See example below for caching techniques to avoid recomputing this data unnecessarily. file_name (str) An optional string to use as the name of the file to be downloaded, such as 'my_file.csv'. If not specified, the name will be automatically generated. mime (str or None) The MIME type of the data. If None, defaults to ""text/plain"" (if data is of type str or is a textual file) or ""application/octet-stream"" (if data is of type bytes or is a binary file). key (str or int) An optional string or integer to use as the unique key for the widget. If this is omitted, a key will be generated for the widget based on its content. Multiple widgets of the same type may not share the same key. help (str) An optional tooltip that gets displayed when the button is hovered over. on_click (callable) An optional callback invoked when this button is clicked. args (tuple) An optional tuple of args to pass to the callback. kwargs (dict) An optional dict of kwargs to pass to the callback. type (""secondary"" or ""primary"") An optional string that specifies the button type. Can be ""primary"" for a button with additional emphasis or ""secondary"" for a normal button. Defaults to ""secondary"". disabled (bool) An optional boolean, which disables the download button if set to True. The default is False. use_container_width (bool) An optional boolean, which makes the button stretch its width to match the parent container. Returns(bool) True if the button was clicked on the last run of the app, False otherwise. Examples Download a large DataFrame as a CSV: import streamlit as st @st.cache_data def convert_df(df): # IMPORTANT: Cache the conversion to prevent computation on every rerun return df.to_csv().encode(""utf-8"") csv = convert_df(my_large_df) st.download_button( label=""Download data as CSV"", data=csv, file_name=""large_df.csv"", mime=""text/csv"", ) Download a string as a file: import streamlit as st text_contents = '''This is some text''' st.download_button(""Download some text"", text_contents) Download a binary file: import streamlit as st binary_contents = b""example content"" # Defaults to ""application/octet-stream"" st.download_button(""Download binary file"", binary_contents) Download an image: import streamlit as st with open(""flower.png"", ""rb"") as file: btn = st.download_button( label=""Download image"", data=file, file_name=""flower.png"", mime=""image/png"" ) Built with Streamlit 🎈Fullscreen open_in_new Previous: st.buttonNext: st.form_submit_buttonforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy" https://docs.streamlit.io/library/advanced-features/configuration#configtoml,"DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceremovePAGE ELEMENTSWrite and magicaddText elementsaddData elementsaddChart elementsaddInput widgetsaddMedia elementsaddLayouts and containersaddChat elementsaddStatus elementsaddThird-party componentsopen_in_newAPPLICATION LOGICNavigation and pagesaddExecution flowaddCaching and stateaddConnections and secretsaddCustom componentsaddUtilitiesaddConfigurationremoveconfig.tomlst.set_page_configTOOLSApp testingaddCommand lineaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Develop/API reference/Configuration/config.tomlconfig.toml config.toml is an optional file you can define for your working directory or global development environment. When config.toml is defined both globally and in your working directory, Streamlit combines the configuration options and gives precendence to the working-directory configuration. Additionally, you can use environment variables and command-line options to override additional configuration options. For more information, see Configuration options. File location To define your configuration locally or per-project, add .streamlit/config.toml to your working directory. Your working directory is wherever you call streamlit run. If you haven't previously created the .streamlit directory, you will need to add it. To define your configuration globally, you must first locate your global .streamlit directory. Streamlit adds this hidden directory to your OS user profile during installation. For MacOS/Linx, this will be ~/.streamlit/config.toml. For Windows, this will be %userprofile%/.streamlit/config.toml. File format config.toml is a TOML file. Example [client] showErrorDetails = false [theme] primaryColor = ""#F63366"" backgroundColor = ""black"" Available configuration options Below are all the sections and options you can have in your .streamlit/config.toml file. To see all configurations, use the following command in your terminal or CLI: streamlit config show Global [global] # ***DEPRECATED*** # global.disableWatchdogWarning has been deprecated has been deprecated and # will be removed in a future version. This option will be removed on or after # 2024-01-20. # **************** # By default, Streamlit checks if the Python watchdog module is available # and, if not, prints a warning asking for you to install it. The watchdog # module is not required, but highly recommended. It improves Streamlit's # ability to detect changes to files in your filesystem. # If you'd like to turn off this warning, set this to True. # Default: false disableWatchdogWarning = false # By default, Streamlit displays a warning when a user sets both a widget # default value in the function defining the widget and a widget value via # the widget's key in `st.session_state`. # If you'd like to turn off this warning, set this to True. # Default: false disableWidgetStateDuplicationWarning = false # If True, will show a warning when you run a Streamlit-enabled script # via ""python my_script.py"". # Default: true showWarningOnDirectExecution = true Logger [logger] # Level of logging: 'error', 'warning', 'info', or 'debug'. # Default: 'info' level = ""info"" # String format for logging messages. If logger.datetimeFormat is set, # logger messages will default to `%(asctime)s.%(msecs)03d %(message)s`. See # Python's documentation for available attributes: # https://docs.python.org/2.6/develop/logging.html#formatter-objects # Default: ""%(asctime)s %(message)s"" messageFormat = ""%(asctime)s %(message)s"" Client [client] # ***DEPRECATED*** # client.caching has been deprecated and is not required anymore for our new # caching commands. This option will be removed on or after 2024-01-20. # **************** # Whether to enable st.cache. This does not affect st.cache_data or # st.cache_resource. # Default: true caching = true # ***DEPRECATED*** # client.displayEnabled has been deprecated and will be removed in a future # version. This option will be removed on or after 2024-01-20. # **************** # If false, makes your Streamlit script not draw to a Streamlit app. # Default: true displayEnabled = true # Controls whether uncaught app exceptions and deprecation warnings # are displayed in the browser. By default, this is set to True and # Streamlit displays app exceptions and associated tracebacks, and # deprecation warnings, in the browser. # # If set to False, deprecation warnings and full exception messages # will print to the console only. Exceptions will still display in the # browser with a generic error message. For now, the exception type and # traceback show in the browser also, but they will be removed in the # future. # Default: true showErrorDetails = true # Change the visibility of items in the toolbar, options menu, # and settings dialog (top right of the app). # Allowed values: # * ""auto"" : Show the developer options if the app is accessed through # localhost or through Streamlit Community Cloud as a developer. # Hide them otherwise. # * ""developer"" : Show the developer options. # * ""viewer"" : Hide the developer options. # * ""minimal"" : Show only options set externally (e.g. through # Streamlit Community Cloud) or through st.set_page_config. # If there are no options left, hide the menu. # Default: ""auto"" toolbarMode = ""auto"" # Controls whether the default sidebar page navigation in a multipage app is # displayed. # Default: true showSidebarNavigation = true Runner [runner] # Allows you to type a variable or string by itself in a single line of # Python code to write it to the app. # Default: true magicEnabled = true # ***DEPRECATED*** # runner.installTracer has been deprecated and will be removed in a future # version. This option will be removed on or after 2024-01-20. # **************** # Install a Python tracer to allow you to stop or pause your script at # any point and introspect it. As a side-effect, this slows down your # script's execution. # Default: false installTracer = false # ***DEPRECATED*** # runner.fixMatplotlib has been deprecated and will be removed in a future # version. This option will be removed on or after 2024-01-20. # **************** # Sets the MPLBACKEND environment variable to Agg inside Streamlit to # prevent Python crashing. # Default: true fixMatplotlib = true # Handle script rerun requests immediately, rather than waiting for script # execution to reach a yield point. This makes Streamlit much more # responsive to user interaction, but it can lead to race conditions in # apps that mutate session_state data outside of explicit session_state # assignment statements. # Default: true fastReruns = true # Raise an exception after adding unserializable data to Session State. # Some execution environments may require serializing all data in Session # State, so it may be useful to detect incompatibility during development, # or when the execution environment will stop supporting it in the future. # Default: false enforceSerializableSessionState = false # Adjust how certain 'options' widgets like radio, selectbox, and # multiselect coerce Enum members when the Enum class gets # re-defined during a script re-run. For more information, check out the docs: # https://docs.streamlit.io/develop/concepts/design/custom-classes#enums # # Allowed values: # * ""off"" : Disables Enum coercion. # * ""nameOnly"" : Enum classes can be coerced if their member names match. # * ""nameAndValue"" : Enum classes can be coerced if their member names AND # member values match. # Default: ""nameOnly"" enumCoercion = ""nameOnly"" Server [server] # List of folders that should not be watched for changes. This # impacts both ""Run on Save"" and @st.cache. # Relative paths will be taken as relative to the current working directory. # Example: ['/home/user1/env', 'relative/path/to/folder'] # Default: [] folderWatchBlacklist = [] # Change the type of file watcher used by Streamlit, or turn it off # completely. # Allowed values: # * ""auto"" : Streamlit will attempt to use the watchdog module, and # falls back to polling if watchdog is not available. # * ""watchdog"" : Force Streamlit to use the watchdog module. # * ""poll"" : Force Streamlit to always use polling. # * ""none"" : Streamlit will not watch files. # Default: ""auto"" fileWatcherType = ""auto"" # Symmetric key used to produce signed cookies. If deploying on multiple # replicas, this should be set to the same value across all replicas to ensure # they all share the same secret. # Default: randomly generated secret key. cookieSecret = ""a-random-key-appears-here"" # If false, will attempt to open a browser window on start. # Default: false unless (1) we are on a Linux box where DISPLAY is unset, or # (2) we are running in the Streamlit Atom plugin. headless = false # Automatically rerun script when the file is modified on disk. # Default: false runOnSave = false # The address where the server will listen for client and browser # connections. Use this if you want to bind the server to a specific address. # If set, the server will only be accessible from this address, and not from # any aliases (like localhost). # Default: (unset) address = # The port where the server will listen for browser connections. # Don't use port 3000 which is reserved for internal development. # Default: 8501 port = 8501 # The base path for the URL where Streamlit should be served from. # Default: """" baseUrlPath = """" # Enables support for Cross-Origin Resource Sharing (CORS) protection, for # added security. # Due to conflicts between CORS and XSRF, if `server.enableXsrfProtection` is # on and `server.enableCORS` is off at the same time, we will prioritize # `server.enableXsrfProtection`. # Default: true enableCORS = true # Enables support for Cross-Site Request Forgery (XSRF) protection, for added # security. # Due to conflicts between CORS and XSRF, if `server.enableXsrfProtection` is # on and `server.enableCORS` is off at the same time, we will prioritize # `server.enableXsrfProtection`. # Default: true enableXsrfProtection = true # Max size, in megabytes, for files uploaded with the file_uploader. # Default: 200 maxUploadSize = 200 # Max size, in megabytes, of messages that can be sent via the WebSocket # connection. # Default: 200 maxMessageSize = 200 # Enables support for websocket compression. # Default: false enableWebsocketCompression = false # Enable serving files from a `static` directory in the running app's # directory. # Default: false enableStaticServing = false # Server certificate file for connecting via HTTPS. # Must be set at the same time as ""server.sslKeyFile"". # ['DO NOT USE THIS OPTION IN A PRODUCTION ENVIRONMENT. It has not gone through # security audits or performance tests. For the production environment, we # recommend performing SSL termination by the load balancer or the reverse # proxy.'] # sslCertFile = # Cryptographic key file for connecting via HTTPS. # Must be set at the same time as ""server.sslCertFile"". # ['DO NOT USE THIS OPTION IN A PRODUCTION ENVIRONMENT. It has not gone through # security audits or performance tests. For the production environment, we # recommend performing SSL termination by the load balancer or the reverse # proxy.'] # sslKeyFile = Browser [browser] # Internet address where users should point their browsers in order to # connect to the app. Can be IP address or DNS name and path. # This is used to: # - Set the correct URL for CORS and XSRF protection purposes. # - Show the URL on the terminal # - Open the browser # Default: ""localhost"" serverAddress = ""localhost"" # Whether to send usage statistics to Streamlit. # Default: true gatherUsageStats = true # Port where users should point their browsers in order to connect to the # app. # This is used to: # - Set the correct URL for XSRF protection purposes. # - Show the URL on the terminal (part of `streamlit run`). # - Open the browser automatically (part of `streamlit run`). # This option is for advanced use cases. To change the port of your app, use # `server.Port` instead. Don't use port 3000 which is reserved for internal # development. # Default: whatever value is set in server.port. serverPort = 8501 Mapbox [mapbox] # Configure Streamlit to use a custom Mapbox # token for elements like st.pydeck_chart and st.map. # To get a token for yourself, create an account at # https://mapbox.com. It's free (for moderate usage levels)! # Default: """" token = """" Deprecation [deprecation] # Set to false to disable the deprecation warning for using the global pyplot # instance. # Default: true showPyplotGlobalUse = true Theme [theme] # The preset Streamlit theme that your custom theme inherits from. # One of ""light"" or ""dark"". # base = # Primary accent color for interactive elements. # primaryColor = # Background color for the main content area. # backgroundColor = # Background color used for the sidebar and most interactive widgets. # secondaryBackgroundColor = # Color used for almost all text. # textColor = # Font family for all text in the app, except code blocks. One of ""sans serif"", # ""serif"", or ""monospace"". # font = Previous: ConfigurationNext: st.set_page_configforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy" https://docs.streamlit.io/deploy/streamlit-community-cloud/get-started/trust-and-security#incident-response,"DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudremoveGet startedremoveQuickstartCreate your accountConnect your GitHub accountExplore your workspaceFork and edit a public appTrust and securityDeploy your appaddManage your appaddShare your appaddManage your accountaddTroubleshootingStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Deploy/Streamlit Community Cloud/Get started/Trust and securityStreamlit trust and security Streamlit is a framework that turns Python scripts into interactive apps, giving data scientists the ability to quickly create data and model-based apps for the entire company. A simple Streamlit app is: import streamlit as st number = st.slider(""Pick a number: "", min_value=1, max_value=10) st.text(""Your number is "" + str(number)) When you streamlit run my_app.py, you start a web server that runs the interactive application on your local computer at http://localhost:8501. This is great for local development. When you want to share with your colleagues, Streamlit Community Cloud enables you to deploy and run these applications in the cloud. Streamlit Community Cloud handles the details of containerization and provides you an interface for easily managing your deployed apps. This document provides an overview of the security safeguards we've implemented to protect you and your data. Security, however, is a shared responsibility and you are ultimately responsible for making appropriate use of Streamlit and the Streamlit Community Cloud, including implementation of appropriate user-configurable security safeguards and best practices. Product security Authentication You must authenticate through GitHub to deploy or administer an app. Authentication through Google or single-use emailed links are required to view a private app when you don't have push or admin permissions on the associated GitHub repository. The single-use emailed links are valid for 15 minutes once requested. Permissions Streamlit Community Cloud inherits the permissions you have assigned in GitHub. Users with write access to a GitHub repository for a given app will be able to make changes in the Streamlit administrative console. However, only users with admin access to a repository are able to deploy and delete apps. Network and application security Data hosting Our physical infrastructure is hosted and managed within secure data centers maintained by infrastructure-as-a-service cloud providers. Streamlit leverages many of these platforms' built-in security, privacy, and redundancy features. Our cloud providers continually monitor their data centers for risk and undergo assessments to ensure compliance with industry standards. Data deletion Community Cloud users have the option to delete any apps they’ve deployed as well as their entire account. When a user deletes their application from the admin console, we delete their source code, including any files copied from their GitHub repository or created within our system from the running app. However, we keep a record representing the application in our database. This record contains the coordinates of the application: the GitHub organization or user, the GitHub repository, the branch, and the path of the main module file. When a user deletes their account, we perform a hard deletion of their data and a hard deletion of all the apps that belong to the GitHub identity associated with their account. In this case, we do not maintain the records of application coordinates described above. When an account is deleted, we also delete any HubSpot contact associated with the Community Cloud account. Virtual private cloud All of our servers are within a virtual private cloud (VPC) with firewalls and network access control lists (ACLs) to allow external access to a select few API endpoints; all other internal services are only accessible within the VPC. Encryption Streamlit apps are served entirely over HTTPS. We use only strong cipher suites and HTTP Strict Transport Security (HSTS) to ensure browsers interact with Streamlit apps over HTTPS. All data sent to or from Streamlit over the public internet is encrypted in transit using 256-bit encryption. Our API and application endpoints use Transport Layer Security (TLS) 1.2 (or better). We also encrypt data at rest on disk using AES-256. Permissions and authentication Access to Community Cloud user account data is limited to authorized personnel. We run a zero-trust corporate network, utilize single sign-on and multi-factor authentication (MFA), and enforce strong password policies to ensure access to cloud-related services is protected. Incident response Our internal protocol for handling security events includes detection, analysis, response, escalation, and mitigation. Security advisories are made available at https://streamlit.io/advisories. Penetration testing Streamlit uses third-party security tools to scan for vulnerabilities on a regular basis. Our security teams conduct periodic, intensive penetration tests on the Streamlit platform. Our product development team responds to any identified issues or potential vulnerabilities to ensure the quality, security, and availability of Streamlit applications. Vulnerability management We keep our systems up-to-date with the latest security patches and continuously monitor for new vulnerabilities. This includes automated scanning of our code repositories for vulnerable dependencies. If you discover a vulnerability in one of our products or websites, please report the issue to HackerOne.Previous: Fork and edit a public appNext: Deploy your appforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy" https://docs.streamlit.io/develop/concepts/architecture/forms#forms-are-containers,"DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsremoveCOREArchitecture & executionremoveRunning your appStreamlit's architectureThe app chromeCachingSession StateFormsFragmentsWidget behaviorMultipage appsaddApp designaddADDITIONALConnections and secretsaddCustom componentsaddConfiguration and themingaddApp testingaddAPI referenceaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Develop/Concepts/Architecture & execution/FormsUsing forms When you don't want to rerun your script with each input made by a user, st.form is here to help! Forms make it easy to batch user input into a single rerun. This guide to using forms provides examples and explains how users interact with forms. Example In the following example, a user can set multiple parameters to update the map. As the user changes the parameters, the script will not rerun and the map will not update. When the user submits the form with the button labeled ""Update map"", the script reruns and the map updates. If at any time the user clicks ""Generate new points"" which is outside of the form, the script will rerun. If the user has any unsubmitted changes within the form, these will not be sent with the rerun. All changes made to a form will only be sent to the Python backend when the form itself is submitted. View source codeexpand_moreimport streamlit as st import pandas as pd import numpy as np def get_data(): df = pd.DataFrame({ ""lat"": np.random.randn(200) / 50 + 37.76, ""lon"": np.random.randn(200) / 50 + -122.4, ""team"": ['A','B']*100 }) return df if st.button('Generate new points'): st.session_state.df = get_data() if 'df' not in st.session_state: st.session_state.df = get_data() df = st.session_state.df with st.form(""my_form""): header = st.columns([1,2,2]) header[0].subheader('Color') header[1].subheader('Opacity') header[2].subheader('Size') row1 = st.columns([1,2,2]) colorA = row1[0].color_picker('Team A', '#0000FF') opacityA = row1[1].slider('A opacity', 20, 100, 50, label_visibility='hidden') sizeA = row1[2].slider('A size', 50, 200, 100, step=10, label_visibility='hidden') row2 = st.columns([1,2,2]) colorB = row2[0].color_picker('Team B', '#FF0000') opacityB = row2[1].slider('B opacity', 20, 100, 50, label_visibility='hidden') sizeB = row2[2].slider('B size', 50, 200, 100, step=10, label_visibility='hidden') st.form_submit_button('Update map') alphaA = int(opacityA*255/100) alphaB = int(opacityB*255/100) df['color'] = np.where(df.team=='A',colorA+f'{alphaA:02x}',colorB+f'{alphaB:02x}') df['size'] = np.where(df.team=='A',sizeA, sizeB) st.map(df, size='size', color='color') Built with Streamlit 🎈Fullscreen open_in_new User interaction If a widget is not in a form, that widget will trigger a script rerun whenever a user changes its value. For widgets with keyed input (st.number_input, st.text_input, st.text_area), a new value triggers a rerun when the user clicks or tabs out of the widget. A user can also submit a change by pressing Enter while thier cursor is active in the widget. On the other hand if a widget is inside of a form, the script will not rerun when a user clicks or tabs out of that widget. For widgets inside a form, the script will rerun when the form is submitted and all widgets within the form will send their updated values to the Python backend. A user can submit a form using Enter on their keyboard if their cursor active in a widget that accepts keyed input. Within st.number_input and st.text_input a user presses Enter to submit the form. Within st.text_area a user presses Ctrl+Enter/⌘+Enter to submit the form. Widget values Before a form is submitted, all widgets within that form will have default values, just like widgets outside of a form have default values. import streamlit as st with st.form(""my_form""): st.write(""Inside the form"") my_number = st.slider('Pick a number', 1, 10) my_color = st.selectbox('Pick a color', ['red','orange','green','blue','violet']) st.form_submit_button('Submit my picks') # This is outside the form st.write(my_number) st.write(my_color) Built with Streamlit 🎈Fullscreen open_in_new Forms are containers When st.form is called, a container is created on the frontend. You can write to that container like you do with other container elements. That is, you can use Python's with statement as shown in the example above, or you can assign the form container to a variable and call methods on it directly. Additionally, you can place st.form_submit_button anywhere in the form container. import streamlit as st animal = st.form('my_animal') # This is writing directly to the main body. Since the form container is # defined above, this will appear below everything written in the form. sound = st.selectbox('Sounds like', ['meow','woof','squeak','tweet']) # These methods called on the form container, so they appear inside the form. submit = animal.form_submit_button(f'Say it with {sound}!') sentence = animal.text_input('Your sentence:', 'Where\'s the tuna?') say_it = sentence.rstrip('.,!?') + f', {sound}!' if submit: animal.subheader(say_it) else: animal.subheader(' ') Built with Streamlit 🎈Fullscreen open_in_new Processing form submissions The purpose of a form is to override the default behavior of Streamlit which reruns a script as soon as the user makes a change. For widgets outside of a form, the logical flow is: The user changes a widget's value on the frontend. The widget's value in st.session_state and in the Python backend (server) is updated. The script rerun begins. If the widget has a callback, it is executed as a prefix to the page rerun. When the updated widget's function is executed during the rerun, it outputs the new value. For widgets inside a form, any changes made by a user (step 1) do not get passed to the Python backend (step 2) until the form is submitted. Furthermore, the only widget inside a form that can have a callback function is the st.form_submit_button. If you need to execute a process using newly submitted values, you have three major patterns for doing so. Execute the process after the form If you need to execute a one-time process as a result of a form submission, you can condition that process on the st.form_submit_button and execute it after the form. If you need results from your process to display above the form, you can use containers to control where the form displays relative to your output. import streamlit as st col1,col2 = st.columns([1,2]) col1.title('Sum:') with st.form('addition'): a = st.number_input('a') b = st.number_input('b') submit = st.form_submit_button('add') if submit: col2.title(f'{a+b:.2f}') Built with Streamlit 🎈Fullscreen open_in_new Use a callback with session state You can use a callback to execute a process as a prefix to the script rerunning. priority_highImportantWhen processing newly updated values within a callback, do not pass those values to the callback directly through the args or kwargs parameters. You need to assign a key to any widget whose value you use within the callback. If you look up the value of that widget from st.session_state within the body of the callback, you will be able to access the newly submitted value. See the example below. import streamlit as st if 'sum' not in st.session_state: st.session_state.sum = '' def sum(): result = st.session_state.a + st.session_state.b st.session_state.sum = result col1,col2 = st.columns(2) col1.title('Sum:') if isinstance(st.session_state.sum, float): col2.title(f'{st.session_state.sum:.2f}') with st.form('addition'): st.number_input('a', key = 'a') st.number_input('b', key = 'b') st.form_submit_button('add', on_click=sum) Built with Streamlit 🎈Fullscreen open_in_new Use st.rerun If your process affects content above your form, another alternative is using an extra rerun. This can be less resource-efficient though, and may be less desirable that the above options. import streamlit as st if 'sum' not in st.session_state: st.session_state.sum = '' col1,col2 = st.columns(2) col1.title('Sum:') if isinstance(st.session_state.sum, float): col2.title(f'{st.session_state.sum:.2f}') with st.form('addition'): a = st.number_input('a') b = st.number_input('b') submit = st.form_submit_button('add') # The value of st.session_state.sum is updated at the end of the script rerun, # so the displayed value at the top in col2 does not show the new sum. Trigger # a second rerun when the form is submitted to update the value above. st.session_state.sum = a + b if submit: st.rerun() Built with Streamlit 🎈Fullscreen open_in_new Limitations Every form must contain a st.form_submit_button. st.button and st.download_button cannot be added to a form. st.form cannot be embedded inside another st.form. Callback functions can only be assigned to st.form_submit_button within a form; no other widgets in a form can have a callback. Interdependent widgets within a form are unlikely to be particularly useful. If you pass widget1's value into widget2 when they are both inside a form, then widget2 will only update when the form is submitted. Previous: Session StateNext: FragmentsforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy" https://docs.streamlit.io/develop/api-reference/app-testing/testing-element-classes#selectboxselect,"DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceremovePAGE ELEMENTSWrite and magicaddText elementsaddData elementsaddChart elementsaddInput widgetsaddMedia elementsaddLayouts and containersaddChat elementsaddStatus elementsaddThird-party componentsopen_in_newAPPLICATION LOGICNavigation and pagesaddExecution flowaddCaching and stateaddConnections and secretsaddCustom componentsaddUtilitiesaddConfigurationaddTOOLSApp testingremovest.testing.v1.AppTestTesting element classesCommand lineaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Develop/API reference/App testing/Testing element classesTesting element classes st.testing.v1.element_tree.Block The Block class has the same methods and attributes as AppTest. A Block instance represents a container of elements just as AppTest represents the entire app. For example, Block.button will produce a WidgetList of Button in the same manner as AppTest.button. ChatMessage, Column, and Tab all inherit from Block. For all container classes, parameters of the original element can be obtained as properties. For example, ChatMessage.avatar and Tab.label. st.testing.v1.element_tree.ElementStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeElement base class for testing. This class's methods and attributes are universal for all elements implemented in testing. For example, Caption, Code, Text, and Title inherit from Element. All widget classes also inherit from Element, but have additional methods specific to each widget type. See the AppTest class for the full list of supported elements. For all element classes, parameters of the original element can be obtained as properties. For example, Button.label, Caption.help, and Toast.icon. Class description[source] st.testing.v1.element_tree.Element(proto, root) Methods run(*, timeout=None) Run the AppTest script which contains the element. Attributes value The value or contents of the element. st.testing.v1.element_tree.ButtonStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.button and st.form_submit_button. Class description[source] st.testing.v1.element_tree.Button(proto, root) Methods click() Set the value of the button to True. run(*, timeout=None) Run the AppTest script which contains the element. set_value(v) Set the value of the button. Attributes value The value of the button. (bool) st.testing.v1.element_tree.ChatInputStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.chat_input. Class description[source] st.testing.v1.element_tree.ChatInput(proto, root) Methods run(*, timeout=None) Run the AppTest script which contains the element. set_value(v) Set the value of the widget. Attributes value The value of the widget. (str) st.testing.v1.element_tree.CheckboxStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.checkbox. Class description[source] st.testing.v1.element_tree.Checkbox(proto, root) Methods check() Set the value of the widget to True. run(*, timeout=None) Run the AppTest script which contains the element. set_value(v) Set the value of the widget. uncheck() Set the value of the widget to False. Attributes value The value of the widget. (bool) st.testing.v1.element_tree.ColorPickerStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.color_picker. Class description[source] st.testing.v1.element_tree.ColorPicker(proto, root) Methods pick(v) Set the value of the widget as a hex string. May omit the ""#"" prefix. run(*, timeout=None) Run the AppTest script which contains the element. set_value(v) Set the value of the widget as a hex string. Attributes value The currently selected value as a hex string. (str) st.testing.v1.element_tree.DateInputStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.date_input. Class description[source] st.testing.v1.element_tree.DateInput(proto, root) Methods run(*, timeout=None) Run the AppTest script which contains the element. set_value(v) Set the value of the widget. Attributes value The value of the widget. (date or Tuple of date) st.testing.v1.element_tree.MultiselectStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.multiselect. Class description[source] st.testing.v1.element_tree.Multiselect(proto, root) Methods run(*, timeout=None) Run the AppTest script which contains the element. select(v) Add a selection to the widget. Do nothing if the value is already selected. If testing a multiselect widget with repeated options, use set_value instead. set_value(v) Set the value of the multiselect widget. (list) unselect(v) Remove a selection from the widget. Do nothing if the value is not already selected. If a value is selected multiple times, the first instance is removed. Attributes format_func The widget's formatting function for displaying options. (callable) indices The indices of the currently selected values from the options. (list) value The currently selected values from the options. (list) st.testing.v1.element_tree.NumberInputStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.number_input. Class description[source] st.testing.v1.element_tree.NumberInput(proto, root) Methods decrement() Decrement the st.number_input widget as if the user clicked ""-"". increment() Increment the st.number_input widget as if the user clicked ""+"". run(*, timeout=None) Run the AppTest script which contains the element. set_value(v) Set the value of the st.number_input widget. Attributes value Get the current value of the st.number_input widget. st.testing.v1.element_tree.RadioStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.radio. Class description[source] st.testing.v1.element_tree.Radio(proto, root) Methods run(*, timeout=None) Run the AppTest script which contains the element. set_value(v) Set the selection by value. Attributes format_func The widget's formatting function for displaying options. (callable) index The index of the current selection. (int) value The currently selected value from the options. (Any) st.testing.v1.element_tree.SelectSliderStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.select_slider. Class description[source] st.testing.v1.element_tree.SelectSlider(proto, root) Methods run(*, timeout=None) Run the AppTest script which contains the element. set_range(lower, upper) Set the ranged selection by values. set_value(v) Set the (single) selection by value. Attributes format_func The widget's formatting function for displaying options. (callable) value The currently selected value or range. (Any or Sequence of Any) st.testing.v1.element_tree.SelectboxStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.selectbox. Class description[source] st.testing.v1.element_tree.Selectbox(proto, root) Methods run(*, timeout=None) Run the AppTest script which contains the element. select(v) Set the selection by value. select_index(index) Set the selection by index. set_value(v) Set the selection by value. Attributes format_func The widget's formatting function for displaying options. (callable) index The index of the current selection. (int) value The currently selected value from the options. (Any) st.testing.v1.element_tree.SliderStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.slider. Class description[source] st.testing.v1.element_tree.Slider(proto, root) Methods run(*, timeout=None) Run the AppTest script which contains the element. set_range(lower, upper) Set the ranged value of the slider. set_value(v) Set the (single) value of the slider. Attributes value The currently selected value or range. (Any or Sequence of Any) st.testing.v1.element_tree.TextAreaStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.text_area. Class description[source] st.testing.v1.element_tree.TextArea(proto, root) Methods input(v) Set the value of the widget only if the value does not exceed the maximum allowed characters. run(*, timeout=None) Run the AppTest script which contains the element. set_value(v) Set the value of the widget. Attributes value The current value of the widget. (str) st.testing.v1.element_tree.TextInputStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.text_input. Class description[source] st.testing.v1.element_tree.TextInput(proto, root) Methods input(v) Set the value of the widget only if the value does not exceed the maximum allowed characters. run(*, timeout=None) Run the AppTest script which contains the element. set_value(v) Set the value of the widget. Attributes value The current value of the widget. (str) st.testing.v1.element_tree.TimeInputStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.time_input. Class description[source] st.testing.v1.element_tree.TimeInput(proto, root) Methods decrement() Select the previous available time. increment() Select the next available time. run(*, timeout=None) Run the AppTest script which contains the element. set_value(v) Set the value of the widget. Attributes value The current value of the widget. (time) st.testing.v1.element_tree.ToggleStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.toggle. Class description[source] st.testing.v1.element_tree.Toggle(proto, root) Methods run(*, timeout=None) Run the AppTest script which contains the element. set_value(v) Set the value of the widget. Attributes value The current value of the widget. (bool) Previous: st.testing.v1.AppTestNext: Command lineforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy" https://docs.streamlit.io/deploy/tutorials/kubernetes#create-a-kubernetes-configuration-file,"DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsremoveDockerKubernetesschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Deploy/Other platforms/KubernetesDeploy Streamlit using Kubernetes Introduction So you have an amazing app and you want to start sharing it with other people, what do you do? You have a few options. First, where do you want to run your Streamlit app, and how do you want to access it? On your corporate network - Most corporate networks are closed to the outside world. You typically use a VPN to log onto your corporate network and access resources there. You could run your Streamlit app on a server in your corporate network for security reasons, to ensure that only folks internal to your company can access it. On the cloud - If you'd like to access your Streamlit app from outside of a corporate network, or share your app with folks outside of your home network or laptop, you might choose this option. In this case, it'll depend on your hosting provider. We have community-submitted guides from Heroku, AWS, and other providers. Wherever you decide to deploy your app, you will first need to containerize it. This guide walks you through using Kubernetes to deploy your app. If you prefer Docker see Deploy Streamlit using Docker. Prerequisites Install Docker Engine Install the gcloud CLI Install Docker Engine If you haven't already done so, install Docker on your server. Docker provides .deb and .rpm packages from many Linux distributions, including: Debian Ubuntu Verify that Docker Engine is installed correctly by running the hello-world Docker image: sudo docker run hello-world starTipFollow Docker's official post-installation steps for Linux to run Docker as a non-root user, so that you don't have to preface the docker command with sudo. Install the gcloud CLI In this guide, we will orchestrate Docker containers with Kubernetes and host docker images on the Google Container Registry (GCR). As GCR is a Google-supported Docker registry, we need to register gcloud as the Docker credential helper. Follow the official documentation to Install the gcloud CLI and initialize it. Create a Docker container We need to create a docker container which contains all the dependencies and the application code. Below you can see the entrypoint, i.e. the command run when the container starts, and the Dockerfile definition. Create an entrypoint script Create a run.sh script containing the following: #!/bin/bash APP_PID= stopRunningProcess() { # Based on https://linuxconfig.org/how-to-propagate-a-signal-to-child-processes-from-a-bash-script if test ! ""${APP_PID}"" = '' && ps -p ${APP_PID} > /dev/null ; then > /proc/1/fd/1 echo ""Stopping ${COMMAND_PATH} which is running with process ID ${APP_PID}"" kill -TERM ${APP_PID} > /proc/1/fd/1 echo ""Waiting for ${COMMAND_PATH} to process SIGTERM signal"" wait ${APP_PID} > /proc/1/fd/1 echo ""All processes have stopped running"" else > /proc/1/fd/1 echo ""${COMMAND_PATH} was not started when the signal was sent or it has already been stopped"" fi } trap stopRunningProcess EXIT TERM source ${VIRTUAL_ENV}/bin/activate streamlit run ${HOME}/app/streamlit_app.py & APP_ID=${!} wait ${APP_ID} Create a Dockerfile Docker builds images by reading the instructions from a Dockerfile. A Dockerfile is a text document that contains all the commands a user could call on the command line to assemble an image. Learn more in the Dockerfile reference. The docker build command builds an image from a Dockerfile. The docker run command first creates a container over the specified image, and then starts it using the specified command. Here's an example Dockerfile that you can add to the root of your directory. FROM python:3.8-slim RUN groupadd --gid 1000 appuser \ && useradd --uid 1000 --gid 1000 -ms /bin/bash appuser RUN pip3 install --no-cache-dir --upgrade \ pip \ virtualenv RUN apt-get update && apt-get install -y \ build-essential \ software-properties-common \ git USER appuser WORKDIR /home/appuser RUN git clone https://github.com/streamlit/streamlit-example.git app ENV VIRTUAL_ENV=/home/appuser/venv RUN virtualenv ${VIRTUAL_ENV} RUN . ${VIRTUAL_ENV}/bin/activate && pip install -r app/requirements.txt EXPOSE 8501 COPY run.sh /home/appuser ENTRYPOINT [""./run.sh""] priority_highImportantAs mentioned in Development flow, for Streamlit version 1.10.0 and higher, Streamlit apps cannot be run from the root directory of Linux distributions. Your main script should live in a directory other than the root directory. If you try to run a Streamlit app from the root directory, Streamlit will throw a FileNotFoundError: [Errno 2] No such file or directory error. For more information, see GitHub issue #5239.If you are using Streamlit version 1.10.0 or higher, you must set the WORKDIR to a directory other than the root directory. For example, you can set the WORKDIR to /home/appuser as shown in the example Dockerfile above. Build a Docker image Put the above files (run.sh and Dockerfile) in the same folder and build the docker image: docker build --platform linux/amd64 -t gcr.io/$GCP_PROJECT_ID/k8s-streamlit:test . priority_highImportantReplace $GCP_PROJECT_ID in the above command with the name of your Google Cloud project. Upload the Docker image to a container registry The next step is to upload the Docker image to a container registry. In this example, we will use the Google Container Registry (GCR). Start by enabling the Container Registry API. Sign in to Google Cloud and navigate to your project’s Container Registry and click Enable. We can now build the Docker image from the previous step and push it to our project’s GCR. Be sure to replace $GCP_PROJECT_ID in the docker push command with the name of your project: gcloud auth configure-docker docker push gcr.io/$GCP_PROJECT_ID/k8s-streamlit:test Create a Kubernetes deployment For this step you will need a: Running Kubernetes service Custom domain for which you can generate a TLS certificate DNS service where you can configure your custom domain to point to the application IP As the image was uploaded to the container registry in the previous step, we can run it in Kubernetes using the below configurations. Install and run Kubernetes Make sure your Kubernetes client, kubectl, is installed and running on your machine. Configure a Google OAuth Client and oauth2-proxy For configuring the Google OAuth Client, please see Google Auth Provider. Configure oauth2-proxy to use the desired OAuth Provider Configuration and update the oath2-proxy config in the config map. The below configuration contains a ouath2-proxy sidecar container which handles the authentication with Google. You can learn more from the oauth2-proxy repository. Create a Kubernetes configuration file Create a YAML configuration file named k8s-streamlit.yaml: apiVersion: v1 kind: ConfigMap metadata: name: streamlit-configmap data: oauth2-proxy.cfg: |- http_address = ""0.0.0.0:4180"" upstreams = [""http://127.0.0.1:8501/""] email_domains = [""*""] client_id = """" client_secret = """" cookie_secret = ""<16, 24, or 32 bytes>"" redirect_url = --- apiVersion: apps/v1 kind: Deployment metadata: name: streamlit-deployment labels: app: streamlit spec: replicas: 1 selector: matchLabels: app: streamlit template: metadata: labels: app: streamlit spec: containers: - name: oauth2-proxy image: quay.io/oauth2-proxy/oauth2-proxy:v7.2.0 args: [""--config"", ""/etc/oauth2-proxy/oauth2-proxy.cfg""] ports: - containerPort: 4180 livenessProbe: httpGet: path: /ping port: 4180 scheme: HTTP readinessProbe: httpGet: path: /ping port: 4180 scheme: HTTP volumeMounts: - mountPath: ""/etc/oauth2-proxy"" name: oauth2-config - name: streamlit image: gcr.io/GCP_PROJECT_ID/k8s-streamlit:test imagePullPolicy: Always ports: - containerPort: 8501 livenessProbe: httpGet: path: /_stcore/health port: 8501 scheme: HTTP timeoutSeconds: 1 readinessProbe: httpGet: path: /_stcore/health port: 8501 scheme: HTTP timeoutSeconds: 1 resources: limits: cpu: 1 memory: 2Gi requests: cpu: 100m memory: 745Mi volumes: - name: oauth2-config configMap: name: streamlit-configmap --- apiVersion: v1 kind: Service metadata: name: streamlit-service spec: type: LoadBalancer selector: app: streamlit ports: - name: streamlit-port protocol: TCP port: 80 targetPort: 4180 priority_highImportantWhile the above configurations can be copied verbatim, you will have to configure the oauth2-proxy yourself and use the correct GOOGLE_CLIENT_ID, GOOGLE_CLIENT_ID, GCP_PROJECT_ID, and REDIRECT_URL. Now create the configuration from the file in Kubernetes with the kubectl create command: kubctl create -f k8s-streamlit.yaml Set up TLS support Since you are using the Google authentication, you will need to set up TLS support. Find out how in TLS Configuration. Verify the deployment Once the deployment and the service are created, we need to wait a couple of minutes for the public IP address to become available. We can check when that is ready by running: kubectl get service streamlit-service -o jsonpath='{.status.loadBalancer.ingress[0].ip}' After the public IP is assigned, you will need to configure in your DNS service an A record pointing to the above IP address.Previous: DockerNext: Knowledge baseforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy" https://docs.streamlit.io/develop/api-reference/configuration/config.toml,"DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceremovePAGE ELEMENTSWrite and magicaddText elementsaddData elementsaddChart elementsaddInput widgetsaddMedia elementsaddLayouts and containersaddChat elementsaddStatus elementsaddThird-party componentsopen_in_newAPPLICATION LOGICNavigation and pagesaddExecution flowaddCaching and stateaddConnections and secretsaddCustom componentsaddUtilitiesaddConfigurationremoveconfig.tomlst.set_page_configTOOLSApp testingaddCommand lineaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Develop/API reference/Configuration/config.tomlconfig.toml config.toml is an optional file you can define for your working directory or global development environment. When config.toml is defined both globally and in your working directory, Streamlit combines the configuration options and gives precendence to the working-directory configuration. Additionally, you can use environment variables and command-line options to override additional configuration options. For more information, see Configuration options. File location To define your configuration locally or per-project, add .streamlit/config.toml to your working directory. Your working directory is wherever you call streamlit run. If you haven't previously created the .streamlit directory, you will need to add it. To define your configuration globally, you must first locate your global .streamlit directory. Streamlit adds this hidden directory to your OS user profile during installation. For MacOS/Linx, this will be ~/.streamlit/config.toml. For Windows, this will be %userprofile%/.streamlit/config.toml. File format config.toml is a TOML file. Example [client] showErrorDetails = false [theme] primaryColor = ""#F63366"" backgroundColor = ""black"" Available configuration options Below are all the sections and options you can have in your .streamlit/config.toml file. To see all configurations, use the following command in your terminal or CLI: streamlit config show Global [global] # ***DEPRECATED*** # global.disableWatchdogWarning has been deprecated has been deprecated and # will be removed in a future version. This option will be removed on or after # 2024-01-20. # **************** # By default, Streamlit checks if the Python watchdog module is available # and, if not, prints a warning asking for you to install it. The watchdog # module is not required, but highly recommended. It improves Streamlit's # ability to detect changes to files in your filesystem. # If you'd like to turn off this warning, set this to True. # Default: false disableWatchdogWarning = false # By default, Streamlit displays a warning when a user sets both a widget # default value in the function defining the widget and a widget value via # the widget's key in `st.session_state`. # If you'd like to turn off this warning, set this to True. # Default: false disableWidgetStateDuplicationWarning = false # If True, will show a warning when you run a Streamlit-enabled script # via ""python my_script.py"". # Default: true showWarningOnDirectExecution = true Logger [logger] # Level of logging: 'error', 'warning', 'info', or 'debug'. # Default: 'info' level = ""info"" # String format for logging messages. If logger.datetimeFormat is set, # logger messages will default to `%(asctime)s.%(msecs)03d %(message)s`. See # Python's documentation for available attributes: # https://docs.python.org/2.6/develop/logging.html#formatter-objects # Default: ""%(asctime)s %(message)s"" messageFormat = ""%(asctime)s %(message)s"" Client [client] # ***DEPRECATED*** # client.caching has been deprecated and is not required anymore for our new # caching commands. This option will be removed on or after 2024-01-20. # **************** # Whether to enable st.cache. This does not affect st.cache_data or # st.cache_resource. # Default: true caching = true # ***DEPRECATED*** # client.displayEnabled has been deprecated and will be removed in a future # version. This option will be removed on or after 2024-01-20. # **************** # If false, makes your Streamlit script not draw to a Streamlit app. # Default: true displayEnabled = true # Controls whether uncaught app exceptions and deprecation warnings # are displayed in the browser. By default, this is set to True and # Streamlit displays app exceptions and associated tracebacks, and # deprecation warnings, in the browser. # # If set to False, deprecation warnings and full exception messages # will print to the console only. Exceptions will still display in the # browser with a generic error message. For now, the exception type and # traceback show in the browser also, but they will be removed in the # future. # Default: true showErrorDetails = true # Change the visibility of items in the toolbar, options menu, # and settings dialog (top right of the app). # Allowed values: # * ""auto"" : Show the developer options if the app is accessed through # localhost or through Streamlit Community Cloud as a developer. # Hide them otherwise. # * ""developer"" : Show the developer options. # * ""viewer"" : Hide the developer options. # * ""minimal"" : Show only options set externally (e.g. through # Streamlit Community Cloud) or through st.set_page_config. # If there are no options left, hide the menu. # Default: ""auto"" toolbarMode = ""auto"" # Controls whether the default sidebar page navigation in a multipage app is # displayed. # Default: true showSidebarNavigation = true Runner [runner] # Allows you to type a variable or string by itself in a single line of # Python code to write it to the app. # Default: true magicEnabled = true # ***DEPRECATED*** # runner.installTracer has been deprecated and will be removed in a future # version. This option will be removed on or after 2024-01-20. # **************** # Install a Python tracer to allow you to stop or pause your script at # any point and introspect it. As a side-effect, this slows down your # script's execution. # Default: false installTracer = false # ***DEPRECATED*** # runner.fixMatplotlib has been deprecated and will be removed in a future # version. This option will be removed on or after 2024-01-20. # **************** # Sets the MPLBACKEND environment variable to Agg inside Streamlit to # prevent Python crashing. # Default: true fixMatplotlib = true # Handle script rerun requests immediately, rather than waiting for script # execution to reach a yield point. This makes Streamlit much more # responsive to user interaction, but it can lead to race conditions in # apps that mutate session_state data outside of explicit session_state # assignment statements. # Default: true fastReruns = true # Raise an exception after adding unserializable data to Session State. # Some execution environments may require serializing all data in Session # State, so it may be useful to detect incompatibility during development, # or when the execution environment will stop supporting it in the future. # Default: false enforceSerializableSessionState = false # Adjust how certain 'options' widgets like radio, selectbox, and # multiselect coerce Enum members when the Enum class gets # re-defined during a script re-run. For more information, check out the docs: # https://docs.streamlit.io/develop/concepts/design/custom-classes#enums # # Allowed values: # * ""off"" : Disables Enum coercion. # * ""nameOnly"" : Enum classes can be coerced if their member names match. # * ""nameAndValue"" : Enum classes can be coerced if their member names AND # member values match. # Default: ""nameOnly"" enumCoercion = ""nameOnly"" Server [server] # List of folders that should not be watched for changes. This # impacts both ""Run on Save"" and @st.cache. # Relative paths will be taken as relative to the current working directory. # Example: ['/home/user1/env', 'relative/path/to/folder'] # Default: [] folderWatchBlacklist = [] # Change the type of file watcher used by Streamlit, or turn it off # completely. # Allowed values: # * ""auto"" : Streamlit will attempt to use the watchdog module, and # falls back to polling if watchdog is not available. # * ""watchdog"" : Force Streamlit to use the watchdog module. # * ""poll"" : Force Streamlit to always use polling. # * ""none"" : Streamlit will not watch files. # Default: ""auto"" fileWatcherType = ""auto"" # Symmetric key used to produce signed cookies. If deploying on multiple # replicas, this should be set to the same value across all replicas to ensure # they all share the same secret. # Default: randomly generated secret key. cookieSecret = ""a-random-key-appears-here"" # If false, will attempt to open a browser window on start. # Default: false unless (1) we are on a Linux box where DISPLAY is unset, or # (2) we are running in the Streamlit Atom plugin. headless = false # Automatically rerun script when the file is modified on disk. # Default: false runOnSave = false # The address where the server will listen for client and browser # connections. Use this if you want to bind the server to a specific address. # If set, the server will only be accessible from this address, and not from # any aliases (like localhost). # Default: (unset) address = # The port where the server will listen for browser connections. # Don't use port 3000 which is reserved for internal development. # Default: 8501 port = 8501 # The base path for the URL where Streamlit should be served from. # Default: """" baseUrlPath = """" # Enables support for Cross-Origin Resource Sharing (CORS) protection, for # added security. # Due to conflicts between CORS and XSRF, if `server.enableXsrfProtection` is # on and `server.enableCORS` is off at the same time, we will prioritize # `server.enableXsrfProtection`. # Default: true enableCORS = true # Enables support for Cross-Site Request Forgery (XSRF) protection, for added # security. # Due to conflicts between CORS and XSRF, if `server.enableXsrfProtection` is # on and `server.enableCORS` is off at the same time, we will prioritize # `server.enableXsrfProtection`. # Default: true enableXsrfProtection = true # Max size, in megabytes, for files uploaded with the file_uploader. # Default: 200 maxUploadSize = 200 # Max size, in megabytes, of messages that can be sent via the WebSocket # connection. # Default: 200 maxMessageSize = 200 # Enables support for websocket compression. # Default: false enableWebsocketCompression = false # Enable serving files from a `static` directory in the running app's # directory. # Default: false enableStaticServing = false # Server certificate file for connecting via HTTPS. # Must be set at the same time as ""server.sslKeyFile"". # ['DO NOT USE THIS OPTION IN A PRODUCTION ENVIRONMENT. It has not gone through # security audits or performance tests. For the production environment, we # recommend performing SSL termination by the load balancer or the reverse # proxy.'] # sslCertFile = # Cryptographic key file for connecting via HTTPS. # Must be set at the same time as ""server.sslCertFile"". # ['DO NOT USE THIS OPTION IN A PRODUCTION ENVIRONMENT. It has not gone through # security audits or performance tests. For the production environment, we # recommend performing SSL termination by the load balancer or the reverse # proxy.'] # sslKeyFile = Browser [browser] # Internet address where users should point their browsers in order to # connect to the app. Can be IP address or DNS name and path. # This is used to: # - Set the correct URL for CORS and XSRF protection purposes. # - Show the URL on the terminal # - Open the browser # Default: ""localhost"" serverAddress = ""localhost"" # Whether to send usage statistics to Streamlit. # Default: true gatherUsageStats = true # Port where users should point their browsers in order to connect to the # app. # This is used to: # - Set the correct URL for XSRF protection purposes. # - Show the URL on the terminal (part of `streamlit run`). # - Open the browser automatically (part of `streamlit run`). # This option is for advanced use cases. To change the port of your app, use # `server.Port` instead. Don't use port 3000 which is reserved for internal # development. # Default: whatever value is set in server.port. serverPort = 8501 Mapbox [mapbox] # Configure Streamlit to use a custom Mapbox # token for elements like st.pydeck_chart and st.map. # To get a token for yourself, create an account at # https://mapbox.com. It's free (for moderate usage levels)! # Default: """" token = """" Deprecation [deprecation] # Set to false to disable the deprecation warning for using the global pyplot # instance. # Default: true showPyplotGlobalUse = true Theme [theme] # The preset Streamlit theme that your custom theme inherits from. # One of ""light"" or ""dark"". # base = # Primary accent color for interactive elements. # primaryColor = # Background color for the main content area. # backgroundColor = # Background color used for the sidebar and most interactive widgets. # secondaryBackgroundColor = # Color used for almost all text. # textColor = # Font family for all text in the app, except code blocks. One of ""sans serif"", # ""serif"", or ""monospace"". # font = Previous: ConfigurationNext: st.set_page_configforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy" https://docs.streamlit.io/develop/api-reference/widgets/st.select_slider#featured-videos,"DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceremovePAGE ELEMENTSWrite and magicaddText elementsaddData elementsaddChart elementsaddInput widgetsremoveBUTTONSst.buttonst.download_buttonst.form_submit_buttonlinkst.link_buttonst.page_linkSELECTIONSst.checkboxst.color_pickerst.multiselectst.radiost.selectboxst.select_sliderst.toggleNUMERICst.number_inputst.sliderDATE & TIMEst.date_inputst.time_inputTEXTst.chat_inputlinkst.text_areast.text_inputMEDIA & FILESst.camera_inputst.data_editorlinkst.file_uploaderMedia elementsaddLayouts and containersaddChat elementsaddStatus elementsaddThird-party componentsopen_in_newAPPLICATION LOGICNavigation and pagesaddExecution flowaddCaching and stateaddConnections and secretsaddCustom componentsaddUtilitiesaddConfigurationaddTOOLSApp testingaddCommand lineaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Develop/API reference/Input widgets/st.select_sliderst.select_sliderStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeDisplay a slider widget to select items from a list. This also allows you to render a range slider by passing a two-element tuple or list as the value. The difference between st.select_slider and st.slider is that select_slider accepts any datatype and takes an iterable set of options, while st.slider only accepts numerical or date/time data and takes a range as input. Function signature[source] st.select_slider(label, options=(), value=None, format_func=special_internal_function, key=None, help=None, on_change=None, args=None, kwargs=None, *, disabled=False, label_visibility=""visible"") Parameters label (str) A short label explaining to the user what this slider is for. The label can optionally contain Markdown and supports the following elements: Bold, Italics, Strikethroughs, Inline Code, Emojis, and Links. This also supports: Emoji shortcodes, such as :+1: and :sunglasses:. For a list of all supported codes, see https://share.streamlit.io/streamlit/emoji-shortcodes. LaTeX expressions, by wrapping them in ""$"" or ""$$"" (the ""$$"" must be on their own lines). Supported LaTeX functions are listed at https://katex.org/docs/supported.html. Colored text and background colors for text, using the syntax :color[text to be colored] and :color-background[text to be colored], respectively. color must be replaced with any of the following supported colors: blue, green, orange, red, violet, gray/grey, rainbow. For example, you can use :orange[your text here] or :blue-background[your text here]. Unsupported elements are unwrapped so only their children (text contents) render. Display unsupported elements as literal characters by backslash-escaping them. E.g. 1\. Not an ordered list. For accessibility reasons, you should never set an empty label (label="""") but hide it with label_visibility if needed. In the future, we may disallow empty labels by raising an exception. options (Iterable) Labels for the select options in an Iterable. For example, this can be a list, numpy.ndarray, pandas.Series, pandas.DataFrame, or pandas.Index. For pandas.DataFrame, the first column is used. Each label will be cast to str internally by default. value (a supported type or a tuple/list of supported types or None) The value of the slider when it first renders. If a tuple/list of two values is passed here, then a range slider with those lower and upper bounds is rendered. For example, if set to (1, 10) the slider will have a selectable range between 1 and 10. Defaults to first option. format_func (function) Function to modify the display of the labels from the options. argument. It receives the option as an argument and its output will be cast to str. key (str or int) An optional string or integer to use as the unique key for the widget. If this is omitted, a key will be generated for the widget based on its content. Multiple widgets of the same type may not share the same key. help (str) An optional tooltip that gets displayed next to the select slider. on_change (callable) An optional callback invoked when this select_slider's value changes. args (tuple) An optional tuple of args to pass to the callback. kwargs (dict) An optional dict of kwargs to pass to the callback. disabled (bool) An optional boolean, which disables the select slider if set to True. The default is False. label_visibility (""visible"", ""hidden"", or ""collapsed"") The visibility of the label. If ""hidden"", the label doesn't show but there is still empty space for it above the widget (equivalent to label=""""). If ""collapsed"", both the label and the space are removed. Default is ""visible"". Returns(any value or tuple of any value) The current value of the slider widget. The return type will match the data type of the value parameter. Examples import streamlit as st color = st.select_slider( ""Select a color of the rainbow"", options=[""red"", ""orange"", ""yellow"", ""green"", ""blue"", ""indigo"", ""violet""]) st.write(""My favorite color is"", color) And here's an example of a range select slider: import streamlit as st start_color, end_color = st.select_slider( ""Select a range of color wavelength"", options=[""red"", ""orange"", ""yellow"", ""green"", ""blue"", ""indigo"", ""violet""], value=(""red"", ""blue"")) st.write(""You selected wavelengths between"", start_color, ""and"", end_color) Built with Streamlit 🎈Fullscreen open_in_new Featured videos Check out our video on how to use one of Streamlit's core functions, the select slider! 🎈 In the video below, we'll take it a step further and make a double-ended slider. Previous: st.selectboxNext: st.toggleforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy" https://docs.streamlit.io/develop/api-reference/data/st.data_editor#configuring-columns,"DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceremovePAGE ELEMENTSWrite and magicaddText elementsaddData elementsremovest.dataframest.data_editorst.column_configaddst.tablest.metricst.jsonChart elementsaddInput widgetsaddMedia elementsaddLayouts and containersaddChat elementsaddStatus elementsaddThird-party componentsopen_in_newAPPLICATION LOGICNavigation and pagesaddExecution flowaddCaching and stateaddConnections and secretsaddCustom componentsaddUtilitiesaddConfigurationaddTOOLSApp testingaddCommand lineaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Develop/API reference/Data elements/st.data_editorstarTipThis page only contains information on the st.data_editor API. For an overview of working with dataframes and to learn more about the data editor's capabilities and limitations, read Dataframes. st.data_editorStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeDisplay a data editor widget. The data editor widget allows you to edit dataframes and many other data structures in a table-like UI. Warning When going from st.experimental_data_editor to st.data_editor in 1.23.0, the data editor's representation in st.session_state was changed. The edited_cells dictionary is now called edited_rows and uses a different format ({0: {""column name"": ""edited value""}} instead of {""0:1"": ""edited value""}). You may need to adjust the code if your app uses st.experimental_data_editor in combination with st.session_state. Function signature[source] st.data_editor(data, *, width=None, height=None, use_container_width=False, hide_index=None, column_order=None, column_config=None, num_rows=""fixed"", disabled=False, key=None, on_change=None, args=None, kwargs=None) Parameters data (pandas.DataFrame, pandas.Series, pandas.Styler, pandas.Index, pyarrow.Table, numpy.ndarray, pyspark.sql.DataFrame, snowflake.snowpark.DataFrame, list, set, tuple, dict, or None) The data to edit in the data editor. Note Styles from pandas.Styler will only be applied to non-editable columns. Mixing data types within a column can make the column uneditable. Additionally, the following data types are not yet supported for editing: complex, list, tuple, bytes, bytearray, memoryview, dict, set, frozenset, fractions.Fraction, pandas.Interval, and pandas.Period. To prevent overflow in JavaScript, columns containing datetime.timedelta and pandas.Timedelta values will default to uneditable but this can be changed through column configuration. width (int or None) Desired width of the data editor expressed in pixels. If None, the width will be automatically determined. height (int or None) Desired height of the data editor expressed in pixels. If None, the height will be automatically determined. use_container_width (bool) If True, set the data editor width to the width of the parent container. This takes precedence over the width argument. Defaults to False. hide_index (bool or None) Whether to hide the index column(s). If None (default), the visibility of index columns is automatically determined based on the data. column_order (Iterable of str or None) Specifies the display order of columns. This also affects which columns are visible. For example, column_order=(""col2"", ""col1"") will display 'col2' first, followed by 'col1', and will hide all other non-index columns. If None (default), the order is inherited from the original data structure. column_config (dict or None) Configures how columns are displayed, e.g. their title, visibility, type, or format, as well as editing properties such as min/max value or step. This needs to be a dictionary where each key is a column name and the value is one of: None to hide the column. A string to set the display label of the column. One of the column types defined under st.column_config, e.g. st.column_config.NumberColumn(""Dollar values”, format=”$ %d"") to show a column as dollar amounts. See more info on the available column types and config options here. To configure the index column(s), use _index as the column name. num_rows (""fixed"" or ""dynamic"") Specifies if the user can add and delete rows in the data editor. If ""fixed"", the user cannot add or delete rows. If ""dynamic"", the user can add and delete rows in the data editor, but column sorting is disabled. Defaults to ""fixed"". disabled (bool or Iterable of str) Controls the editing of columns. If True, editing is disabled for all columns. If an Iterable of column names is provided (e.g., disabled=(""col1"", ""col2"")), only the specified columns will be disabled for editing. If False (default), all columns that support editing are editable. key (str) An optional string to use as the unique key for this widget. If this is omitted, a key will be generated for the widget based on its content. Multiple widgets of the same type may not share the same key. on_change (callable) An optional callback invoked when this data_editor's value changes. args (tuple) An optional tuple of args to pass to the callback. kwargs (dict) An optional dict of kwargs to pass to the callback. Returns(pandas.DataFrame, pandas.Series, pyarrow.Table, numpy.ndarray, list, set, tuple, or dict.) The edited data. The edited data is returned in its original data type if it corresponds to any of the supported return types. All other data types are returned as a pandas.DataFrame. Examples import streamlit as st import pandas as pd df = pd.DataFrame( [ {""command"": ""st.selectbox"", ""rating"": 4, ""is_widget"": True}, {""command"": ""st.balloons"", ""rating"": 5, ""is_widget"": False}, {""command"": ""st.time_input"", ""rating"": 3, ""is_widget"": True}, ] ) edited_df = st.data_editor(df) favorite_command = edited_df.loc[edited_df[""rating""].idxmax()][""command""] st.markdown(f""Your favorite command is **{favorite_command}** 🎈"") Built with Streamlit 🎈Fullscreen open_in_new You can also allow the user to add and delete rows by setting num_rows to ""dynamic"": import streamlit as st import pandas as pd df = pd.DataFrame( [ {""command"": ""st.selectbox"", ""rating"": 4, ""is_widget"": True}, {""command"": ""st.balloons"", ""rating"": 5, ""is_widget"": False}, {""command"": ""st.time_input"", ""rating"": 3, ""is_widget"": True}, ] ) edited_df = st.data_editor(df, num_rows=""dynamic"") favorite_command = edited_df.loc[edited_df[""rating""].idxmax()][""command""] st.markdown(f""Your favorite command is **{favorite_command}** 🎈"") Built with Streamlit 🎈Fullscreen open_in_new Or you can customize the data editor via column_config, hide_index, column_order, or disabled: import pandas as pd import streamlit as st df = pd.DataFrame( [ {""command"": ""st.selectbox"", ""rating"": 4, ""is_widget"": True}, {""command"": ""st.balloons"", ""rating"": 5, ""is_widget"": False}, {""command"": ""st.time_input"", ""rating"": 3, ""is_widget"": True}, ] ) edited_df = st.data_editor( df, column_config={ ""command"": ""Streamlit Command"", ""rating"": st.column_config.NumberColumn( ""Your rating"", help=""How much do you like this command (1-5)?"", min_value=1, max_value=5, step=1, format=""%d ⭐"", ), ""is_widget"": ""Widget ?"", }, disabled=[""command"", ""is_widget""], hide_index=True, ) favorite_command = edited_df.loc[edited_df[""rating""].idxmax()][""command""] st.markdown(f""Your favorite command is **{favorite_command}** 🎈"") Built with Streamlit 🎈Fullscreen open_in_new Configuring columns You can configure the display and editing behavior of columns in st.dataframe and st.data_editor via the Column configuration API. We have developed the API to let you add images, charts, and clickable URLs in dataframe and data editor columns. Additionally, you can make individual columns editable, set columns as categorical and specify which options they can take, hide the index of the dataframe, and much more. Built with Streamlit 🎈Fullscreen open_in_newPrevious: st.dataframeNext: st.column_configforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy" https://docs.streamlit.io/deploy/streamlit-community-cloud/share-your-app#invite-viewers-from-the-share-button,"DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudremoveGet startedaddDeploy your appaddManage your appaddShare your appremoveEmbed your appSearch indexabilityShare previewsManage your accountaddTroubleshootingStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Deploy/Streamlit Community Cloud/Share your appShare your app Now that your app is deployed you can easily share it and collaborate on it. But first, let's take a moment and do a little joy dance for getting that app deployed! 🕺💃 Your app is now live at a fixed URL, so go wild and share it with whomever you want. Your app will inherit permissions from your GitHub repo, meaning that if your repo is private your app will be private and if your repo is public your app will be public. If you want to change that you can simply do so from the app settings menu. You are only allowed one private app at a time. If you've deployed from a private repository, you will have to make that app public or delete it before you can deploy another app from a private repository. Only developers can change your app between public and private. Make your app public or private Share your public app Share your private app Make your app public or private If you deployed your app from a public repository, your app will be public by default. If you deployed your app from a private repository, you will need to make the app public if you want to freely share it with the community at large. Set privacy from your app settings Access your App settings and go to the ""Sharing"" section. Set your app's privacy under ""Who can view this app."" Select ""This app is public and searchable"" to make your app public. Select ""Only specific people can view this app"" to make your app private. Set privacy from the share button From your app at .streamlit.app, click ""Share"" in the upper-right corner. Toggle your app between public and private by clicking ""Make this app public"". Share your public app Once your app is public, just give anyone your app's URL and they view it! Streamlit Community Cloud has several convenient shortcuts for sharing your app. Share your app on social media From your app at .streamlit.app, click ""Share"" in the upper-right corner. Click ""Social"" to access convenient social media share buttons. starTipUse the social media sharing buttons to post your app on our forum! We'd love to see what you make and perhaps feature your app as our app of the month. 💖 Invite viewers by email Whether your app is public or private, you can send an email invite to your app directly from Streamlit Community Cloud. This grants the viewer access to analytics for all your public apps and the ability to invite other viewers to your workspace. Developers and invited viewers are identified by their email in analytics instead of appearing anonymously (if they view any of your apps while logged in). Read more about viewers in App analytics. From your app at .streamlit.app, click ""Share"" in the upper-right corner. Enter an email address and click ""Invite"". Invited users will get a direct link to your app in their inbox. Copy your app's URL You can convenitiently copy your app's URL from the share menu or from your workspace. From your app click ""Share"" in the upper-right corner then click ""Copy link"". From your workspace click the overflow menu icon (more_vert) then click ""Copy URL"". Add a badge to your GitHub repository To help others find and play with your Streamlit app, you can add Streamlit's GitHub badge to your repo. Below is an enlarged example of what the badge looks like. Clicking on the badge takes you to—in this case—Streamlit's Roadmap. Once you deploy your app, you can embed this badge right into your GitHub README.md by adding the following Markdown: [![Streamlit App](https://static.streamlit.io/badges/streamlit_badge_black_white.svg)](https://.streamlit.app) push_pinNoteBe sure to replace https://.streamlit.app with the URL of your deployed app! Share your private app By default an app deployed from a private repository will be private to the developers in the workspace. A private app will not be visible to anyone else unless you grant them explicit permission. You can grant permission by adding them as a developer on GitHub or by adding them as a viewer on Streamlit Community Cloud. Once you have added someone's email address to your app's viewer list, that person will be able to sign in and view your private app. If their email is associated to a Google account, they will be able to sign in with Google OAuth. Otherwise, they will be able to sign in with single-use, emailed links. Streamlit sends an email invitation with a link to your app every time you invite someone. priority_highImportantWhen you add a viewer to any app in your workspace, they are granted access to analytics for that app as well as analytics for all your public apps. They can also pass these permissions to others by inviting more viewers. All viewers and developers in your workspace are identified by their email in analytics. Furthermore, their emails show in analytics for every app in your workspace and not just apps they are explicitly invited to. Read more about viewers in App analytics Invite viewers from the share button From your app at .streamlit.app, click ""Share"" in the upper-right corner. Enter the email to send an invitation to and click ""Invite"". Invited users appear in the list below. Invited users will get a direct link to your app in their inbox. To remove a viewer, simply access the share menu as above and click the close next to their name. Invite viewers from your app settings Access your App settings and go to the ""Sharing"" section. Add or remove users from the list of viewers. Click ""Save"". Previous: Manage your appNext: Embed your appforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy" https://docs.streamlit.io/knowledge-base/tutorials/build-conversational-apps#add-openai-api-key-to-streamlit-secrets,"DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceaddTutorialsremoveExecution flowaddConnect to data sourcesaddMultipage appsaddWork with LLMsremoveBuild a basic LLM chat appBuild an LLM app using LangChainQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Develop/Tutorials/Work with LLMs/Build a basic LLM chat appBuild a basic LLM chat app Introduction The advent of large language models like GPT has revolutionized the ease of developing chat-based applications. Streamlit offers several Chat elements, enabling you to build Graphical User Interfaces (GUIs) for conversational agents or chatbots. Leveraging session state along with these elements allows you to construct anything from a basic chatbot to a more advanced, ChatGPT-like experience using purely Python code. In this tutorial, we'll start by walking through Streamlit's chat elements, st.chat_message and st.chat_input. Then we'll proceed to construct three distinct applications, each showcasing an increasing level of complexity and functionality: First, we'll Build a bot that mirrors your input to get a feel for the chat elements and how they work. We'll also introduce session state and how it can be used to store the chat history. This section will serve as a foundation for the rest of the tutorial. Next, you'll learn how to Build a simple chatbot GUI with streaming. Finally, we'll Build a ChatGPT-like app that leverages session state to remember conversational context, all within less than 50 lines of code. Here's a sneak peek of the LLM-powered chatbot GUI with streaming we'll build in this tutorial: Built with Streamlit 🎈Fullscreen open_in_new Play around with the above demo to get a feel for what we'll build in this tutorial. A few things to note: There's a chat input at the bottom of the screen that's always visible. It contains some placeholder text. You can type in a message and press Enter or click the run button to send it. When you enter a message, it appears as a chat message in the container above. The container is scrollable, so you can scroll up to see previous messages. A default avatar is displayed to your messages' left. The assistant's responses are streamed to the frontend and are displayed with a different default avatar. Before we start building, let's take a closer look at the chat elements we'll use. Chat elements Streamlit offers several commands to help you build conversational apps. These chat elements are designed to be used in conjunction with each other, but you can also use them separately. st.chat_message lets you insert a chat message container into the app so you can display messages from the user or the app. Chat containers can contain other Streamlit elements, including charts, tables, text, and more. st.chat_input lets you display a chat input widget so the user can type in a message. For an overview of the API, check out this video tutorial by Chanin Nantasenamat (@dataprofessor), a Senior Developer Advocate at Streamlit. st.chat_message st.chat_message lets you insert a multi-element chat message container into your app. The returned container can contain any Streamlit element, including charts, tables, text, and more. To add elements to the returned container, you can use with notation. st.chat_message's first parameter is the name of the message author, which can be either ""user"" or ""assistant"" to enable preset styling and avatars, like in the demo above. You can also pass in a custom string to use as the author name. Currently, the name is not shown in the UI but is only set as an accessibility label. For accessibility reasons, you should not use an empty string. Here's an minimal example of how to use st.chat_message to display a welcome message: import streamlit as st with st.chat_message(""user""): st.write(""Hello 👋"") Notice the message is displayed with a default avatar and styling since we passed in ""user"" as the author name. You can also pass in ""assistant"" as the author name to use a different default avatar and styling, or pass in a custom name and avatar. See the API reference for more details. import streamlit as st import numpy as np with st.chat_message(""assistant""): st.write(""Hello human"") st.bar_chart(np.random.randn(30, 3)) Built with Streamlit 🎈Fullscreen open_in_new While we've used the preferred with notation in the above examples, you can also just call methods directly in the returned objects. The below example is equivalent to the one above: import streamlit as st import numpy as np message = st.chat_message(""assistant"") message.write(""Hello human"") message.bar_chart(np.random.randn(30, 3)) So far, we've displayed predefined messages. But what if we want to display messages based on user input? st.chat_input st.chat_input lets you display a chat input widget so the user can type in a message. The returned value is the user's input, which is None if the user hasn't sent a message yet. You can also pass in a default prompt to display in the input widget. Here's an example of how to use st.chat_input to display a chat input widget and show the user's input: import streamlit as st prompt = st.chat_input(""Say something"") if prompt: st.write(f""User has sent the following prompt: {prompt}"") Built with Streamlit 🎈Fullscreen open_in_new Pretty straightforward, right? Now let's combine st.chat_message and st.chat_input to build a bot the mirrors or echoes your input. Build a bot that mirrors your input In this section, we'll build a bot that mirrors or echoes your input. More specifically, the bot will respond to your input with the same message. We'll use st.chat_message to display the user's input and st.chat_input to accept user input. We'll also use session state to store the chat history so we can display it in the chat message container. First, let's think about the different components we'll need to build our bot: Two chat message containers to display messages from the user and the bot, respectively. A chat input widget so the user can type in a message. A way to store the chat history so we can display it in the chat message containers. We can use a list to store the messages, and append to it every time the user or bot sends a message. Each entry in the list will be a dictionary with the following keys: role (the author of the message), and content (the message content). import streamlit as st st.title(""Echo Bot"") # Initialize chat history if ""messages"" not in st.session_state: st.session_state.messages = [] # Display chat messages from history on app rerun for message in st.session_state.messages: with st.chat_message(message[""role""]): st.markdown(message[""content""]) In the above snippet, we've added a title to our app and a for loop to iterate through the chat history and display each message in the chat message container (with the author role and message content). We've also added a check to see if the messages key is in st.session_state. If it's not, we initialize it to an empty list. This is because we'll be adding messages to the list later on, and we don't want to overwrite the list every time the app reruns. Now let's accept user input with st.chat_input, display the user's message in the chat message container, and add it to the chat history. # React to user input if prompt := st.chat_input(""What is up?""): # Display user message in chat message container with st.chat_message(""user""): st.markdown(prompt) # Add user message to chat history st.session_state.messages.append({""role"": ""user"", ""content"": prompt}) We used the := operator to assign the user's input to the prompt variable and checked if it's not None in the same line. If the user has sent a message, we display the message in the chat message container and append it to the chat history. All that's left to do is add the chatbot's responses within the if block. We'll use the same logic as before to display the bot's response (which is just the user's prompt) in the chat message container and add it to the history. response = f""Echo: {prompt}"" # Display assistant response in chat message container with st.chat_message(""assistant""): st.markdown(response) # Add assistant response to chat history st.session_state.messages.append({""role"": ""assistant"", ""content"": response}) Putting it all together, here's the full code for our simple chatbot GUI and the result: View full codeexpand_moreimport streamlit as st st.title(""Echo Bot"") # Initialize chat history if ""messages"" not in st.session_state: st.session_state.messages = [] # Display chat messages from history on app rerun for message in st.session_state.messages: with st.chat_message(message[""role""]): st.markdown(message[""content""]) # React to user input if prompt := st.chat_input(""What is up?""): # Display user message in chat message container st.chat_message(""user"").markdown(prompt) # Add user message to chat history st.session_state.messages.append({""role"": ""user"", ""content"": prompt}) response = f""Echo: {prompt}"" # Display assistant response in chat message container with st.chat_message(""assistant""): st.markdown(response) # Add assistant response to chat history st.session_state.messages.append({""role"": ""assistant"", ""content"": response}) Built with Streamlit 🎈Fullscreen open_in_new While the above example is very simple, it's a good starting point for building more complex conversational apps. Notice how the bot responds instantly to your input. In the next section, we'll add a delay to simulate the bot ""thinking"" before responding. Build a simple chatbot GUI with streaming In this section, we'll build a simple chatbot GUI that responds to user input with a random message from a list of pre-determind responses. In the next section, we'll convert this simple toy example into a ChatGPT-like experience using OpenAI. Just like previously, we still require the same components to build our chatbot. Two chat message containers to display messages from the user and the bot, respectively. A chat input widget so the user can type in a message. And a way to store the chat history so we can display it in the chat message containers. Let's just copy the code from the previous section and add a few tweaks to it. import streamlit as st import random import time st.title(""Simple chat"") # Initialize chat history if ""messages"" not in st.session_state: st.session_state.messages = [] # Display chat messages from history on app rerun for message in st.session_state.messages: with st.chat_message(message[""role""]): st.markdown(message[""content""]) # Accept user input if prompt := st.chat_input(""What is up?""): # Display user message in chat message container with st.chat_message(""user""): st.markdown(prompt) # Add user message to chat history st.session_state.messages.append({""role"": ""user"", ""content"": prompt}) The only difference so far is we've changed the title of our app and added imports for random and time. We'll use random to randomly select a response from a list of responses and time to add a delay to simulate the chatbot ""thinking"" before responding. All that's left to do is add the chatbot's responses within the if block. We'll use a list of responses and randomly select one to display. We'll also add a delay to simulate the chatbot ""thinking"" before responding (or stream its response). Let's make a helper function for this and insert it at the top of our app. # Streamed response emulator def response_generator(): response = random.choice( [ ""Hello there! How can I assist you today?"", ""Hi, human! Is there anything I can help you with?"", ""Do you need help?"", ] ) for word in response.split(): yield word + "" "" time.sleep(0.05) Back to writing the response in our chat interface, we'll use st.write_stream to write out the streamed response with a typewriter effect. # Display assistant response in chat message container with st.chat_message(""assistant""): response = st.write_stream(response_generator()) # Add assistant response to chat history st.session_state.messages.append({""role"": ""assistant"", ""content"": response}) Above, we've added a placeholder to display the chatbot's response. We've also added a for loop to iterate through the response and display it one word at a time. We've added a delay of 0.05 seconds between each word to simulate the chatbot ""thinking"" before responding. Finally, we append the chatbot's response to the chat history. As you've probably guessed, this is a naive implementation of streaming. We'll see how to implement streaming with OpenAI in the next section. Putting it all together, here's the full code for our simple chatbot GUI and the result: View full codeexpand_moreimport streamlit as st import random import time # Streamed response emulator def response_generator(): response = random.choice( [ ""Hello there! How can I assist you today?"", ""Hi, human! Is there anything I can help you with?"", ""Do you need help?"", ] ) for word in response.split(): yield word + "" "" time.sleep(0.05) st.title(""Simple chat"") # Initialize chat history if ""messages"" not in st.session_state: st.session_state.messages = [] # Display chat messages from history on app rerun for message in st.session_state.messages: with st.chat_message(message[""role""]): st.markdown(message[""content""]) # Accept user input if prompt := st.chat_input(""What is up?""): # Add user message to chat history st.session_state.messages.append({""role"": ""user"", ""content"": prompt}) # Display user message in chat message container with st.chat_message(""user""): st.markdown(prompt) # Display assistant response in chat message container with st.chat_message(""assistant""): response = st.write_stream(response_generator()) # Add assistant response to chat history st.session_state.messages.append({""role"": ""assistant"", ""content"": response}) Built with Streamlit 🎈Fullscreen open_in_new Play around with the above demo to get a feel for what we've built. It's a very simple chatbot GUI, but it has all the components of a more sophisticated chatbot. In the next section, we'll see how to build a ChatGPT-like app using OpenAI. Build a ChatGPT-like app Now that you've understood the basics of Streamlit's chat elements, let's make a few tweaks to it to build our own ChatGPT-like app. You'll need to install the OpenAI Python library and get an API key to follow along. Install dependencies First let's install the dependencies we'll need for this section: pip install openai streamlit Add OpenAI API key to Streamlit secrets Next, let's add our OpenAI API key to Streamlit secrets. We do this by creating .streamlit/secrets.toml file in our project directory and adding the following lines to it: # .streamlit/secrets.toml OPENAI_API_KEY = ""YOUR_API_KEY"" Write the app Now let's write the app. We'll use the same code as before, but we'll replace the list of responses with a call to the OpenAI API. We'll also add a few more tweaks to make the app more ChatGPT-like. import streamlit as st from openai import OpenAI st.title(""ChatGPT-like clone"") # Set OpenAI API key from Streamlit secrets client = OpenAI(api_key=st.secrets[""OPENAI_API_KEY""]) # Set a default model if ""openai_model"" not in st.session_state: st.session_state[""openai_model""] = ""gpt-3.5-turbo"" # Initialize chat history if ""messages"" not in st.session_state: st.session_state.messages = [] # Display chat messages from history on app rerun for message in st.session_state.messages: with st.chat_message(message[""role""]): st.markdown(message[""content""]) # Accept user input if prompt := st.chat_input(""What is up?""): # Add user message to chat history st.session_state.messages.append({""role"": ""user"", ""content"": prompt}) # Display user message in chat message container with st.chat_message(""user""): st.markdown(prompt) All that's changed is that we've added a default model to st.session_state and set our OpenAI API key from Streamlit secrets. Here's where it gets interesting. We can replace our emulated stream with the model's responses from OpenAI: # Display assistant response in chat message container with st.chat_message(""assistant""): stream = client.chat.completions.create( model=st.session_state[""openai_model""], messages=[ {""role"": m[""role""], ""content"": m[""content""]} for m in st.session_state.messages ], stream=True, ) response = st.write_stream(stream) st.session_state.messages.append({""role"": ""assistant"", ""content"": response}) Above, we've replaced the list of responses with a call to OpenAI().chat.completions.create. We've set stream=True to stream the responses to the frontend. In the API call, we pass the model name we hardcoded in session state and pass the chat history as a list of messages. We also pass the role and content of each message in the chat history. Finally, OpenAI returns a stream of responses (split into chunks of tokens), which we iterate through and display each chunk. Putting it all together, here's the full code for our ChatGPT-like app and the result: View full codeexpand_morefrom openai import OpenAI import streamlit as st st.title(""ChatGPT-like clone"") client = OpenAI(api_key=st.secrets[""OPENAI_API_KEY""]) if ""openai_model"" not in st.session_state: st.session_state[""openai_model""] = ""gpt-3.5-turbo"" if ""messages"" not in st.session_state: st.session_state.messages = [] for message in st.session_state.messages: with st.chat_message(message[""role""]): st.markdown(message[""content""]) if prompt := st.chat_input(""What is up?""): st.session_state.messages.append({""role"": ""user"", ""content"": prompt}) with st.chat_message(""user""): st.markdown(prompt) with st.chat_message(""assistant""): stream = client.chat.completions.create( model=st.session_state[""openai_model""], messages=[ {""role"": m[""role""], ""content"": m[""content""]} for m in st.session_state.messages ], stream=True, ) response = st.write_stream(stream) st.session_state.messages.append({""role"": ""assistant"", ""content"": response}) Built with Streamlit 🎈Fullscreen open_in_new Congratulations! You've built your own ChatGPT-like app in less than 50 lines of code. We're very excited to see what you'll build with Streamlit's chat elements. Experiment with different models and tweak the code to build your own conversational apps. If you build something cool, let us know on the Forum or check out some other Generative AI apps for inspiration. 🎈Previous: Work with LLMsNext: Build an LLM app using LangChainforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy" https://docs.streamlit.io/en/0.65.0/api.html#input-widgets,"DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceremovePAGE ELEMENTSWrite and magicaddText elementsaddData elementsaddChart elementsaddInput widgetsaddMedia elementsaddLayouts and containersaddChat elementsaddStatus elementsaddThird-party componentsopen_in_newAPPLICATION LOGICNavigation and pagesaddExecution flowaddCaching and stateaddConnections and secretsaddCustom componentsaddUtilitiesaddConfigurationaddTOOLSApp testingaddCommand lineaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Develop/API referenceAPI reference Streamlit makes it easy for you to visualize, mutate, and share data. The API reference is organized by activity type, like displaying data or optimizing performance. Each section includes methods associated with the activity type, including examples. Browse our API below and click to learn more about any of our available commands! 🎈 Display almost anything Write and magic st.writeWrite arguments to the app.st.write(""Hello **world**!"") st.write(my_data_frame) st.write(my_mpl_figure) st.write_streamWrite generators or streams to the app with a typewriter effect.st.write_stream(my_generator) st.write_stream(my_llm_stream) MagicAny time Streamlit sees either a variable or literal value on its own line, it automatically writes that to your app using st.write""Hello **world**!"" my_data_frame my_mpl_figure Text elements MarkdownDisplay string formatted as Markdown.st.markdown(""Hello **world**!"") TitleDisplay text in title formatting.st.title(""The app title"") HeaderDisplay text in header formatting.st.header(""This is a header"") SubheaderDisplay text in subheader formatting.st.subheader(""This is a subheader"") CaptionDisplay text in small font.st.caption(""This is written small caption text"") Code blockDisplay a code block with optional syntax highlighting.st.code(""a = 1234"") EchoDisplay some code in the app, then execute it. Useful for tutorials.with st.echo(): st.write('This code will be printed') LaTeXDisplay mathematical expressions formatted as LaTeX.st.latex(""\int a x^2 \,dx"") Preformatted textWrite fixed-width and preformatted text.st.text(""Hello world"") DividerDisplay a horizontal rule.st.divider() Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration! PreviousTagsAdd tags to your Streamlit apps. Created by @gagan3012.st_tags(label='# Enter Keywords:', text='Press enter to add more', value=['Zero', 'One', 'Two'], suggestions=['five', 'six', 'seven', 'eight', 'nine', 'three', 'eleven', 'ten', 'four'], maxtags = 4, key='1') NLUApply text mining on a dataframe. Created by @JohnSnowLabs.nlu.load('sentiment').predict('I love NLU! <3') Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.mention(label=""An awesome Streamlit App"", icon=""streamlit"", url=""https://extras.streamlit.app"",) Annotated textDisplay annotated text in Streamlit apps. Created by @tvst.annotated_text(""This "", (""is"", ""verb""), "" some "", (""annotated"", ""adj""), (""text"", ""noun""), "" for those of "", (""you"", ""pronoun""), "" who "", (""like"", ""verb""), "" this sort of "", (""thing"", ""noun""), ""."") Drawable CanvasProvides a sketching canvas using Fabric.js. Created by @andfanilo.st_canvas(fill_color=""rgba(255, 165, 0, 0.3)"", stroke_width=stroke_width, stroke_color=stroke_color, background_color=bg_color, background_image=Image.open(bg_image) if bg_image else None, update_streamlit=realtime_update, height=150, drawing_mode=drawing_mode, point_display_radius=point_display_radius if drawing_mode == 'point' else 0, key=""canvas"",) TagsAdd tags to your Streamlit apps. Created by @gagan3012.st_tags(label='# Enter Keywords:', text='Press enter to add more', value=['Zero', 'One', 'Two'], suggestions=['five', 'six', 'seven', 'eight', 'nine', 'three', 'eleven', 'ten', 'four'], maxtags = 4, key='1') NLUApply text mining on a dataframe. Created by @JohnSnowLabs.nlu.load('sentiment').predict('I love NLU! <3') Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.mention(label=""An awesome Streamlit App"", icon=""streamlit"", url=""https://extras.streamlit.app"",) Annotated textDisplay annotated text in Streamlit apps. Created by @tvst.annotated_text(""This "", (""is"", ""verb""), "" some "", (""annotated"", ""adj""), (""text"", ""noun""), "" for those of "", (""you"", ""pronoun""), "" who "", (""like"", ""verb""), "" this sort of "", (""thing"", ""noun""), ""."") Drawable CanvasProvides a sketching canvas using Fabric.js. Created by @andfanilo.st_canvas(fill_color=""rgba(255, 165, 0, 0.3)"", stroke_width=stroke_width, stroke_color=stroke_color, background_color=bg_color, background_image=Image.open(bg_image) if bg_image else None, update_streamlit=realtime_update, height=150, drawing_mode=drawing_mode, point_display_radius=point_display_radius if drawing_mode == 'point' else 0, key=""canvas"",) TagsAdd tags to your Streamlit apps. Created by @gagan3012.st_tags(label='# Enter Keywords:', text='Press enter to add more', value=['Zero', 'One', 'Two'], suggestions=['five', 'six', 'seven', 'eight', 'nine', 'three', 'eleven', 'ten', 'four'], maxtags = 4, key='1') NLUApply text mining on a dataframe. Created by @JohnSnowLabs.nlu.load('sentiment').predict('I love NLU! <3') Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.mention(label=""An awesome Streamlit App"", icon=""streamlit"", url=""https://extras.streamlit.app"",) Next Data elements DataframesDisplay a dataframe as an interactive table.st.dataframe(my_data_frame) Data editorDisplay a data editor widget.edited = st.data_editor(df, num_rows=""dynamic"") Column configurationConfigure the display and editing behavior of dataframes and data editors.st.column_config.NumberColumn(""Price (in USD)"", min_value=0, format=""$%d"") Static tablesDisplay a static table.st.table(my_data_frame) MetricsDisplay a metric in big bold font, with an optional indicator of how the metric changed.st.metric(""My metric"", 42, 2) Dicts and JSONDisplay object or string as a pretty-printed JSON string.st.json(my_dict) Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration! PreviousImage CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates value = streamlit_image_coordinates(""https://placekitten.com/200/300"") st.write(value) Plotly EventsMake Plotly charts interactive!. Created by @null-jones.from streamlit_plotly_events import plotly_events fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.metric_cards import style_metric_cards col3.metric(label=""No Change"", value=5000, delta=0) style_metric_cards() Streamlit AggridImplementation of Ag-Grid component for Streamlit. Created by @PablocFonseca.df = pd.DataFrame({'col1': [1, 2, 3], 'col2': [4, 5, 6]}) grid_return = AgGrid(df, editable=True) new_df = grid_return['data'] Streamlit FoliumStreamlit Component for rendering Folium maps. Created by @randyzwitch.m = folium.Map(location=[39.949610, -75.150282], zoom_start=16) folium.Marker([39.949610, -75.150282], popup=""Liberty Bell"", tooltip=""Liberty Bell"").add_to(m) st_data = st_folium(m, width=725) Pandas ProfilingPandas profiling component for Streamlit. Created by @okld.df = pd.read_csv(""https://storage.googleapis.com/tf-datasets/titanic/train.csv"") pr = df.profile_report() st_profile_report(pr) Image CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates value = streamlit_image_coordinates(""https://placekitten.com/200/300"") st.write(value) Plotly EventsMake Plotly charts interactive!. Created by @null-jones.from streamlit_plotly_events import plotly_events fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.metric_cards import style_metric_cards col3.metric(label=""No Change"", value=5000, delta=0) style_metric_cards() Streamlit AggridImplementation of Ag-Grid component for Streamlit. Created by @PablocFonseca.df = pd.DataFrame({'col1': [1, 2, 3], 'col2': [4, 5, 6]}) grid_return = AgGrid(df, editable=True) new_df = grid_return['data'] Streamlit FoliumStreamlit Component for rendering Folium maps. Created by @randyzwitch.m = folium.Map(location=[39.949610, -75.150282], zoom_start=16) folium.Marker([39.949610, -75.150282], popup=""Liberty Bell"", tooltip=""Liberty Bell"").add_to(m) st_data = st_folium(m, width=725) Pandas ProfilingPandas profiling component for Streamlit. Created by @okld.df = pd.read_csv(""https://storage.googleapis.com/tf-datasets/titanic/train.csv"") pr = df.profile_report() st_profile_report(pr) Image CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates value = streamlit_image_coordinates(""https://placekitten.com/200/300"") st.write(value) Plotly EventsMake Plotly charts interactive!. Created by @null-jones.from streamlit_plotly_events import plotly_events fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.metric_cards import style_metric_cards col3.metric(label=""No Change"", value=5000, delta=0) style_metric_cards() Next Chart elements Simple area chartsDisplay an area chart.st.area_chart(my_data_frame) Simple bar chartsDisplay a bar chart.st.bar_chart(my_data_frame) Simple line chartsDisplay a line chart.st.line_chart(my_data_frame) Simple scatter chartsDisplay a line chart.st.scatter_chart(my_data_frame) Scatterplots on mapsDisplay a map with points on it.st.map(my_data_frame) MatplotlibDisplay a matplotlib.pyplot figure.st.pyplot(my_mpl_figure) AltairDisplay a chart using the Altair library.st.altair_chart(my_altair_chart) Vega-LiteDisplay a chart using the Vega-Lite library.st.vega_lite_chart(my_vega_lite_chart) PlotlyDisplay an interactive Plotly chart.st.plotly_chart(my_plotly_chart) BokehDisplay an interactive Bokeh chart.st.bokeh_chart(my_bokeh_chart) PyDeckDisplay a chart using the PyDeck library.st.pydeck_chart(my_pydeck_chart) GraphVizDisplay a graph using the dagre-d3 library.st.graphviz_chart(my_graphviz_spec) Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration! PreviousStreamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl(""https://assets5.lottiefiles.com/packages/lf20_V9t630.json"") st_lottie(lottie_hello, key=""hello"") Plotly EventsMake Plotly charts interactive!. Created by @null-jones.fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.chart += get_annotations_chart(annotations=[(""Mar 01, 2008"", ""Pretty good day for GOOG""), (""Dec 01, 2007"", ""Something's going wrong for GOOG & AAPL""), (""Nov 01, 2008"", ""Market starts again thanks to...""), (""Dec 01, 2009"", ""Small crash for GOOG after...""),],) st.altair_chart(chart, use_container_width=True) PlostA deceptively simple plotting library for Streamlit. Created by @tvst.import plost plost.line_chart(my_dataframe, x='time', y='stock_value', color='stock_name',) HiPlotHigh dimensional Interactive Plotting. Created by @facebookresearch.data = [{'dropout':0.1, 'lr': 0.001, 'loss': 10.0, 'optimizer': 'SGD'}, {'dropout':0.15, 'lr': 0.01, 'loss': 3.5, 'optimizer': 'Adam'}, {'dropout':0.3, 'lr': 0.1, 'loss': 4.5, 'optimizer': 'Adam'}] hip.Experiment.from_iterable(data).display() EChartsHigh dimensional Interactive Plotting. Created by @andfanilo.from streamlit_echarts import st_echarts st_echarts(options=options) Streamlit FoliumStreamlit Component for rendering Folium maps. Created by @randyzwitch.m = folium.Map(location=[39.949610, -75.150282], zoom_start=16) st_data = st_folium(m, width=725) Spacy-StreamlitspaCy building blocks and visualizers for Streamlit apps. Created by @explosion.models = [""en_core_web_sm"", ""en_core_web_md""] spacy_streamlit.visualize(models, ""Sundar Pichai is the CEO of Google."") Streamlit AgraphA Streamlit Graph Vis, based on react-grah-vis. Created by @ChrisDelClea.from streamlit_agraph import agraph, Node, Edge, Config agraph(nodes=nodes, edges=edges, config=config) Streamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl(""https://assets5.lottiefiles.com/packages/lf20_V9t630.json"") st_lottie(lottie_hello, key=""hello"") Plotly EventsMake Plotly charts interactive!. Created by @null-jones.fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.chart += get_annotations_chart(annotations=[(""Mar 01, 2008"", ""Pretty good day for GOOG""), (""Dec 01, 2007"", ""Something's going wrong for GOOG & AAPL""), (""Nov 01, 2008"", ""Market starts again thanks to...""), (""Dec 01, 2009"", ""Small crash for GOOG after...""),],) st.altair_chart(chart, use_container_width=True) PlostA deceptively simple plotting library for Streamlit. Created by @tvst.import plost plost.line_chart(my_dataframe, x='time', y='stock_value', color='stock_name',) HiPlotHigh dimensional Interactive Plotting. Created by @facebookresearch.data = [{'dropout':0.1, 'lr': 0.001, 'loss': 10.0, 'optimizer': 'SGD'}, {'dropout':0.15, 'lr': 0.01, 'loss': 3.5, 'optimizer': 'Adam'}, {'dropout':0.3, 'lr': 0.1, 'loss': 4.5, 'optimizer': 'Adam'}] hip.Experiment.from_iterable(data).display() EChartsHigh dimensional Interactive Plotting. Created by @andfanilo.from streamlit_echarts import st_echarts st_echarts(options=options) Streamlit FoliumStreamlit Component for rendering Folium maps. Created by @randyzwitch.m = folium.Map(location=[39.949610, -75.150282], zoom_start=16) st_data = st_folium(m, width=725) Spacy-StreamlitspaCy building blocks and visualizers for Streamlit apps. Created by @explosion.models = [""en_core_web_sm"", ""en_core_web_md""] spacy_streamlit.visualize(models, ""Sundar Pichai is the CEO of Google."") Streamlit AgraphA Streamlit Graph Vis, based on react-grah-vis. Created by @ChrisDelClea.from streamlit_agraph import agraph, Node, Edge, Config agraph(nodes=nodes, edges=edges, config=config) Streamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl(""https://assets5.lottiefiles.com/packages/lf20_V9t630.json"") st_lottie(lottie_hello, key=""hello"") Plotly EventsMake Plotly charts interactive!. Created by @null-jones.fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.chart += get_annotations_chart(annotations=[(""Mar 01, 2008"", ""Pretty good day for GOOG""), (""Dec 01, 2007"", ""Something's going wrong for GOOG & AAPL""), (""Nov 01, 2008"", ""Market starts again thanks to...""), (""Dec 01, 2009"", ""Small crash for GOOG after...""),],) st.altair_chart(chart, use_container_width=True) Next Input widgets ButtonDisplay a button widget.clicked = st.button(""Click me"") Download buttonDisplay a download button widget.st.download_button(""Download file"", file) Form buttonDisplay a form submit button. For use with st.form.st.form_submit_button(""Sign up"") Link buttonDisplay a link button.st.link_button(""Go to gallery"", url) Page linkDisplay a link to another page in a multipage app.st.page_link(""app.py"", label=""Home"", icon=""🏠"") st.page_link(""pages/profile.py"", label=""My profile"") CheckboxDisplay a checkbox widget.selected = st.checkbox(""I agree"") Color pickerDisplay a color picker widget.color = st.color_picker(""Pick a color"") MultiselectDisplay a multiselect widget. The multiselect widget starts as empty.choices = st.multiselect(""Buy"", [""milk"", ""apples"", ""potatoes""]) RadioDisplay a radio button widget.choice = st.radio(""Pick one"", [""cats"", ""dogs""]) SelectboxDisplay a select widget.choice = st.selectbox(""Pick one"", [""cats"", ""dogs""]) Select-sliderDisplay a slider widget to select items from a list.size = st.select_slider(""Pick a size"", [""S"", ""M"", ""L""]) ToggleDisplay a toggle widget.activated = st.toggle(""Activate"") Number inputDisplay a numeric input widget.choice = st.number_input(""Pick a number"", 0, 10) SliderDisplay a slider widget.number = st.slider(""Pick a number"", 0, 100) Date inputDisplay a date input widget.date = st.date_input(""Your birthday"") Time inputDisplay a time input widget.time = st.time_input(""Meeting time"") Chat inputDisplay a chat input widget.prompt = st.chat_input(""Say something"") if prompt: st.write(f""The user has sent: {prompt}"") Text-areaDisplay a multi-line text input widget.text = st.text_area(""Text to translate"") Text inputDisplay a single-line text input widget.name = st.text_input(""First name"") Data editorDisplay a data editor widget.edited = st.experimental_data_editor(df, num_rows=""dynamic"") File UploaderDisplay a file uploader widget.data = st.file_uploader(""Upload a CSV"") Camera inputDisplay a widget that allows users to upload images directly from a camera.image = st.camera_input(""Take a picture"") Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration! PreviousStreamlit ChatStreamlit Component for a Chatbot UI. Created by @AI-Yash.from streamlit_chat import message message(""My message"") message(""Hello bot!"", is_user=True) # align's the message to the right Streamlit Option MenuSelect a single item from a list of options in a menu. Created by @victoryhb.from streamlit_option_menu import option_menu option_menu(""Main Menu"", [""Home"", 'Settings'], icons=['house', 'gear'], menu_icon=""cast"", default_index=1) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.stoggle import stoggle stoggle( ""Click me!"", """"""🥷 Surprise! Here's some additional content"""""",) Streamlit ElementsCreate a draggable and resizable dashboard in Streamlit. Created by @okls.from streamlit_elements import elements, mui, html with elements(""new_element""): mui.Typography(""Hello world"") TagsAdd tags to your Streamlit apps. Created by @gagan3012.from streamlit_tags import st_tags st_tags(label='# Enter Keywords:', text='Press enter to add more', value=['Zero', 'One', 'Two'], suggestions=['five', 'six', 'seven', 'eight', 'nine', 'three', 'eleven', 'ten', 'four'], maxtags = 4, key='1') StqdmThe simplest way to handle a progress bar in streamlit app. Created by @Wirg.from stqdm import stqdm for _ in stqdm(range(50)): sleep(0.5) TimelineDisplay a Timeline in Streamlit apps using TimelineJS. Created by @innerdoc.from streamlit_timeline import timeline with open('example.json', ""r"") as f: timeline(f.read(), height=800) Camera input liveAlternative for st.camera_input which returns the webcam images live. Created by @blackary.from camera_input_live import camera_input_live image = camera_input_live() st.image(value) Streamlit AceAce editor component for Streamlit. Created by @okld.from streamlit_ace import st_ace content = st_ace() content Streamlit ChatStreamlit Component for a Chatbot UI. Created by @AI-Yash.from streamlit_chat import message message(""My message"") message(""Hello bot!"", is_user=True) # align's the message to the right Streamlit Option MenuSelect a single item from a list of options in a menu. Created by @victoryhb.from streamlit_option_menu import option_menu option_menu(""Main Menu"", [""Home"", 'Settings'], icons=['house', 'gear'], menu_icon=""cast"", default_index=1) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.stoggle import stoggle stoggle( ""Click me!"", """"""🥷 Surprise! Here's some additional content"""""",) Streamlit ElementsCreate a draggable and resizable dashboard in Streamlit. Created by @okls.from streamlit_elements import elements, mui, html with elements(""new_element""): mui.Typography(""Hello world"") TagsAdd tags to your Streamlit apps. Created by @gagan3012.from streamlit_tags import st_tags st_tags(label='# Enter Keywords:', text='Press enter to add more', value=['Zero', 'One', 'Two'], suggestions=['five', 'six', 'seven', 'eight', 'nine', 'three', 'eleven', 'ten', 'four'], maxtags = 4, key='1') StqdmThe simplest way to handle a progress bar in streamlit app. Created by @Wirg.from stqdm import stqdm for _ in stqdm(range(50)): sleep(0.5) TimelineDisplay a Timeline in Streamlit apps using TimelineJS. Created by @innerdoc.from streamlit_timeline import timeline with open('example.json', ""r"") as f: timeline(f.read(), height=800) Camera input liveAlternative for st.camera_input which returns the webcam images live. Created by @blackary.from camera_input_live import camera_input_live image = camera_input_live() st.image(value) Streamlit AceAce editor component for Streamlit. Created by @okld.from streamlit_ace import st_ace content = st_ace() content Streamlit ChatStreamlit Component for a Chatbot UI. Created by @AI-Yash.from streamlit_chat import message message(""My message"") message(""Hello bot!"", is_user=True) # align's the message to the right Streamlit Option MenuSelect a single item from a list of options in a menu. Created by @victoryhb.from streamlit_option_menu import option_menu option_menu(""Main Menu"", [""Home"", 'Settings'], icons=['house', 'gear'], menu_icon=""cast"", default_index=1) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.stoggle import stoggle stoggle( ""Click me!"", """"""🥷 Surprise! Here's some additional content"""""",) Next Media elements ImageDisplay an image or list of images.st.image(numpy_array) st.image(image_bytes) st.image(file) st.image(""https://example.com/myimage.jpg"") AudioDisplay an audio player.st.audio(numpy_array) st.audio(audio_bytes) st.audio(file) st.audio(""https://example.com/myaudio.mp3"", format=""audio/mp3"") VideoDisplay a video player.st.video(numpy_array) st.video(video_bytes) st.video(file) st.video(""https://example.com/myvideo.mp4"", format=""video/mp4"") Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration! PreviousStreamlit CropperA simple image cropper for Streamlit. Created by @turner-anderson.from streamlit_cropper import st_cropper st_cropper(img, realtime_update=realtime_update, box_color=box_color, aspect_ratio=aspect_ratio) Image CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates streamlit_image_coordinates(""https://placekitten.com/200/300"") Streamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl(""https://assets5.lottiefiles.com/packages/lf20_V9t630.json"") st_lottie(lottie_hello, key=""hello"") Streamlit WebrtcHandling and transmitting real-time video/audio streams with Streamlit. Created by @whitphx.from streamlit_webrtc import webrtc_streamer webrtc_streamer(key=""sample"") Drawable CanvasProvides a sketching canvas using Fabric.js. Created by @andfanilo.from streamlit_drawable_canvas import st_canvas st_canvas(fill_color=""rgba(255, 165, 0, 0.3)"", stroke_width=stroke_width, stroke_color=stroke_color, background_color=bg_color, background_image=Image.open(bg_image) if bg_image else None, update_streamlit=realtime_update, height=150, drawing_mode=drawing_mode, point_display_radius=point_display_radius if drawing_mode == 'point' else 0, key=""canvas"",) Image ComparisonCompare images with a slider using JuxtaposeJS. Created by @fcakyon.from streamlit_image_comparison import image_comparison image_comparison(img1=""image1.jpg"", img2=""image2.jpg"",) Streamlit CropperA simple image cropper for Streamlit. Created by @turner-anderson.from streamlit_cropper import st_cropper st_cropper(img, realtime_update=realtime_update, box_color=box_color, aspect_ratio=aspect_ratio) Image CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates streamlit_image_coordinates(""https://placekitten.com/200/300"") Streamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl(""https://assets5.lottiefiles.com/packages/lf20_V9t630.json"") st_lottie(lottie_hello, key=""hello"") Streamlit WebrtcHandling and transmitting real-time video/audio streams with Streamlit. Created by @whitphx.from streamlit_webrtc import webrtc_streamer webrtc_streamer(key=""sample"") Drawable CanvasProvides a sketching canvas using Fabric.js. Created by @andfanilo.from streamlit_drawable_canvas import st_canvas st_canvas(fill_color=""rgba(255, 165, 0, 0.3)"", stroke_width=stroke_width, stroke_color=stroke_color, background_color=bg_color, background_image=Image.open(bg_image) if bg_image else None, update_streamlit=realtime_update, height=150, drawing_mode=drawing_mode, point_display_radius=point_display_radius if drawing_mode == 'point' else 0, key=""canvas"",) Image ComparisonCompare images with a slider using JuxtaposeJS. Created by @fcakyon.from streamlit_image_comparison import image_comparison image_comparison(img1=""image1.jpg"", img2=""image2.jpg"",) Streamlit CropperA simple image cropper for Streamlit. Created by @turner-anderson.from streamlit_cropper import st_cropper st_cropper(img, realtime_update=realtime_update, box_color=box_color, aspect_ratio=aspect_ratio) Image CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates streamlit_image_coordinates(""https://placekitten.com/200/300"") Streamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl(""https://assets5.lottiefiles.com/packages/lf20_V9t630.json"") st_lottie(lottie_hello, key=""hello"") Next Layouts and containers ColumnsInsert containers laid out as side-by-side columns.col1, col2 = st.columns(2) col1.write(""this is column 1"") col2.write(""this is column 2"") ContainerInsert a multi-element container.c = st.container() st.write(""This will show last"") c.write(""This will show first"") c.write(""This will show second"") Modal dialogsInsert a modal dialog that can rerun independently from the rest of the script.@st.experimental_dialog(""Sign up"") def email_form(): name = st.text_input(""Name"") email = st.text_input(""Email"") EmptyInsert a single-element container.c = st.empty() st.write(""This will show last"") c.write(""This will be replaced"") c.write(""This will show first"") ExpanderInsert a multi-element container that can be expanded/collapsed.with st.expander(""Open to see more""): st.write(""This is more content"") PopoverInsert a multi-element popover container that can be opened/closed.with st.popover(""Settings""): st.checkbox(""Show completed"") SidebarDisplay items in a sidebar.st.sidebar.write(""This lives in the sidebar"") st.sidebar.button(""Click me!"") TabsInsert containers separated into tabs.tab1, tab2 = st.tabs([""Tab 1"", ""Tab2""]) tab1.write(""this is tab 1"") tab2.write(""this is tab 2"") Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration!Streamlit ElementsCreate a draggable and resizable dashboard in Streamlit. Created by @okls.from streamlit_elements import elements, mui, html with elements(""new_element""): mui.Typography(""Hello world"") PydanticAuto-generate Streamlit UI from Pydantic Models and Dataclasses. Created by @lukasmasuch.import streamlit_pydantic as sp sp.pydantic_form(key=""my_form"", model=ExampleModel) Streamlit PagesAn experimental version of Streamlit Multi-Page Apps. Created by @blackary.from st_pages import Page, show_pages, add_page_title show_pages([ Page(""streamlit_app.py"", ""Home"", ""🏠""), Page(""other_pages/page2.py"", ""Page 2"", "":books:""), ]) Chat elements Streamlit provides a few commands to help you build conversational apps. These chat elements are designed to be used in conjunction with each other, but you can also use them separately. st.chat_message lets you insert a chat message container into the app so you can display messages from the user or the app. Chat containers can contain other Streamlit elements, including charts, tables, text, and more. st.chat_input lets you display a chat input widget so the user can type in a message. Chat inputDisplay a chat input widget.prompt = st.chat_input(""Say something"") if prompt: st.write(f""The user has sent: {prompt}"") Chat messageInsert a chat message container.import numpy as np with st.chat_message(""user""): st.write(""Hello 👋"") st.line_chart(np.random.randn(30, 3)) Status containerDisplay output of long-running tasks in a container.with st.status('Running'): do_something_slow() st.write_streamWrite generators or streams to the app with a typewriter effect.st.write_stream(my_generator) st.write_stream(my_llm_stream) Status elements Progress barDisplay a progress bar.for i in range(101): st.progress(i) do_something_slow() SpinnerTemporarily displays a message while executing a block of code.with st.spinner(""Please wait...""): do_something_slow() Status containerDisplay output of long-running tasks in a container.with st.status('Running'): do_something_slow() ToastBriefly displays a toast message in the bottom-right corner.st.toast('Butter!', icon='🧈') BalloonsDisplay celebratory balloons!do_something() # Celebrate when all done! st.balloons() SnowflakesDisplay celebratory snowflakes!do_something() # Celebrate when all done! st.snow() Success boxDisplay a success message.st.success(""Match found!"") Info boxDisplay an informational message.st.info(""Dataset is updated every day at midnight."") Warning boxDisplay warning message.st.warning(""Unable to fetch image. Skipping..."") Error boxDisplay error message.st.error(""We encountered an error"") Exception outputDisplay an exception.e = RuntimeError(""This is an exception of type RuntimeError"") st.exception(e) Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration!StqdmThe simplest way to handle a progress bar in streamlit app. Created by @Wirg.from stqdm import stqdm for _ in stqdm(range(50)): sleep(0.5) Custom notification boxA custom notification box with the ability to close it out. Created by @Socvest.from streamlit_custom_notification_box import custom_notification_box styles = {'material-icons':{'color': 'red'}, 'text-icon-link-close-container': {'box-shadow': '#3896de 0px 4px'}, 'notification-text': {'':''}, 'close-button':{'':''}, 'link':{'':''}} custom_notification_box(icon='info', textDisplay='We are almost done with your registration...', externalLink='more info', url='#', styles=styles, key=""foo"") Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.let_it_rain import rain rain(emoji=""🎈"", font_size=54, falling_speed=5, animation_length=""infinite"",) App logic and configuration Navigation and pages Switch pageProgrammatically navigates to a specified page.st.switch_page(""pages/my_page.py"") Page linkDisplay a link to another page in a multipage app.st.page_link(""app.py"", label=""Home"", icon=""🏠"") st.page_link(""pages/profile.py"", label=""My profile"") Execution flow Modal dialogsInsert a modal dialog that can rerun independently from the rest of the script.@st.experimental_dialog(""Sign up"") def email_form(): name = st.text_input(""Name"") email = st.text_input(""Email"") FormsCreate a form that batches elements together with a “Submit"" button.with st.form(key='my_form'): name = st.text_input(""Name"") email = st.text_input(""Email"") st.form_submit_button(""Sign up"") Partial rerunsDefine a fragment to rerun independently from the rest of the script.@st.experimental_fragment(run_every=""10s"") def fragment(): df = get_data() st.line_chart(df) Rerun scriptRerun the script immediately.st.rerun() Stop executionStops execution immediately.st.stop() Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration!AutorefreshForce a refresh without tying up a script. Created by @kmcgrady.from streamlit_autorefresh import st_autorefresh st_autorefresh(interval=2000, limit=100, key=""fizzbuzzcounter"") PydanticAuto-generate Streamlit UI from Pydantic Models and Dataclasses. Created by @lukasmasuch.import streamlit_pydantic as sp sp.pydantic_form(key=""my_form"", model=ExampleModel) Streamlit PagesAn experimental version of Streamlit Multi-Page Apps. Created by @blackary.from st_pages import Page, show_pages, add_page_title show_pages([ Page(""streamlit_app.py"", ""Home"", ""🏠""), Page(""other_pages/page2.py"", ""Page 2"", "":books:""), ]) Caching and state Cache dataFunction decorator to cache functions that return data (e.g. dataframe transforms, database queries, ML inference).@st.cache_data def long_function(param1, param2): # Perform expensive computation here or # fetch data from the web here return data Cache resourceFunction decorator to cache functions that return global resources (e.g. database connections, ML models).@st.cache_resource def init_model(): # Return a global resource here return pipeline( ""sentiment-analysis"", model=""distilbert-base-uncased-finetuned-sst-2-english"" ) Session stateSession state is a way to share variables between reruns, for each user session.st.session_state['key'] = value Query parametersGet, set, or clear the query parameters that are shown in the browser's URL bar.st.query_params[key] = value st.query_params.clear() Connections and databases Setup your connection Create a connectionConnect to a data source or APIconn = st.connection('pets_db', type='sql') pet_owners = conn.query('select * from pet_owners') st.dataframe(pet_owners) Built-in connections SnowflakeConnectionA connection to Snowflake.conn = st.connection('snowflake') SQLConnectionA connection to a SQL database using SQLAlchemy.conn = st.connection('sql') Build your own connections Connection base classBuild your own connection with BaseConnection.class MyConnection(BaseConnection[myconn.MyConnection]): def _connect(self, **kwargs) -> MyConnection: return myconn.connect(**self._secrets, **kwargs) def query(self, query): return self._instance.query(query) Secrets management Secrets singletonAccess secrets from a local TOML file.key = st.secrets[""OpenAI_key""] Secrets fileSave your secrets in a per-project or per-profile TOML file.OpenAI_key = """" Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration!AuthenticatorA secure authentication module to validate user credentials. Created by @mkhorasani.import streamlit_authenticator as stauth authenticator = stauth.Authenticate( config['credentials'], config['cookie']['name'], config['cookie']['key'], config['cookie']['expiry_days'], config['preauthorized']) WS localStorageA simple synchronous way of accessing localStorage from your app. Created by @gagangoku.from streamlit_ws_localstorage import injectWebsocketCode ret = conn.setLocalStorageVal(key='k1', val='v1') st.write('ret: ' + ret) Streamlit Auth0The fastest way to provide comprehensive login inside Streamlit. Created by @conradbez.from auth0_component import login_button user_info = login_button(clientId, domain = domain) st.write(user_info) Custom Components Declare a componentCreate and register a custom component.st.components.v1.declare_component( ""custom_slider"", ""/frontend"", ) HTMLDisplay an HTML string in an iframe.st.components.v1.html( ""

Foo bar.

"" ) iframeLoad a remote URL in an iframe.st.components.v1.iframe( ""docs.streamlit.io"" ) Utilities and user info User infost.experimental_user returns information about the logged-in user of private apps on Streamlit Community Cloud.if st.experimental_user.email == ""foo@corp.com"": st.write(""Welcome back, "", st.experimental_user.email) else: st.write(""You are not authorized to view this page."") Get helpDisplay object’s doc string, nicely formatted.st.help(st.write) st.help(pd.DataFrame) Render HTMLRenders HTML strings to your app.css = """""" """""" st.html(css) Configuration Configuration fileConfigures the default settings for your app.your-project/ ├── .streamlit/ │ └── config.toml └── your_app.py Set page title, favicon, and moreConfigures the default settings of the page.st.set_page_config( page_title=""My app"", page_icon="":shark:"", ) Developer tools App testing st.testing.v1.AppTestst.testing.v1.AppTest simulates a running Streamlit app for testing.from streamlit.testing.v1 import AppTest at = AppTest.from_file(""streamlit_app.py"") at.secrets[""WORD""] = ""Foobar"" at.run() assert not at.exception at.text_input(""word"").input(""Bazbat"").run() assert at.warning[0].value == ""Try again."" AppTest.from_filest.testing.v1.AppTest.from_file initializes a simulated app from a file.from streamlit.testing.v1 import AppTest at = AppTest.from_file(""streamlit_app.py"") at.run() AppTest.from_stringst.testing.v1.AppTest.from_string initializes a simulated app from a string.from streamlit.testing.v1 import AppTest at = AppTest.from_string(app_script_as_string) at.run() AppTest.from_functionst.testing.v1.AppTest.from_function initializes a simulated app from a function.from streamlit.testing.v1 import AppTest at = AppTest.from_function(app_script_as_callable) at.run() BlockA representation of container elements, including: st.chat_message st.columns st.sidebar st.tabs The main body of the app. # at.sidebar returns a Block at.sidebar.button[0].click().run() assert not at.exception ElementThe base class for representation of all elements, including: st.title st.header st.markdown st.dataframe # at.title returns a sequence of Title # Title inherits from Element assert at.title[0].value == ""My awesome app"" ButtonA representation of st.button and st.form_submit_button.at.button[0].click().run() ChatInputA representation of st.chat_input.at.chat_input[0].set_value(""What is Streamlit?"").run() CheckboxA representation of st.checkbox.at.checkbox[0].check().run() ColorPickerA representation of st.color_picker.at.color_picker[0].pick(""#FF4B4B"").run() DateInputA representation of st.date_input.release_date = datetime.date(2023, 10, 26) at.date_input[0].set_value(release_date).run() MultiselectA representation of st.multiselect.at.multiselect[0].select(""New York"").run() NumberInputA representation of st.number_input.at.number_input[0].increment().run() RadioA representation of st.radio.at.radio[0].set_value(""New York"").run() SelectSliderA representation of st.select_slider.at.select_slider[0].set_range(""A"",""C"").run() SelectboxA representation of st.selectbox.at.selectbox[0].select(""New York"").run() SliderA representation of st.slider.at.slider[0].set_range(2,5).run() TextAreaA representation of st.text_area.at.text_area[0].input(""Streamlit is awesome!"").run() TextInputA representation of st.text_input.at.text_input[0].input(""Streamlit"").run() TimeInputA representation of st.time_input.at.time_input[0].increment().run() ToggleA representation of st.toggle.at.toggle[0].set_value(""True"").run() Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration!Pandas ProfilingPandas profiling component for Streamlit. Created by @okld.df = pd.read_csv(""https://storage.googleapis.com/tf-datasets/titanic/train.csv"") pr = df.profile_report() st_profile_report(pr) Streamlit AceAce editor component for Streamlit. Created by @okld.from streamlit_ace import st_ace content = st_ace() content Streamlit AnalyticsTrack & visualize user interactions with your streamlit app. Created by @jrieke.import streamlit_analytics with streamlit_analytics.track(): st.text_input(""Write something"") Previous: ConceptsNext: Write and magicforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy" https://docs.streamlit.io/develop/api-reference/app-testing/testing-element-classes#checkboxcheck,"DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceremovePAGE ELEMENTSWrite and magicaddText elementsaddData elementsaddChart elementsaddInput widgetsaddMedia elementsaddLayouts and containersaddChat elementsaddStatus elementsaddThird-party componentsopen_in_newAPPLICATION LOGICNavigation and pagesaddExecution flowaddCaching and stateaddConnections and secretsaddCustom componentsaddUtilitiesaddConfigurationaddTOOLSApp testingremovest.testing.v1.AppTestTesting element classesCommand lineaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Develop/API reference/App testing/Testing element classesTesting element classes st.testing.v1.element_tree.Block The Block class has the same methods and attributes as AppTest. A Block instance represents a container of elements just as AppTest represents the entire app. For example, Block.button will produce a WidgetList of Button in the same manner as AppTest.button. ChatMessage, Column, and Tab all inherit from Block. For all container classes, parameters of the original element can be obtained as properties. For example, ChatMessage.avatar and Tab.label. st.testing.v1.element_tree.ElementStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeElement base class for testing. This class's methods and attributes are universal for all elements implemented in testing. For example, Caption, Code, Text, and Title inherit from Element. All widget classes also inherit from Element, but have additional methods specific to each widget type. See the AppTest class for the full list of supported elements. For all element classes, parameters of the original element can be obtained as properties. For example, Button.label, Caption.help, and Toast.icon. Class description[source] st.testing.v1.element_tree.Element(proto, root) Methods run(*, timeout=None) Run the AppTest script which contains the element. Attributes value The value or contents of the element. st.testing.v1.element_tree.ButtonStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.button and st.form_submit_button. Class description[source] st.testing.v1.element_tree.Button(proto, root) Methods click() Set the value of the button to True. run(*, timeout=None) Run the AppTest script which contains the element. set_value(v) Set the value of the button. Attributes value The value of the button. (bool) st.testing.v1.element_tree.ChatInputStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.chat_input. Class description[source] st.testing.v1.element_tree.ChatInput(proto, root) Methods run(*, timeout=None) Run the AppTest script which contains the element. set_value(v) Set the value of the widget. Attributes value The value of the widget. (str) st.testing.v1.element_tree.CheckboxStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.checkbox. Class description[source] st.testing.v1.element_tree.Checkbox(proto, root) Methods check() Set the value of the widget to True. run(*, timeout=None) Run the AppTest script which contains the element. set_value(v) Set the value of the widget. uncheck() Set the value of the widget to False. Attributes value The value of the widget. (bool) st.testing.v1.element_tree.ColorPickerStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.color_picker. Class description[source] st.testing.v1.element_tree.ColorPicker(proto, root) Methods pick(v) Set the value of the widget as a hex string. May omit the ""#"" prefix. run(*, timeout=None) Run the AppTest script which contains the element. set_value(v) Set the value of the widget as a hex string. Attributes value The currently selected value as a hex string. (str) st.testing.v1.element_tree.DateInputStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.date_input. Class description[source] st.testing.v1.element_tree.DateInput(proto, root) Methods run(*, timeout=None) Run the AppTest script which contains the element. set_value(v) Set the value of the widget. Attributes value The value of the widget. (date or Tuple of date) st.testing.v1.element_tree.MultiselectStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.multiselect. Class description[source] st.testing.v1.element_tree.Multiselect(proto, root) Methods run(*, timeout=None) Run the AppTest script which contains the element. select(v) Add a selection to the widget. Do nothing if the value is already selected. If testing a multiselect widget with repeated options, use set_value instead. set_value(v) Set the value of the multiselect widget. (list) unselect(v) Remove a selection from the widget. Do nothing if the value is not already selected. If a value is selected multiple times, the first instance is removed. Attributes format_func The widget's formatting function for displaying options. (callable) indices The indices of the currently selected values from the options. (list) value The currently selected values from the options. (list) st.testing.v1.element_tree.NumberInputStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.number_input. Class description[source] st.testing.v1.element_tree.NumberInput(proto, root) Methods decrement() Decrement the st.number_input widget as if the user clicked ""-"". increment() Increment the st.number_input widget as if the user clicked ""+"". run(*, timeout=None) Run the AppTest script which contains the element. set_value(v) Set the value of the st.number_input widget. Attributes value Get the current value of the st.number_input widget. st.testing.v1.element_tree.RadioStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.radio. Class description[source] st.testing.v1.element_tree.Radio(proto, root) Methods run(*, timeout=None) Run the AppTest script which contains the element. set_value(v) Set the selection by value. Attributes format_func The widget's formatting function for displaying options. (callable) index The index of the current selection. (int) value The currently selected value from the options. (Any) st.testing.v1.element_tree.SelectSliderStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.select_slider. Class description[source] st.testing.v1.element_tree.SelectSlider(proto, root) Methods run(*, timeout=None) Run the AppTest script which contains the element. set_range(lower, upper) Set the ranged selection by values. set_value(v) Set the (single) selection by value. Attributes format_func The widget's formatting function for displaying options. (callable) value The currently selected value or range. (Any or Sequence of Any) st.testing.v1.element_tree.SelectboxStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.selectbox. Class description[source] st.testing.v1.element_tree.Selectbox(proto, root) Methods run(*, timeout=None) Run the AppTest script which contains the element. select(v) Set the selection by value. select_index(index) Set the selection by index. set_value(v) Set the selection by value. Attributes format_func The widget's formatting function for displaying options. (callable) index The index of the current selection. (int) value The currently selected value from the options. (Any) st.testing.v1.element_tree.SliderStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.slider. Class description[source] st.testing.v1.element_tree.Slider(proto, root) Methods run(*, timeout=None) Run the AppTest script which contains the element. set_range(lower, upper) Set the ranged value of the slider. set_value(v) Set the (single) value of the slider. Attributes value The currently selected value or range. (Any or Sequence of Any) st.testing.v1.element_tree.TextAreaStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.text_area. Class description[source] st.testing.v1.element_tree.TextArea(proto, root) Methods input(v) Set the value of the widget only if the value does not exceed the maximum allowed characters. run(*, timeout=None) Run the AppTest script which contains the element. set_value(v) Set the value of the widget. Attributes value The current value of the widget. (str) st.testing.v1.element_tree.TextInputStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.text_input. Class description[source] st.testing.v1.element_tree.TextInput(proto, root) Methods input(v) Set the value of the widget only if the value does not exceed the maximum allowed characters. run(*, timeout=None) Run the AppTest script which contains the element. set_value(v) Set the value of the widget. Attributes value The current value of the widget. (str) st.testing.v1.element_tree.TimeInputStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.time_input. Class description[source] st.testing.v1.element_tree.TimeInput(proto, root) Methods decrement() Select the previous available time. increment() Select the next available time. run(*, timeout=None) Run the AppTest script which contains the element. set_value(v) Set the value of the widget. Attributes value The current value of the widget. (time) st.testing.v1.element_tree.ToggleStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.toggle. Class description[source] st.testing.v1.element_tree.Toggle(proto, root) Methods run(*, timeout=None) Run the AppTest script which contains the element. set_value(v) Set the value of the widget. Attributes value The current value of the widget. (bool) Previous: st.testing.v1.AppTestNext: Command lineforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy" https://docs.streamlit.io/develop/api-reference/caching-and-state/st.cache_resource#example,"DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceremovePAGE ELEMENTSWrite and magicaddText elementsaddData elementsaddChart elementsaddInput widgetsaddMedia elementsaddLayouts and containersaddChat elementsaddStatus elementsaddThird-party componentsopen_in_newAPPLICATION LOGICNavigation and pagesaddExecution flowaddCaching and stateremovest.cache_datast.cache_resourcest.cachedeletest.session_statest.query_paramsst.experimental_get_query_paramsdeletest.experimental_set_query_paramsdeleteConnections and secretsaddCustom componentsaddUtilitiesaddConfigurationaddTOOLSApp testingaddCommand lineaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Develop/API reference/Caching and state/st.cache_resourcestarTipThis page only contains information on the st.cache_resource API. For a deeper dive into caching and how to use it, check out Caching. st.cache_resourceStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeDecorator to cache functions that return global resources (e.g. database connections, ML models). Cached objects are shared across all users, sessions, and reruns. They must be thread-safe because they can be accessed from multiple threads concurrently. If thread safety is an issue, consider using st.session_state to store resources per session instead. You can clear a function's cache with func.clear() or clear the entire cache with st.cache_resource.clear(). To cache data, use st.cache_data instead. Learn more about caching at https://docs.streamlit.io/library/advanced-features/caching. Function signature[source] st.cache_resource(func, *, ttl, max_entries, show_spinner, validate, experimental_allow_widgets, hash_funcs=None) Parameters func (callable) The function that creates the cached resource. Streamlit hashes the function's source code. ttl (float, timedelta, str, or None) The maximum time to keep an entry in the cache. Can be one of: None if cache entries should never expire (default). A number specifying the time in seconds. A string specifying the time in a format supported by Pandas's Timedelta constructor, e.g. ""1d"", ""1.5 days"", or ""1h23s"". A timedelta object from Python's built-in datetime library, e.g. timedelta(days=1). max_entries (int or None) The maximum number of entries to keep in the cache, or None for an unbounded cache. When a new entry is added to a full cache, the oldest cached entry will be removed. Defaults to None. show_spinner (bool or str) Enable the spinner. Default is True to show a spinner when there is a ""cache miss"" and the cached resource is being created. If string, value of show_spinner param will be used for spinner text. validate (callable or None) An optional validation function for cached data. validate is called each time the cached value is accessed. It receives the cached value as its only parameter and it must return a boolean. If validate returns False, the current cached value is discarded, and the decorated function is called to compute a new value. This is useful e.g. to check the health of database connections. experimental_allow_widgets (bool) Allow widgets to be used in the cached function. Defaults to False. Support for widgets in cached functions is currently experimental. Setting this parameter to True may lead to excessive memory use since the widget value is treated as an additional input parameter to the cache. We may remove support for this option at any time without notice. hash_funcs (dict or None) Mapping of types or fully qualified names to hash functions. This is used to override the behavior of the hasher inside Streamlit's caching mechanism: when the hasher encounters an object, it will first check to see if its type matches a key in this dict and, if so, will use the provided function to generate a hash for it. See below for an example of how this can be used. Example import streamlit as st @st.cache_resource def get_database_session(url): # Create a database session object that points to the URL. return session s1 = get_database_session(SESSION_URL_1) # Actually executes the function, since this is the first time it was # encountered. s2 = get_database_session(SESSION_URL_1) # Does not execute the function. Instead, returns its previously computed # value. This means that now the connection object in s1 is the same as in s2. s3 = get_database_session(SESSION_URL_2) # This is a different URL, so the function executes. By default, all parameters to a cache_resource function must be hashable. Any parameter whose name begins with _ will not be hashed. You can use this as an ""escape hatch"" for parameters that are not hashable: import streamlit as st @st.cache_resource def get_database_session(_sessionmaker, url): # Create a database connection object that points to the URL. return connection s1 = get_database_session(create_sessionmaker(), DATA_URL_1) # Actually executes the function, since this is the first time it was # encountered. s2 = get_database_session(create_sessionmaker(), DATA_URL_1) # Does not execute the function. Instead, returns its previously computed # value - even though the _sessionmaker parameter was different # in both calls. A cache_resource function's cache can be procedurally cleared: import streamlit as st @st.cache_resource def get_database_session(_sessionmaker, url): # Create a database connection object that points to the URL. return connection fetch_and_clean_data.clear(_sessionmaker, ""https://streamlit.io/"") # Clear the cached entry for the arguments provided. get_database_session.clear() # Clear all cached entries for this function. To override the default hashing behavior, pass a custom hash function. You can do that by mapping a type (e.g. Person) to a hash function (str) like this: import streamlit as st from pydantic import BaseModel class Person(BaseModel): name: str @st.cache_resource(hash_funcs={Person: str}) def get_person_name(person: Person): return person.name Alternatively, you can map the type's fully-qualified name (e.g. ""__main__.Person"") to the hash function instead: import streamlit as st from pydantic import BaseModel class Person(BaseModel): name: str @st.cache_resource(hash_funcs={""__main__.Person"": str}) def get_person_name(person: Person): return person.name st.cache_resource.clearStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeClear all cache_resource caches. Function signature[source] st.cache_resource.clear() Example In the example below, pressing the ""Clear All"" button will clear all cache_resource caches. i.e. Clears cached global resources from all functions decorated with @st.cache_resource. import streamlit as st from transformers import BertModel @st.cache_resource def get_database_session(url): # Create a database session object that points to the URL. return session @st.cache_resource def get_model(model_type): # Create a model of the specified type. return BertModel.from_pretrained(model_type) if st.button(""Clear All""): # Clears all st.cache_resource caches: st.cache_resource.clear() CachedFunc.clearStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeClear the cached function's associated cache. If no arguments are passed, Streamlit will clear all values cached for the function. If arguments are passed, Streamlit will clear the cached value for these arguments only. Function signature[source] CachedFunc.clear(*args, **kwargs) Parameters *args (Any) Arguments of the cached functions. **kwargs (Any) Keyword arguments of the cached function. Example import streamlit as st import time @st.cache_data def foo(bar): time.sleep(2) st.write(f""Executed foo({bar})."") return bar if st.button(""Clear all cached values for `foo`"", on_click=foo.clear): foo.clear() if st.button(""Clear the cached value of `foo(1)`""): foo.clear(1) foo(1) foo(2) Using Streamlit commands in cached functions Static elements Since version 1.16.0, cached functions can contain Streamlit commands! For example, you can do this: from transformers import pipeline @st.cache_resource def load_model(): model = pipeline(""sentiment-analysis"") st.success(""Loaded NLP model from Hugging Face!"") # 👈 Show a success message return model As we know, Streamlit only runs this function if it hasn’t been cached before. On this first run, the st.success message will appear in the app. But what happens on subsequent runs? It still shows up! Streamlit realizes that there is an st. command inside the cached function, saves it during the first run, and replays it on subsequent runs. Replaying static elements works for both caching decorators. You can also use this functionality to cache entire parts of your UI: @st.cache_resource def load_model(): st.header(""Data analysis"") model = torchvision.models.resnet50(weights=ResNet50_Weights.DEFAULT) st.success(""Loaded model!"") st.write(""Turning on evaluation mode..."") model.eval() st.write(""Here's the model:"") return model Input widgets You can also use interactive input widgets like st.slider or st.text_input in cached functions. Widget replay is an experimental feature at the moment. To enable it, you need to set the experimental_allow_widgets parameter: @st.cache_resource(experimental_allow_widgets=True) # 👈 Set the parameter def load_model(): pretrained = st.checkbox(""Use pre-trained model:"") # 👈 Add a checkbox model = torchvision.models.resnet50(weights=ResNet50_Weights.DEFAULT, pretrained=pretrained) return model Streamlit treats the checkbox like an additional input parameter to the cached function. If you uncheck it, Streamlit will see if it has already cached the function for this checkbox state. If yes, it will return the cached value. If not, it will rerun the function using the new slider value. Using widgets in cached functions is extremely powerful because it lets you cache entire parts of your app. But it can be dangerous! Since Streamlit treats the widget value as an additional input parameter, it can easily lead to excessive memory usage. Imagine your cached function has five sliders and returns a 100 MB DataFrame. Then we’ll add 100 MB to the cache for every permutation of these five slider values – even if the sliders do not influence the returned data! These additions can make your cache explode very quickly. Please be aware of this limitation if you use widgets in cached functions. We recommend using this feature only for isolated parts of your UI where the widgets directly influence the cached return value. priority_highWarningSupport for widgets in cached functions is currently experimental. We may change or remove it anytime without warning. Please use it with care! push_pinNoteTwo widgets are currently not supported in cached functions: st.file_uploader and st.camera_input. We may support them in the future. Feel free to open a GitHub issue if you need them!Previous: st.cache_dataNext: st.cacheforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy" https://docs.streamlit.io/deploy/streamlit-community-cloud/troubleshooting#general-help,"DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudremoveGet startedaddDeploy your appaddManage your appaddShare your appaddManage your accountaddTroubleshootingStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Deploy/Streamlit Community Cloud/TroubleshootingTroubleshooting Sorry to hear you're having issues! Please take a look at some frequently asked questions and issues below. If you cannot find an answer to your issue, please post on our Community forum so that our engineers or community members can help you. Table of contents General help Deploying apps Sharing and accessing apps Data and app security GitHub integration Limitations and known issues General help How can I get help with my app? If you have any questions, feedback, run into any issues, or need to reach us, you can ask on our Community forum. This is best suited for any questions related to the open source library and Community Cloud - debugging code, deployment, resource limits, etc. Deploying apps My repo isn't showing on the Deploy page It's possible it just isn't showing up even though it is already there. Try typing it in. If we don't recognize it, you'll see the message below with a link to click and give access. If for some reason that doesn't work, please try logging out and back in again to make sure the change took effect. And if that doesn't work - please let us know and we'll get you sorted! It won't let me deploy the app To deploy an app for the first time you must have admin-level access to the repo in GitHub. Please check with your administrator to make sure you have that access. If not, please ask them to deploy for the first time (we need this in order to establish webhooks for continuous integration) and from there you can then push updates to the app. I need to set a specific Python version for my app When deploying an app, under advanced settings, you can choose which version of Python you wish your app to use. How do I store files locally? If you want to store your data locally as opposed to in a database, you can store the file in your GitHub repository. Streamlit is just python, so you can read the file using: pandas.read_csv(""data.csv"") or open(""data.csv"") starTipIf you have really big or binary data that you change frequently, and git is feeling slow, you might want to check out Git Large File Store (LFS) as a better way to store large files in GitHub. You don't need to make any changes to your app to start using it. If your GitHub repo uses LFS, it will now just work with Streamlit. My app is running into issues while deploying Check your Cloud logs by clicking on the ""Manage app"" expander in the bottom right corner of your screen. Often the trouble is due to a dependency not being declared. See here for more information on dependency management. If that's not the issue, then please send the logs and warning you are seeing to our Community forum and we'll help get you sorted! My app is hitting resource limits / my app is running very slowly If your app is running slowly or you're hitting the 'Argh' page, we first highly recommend going through and implementing the suggestions in the following blog posts to prevent your app from hitting the resource limits and to detect if your Streamlit app leaks memory: Common app problems: Resource limits 3 steps to fix app memory leaks If you're still having issues, click here to learn more about resource limits. Can I get a custom URL for my app? Yes! You can find instructions for setting a custom subdomain here. Sharing and accessing apps Don't have SSO? No problem! You can sign in to Streamlit with your email address. Click here for step-by-step instructions on how to sign in with email. */} How do I add viewers to my Streamlit apps? Viewer auth allows you to restrict the viewers of your private app. To access your app, users have to authenticate using an email-based passwordless login or Google OAuth. To learn more about how to share your public and private apps with viewers, click here. Do viewers need access to the GitHub repo? Nope! You only need access to the GitHub repo if you want to push changes to the app. What will unauthorized/logged out viewers see when they view my app? A 404 error is displayed to unauthorized viewers to avoid providing any unnecessary information about your app to unintended viewers. Users who satisfy any of the following conditions will see a 404 error when attempting to view your app after you have configured viewer auth: User is not logged in with their primary identity. User is not included in the list of allowed viewers provided in the app settings. User lacks read access to your app's GitHub repo. User has read access to your app's GitHub repo but is not enrolled in Streamlit Community Cloud. I've added someone to the viewer list but they still see a 404 error when attempting to view the app If a user is still seeing a 404 error after their email address has been added to the viewer list, we recommend that you: Check that the user did not log into a different Google account via Single Sign-On (if you have added their work email address to the viewer list, ask the user to check that they are not logged into their personal Google account, and vice versa). Check that the user has navigated to the correct URL. Check that the user's email address has been entered correctly in the viewer list. Reach out on our Community forum and we will be happy to help. Data and app security How will Streamlit secure my data? Streamlit takes a number of industry best-practice measures to ensure your code, data, and apps are all secure. Read more in our Trust and Security memo. How do I set up SSO for my organization? Community Cloud uses Google OAuth, by default. If you use Google for authentication you're all set. Billing and administration The Community Cloud is a free service. You don't have to worry about setting up billing or being charged. GitHub integration Why does Streamlit require additional OAuth scope? In order to deploy your app, Streamlit requires access to your app's source code in GitHub and also the ability to manage the public keys associated with the repositories. The default GitHub OAuth scopes are sufficient to work with apps in public GitHub repositories. However, in order to work with apps in private GitHub repositories, Streamlit requires the additional repo OAuth scope from GitHub. We recognize that this scope provides Streamlit with extra permissions that we do not really need, and which, as people who prize security, we'd rather not even be granted. Alas, we need to work with the APIs we are provided by GitHub. After deploying my private-repo app, I received an email from GitHub saying a new public key was added to my repo. Is this expected? This is the expected behavior. When you try to deploy an app that lives in a private repo, Streamlit Community Cloud needs to get access to that repo somehow. For this, we create a read-only GitHub Deploy Key then access your repo using a public SSH key. When we set this up, GitHub notifies admins of the repo that the key was created as a security measure. What happens when a user's permissions change on GitHub? Once a user is added to a repository on GitHub, it will take at most 15 minutes before they can deploy the app on Cloud. If a user is removed from a repository on GitHub, it will take at most 15 minutes before their permissions to manage the app from that repository are revoked. Limitations and known issues Here are some limitations and known issues that we're actively working to resolve. When you print something to the Cloud logs, you may need to do a sys.stdout.flush() before it shows up. Matplotlib doesn't work well with threads. So if you're using Matplotlib you should wrap your code with locks as shown in the snippet below. This Matplotlib bug is more prominent when you share your app apps since you're more likely to get more concurrent users then. from matplotlib.backends.backend_agg import RendererAgg _lock = RendererAgg.lock with _lock: fig.title('This is a figure)') fig.plot([1,20,3,40]) st.pyplot(fig) All apps are hosted in the United States. This is currently not configurable. Previous: Manage your accountNext: Streamlit in SnowflakeforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy" https://docs.streamlit.io/develop/api-reference/app-testing/testing-element-classes#elementrun,"DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceremovePAGE ELEMENTSWrite and magicaddText elementsaddData elementsaddChart elementsaddInput widgetsaddMedia elementsaddLayouts and containersaddChat elementsaddStatus elementsaddThird-party componentsopen_in_newAPPLICATION LOGICNavigation and pagesaddExecution flowaddCaching and stateaddConnections and secretsaddCustom componentsaddUtilitiesaddConfigurationaddTOOLSApp testingremovest.testing.v1.AppTestTesting element classesCommand lineaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Develop/API reference/App testing/Testing element classesTesting element classes st.testing.v1.element_tree.Block The Block class has the same methods and attributes as AppTest. A Block instance represents a container of elements just as AppTest represents the entire app. For example, Block.button will produce a WidgetList of Button in the same manner as AppTest.button. ChatMessage, Column, and Tab all inherit from Block. For all container classes, parameters of the original element can be obtained as properties. For example, ChatMessage.avatar and Tab.label. st.testing.v1.element_tree.ElementStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeElement base class for testing. This class's methods and attributes are universal for all elements implemented in testing. For example, Caption, Code, Text, and Title inherit from Element. All widget classes also inherit from Element, but have additional methods specific to each widget type. See the AppTest class for the full list of supported elements. For all element classes, parameters of the original element can be obtained as properties. For example, Button.label, Caption.help, and Toast.icon. Class description[source] st.testing.v1.element_tree.Element(proto, root) Methods run(*, timeout=None) Run the AppTest script which contains the element. Attributes value The value or contents of the element. st.testing.v1.element_tree.ButtonStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.button and st.form_submit_button. Class description[source] st.testing.v1.element_tree.Button(proto, root) Methods click() Set the value of the button to True. run(*, timeout=None) Run the AppTest script which contains the element. set_value(v) Set the value of the button. Attributes value The value of the button. (bool) st.testing.v1.element_tree.ChatInputStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.chat_input. Class description[source] st.testing.v1.element_tree.ChatInput(proto, root) Methods run(*, timeout=None) Run the AppTest script which contains the element. set_value(v) Set the value of the widget. Attributes value The value of the widget. (str) st.testing.v1.element_tree.CheckboxStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.checkbox. Class description[source] st.testing.v1.element_tree.Checkbox(proto, root) Methods check() Set the value of the widget to True. run(*, timeout=None) Run the AppTest script which contains the element. set_value(v) Set the value of the widget. uncheck() Set the value of the widget to False. Attributes value The value of the widget. (bool) st.testing.v1.element_tree.ColorPickerStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.color_picker. Class description[source] st.testing.v1.element_tree.ColorPicker(proto, root) Methods pick(v) Set the value of the widget as a hex string. May omit the ""#"" prefix. run(*, timeout=None) Run the AppTest script which contains the element. set_value(v) Set the value of the widget as a hex string. Attributes value The currently selected value as a hex string. (str) st.testing.v1.element_tree.DateInputStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.date_input. Class description[source] st.testing.v1.element_tree.DateInput(proto, root) Methods run(*, timeout=None) Run the AppTest script which contains the element. set_value(v) Set the value of the widget. Attributes value The value of the widget. (date or Tuple of date) st.testing.v1.element_tree.MultiselectStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.multiselect. Class description[source] st.testing.v1.element_tree.Multiselect(proto, root) Methods run(*, timeout=None) Run the AppTest script which contains the element. select(v) Add a selection to the widget. Do nothing if the value is already selected. If testing a multiselect widget with repeated options, use set_value instead. set_value(v) Set the value of the multiselect widget. (list) unselect(v) Remove a selection from the widget. Do nothing if the value is not already selected. If a value is selected multiple times, the first instance is removed. Attributes format_func The widget's formatting function for displaying options. (callable) indices The indices of the currently selected values from the options. (list) value The currently selected values from the options. (list) st.testing.v1.element_tree.NumberInputStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.number_input. Class description[source] st.testing.v1.element_tree.NumberInput(proto, root) Methods decrement() Decrement the st.number_input widget as if the user clicked ""-"". increment() Increment the st.number_input widget as if the user clicked ""+"". run(*, timeout=None) Run the AppTest script which contains the element. set_value(v) Set the value of the st.number_input widget. Attributes value Get the current value of the st.number_input widget. st.testing.v1.element_tree.RadioStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.radio. Class description[source] st.testing.v1.element_tree.Radio(proto, root) Methods run(*, timeout=None) Run the AppTest script which contains the element. set_value(v) Set the selection by value. Attributes format_func The widget's formatting function for displaying options. (callable) index The index of the current selection. (int) value The currently selected value from the options. (Any) st.testing.v1.element_tree.SelectSliderStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.select_slider. Class description[source] st.testing.v1.element_tree.SelectSlider(proto, root) Methods run(*, timeout=None) Run the AppTest script which contains the element. set_range(lower, upper) Set the ranged selection by values. set_value(v) Set the (single) selection by value. Attributes format_func The widget's formatting function for displaying options. (callable) value The currently selected value or range. (Any or Sequence of Any) st.testing.v1.element_tree.SelectboxStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.selectbox. Class description[source] st.testing.v1.element_tree.Selectbox(proto, root) Methods run(*, timeout=None) Run the AppTest script which contains the element. select(v) Set the selection by value. select_index(index) Set the selection by index. set_value(v) Set the selection by value. Attributes format_func The widget's formatting function for displaying options. (callable) index The index of the current selection. (int) value The currently selected value from the options. (Any) st.testing.v1.element_tree.SliderStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.slider. Class description[source] st.testing.v1.element_tree.Slider(proto, root) Methods run(*, timeout=None) Run the AppTest script which contains the element. set_range(lower, upper) Set the ranged value of the slider. set_value(v) Set the (single) value of the slider. Attributes value The currently selected value or range. (Any or Sequence of Any) st.testing.v1.element_tree.TextAreaStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.text_area. Class description[source] st.testing.v1.element_tree.TextArea(proto, root) Methods input(v) Set the value of the widget only if the value does not exceed the maximum allowed characters. run(*, timeout=None) Run the AppTest script which contains the element. set_value(v) Set the value of the widget. Attributes value The current value of the widget. (str) st.testing.v1.element_tree.TextInputStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.text_input. Class description[source] st.testing.v1.element_tree.TextInput(proto, root) Methods input(v) Set the value of the widget only if the value does not exceed the maximum allowed characters. run(*, timeout=None) Run the AppTest script which contains the element. set_value(v) Set the value of the widget. Attributes value The current value of the widget. (str) st.testing.v1.element_tree.TimeInputStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.time_input. Class description[source] st.testing.v1.element_tree.TimeInput(proto, root) Methods decrement() Select the previous available time. increment() Select the next available time. run(*, timeout=None) Run the AppTest script which contains the element. set_value(v) Set the value of the widget. Attributes value The current value of the widget. (time) st.testing.v1.element_tree.ToggleStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.toggle. Class description[source] st.testing.v1.element_tree.Toggle(proto, root) Methods run(*, timeout=None) Run the AppTest script which contains the element. set_value(v) Set the value of the widget. Attributes value The current value of the widget. (bool) Previous: st.testing.v1.AppTestNext: Command lineforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy" https://docs.streamlit.io/develop/api-reference/app-testing/testing-element-classes#selectboxvalue,"DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceremovePAGE ELEMENTSWrite and magicaddText elementsaddData elementsaddChart elementsaddInput widgetsaddMedia elementsaddLayouts and containersaddChat elementsaddStatus elementsaddThird-party componentsopen_in_newAPPLICATION LOGICNavigation and pagesaddExecution flowaddCaching and stateaddConnections and secretsaddCustom componentsaddUtilitiesaddConfigurationaddTOOLSApp testingremovest.testing.v1.AppTestTesting element classesCommand lineaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Develop/API reference/App testing/Testing element classesTesting element classes st.testing.v1.element_tree.Block The Block class has the same methods and attributes as AppTest. A Block instance represents a container of elements just as AppTest represents the entire app. For example, Block.button will produce a WidgetList of Button in the same manner as AppTest.button. ChatMessage, Column, and Tab all inherit from Block. For all container classes, parameters of the original element can be obtained as properties. For example, ChatMessage.avatar and Tab.label. st.testing.v1.element_tree.ElementStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeElement base class for testing. This class's methods and attributes are universal for all elements implemented in testing. For example, Caption, Code, Text, and Title inherit from Element. All widget classes also inherit from Element, but have additional methods specific to each widget type. See the AppTest class for the full list of supported elements. For all element classes, parameters of the original element can be obtained as properties. For example, Button.label, Caption.help, and Toast.icon. Class description[source] st.testing.v1.element_tree.Element(proto, root) Methods run(*, timeout=None) Run the AppTest script which contains the element. Attributes value The value or contents of the element. st.testing.v1.element_tree.ButtonStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.button and st.form_submit_button. Class description[source] st.testing.v1.element_tree.Button(proto, root) Methods click() Set the value of the button to True. run(*, timeout=None) Run the AppTest script which contains the element. set_value(v) Set the value of the button. Attributes value The value of the button. (bool) st.testing.v1.element_tree.ChatInputStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.chat_input. Class description[source] st.testing.v1.element_tree.ChatInput(proto, root) Methods run(*, timeout=None) Run the AppTest script which contains the element. set_value(v) Set the value of the widget. Attributes value The value of the widget. (str) st.testing.v1.element_tree.CheckboxStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.checkbox. Class description[source] st.testing.v1.element_tree.Checkbox(proto, root) Methods check() Set the value of the widget to True. run(*, timeout=None) Run the AppTest script which contains the element. set_value(v) Set the value of the widget. uncheck() Set the value of the widget to False. Attributes value The value of the widget. (bool) st.testing.v1.element_tree.ColorPickerStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.color_picker. Class description[source] st.testing.v1.element_tree.ColorPicker(proto, root) Methods pick(v) Set the value of the widget as a hex string. May omit the ""#"" prefix. run(*, timeout=None) Run the AppTest script which contains the element. set_value(v) Set the value of the widget as a hex string. Attributes value The currently selected value as a hex string. (str) st.testing.v1.element_tree.DateInputStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.date_input. Class description[source] st.testing.v1.element_tree.DateInput(proto, root) Methods run(*, timeout=None) Run the AppTest script which contains the element. set_value(v) Set the value of the widget. Attributes value The value of the widget. (date or Tuple of date) st.testing.v1.element_tree.MultiselectStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.multiselect. Class description[source] st.testing.v1.element_tree.Multiselect(proto, root) Methods run(*, timeout=None) Run the AppTest script which contains the element. select(v) Add a selection to the widget. Do nothing if the value is already selected. If testing a multiselect widget with repeated options, use set_value instead. set_value(v) Set the value of the multiselect widget. (list) unselect(v) Remove a selection from the widget. Do nothing if the value is not already selected. If a value is selected multiple times, the first instance is removed. Attributes format_func The widget's formatting function for displaying options. (callable) indices The indices of the currently selected values from the options. (list) value The currently selected values from the options. (list) st.testing.v1.element_tree.NumberInputStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.number_input. Class description[source] st.testing.v1.element_tree.NumberInput(proto, root) Methods decrement() Decrement the st.number_input widget as if the user clicked ""-"". increment() Increment the st.number_input widget as if the user clicked ""+"". run(*, timeout=None) Run the AppTest script which contains the element. set_value(v) Set the value of the st.number_input widget. Attributes value Get the current value of the st.number_input widget. st.testing.v1.element_tree.RadioStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.radio. Class description[source] st.testing.v1.element_tree.Radio(proto, root) Methods run(*, timeout=None) Run the AppTest script which contains the element. set_value(v) Set the selection by value. Attributes format_func The widget's formatting function for displaying options. (callable) index The index of the current selection. (int) value The currently selected value from the options. (Any) st.testing.v1.element_tree.SelectSliderStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.select_slider. Class description[source] st.testing.v1.element_tree.SelectSlider(proto, root) Methods run(*, timeout=None) Run the AppTest script which contains the element. set_range(lower, upper) Set the ranged selection by values. set_value(v) Set the (single) selection by value. Attributes format_func The widget's formatting function for displaying options. (callable) value The currently selected value or range. (Any or Sequence of Any) st.testing.v1.element_tree.SelectboxStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.selectbox. Class description[source] st.testing.v1.element_tree.Selectbox(proto, root) Methods run(*, timeout=None) Run the AppTest script which contains the element. select(v) Set the selection by value. select_index(index) Set the selection by index. set_value(v) Set the selection by value. Attributes format_func The widget's formatting function for displaying options. (callable) index The index of the current selection. (int) value The currently selected value from the options. (Any) st.testing.v1.element_tree.SliderStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.slider. Class description[source] st.testing.v1.element_tree.Slider(proto, root) Methods run(*, timeout=None) Run the AppTest script which contains the element. set_range(lower, upper) Set the ranged value of the slider. set_value(v) Set the (single) value of the slider. Attributes value The currently selected value or range. (Any or Sequence of Any) st.testing.v1.element_tree.TextAreaStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.text_area. Class description[source] st.testing.v1.element_tree.TextArea(proto, root) Methods input(v) Set the value of the widget only if the value does not exceed the maximum allowed characters. run(*, timeout=None) Run the AppTest script which contains the element. set_value(v) Set the value of the widget. Attributes value The current value of the widget. (str) st.testing.v1.element_tree.TextInputStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.text_input. Class description[source] st.testing.v1.element_tree.TextInput(proto, root) Methods input(v) Set the value of the widget only if the value does not exceed the maximum allowed characters. run(*, timeout=None) Run the AppTest script which contains the element. set_value(v) Set the value of the widget. Attributes value The current value of the widget. (str) st.testing.v1.element_tree.TimeInputStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.time_input. Class description[source] st.testing.v1.element_tree.TimeInput(proto, root) Methods decrement() Select the previous available time. increment() Select the next available time. run(*, timeout=None) Run the AppTest script which contains the element. set_value(v) Set the value of the widget. Attributes value The current value of the widget. (time) st.testing.v1.element_tree.ToggleStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.toggle. Class description[source] st.testing.v1.element_tree.Toggle(proto, root) Methods run(*, timeout=None) Run the AppTest script which contains the element. set_value(v) Set the value of the widget. Attributes value The current value of the widget. (bool) Previous: st.testing.v1.AppTestNext: Command lineforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy" https://docs.streamlit.io/get-started/fundamentals/additional-features#theming,"DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsremoveBasic conceptsAdvanced conceptsAdditional featuresSummaryFirst stepsaddcodeDevelopConceptsaddAPI referenceaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Get started/Fundamentals/Additional featuresAdditional Streamlit features So you've read all about Streamlit's Basic concepts and gotten a taste of caching and Session State in Advanced concepts. But what about the bells and whistles? Here's a quick look at some extra features to take your app to the next level. Theming Streamlit supports Light and Dark themes out of the box. Streamlit will first check if the user viewing an app has a Light or Dark mode preference set by their operating system and browser. If so, then that preference will be used. Otherwise, the Light theme is applied by default. You can also change the active theme from ""⋮"" → ""Settings"". Want to add your own theme to an app? The ""Settings"" menu has a theme editor accessible by clicking on ""Edit active theme"". You can use this editor to try out different colors and see your app update live. When you're happy with your work, themes can be saved by setting config options in the [theme] config section. After you've defined a theme for your app, it will appear as ""Custom Theme"" in the theme selector and will be applied by default instead of the included Light and Dark themes. More information about the options available when defining a theme can be found in the theme option documentation. push_pinNoteThe theme editor menu is available only in local development. If you've deployed your app using Streamlit Community Cloud, the ""Edit active theme"" button will no longer be displayed in the ""Settings"" menu. starTipAnother way to experiment with different theme colors is to turn on the ""Run on save"" option, edit your config.toml file, and watch as your app reruns with the new theme colors applied. Pages As apps grow large, it becomes useful to organize them into multiple pages. This makes the app easier to manage as a developer and easier to navigate as a user. Streamlit provides a frictionless way to create multipage apps. We designed this feature so that building a multipage app is as easy as building a single-page app! Just add more pages to an existing app as follows: In the folder containing your main script, create a new pages folder. Let’s say your main script is named main_page.py. Add new .py files in the pages folder to add more pages to your app. Run streamlit run main_page.py as usual. That’s it! The main_page.py script will now correspond to the main page of your app. And you’ll see the other scripts from the pages folder in the sidebar page selector. The pages are listed according to filename (without file extensions and disregarding underscores). For example: main_page.pyimport streamlit as st st.markdown(""# Main page 🎈"") st.sidebar.markdown(""# Main page 🎈"") pages/page_2.pyimport streamlit as st st.markdown(""# Page 2 ❄️"") st.sidebar.markdown(""# Page 2 ❄️"") pages/page_3.pyimport streamlit as st st.markdown(""# Page 3 🎉"") st.sidebar.markdown(""# Page 3 🎉"") Now run streamlit run main_page.py and view your shiny new multipage app! Our documentation on Multipage apps teaches you how to add pages to your app, including how to define pages, structure and run multipage apps, and navigate between pages. Once you understand the basics, create your first multipage app! Custom components If you can't find the right component within the Streamlit library, try out custom components to extend Streamlit's built-in functionality. Explore and browse through popular, community-created components in the Components gallery. If you dabble in frontend development, you can build your own custom component with Streamlit's components API. Static file serving As you learned in Streamlit fundamentals, Streamlit runs a server that clients connect to. That means viewers of your app don't have direct access to the files which are local to your app. Most of the time, this doesn't matter because Streamlt commands handle that for you. When you use st.image() your Streamlit server will access the file and handle the necessary hosting so your app viewers can see it. However, if you want a direct URL to an image or file you'll need to host it. This requires setting the correct configuration and placing your hosted files in a directory named static. For example, your project could look like: your-project/ ├── static/ │ └── my_hosted-image.png └── streamlit_app.py To learn more, read our guide on Static file serving. App testing Good development hygeine includes testing your code. Automated testing allows you to write higher quality code, faster! Streamlit has a built-in testing framework that let's you build tests easily. Use your favorite testing framework to run your tests. We like pytest. When you test a Streamlit app, you simulate running the app, declare user input, and inspect the results. You can use GitHub workflows to automate your tests and get instant alerts about breaking changes. Learn more in our guide to App testing.Previous: Advanced conceptsNext: SummaryforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy" https://docs.streamlit.io/deploy/streamlit-community-cloud/manage-your-account/update-your-email#how-to-update-your-email,"DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudremoveGet startedaddDeploy your appaddManage your appaddShare your appaddManage your accountremoveSign in & sign outWorkspace settingsManage your GitHub connectionUpdate your emailDelete your accountTroubleshootingStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Deploy/Streamlit Community Cloud/Manage your account/Update your emailUpdate your email If you wish to update your email on Streamlit Community Cloud, you can do so via your Workspace settings. Updating your email changes the primary identity of your account. Once updated, if your account's email is associated with a Google account, you can sign in with Google OAuth. Otherwise, you through emailed links. The latter involves typing in your email, after which we'll send you a unique, single-use link (valid for 15 minutes). If you are signed in to GitHub and don't already have a primary identity on your account, see Connect Google to your account. How to update your email Sign in to Streamlit Community Cloud at share.streamlit.io. Click ""Settings"" in the page's top-right corner. Click ""Update email"" within the ""Linked accounts"" section. Enter your new email and click ""Update email."" You'll see a confirmation dialog asking you to check your email for a confirmation link. Click ""Done."" Your account settings will show ""Update pending"" until you complete the next step. Check your inbox for an email from Streamlit containing a ""Change email"" button and a confirmation link. This one-time link expires in 15 minutes. Click either one to confirm your new email address for Streamlit Community Cloud. Before doing so, ensure you access the link from the same browser session where you are logged in to Streamlit Community Cloud. priority_highImportantIf you access the confirmation link from a browser session where you are not logged in to Streamlit Community Cloud, the confirmation link will not complete the process. You will be prompted to sign in. If you try to sign in with your new email, you will create a second account instead. See Troubleshooting. A confirmation will display to confirm your email update is complete! 🎈 Resend your confirmation link If your confirmation link expires, don't worry! You can resend it by following these steps: Sign in to Streamlit Community Cloud at share.streamlit.io and click ""Settings"" in the page's top-right corner. Click ""Update pending"" Click ""Resend email"" Continue from step 4 of How to update your email. Troubleshooting If you click the confirmation link in a browser session where you are not signed in, you will be informed that ""Sign in is required."" If you try to sign in with your new email, you will create a second account instead. You cannot resend your confirmation link while you have this second account. If you accidentally created a second account, you can follow the steps to Delete your account to get rid of the duplicate. Afterwards, Resend your confirmation link from your first account. Connect Google to your account If you signed up with GitHub and did not create a primary identity, your workspace will show a warning icon in the upper right corner. Click ""Settings"" to access your workspace settings. When you access your workspace settings, a warning is displayed: ""You are not signed in with a primary identity account."" Click ""Sign in with Google"" and follow Google's authentication prompts. Your account now has both a primary identity and source control account. Previous: Manage your GitHub connectionNext: Delete your accountforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy" https://docs.streamlit.io/develop/api-reference/charts/st.altair_chart#annotating-charts,"DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceremovePAGE ELEMENTSWrite and magicaddText elementsaddData elementsaddChart elementsremoveSIMPLEst.area_chartst.bar_chartst.line_chartst.mapst.scatter_chartADVANCEDst.altair_chartst.bokeh_chartst.graphviz_chartst.plotly_chartst.pydeck_chartst.pyplotst.vega_lite_chartInput widgetsaddMedia elementsaddLayouts and containersaddChat elementsaddStatus elementsaddThird-party componentsopen_in_newAPPLICATION LOGICNavigation and pagesaddExecution flowaddCaching and stateaddConnections and secretsaddCustom componentsaddUtilitiesaddConfigurationaddTOOLSApp testingaddCommand lineaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Develop/API reference/Chart elements/st.altair_chartst.altair_chartStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeDisplay a chart using the Altair library. Function signature[source] st.altair_chart(altair_chart, use_container_width=False, theme=""streamlit"") Parameters altair_chart (altair.Chart) The Altair chart object to display. use_container_width (bool) If True, set the chart width to the column width. This takes precedence over Altair's native width value. theme (""streamlit"" or None) The theme of the chart. Currently, we only support ""streamlit"" for the Streamlit defined design or None to fallback to the default behavior of the library. Example import streamlit as st import pandas as pd import numpy as np import altair as alt chart_data = pd.DataFrame(np.random.randn(20, 3), columns=[""a"", ""b"", ""c""]) c = ( alt.Chart(chart_data) .mark_circle() .encode(x=""a"", y=""b"", size=""c"", color=""c"", tooltip=[""a"", ""b"", ""c""]) ) st.altair_chart(c, use_container_width=True) Built with Streamlit 🎈Fullscreen open_in_new Examples of Altair charts can be found at https://altair-viz.github.io/gallery/. Theming Altair charts are displayed using the Streamlit theme by default. This theme is sleek, user-friendly, and incorporates Streamlit's color palette. The added benefit is that your charts better integrate with the rest of your app's design. The Streamlit theme is available from Streamlit 1.16.0 through the theme=""streamlit"" keyword argument. To disable it, and use Altair's native theme, use theme=None instead. Let's look at an example of charts with the Streamlit theme and the native Altair theme: import altair as alt from vega_datasets import data source = data.cars() chart = alt.Chart(source).mark_circle().encode( x='Horsepower', y='Miles_per_Gallon', color='Origin', ).interactive() tab1, tab2 = st.tabs([""Streamlit theme (default)"", ""Altair native theme""]) with tab1: # Use the Streamlit theme. # This is the default. So you can also omit the theme argument. st.altair_chart(chart, theme=""streamlit"", use_container_width=True) with tab2: # Use the native Altair theme. st.altair_chart(chart, theme=None, use_container_width=True) Click the tabs in the interactive app below to see the charts with the Streamlit theme enabled and disabled. Built with Streamlit 🎈Fullscreen open_in_new If you're wondering if your own customizations will still be taken into account, don't worry! You can still make changes to your chart configurations. In other words, although we now enable the Streamlit theme by default, you can overwrite it with custom colors or fonts. For example, if you want a chart line to be green instead of the default red, you can do it! Here's an example of an Altair chart where manual color passing is done and reflected: See the codeexpand_moreimport altair as alt import streamlit as st from vega_datasets import data source = data.seattle_weather() scale = alt.Scale( domain=[""sun"", ""fog"", ""drizzle"", ""rain"", ""snow""], range=[""#e7ba52"", ""#a7a7a7"", ""#aec7e8"", ""#1f77b4"", ""#9467bd""], ) color = alt.Color(""weather:N"", scale=scale) # We create two selections: # - a brush that is active on the top panel # - a multi-click that is active on the bottom panel brush = alt.selection_interval(encodings=[""x""]) click = alt.selection_multi(encodings=[""color""]) # Top panel is scatter plot of temperature vs time points = ( alt.Chart() .mark_point() .encode( alt.X(""monthdate(date):T"", title=""Date""), alt.Y( ""temp_max:Q"", title=""Maximum Daily Temperature (C)"", scale=alt.Scale(domain=[-5, 40]), ), color=alt.condition(brush, color, alt.value(""lightgray"")), size=alt.Size(""precipitation:Q"", scale=alt.Scale(range=[5, 200])), ) .properties(width=550, height=300) .add_selection(brush) .transform_filter(click) ) # Bottom panel is a bar chart of weather type bars = ( alt.Chart() .mark_bar() .encode( x=""count()"", y=""weather:N"", color=alt.condition(click, color, alt.value(""lightgray"")), ) .transform_filter(brush) .properties( width=550, ) .add_selection(click) ) chart = alt.vconcat(points, bars, data=source, title=""Seattle Weather: 2012-2015"") tab1, tab2 = st.tabs([""Streamlit theme (default)"", ""Altair native theme""]) with tab1: st.altair_chart(chart, theme=""streamlit"", use_container_width=True) with tab2: st.altair_chart(chart, theme=None, use_container_width=True) Notice how the custom colors are still reflected in the chart, even when the Streamlit theme is enabled 👇 Built with Streamlit 🎈Fullscreen open_in_new For many more examples of Altair charts with and without the Streamlit theme, check out the altair.streamlit.app. Annotating charts Altair also allows you to annotate your charts with text, images, and emojis. You can do this by creating layered charts, which let you overlay two different charts on top of each other. The idea is to use the first chart to show the data, and the second chart to show the annotations. The second chart can then be overlaid on top of the first chart using the + operator to create a layered chart. Let's walk through an example of annotating a time-series chart with text and an emoji. Step 1: Create the base chart In this example, we create a time-series chart to track the evolution of stock prices. The chart is interactive and contains a multi-line tooltip. Click here to learn more about multi-line tooltips in Altair. First, we import the required libraries and load the example stocks dataset using the vega_datasets package: import altair as alt import pandas as pd import streamlit as st from vega_datasets import data # We use @st.cache_data to keep the dataset in cache @st.cache_data def get_data(): source = data.stocks() source = source[source.date.gt(""2004-01-01"")] return source source = get_data() Next, we define a function get_chart() to create the interactive time-series chart of the stock prices with a multi-line tooltip. The x-axis represents the date, and the y-axis represents the stock price. We then invoke get_chart() that takes the stock prices dataframe as an input and returns a chart object. This is going to be our base chart on which we will overlay the annotations in Step 2. # Define the base time-series chart. def get_chart(data): hover = alt.selection_single( fields=[""date""], nearest=True, on=""mouseover"", empty=""none"", ) lines = ( alt.Chart(data, title=""Evolution of stock prices"") .mark_line() .encode( x=""date"", y=""price"", color=""symbol"", ) ) # Draw points on the line, and highlight based on selection points = lines.transform_filter(hover).mark_circle(size=65) # Draw a rule at the location of the selection tooltips = ( alt.Chart(data) .mark_rule() .encode( x=""yearmonthdate(date)"", y=""price"", opacity=alt.condition(hover, alt.value(0.3), alt.value(0)), tooltip=[ alt.Tooltip(""date"", title=""Date""), alt.Tooltip(""price"", title=""Price (USD)""), ], ) .add_selection(hover) ) return (lines + points + tooltips).interactive() chart = get_chart(source) Step 2: Annotate the chart Now that we have our first chart that shows the data, we can annotate it with text and an emoji. Let's overlay the ⬇ emoji on top of the time-series chart at specifc points of interest. We want users to hover over the ⬇ emoji to see the associated annotation text. For simplicity, let's annotate four specific dates and set the height of the annotations at constant value of 10. starTipYou can vary the horizontal and vertical postions of the annotations by replacing the hard-coded values with the output of Streamlit widgets! Click here to jump to a live example below, and develop an intuition for the ideal horizontal and vertical positions of the annotations by playing with Streamlit widgets. To do so, we create a dataframe annotations_df containing the dates, annotation text, and the height of the annotations: # Add annotations ANNOTATIONS = [ (""Mar 01, 2008"", ""Pretty good day for GOOG""), (""Dec 01, 2007"", ""Something's going wrong for GOOG & AAPL""), (""Nov 01, 2008"", ""Market starts again thanks to...""), (""Dec 01, 2009"", ""Small crash for GOOG after...""), ] annotations_df = pd.DataFrame(ANNOTATIONS, columns=[""date"", ""event""]) annotations_df.date = pd.to_datetime(annotations_df.date) annotations_df[""y""] = 10 Using this dataframe, we create a scatter plot with the x-axis representing the date, and the y-axis representing the height of the annotation. The data point at the specific date and height is represented by the ⬇ emoji, using Altair's mark_text() mark. The annotation text is displayed as a tooltip when users hover over the ⬇ emoji. This is achieved using Altair's encode() method to map the event column containing the annotation text to the visual attribute ⬇ of the plot. annotation_layer = ( alt.Chart(annotations_df) .mark_text(size=20, text=""⬇"", dx=-8, dy=-10, align=""left"") .encode( x=""date:T"", y=alt.Y(""y:Q""), tooltip=[""event""], ) .interactive() ) Finally, we overlay the annotations on top of the base chart using the + operator to create the final layered chart! 🎈 st.altair_chart( (chart + annotation_layer).interactive(), use_container_width=True ) To use images instead of emojis, replace the line containing .mark_text() with .mark_image(), and replace image_url below with the URL of the image: .mark_image( width=12, height=12, url=""image_url"", ) Interactive example Now that you've learned how to annotate charts, the sky's the limit! We've extended the above example to let you interactively paste your favorite emoji and set its position on the chart with Streamlit widgets. 👇 Built with Streamlit 🎈Fullscreen open_in_newPrevious: st.scatter_chartNext: st.bokeh_chartforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy" https://docs.streamlit.io/en/latest/api.html#app-testing,"DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceremovePAGE ELEMENTSWrite and magicaddText elementsaddData elementsaddChart elementsaddInput widgetsaddMedia elementsaddLayouts and containersaddChat elementsaddStatus elementsaddThird-party componentsopen_in_newAPPLICATION LOGICNavigation and pagesaddExecution flowaddCaching and stateaddConnections and secretsaddCustom componentsaddUtilitiesaddConfigurationaddTOOLSApp testingaddCommand lineaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Develop/API referenceAPI reference Streamlit makes it easy for you to visualize, mutate, and share data. The API reference is organized by activity type, like displaying data or optimizing performance. Each section includes methods associated with the activity type, including examples. Browse our API below and click to learn more about any of our available commands! 🎈 Display almost anything Write and magic st.writeWrite arguments to the app.st.write(""Hello **world**!"") st.write(my_data_frame) st.write(my_mpl_figure) st.write_streamWrite generators or streams to the app with a typewriter effect.st.write_stream(my_generator) st.write_stream(my_llm_stream) MagicAny time Streamlit sees either a variable or literal value on its own line, it automatically writes that to your app using st.write""Hello **world**!"" my_data_frame my_mpl_figure Text elements MarkdownDisplay string formatted as Markdown.st.markdown(""Hello **world**!"") TitleDisplay text in title formatting.st.title(""The app title"") HeaderDisplay text in header formatting.st.header(""This is a header"") SubheaderDisplay text in subheader formatting.st.subheader(""This is a subheader"") CaptionDisplay text in small font.st.caption(""This is written small caption text"") Code blockDisplay a code block with optional syntax highlighting.st.code(""a = 1234"") EchoDisplay some code in the app, then execute it. Useful for tutorials.with st.echo(): st.write('This code will be printed') LaTeXDisplay mathematical expressions formatted as LaTeX.st.latex(""\int a x^2 \,dx"") Preformatted textWrite fixed-width and preformatted text.st.text(""Hello world"") DividerDisplay a horizontal rule.st.divider() Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration! PreviousTagsAdd tags to your Streamlit apps. Created by @gagan3012.st_tags(label='# Enter Keywords:', text='Press enter to add more', value=['Zero', 'One', 'Two'], suggestions=['five', 'six', 'seven', 'eight', 'nine', 'three', 'eleven', 'ten', 'four'], maxtags = 4, key='1') NLUApply text mining on a dataframe. Created by @JohnSnowLabs.nlu.load('sentiment').predict('I love NLU! <3') Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.mention(label=""An awesome Streamlit App"", icon=""streamlit"", url=""https://extras.streamlit.app"",) Annotated textDisplay annotated text in Streamlit apps. Created by @tvst.annotated_text(""This "", (""is"", ""verb""), "" some "", (""annotated"", ""adj""), (""text"", ""noun""), "" for those of "", (""you"", ""pronoun""), "" who "", (""like"", ""verb""), "" this sort of "", (""thing"", ""noun""), ""."") Drawable CanvasProvides a sketching canvas using Fabric.js. Created by @andfanilo.st_canvas(fill_color=""rgba(255, 165, 0, 0.3)"", stroke_width=stroke_width, stroke_color=stroke_color, background_color=bg_color, background_image=Image.open(bg_image) if bg_image else None, update_streamlit=realtime_update, height=150, drawing_mode=drawing_mode, point_display_radius=point_display_radius if drawing_mode == 'point' else 0, key=""canvas"",) TagsAdd tags to your Streamlit apps. Created by @gagan3012.st_tags(label='# Enter Keywords:', text='Press enter to add more', value=['Zero', 'One', 'Two'], suggestions=['five', 'six', 'seven', 'eight', 'nine', 'three', 'eleven', 'ten', 'four'], maxtags = 4, key='1') NLUApply text mining on a dataframe. Created by @JohnSnowLabs.nlu.load('sentiment').predict('I love NLU! <3') Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.mention(label=""An awesome Streamlit App"", icon=""streamlit"", url=""https://extras.streamlit.app"",) Annotated textDisplay annotated text in Streamlit apps. Created by @tvst.annotated_text(""This "", (""is"", ""verb""), "" some "", (""annotated"", ""adj""), (""text"", ""noun""), "" for those of "", (""you"", ""pronoun""), "" who "", (""like"", ""verb""), "" this sort of "", (""thing"", ""noun""), ""."") Drawable CanvasProvides a sketching canvas using Fabric.js. Created by @andfanilo.st_canvas(fill_color=""rgba(255, 165, 0, 0.3)"", stroke_width=stroke_width, stroke_color=stroke_color, background_color=bg_color, background_image=Image.open(bg_image) if bg_image else None, update_streamlit=realtime_update, height=150, drawing_mode=drawing_mode, point_display_radius=point_display_radius if drawing_mode == 'point' else 0, key=""canvas"",) TagsAdd tags to your Streamlit apps. Created by @gagan3012.st_tags(label='# Enter Keywords:', text='Press enter to add more', value=['Zero', 'One', 'Two'], suggestions=['five', 'six', 'seven', 'eight', 'nine', 'three', 'eleven', 'ten', 'four'], maxtags = 4, key='1') NLUApply text mining on a dataframe. Created by @JohnSnowLabs.nlu.load('sentiment').predict('I love NLU! <3') Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.mention(label=""An awesome Streamlit App"", icon=""streamlit"", url=""https://extras.streamlit.app"",) Next Data elements DataframesDisplay a dataframe as an interactive table.st.dataframe(my_data_frame) Data editorDisplay a data editor widget.edited = st.data_editor(df, num_rows=""dynamic"") Column configurationConfigure the display and editing behavior of dataframes and data editors.st.column_config.NumberColumn(""Price (in USD)"", min_value=0, format=""$%d"") Static tablesDisplay a static table.st.table(my_data_frame) MetricsDisplay a metric in big bold font, with an optional indicator of how the metric changed.st.metric(""My metric"", 42, 2) Dicts and JSONDisplay object or string as a pretty-printed JSON string.st.json(my_dict) Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration! PreviousImage CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates value = streamlit_image_coordinates(""https://placekitten.com/200/300"") st.write(value) Plotly EventsMake Plotly charts interactive!. Created by @null-jones.from streamlit_plotly_events import plotly_events fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.metric_cards import style_metric_cards col3.metric(label=""No Change"", value=5000, delta=0) style_metric_cards() Streamlit AggridImplementation of Ag-Grid component for Streamlit. Created by @PablocFonseca.df = pd.DataFrame({'col1': [1, 2, 3], 'col2': [4, 5, 6]}) grid_return = AgGrid(df, editable=True) new_df = grid_return['data'] Streamlit FoliumStreamlit Component for rendering Folium maps. Created by @randyzwitch.m = folium.Map(location=[39.949610, -75.150282], zoom_start=16) folium.Marker([39.949610, -75.150282], popup=""Liberty Bell"", tooltip=""Liberty Bell"").add_to(m) st_data = st_folium(m, width=725) Pandas ProfilingPandas profiling component for Streamlit. Created by @okld.df = pd.read_csv(""https://storage.googleapis.com/tf-datasets/titanic/train.csv"") pr = df.profile_report() st_profile_report(pr) Image CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates value = streamlit_image_coordinates(""https://placekitten.com/200/300"") st.write(value) Plotly EventsMake Plotly charts interactive!. Created by @null-jones.from streamlit_plotly_events import plotly_events fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.metric_cards import style_metric_cards col3.metric(label=""No Change"", value=5000, delta=0) style_metric_cards() Streamlit AggridImplementation of Ag-Grid component for Streamlit. Created by @PablocFonseca.df = pd.DataFrame({'col1': [1, 2, 3], 'col2': [4, 5, 6]}) grid_return = AgGrid(df, editable=True) new_df = grid_return['data'] Streamlit FoliumStreamlit Component for rendering Folium maps. Created by @randyzwitch.m = folium.Map(location=[39.949610, -75.150282], zoom_start=16) folium.Marker([39.949610, -75.150282], popup=""Liberty Bell"", tooltip=""Liberty Bell"").add_to(m) st_data = st_folium(m, width=725) Pandas ProfilingPandas profiling component for Streamlit. Created by @okld.df = pd.read_csv(""https://storage.googleapis.com/tf-datasets/titanic/train.csv"") pr = df.profile_report() st_profile_report(pr) Image CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates value = streamlit_image_coordinates(""https://placekitten.com/200/300"") st.write(value) Plotly EventsMake Plotly charts interactive!. Created by @null-jones.from streamlit_plotly_events import plotly_events fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.metric_cards import style_metric_cards col3.metric(label=""No Change"", value=5000, delta=0) style_metric_cards() Next Chart elements Simple area chartsDisplay an area chart.st.area_chart(my_data_frame) Simple bar chartsDisplay a bar chart.st.bar_chart(my_data_frame) Simple line chartsDisplay a line chart.st.line_chart(my_data_frame) Simple scatter chartsDisplay a line chart.st.scatter_chart(my_data_frame) Scatterplots on mapsDisplay a map with points on it.st.map(my_data_frame) MatplotlibDisplay a matplotlib.pyplot figure.st.pyplot(my_mpl_figure) AltairDisplay a chart using the Altair library.st.altair_chart(my_altair_chart) Vega-LiteDisplay a chart using the Vega-Lite library.st.vega_lite_chart(my_vega_lite_chart) PlotlyDisplay an interactive Plotly chart.st.plotly_chart(my_plotly_chart) BokehDisplay an interactive Bokeh chart.st.bokeh_chart(my_bokeh_chart) PyDeckDisplay a chart using the PyDeck library.st.pydeck_chart(my_pydeck_chart) GraphVizDisplay a graph using the dagre-d3 library.st.graphviz_chart(my_graphviz_spec) Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration! PreviousStreamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl(""https://assets5.lottiefiles.com/packages/lf20_V9t630.json"") st_lottie(lottie_hello, key=""hello"") Plotly EventsMake Plotly charts interactive!. Created by @null-jones.fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.chart += get_annotations_chart(annotations=[(""Mar 01, 2008"", ""Pretty good day for GOOG""), (""Dec 01, 2007"", ""Something's going wrong for GOOG & AAPL""), (""Nov 01, 2008"", ""Market starts again thanks to...""), (""Dec 01, 2009"", ""Small crash for GOOG after...""),],) st.altair_chart(chart, use_container_width=True) PlostA deceptively simple plotting library for Streamlit. Created by @tvst.import plost plost.line_chart(my_dataframe, x='time', y='stock_value', color='stock_name',) HiPlotHigh dimensional Interactive Plotting. Created by @facebookresearch.data = [{'dropout':0.1, 'lr': 0.001, 'loss': 10.0, 'optimizer': 'SGD'}, {'dropout':0.15, 'lr': 0.01, 'loss': 3.5, 'optimizer': 'Adam'}, {'dropout':0.3, 'lr': 0.1, 'loss': 4.5, 'optimizer': 'Adam'}] hip.Experiment.from_iterable(data).display() EChartsHigh dimensional Interactive Plotting. Created by @andfanilo.from streamlit_echarts import st_echarts st_echarts(options=options) Streamlit FoliumStreamlit Component for rendering Folium maps. Created by @randyzwitch.m = folium.Map(location=[39.949610, -75.150282], zoom_start=16) st_data = st_folium(m, width=725) Spacy-StreamlitspaCy building blocks and visualizers for Streamlit apps. Created by @explosion.models = [""en_core_web_sm"", ""en_core_web_md""] spacy_streamlit.visualize(models, ""Sundar Pichai is the CEO of Google."") Streamlit AgraphA Streamlit Graph Vis, based on react-grah-vis. Created by @ChrisDelClea.from streamlit_agraph import agraph, Node, Edge, Config agraph(nodes=nodes, edges=edges, config=config) Streamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl(""https://assets5.lottiefiles.com/packages/lf20_V9t630.json"") st_lottie(lottie_hello, key=""hello"") Plotly EventsMake Plotly charts interactive!. Created by @null-jones.fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.chart += get_annotations_chart(annotations=[(""Mar 01, 2008"", ""Pretty good day for GOOG""), (""Dec 01, 2007"", ""Something's going wrong for GOOG & AAPL""), (""Nov 01, 2008"", ""Market starts again thanks to...""), (""Dec 01, 2009"", ""Small crash for GOOG after...""),],) st.altair_chart(chart, use_container_width=True) PlostA deceptively simple plotting library for Streamlit. Created by @tvst.import plost plost.line_chart(my_dataframe, x='time', y='stock_value', color='stock_name',) HiPlotHigh dimensional Interactive Plotting. Created by @facebookresearch.data = [{'dropout':0.1, 'lr': 0.001, 'loss': 10.0, 'optimizer': 'SGD'}, {'dropout':0.15, 'lr': 0.01, 'loss': 3.5, 'optimizer': 'Adam'}, {'dropout':0.3, 'lr': 0.1, 'loss': 4.5, 'optimizer': 'Adam'}] hip.Experiment.from_iterable(data).display() EChartsHigh dimensional Interactive Plotting. Created by @andfanilo.from streamlit_echarts import st_echarts st_echarts(options=options) Streamlit FoliumStreamlit Component for rendering Folium maps. Created by @randyzwitch.m = folium.Map(location=[39.949610, -75.150282], zoom_start=16) st_data = st_folium(m, width=725) Spacy-StreamlitspaCy building blocks and visualizers for Streamlit apps. Created by @explosion.models = [""en_core_web_sm"", ""en_core_web_md""] spacy_streamlit.visualize(models, ""Sundar Pichai is the CEO of Google."") Streamlit AgraphA Streamlit Graph Vis, based on react-grah-vis. Created by @ChrisDelClea.from streamlit_agraph import agraph, Node, Edge, Config agraph(nodes=nodes, edges=edges, config=config) Streamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl(""https://assets5.lottiefiles.com/packages/lf20_V9t630.json"") st_lottie(lottie_hello, key=""hello"") Plotly EventsMake Plotly charts interactive!. Created by @null-jones.fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.chart += get_annotations_chart(annotations=[(""Mar 01, 2008"", ""Pretty good day for GOOG""), (""Dec 01, 2007"", ""Something's going wrong for GOOG & AAPL""), (""Nov 01, 2008"", ""Market starts again thanks to...""), (""Dec 01, 2009"", ""Small crash for GOOG after...""),],) st.altair_chart(chart, use_container_width=True) Next Input widgets ButtonDisplay a button widget.clicked = st.button(""Click me"") Download buttonDisplay a download button widget.st.download_button(""Download file"", file) Form buttonDisplay a form submit button. For use with st.form.st.form_submit_button(""Sign up"") Link buttonDisplay a link button.st.link_button(""Go to gallery"", url) Page linkDisplay a link to another page in a multipage app.st.page_link(""app.py"", label=""Home"", icon=""🏠"") st.page_link(""pages/profile.py"", label=""My profile"") CheckboxDisplay a checkbox widget.selected = st.checkbox(""I agree"") Color pickerDisplay a color picker widget.color = st.color_picker(""Pick a color"") MultiselectDisplay a multiselect widget. The multiselect widget starts as empty.choices = st.multiselect(""Buy"", [""milk"", ""apples"", ""potatoes""]) RadioDisplay a radio button widget.choice = st.radio(""Pick one"", [""cats"", ""dogs""]) SelectboxDisplay a select widget.choice = st.selectbox(""Pick one"", [""cats"", ""dogs""]) Select-sliderDisplay a slider widget to select items from a list.size = st.select_slider(""Pick a size"", [""S"", ""M"", ""L""]) ToggleDisplay a toggle widget.activated = st.toggle(""Activate"") Number inputDisplay a numeric input widget.choice = st.number_input(""Pick a number"", 0, 10) SliderDisplay a slider widget.number = st.slider(""Pick a number"", 0, 100) Date inputDisplay a date input widget.date = st.date_input(""Your birthday"") Time inputDisplay a time input widget.time = st.time_input(""Meeting time"") Chat inputDisplay a chat input widget.prompt = st.chat_input(""Say something"") if prompt: st.write(f""The user has sent: {prompt}"") Text-areaDisplay a multi-line text input widget.text = st.text_area(""Text to translate"") Text inputDisplay a single-line text input widget.name = st.text_input(""First name"") Data editorDisplay a data editor widget.edited = st.experimental_data_editor(df, num_rows=""dynamic"") File UploaderDisplay a file uploader widget.data = st.file_uploader(""Upload a CSV"") Camera inputDisplay a widget that allows users to upload images directly from a camera.image = st.camera_input(""Take a picture"") Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration! PreviousStreamlit ChatStreamlit Component for a Chatbot UI. Created by @AI-Yash.from streamlit_chat import message message(""My message"") message(""Hello bot!"", is_user=True) # align's the message to the right Streamlit Option MenuSelect a single item from a list of options in a menu. Created by @victoryhb.from streamlit_option_menu import option_menu option_menu(""Main Menu"", [""Home"", 'Settings'], icons=['house', 'gear'], menu_icon=""cast"", default_index=1) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.stoggle import stoggle stoggle( ""Click me!"", """"""🥷 Surprise! Here's some additional content"""""",) Streamlit ElementsCreate a draggable and resizable dashboard in Streamlit. Created by @okls.from streamlit_elements import elements, mui, html with elements(""new_element""): mui.Typography(""Hello world"") TagsAdd tags to your Streamlit apps. Created by @gagan3012.from streamlit_tags import st_tags st_tags(label='# Enter Keywords:', text='Press enter to add more', value=['Zero', 'One', 'Two'], suggestions=['five', 'six', 'seven', 'eight', 'nine', 'three', 'eleven', 'ten', 'four'], maxtags = 4, key='1') StqdmThe simplest way to handle a progress bar in streamlit app. Created by @Wirg.from stqdm import stqdm for _ in stqdm(range(50)): sleep(0.5) TimelineDisplay a Timeline in Streamlit apps using TimelineJS. Created by @innerdoc.from streamlit_timeline import timeline with open('example.json', ""r"") as f: timeline(f.read(), height=800) Camera input liveAlternative for st.camera_input which returns the webcam images live. Created by @blackary.from camera_input_live import camera_input_live image = camera_input_live() st.image(value) Streamlit AceAce editor component for Streamlit. Created by @okld.from streamlit_ace import st_ace content = st_ace() content Streamlit ChatStreamlit Component for a Chatbot UI. Created by @AI-Yash.from streamlit_chat import message message(""My message"") message(""Hello bot!"", is_user=True) # align's the message to the right Streamlit Option MenuSelect a single item from a list of options in a menu. Created by @victoryhb.from streamlit_option_menu import option_menu option_menu(""Main Menu"", [""Home"", 'Settings'], icons=['house', 'gear'], menu_icon=""cast"", default_index=1) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.stoggle import stoggle stoggle( ""Click me!"", """"""🥷 Surprise! Here's some additional content"""""",) Streamlit ElementsCreate a draggable and resizable dashboard in Streamlit. Created by @okls.from streamlit_elements import elements, mui, html with elements(""new_element""): mui.Typography(""Hello world"") TagsAdd tags to your Streamlit apps. Created by @gagan3012.from streamlit_tags import st_tags st_tags(label='# Enter Keywords:', text='Press enter to add more', value=['Zero', 'One', 'Two'], suggestions=['five', 'six', 'seven', 'eight', 'nine', 'three', 'eleven', 'ten', 'four'], maxtags = 4, key='1') StqdmThe simplest way to handle a progress bar in streamlit app. Created by @Wirg.from stqdm import stqdm for _ in stqdm(range(50)): sleep(0.5) TimelineDisplay a Timeline in Streamlit apps using TimelineJS. Created by @innerdoc.from streamlit_timeline import timeline with open('example.json', ""r"") as f: timeline(f.read(), height=800) Camera input liveAlternative for st.camera_input which returns the webcam images live. Created by @blackary.from camera_input_live import camera_input_live image = camera_input_live() st.image(value) Streamlit AceAce editor component for Streamlit. Created by @okld.from streamlit_ace import st_ace content = st_ace() content Streamlit ChatStreamlit Component for a Chatbot UI. Created by @AI-Yash.from streamlit_chat import message message(""My message"") message(""Hello bot!"", is_user=True) # align's the message to the right Streamlit Option MenuSelect a single item from a list of options in a menu. Created by @victoryhb.from streamlit_option_menu import option_menu option_menu(""Main Menu"", [""Home"", 'Settings'], icons=['house', 'gear'], menu_icon=""cast"", default_index=1) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.stoggle import stoggle stoggle( ""Click me!"", """"""🥷 Surprise! Here's some additional content"""""",) Next Media elements ImageDisplay an image or list of images.st.image(numpy_array) st.image(image_bytes) st.image(file) st.image(""https://example.com/myimage.jpg"") AudioDisplay an audio player.st.audio(numpy_array) st.audio(audio_bytes) st.audio(file) st.audio(""https://example.com/myaudio.mp3"", format=""audio/mp3"") VideoDisplay a video player.st.video(numpy_array) st.video(video_bytes) st.video(file) st.video(""https://example.com/myvideo.mp4"", format=""video/mp4"") Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration! PreviousStreamlit CropperA simple image cropper for Streamlit. Created by @turner-anderson.from streamlit_cropper import st_cropper st_cropper(img, realtime_update=realtime_update, box_color=box_color, aspect_ratio=aspect_ratio) Image CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates streamlit_image_coordinates(""https://placekitten.com/200/300"") Streamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl(""https://assets5.lottiefiles.com/packages/lf20_V9t630.json"") st_lottie(lottie_hello, key=""hello"") Streamlit WebrtcHandling and transmitting real-time video/audio streams with Streamlit. Created by @whitphx.from streamlit_webrtc import webrtc_streamer webrtc_streamer(key=""sample"") Drawable CanvasProvides a sketching canvas using Fabric.js. Created by @andfanilo.from streamlit_drawable_canvas import st_canvas st_canvas(fill_color=""rgba(255, 165, 0, 0.3)"", stroke_width=stroke_width, stroke_color=stroke_color, background_color=bg_color, background_image=Image.open(bg_image) if bg_image else None, update_streamlit=realtime_update, height=150, drawing_mode=drawing_mode, point_display_radius=point_display_radius if drawing_mode == 'point' else 0, key=""canvas"",) Image ComparisonCompare images with a slider using JuxtaposeJS. Created by @fcakyon.from streamlit_image_comparison import image_comparison image_comparison(img1=""image1.jpg"", img2=""image2.jpg"",) Streamlit CropperA simple image cropper for Streamlit. Created by @turner-anderson.from streamlit_cropper import st_cropper st_cropper(img, realtime_update=realtime_update, box_color=box_color, aspect_ratio=aspect_ratio) Image CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates streamlit_image_coordinates(""https://placekitten.com/200/300"") Streamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl(""https://assets5.lottiefiles.com/packages/lf20_V9t630.json"") st_lottie(lottie_hello, key=""hello"") Streamlit WebrtcHandling and transmitting real-time video/audio streams with Streamlit. Created by @whitphx.from streamlit_webrtc import webrtc_streamer webrtc_streamer(key=""sample"") Drawable CanvasProvides a sketching canvas using Fabric.js. Created by @andfanilo.from streamlit_drawable_canvas import st_canvas st_canvas(fill_color=""rgba(255, 165, 0, 0.3)"", stroke_width=stroke_width, stroke_color=stroke_color, background_color=bg_color, background_image=Image.open(bg_image) if bg_image else None, update_streamlit=realtime_update, height=150, drawing_mode=drawing_mode, point_display_radius=point_display_radius if drawing_mode == 'point' else 0, key=""canvas"",) Image ComparisonCompare images with a slider using JuxtaposeJS. Created by @fcakyon.from streamlit_image_comparison import image_comparison image_comparison(img1=""image1.jpg"", img2=""image2.jpg"",) Streamlit CropperA simple image cropper for Streamlit. Created by @turner-anderson.from streamlit_cropper import st_cropper st_cropper(img, realtime_update=realtime_update, box_color=box_color, aspect_ratio=aspect_ratio) Image CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates streamlit_image_coordinates(""https://placekitten.com/200/300"") Streamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl(""https://assets5.lottiefiles.com/packages/lf20_V9t630.json"") st_lottie(lottie_hello, key=""hello"") Next Layouts and containers ColumnsInsert containers laid out as side-by-side columns.col1, col2 = st.columns(2) col1.write(""this is column 1"") col2.write(""this is column 2"") ContainerInsert a multi-element container.c = st.container() st.write(""This will show last"") c.write(""This will show first"") c.write(""This will show second"") Modal dialogsInsert a modal dialog that can rerun independently from the rest of the script.@st.experimental_dialog(""Sign up"") def email_form(): name = st.text_input(""Name"") email = st.text_input(""Email"") EmptyInsert a single-element container.c = st.empty() st.write(""This will show last"") c.write(""This will be replaced"") c.write(""This will show first"") ExpanderInsert a multi-element container that can be expanded/collapsed.with st.expander(""Open to see more""): st.write(""This is more content"") PopoverInsert a multi-element popover container that can be opened/closed.with st.popover(""Settings""): st.checkbox(""Show completed"") SidebarDisplay items in a sidebar.st.sidebar.write(""This lives in the sidebar"") st.sidebar.button(""Click me!"") TabsInsert containers separated into tabs.tab1, tab2 = st.tabs([""Tab 1"", ""Tab2""]) tab1.write(""this is tab 1"") tab2.write(""this is tab 2"") Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration!Streamlit ElementsCreate a draggable and resizable dashboard in Streamlit. Created by @okls.from streamlit_elements import elements, mui, html with elements(""new_element""): mui.Typography(""Hello world"") PydanticAuto-generate Streamlit UI from Pydantic Models and Dataclasses. Created by @lukasmasuch.import streamlit_pydantic as sp sp.pydantic_form(key=""my_form"", model=ExampleModel) Streamlit PagesAn experimental version of Streamlit Multi-Page Apps. Created by @blackary.from st_pages import Page, show_pages, add_page_title show_pages([ Page(""streamlit_app.py"", ""Home"", ""🏠""), Page(""other_pages/page2.py"", ""Page 2"", "":books:""), ]) Chat elements Streamlit provides a few commands to help you build conversational apps. These chat elements are designed to be used in conjunction with each other, but you can also use them separately. st.chat_message lets you insert a chat message container into the app so you can display messages from the user or the app. Chat containers can contain other Streamlit elements, including charts, tables, text, and more. st.chat_input lets you display a chat input widget so the user can type in a message. Chat inputDisplay a chat input widget.prompt = st.chat_input(""Say something"") if prompt: st.write(f""The user has sent: {prompt}"") Chat messageInsert a chat message container.import numpy as np with st.chat_message(""user""): st.write(""Hello 👋"") st.line_chart(np.random.randn(30, 3)) Status containerDisplay output of long-running tasks in a container.with st.status('Running'): do_something_slow() st.write_streamWrite generators or streams to the app with a typewriter effect.st.write_stream(my_generator) st.write_stream(my_llm_stream) Status elements Progress barDisplay a progress bar.for i in range(101): st.progress(i) do_something_slow() SpinnerTemporarily displays a message while executing a block of code.with st.spinner(""Please wait...""): do_something_slow() Status containerDisplay output of long-running tasks in a container.with st.status('Running'): do_something_slow() ToastBriefly displays a toast message in the bottom-right corner.st.toast('Butter!', icon='🧈') BalloonsDisplay celebratory balloons!do_something() # Celebrate when all done! st.balloons() SnowflakesDisplay celebratory snowflakes!do_something() # Celebrate when all done! st.snow() Success boxDisplay a success message.st.success(""Match found!"") Info boxDisplay an informational message.st.info(""Dataset is updated every day at midnight."") Warning boxDisplay warning message.st.warning(""Unable to fetch image. Skipping..."") Error boxDisplay error message.st.error(""We encountered an error"") Exception outputDisplay an exception.e = RuntimeError(""This is an exception of type RuntimeError"") st.exception(e) Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration!StqdmThe simplest way to handle a progress bar in streamlit app. Created by @Wirg.from stqdm import stqdm for _ in stqdm(range(50)): sleep(0.5) Custom notification boxA custom notification box with the ability to close it out. Created by @Socvest.from streamlit_custom_notification_box import custom_notification_box styles = {'material-icons':{'color': 'red'}, 'text-icon-link-close-container': {'box-shadow': '#3896de 0px 4px'}, 'notification-text': {'':''}, 'close-button':{'':''}, 'link':{'':''}} custom_notification_box(icon='info', textDisplay='We are almost done with your registration...', externalLink='more info', url='#', styles=styles, key=""foo"") Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.let_it_rain import rain rain(emoji=""🎈"", font_size=54, falling_speed=5, animation_length=""infinite"",) App logic and configuration Navigation and pages Switch pageProgrammatically navigates to a specified page.st.switch_page(""pages/my_page.py"") Page linkDisplay a link to another page in a multipage app.st.page_link(""app.py"", label=""Home"", icon=""🏠"") st.page_link(""pages/profile.py"", label=""My profile"") Execution flow Modal dialogsInsert a modal dialog that can rerun independently from the rest of the script.@st.experimental_dialog(""Sign up"") def email_form(): name = st.text_input(""Name"") email = st.text_input(""Email"") FormsCreate a form that batches elements together with a “Submit"" button.with st.form(key='my_form'): name = st.text_input(""Name"") email = st.text_input(""Email"") st.form_submit_button(""Sign up"") Partial rerunsDefine a fragment to rerun independently from the rest of the script.@st.experimental_fragment(run_every=""10s"") def fragment(): df = get_data() st.line_chart(df) Rerun scriptRerun the script immediately.st.rerun() Stop executionStops execution immediately.st.stop() Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration!AutorefreshForce a refresh without tying up a script. Created by @kmcgrady.from streamlit_autorefresh import st_autorefresh st_autorefresh(interval=2000, limit=100, key=""fizzbuzzcounter"") PydanticAuto-generate Streamlit UI from Pydantic Models and Dataclasses. Created by @lukasmasuch.import streamlit_pydantic as sp sp.pydantic_form(key=""my_form"", model=ExampleModel) Streamlit PagesAn experimental version of Streamlit Multi-Page Apps. Created by @blackary.from st_pages import Page, show_pages, add_page_title show_pages([ Page(""streamlit_app.py"", ""Home"", ""🏠""), Page(""other_pages/page2.py"", ""Page 2"", "":books:""), ]) Caching and state Cache dataFunction decorator to cache functions that return data (e.g. dataframe transforms, database queries, ML inference).@st.cache_data def long_function(param1, param2): # Perform expensive computation here or # fetch data from the web here return data Cache resourceFunction decorator to cache functions that return global resources (e.g. database connections, ML models).@st.cache_resource def init_model(): # Return a global resource here return pipeline( ""sentiment-analysis"", model=""distilbert-base-uncased-finetuned-sst-2-english"" ) Session stateSession state is a way to share variables between reruns, for each user session.st.session_state['key'] = value Query parametersGet, set, or clear the query parameters that are shown in the browser's URL bar.st.query_params[key] = value st.query_params.clear() Connections and databases Setup your connection Create a connectionConnect to a data source or APIconn = st.connection('pets_db', type='sql') pet_owners = conn.query('select * from pet_owners') st.dataframe(pet_owners) Built-in connections SnowflakeConnectionA connection to Snowflake.conn = st.connection('snowflake') SQLConnectionA connection to a SQL database using SQLAlchemy.conn = st.connection('sql') Build your own connections Connection base classBuild your own connection with BaseConnection.class MyConnection(BaseConnection[myconn.MyConnection]): def _connect(self, **kwargs) -> MyConnection: return myconn.connect(**self._secrets, **kwargs) def query(self, query): return self._instance.query(query) Secrets management Secrets singletonAccess secrets from a local TOML file.key = st.secrets[""OpenAI_key""] Secrets fileSave your secrets in a per-project or per-profile TOML file.OpenAI_key = """" Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration!AuthenticatorA secure authentication module to validate user credentials. Created by @mkhorasani.import streamlit_authenticator as stauth authenticator = stauth.Authenticate( config['credentials'], config['cookie']['name'], config['cookie']['key'], config['cookie']['expiry_days'], config['preauthorized']) WS localStorageA simple synchronous way of accessing localStorage from your app. Created by @gagangoku.from streamlit_ws_localstorage import injectWebsocketCode ret = conn.setLocalStorageVal(key='k1', val='v1') st.write('ret: ' + ret) Streamlit Auth0The fastest way to provide comprehensive login inside Streamlit. Created by @conradbez.from auth0_component import login_button user_info = login_button(clientId, domain = domain) st.write(user_info) Custom Components Declare a componentCreate and register a custom component.st.components.v1.declare_component( ""custom_slider"", ""/frontend"", ) HTMLDisplay an HTML string in an iframe.st.components.v1.html( ""

Foo bar.

"" ) iframeLoad a remote URL in an iframe.st.components.v1.iframe( ""docs.streamlit.io"" ) Utilities and user info User infost.experimental_user returns information about the logged-in user of private apps on Streamlit Community Cloud.if st.experimental_user.email == ""foo@corp.com"": st.write(""Welcome back, "", st.experimental_user.email) else: st.write(""You are not authorized to view this page."") Get helpDisplay object’s doc string, nicely formatted.st.help(st.write) st.help(pd.DataFrame) Render HTMLRenders HTML strings to your app.css = """""" """""" st.html(css) Configuration Configuration fileConfigures the default settings for your app.your-project/ ├── .streamlit/ │ └── config.toml └── your_app.py Set page title, favicon, and moreConfigures the default settings of the page.st.set_page_config( page_title=""My app"", page_icon="":shark:"", ) Developer tools App testing st.testing.v1.AppTestst.testing.v1.AppTest simulates a running Streamlit app for testing.from streamlit.testing.v1 import AppTest at = AppTest.from_file(""streamlit_app.py"") at.secrets[""WORD""] = ""Foobar"" at.run() assert not at.exception at.text_input(""word"").input(""Bazbat"").run() assert at.warning[0].value == ""Try again."" AppTest.from_filest.testing.v1.AppTest.from_file initializes a simulated app from a file.from streamlit.testing.v1 import AppTest at = AppTest.from_file(""streamlit_app.py"") at.run() AppTest.from_stringst.testing.v1.AppTest.from_string initializes a simulated app from a string.from streamlit.testing.v1 import AppTest at = AppTest.from_string(app_script_as_string) at.run() AppTest.from_functionst.testing.v1.AppTest.from_function initializes a simulated app from a function.from streamlit.testing.v1 import AppTest at = AppTest.from_function(app_script_as_callable) at.run() BlockA representation of container elements, including: st.chat_message st.columns st.sidebar st.tabs The main body of the app. # at.sidebar returns a Block at.sidebar.button[0].click().run() assert not at.exception ElementThe base class for representation of all elements, including: st.title st.header st.markdown st.dataframe # at.title returns a sequence of Title # Title inherits from Element assert at.title[0].value == ""My awesome app"" ButtonA representation of st.button and st.form_submit_button.at.button[0].click().run() ChatInputA representation of st.chat_input.at.chat_input[0].set_value(""What is Streamlit?"").run() CheckboxA representation of st.checkbox.at.checkbox[0].check().run() ColorPickerA representation of st.color_picker.at.color_picker[0].pick(""#FF4B4B"").run() DateInputA representation of st.date_input.release_date = datetime.date(2023, 10, 26) at.date_input[0].set_value(release_date).run() MultiselectA representation of st.multiselect.at.multiselect[0].select(""New York"").run() NumberInputA representation of st.number_input.at.number_input[0].increment().run() RadioA representation of st.radio.at.radio[0].set_value(""New York"").run() SelectSliderA representation of st.select_slider.at.select_slider[0].set_range(""A"",""C"").run() SelectboxA representation of st.selectbox.at.selectbox[0].select(""New York"").run() SliderA representation of st.slider.at.slider[0].set_range(2,5).run() TextAreaA representation of st.text_area.at.text_area[0].input(""Streamlit is awesome!"").run() TextInputA representation of st.text_input.at.text_input[0].input(""Streamlit"").run() TimeInputA representation of st.time_input.at.time_input[0].increment().run() ToggleA representation of st.toggle.at.toggle[0].set_value(""True"").run() Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration!Pandas ProfilingPandas profiling component for Streamlit. Created by @okld.df = pd.read_csv(""https://storage.googleapis.com/tf-datasets/titanic/train.csv"") pr = df.profile_report() st_profile_report(pr) Streamlit AceAce editor component for Streamlit. Created by @okld.from streamlit_ace import st_ace content = st_ace() content Streamlit AnalyticsTrack & visualize user interactions with your streamlit app. Created by @jrieke.import streamlit_analytics with streamlit_analytics.track(): st.text_input(""Write something"") Previous: ConceptsNext: Write and magicforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy" https://docs.streamlit.io/knowledge-base/deploy/unable-to-edit-or-delete-apps-in-streamlit-community-cloud-after-modifying-github-username,"DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Knowledge base/Deployment issues/Unable to edit or delete apps in Streamlit Community Cloud after modifying GitHub usernameUnable to edit or delete apps in Streamlit Community Cloud after modifying GitHub username Problem After updating the GitHub username, apps cannot be edited or deleted from Streamlit Community Cloud. Solution Support can delete your old applications that were deployed before updating the GitHub username. Once deleted, you can redeploy the applications using the new GitHub username. Please contact Support with a list of the URLs for the apps you need to be deleted. Previous: Upgrade the Streamlit version of your app on Streamlit Community CloudNext: Huh. This is isn't supposed to happen message after trying to log inforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy" https://docs.streamlit.io/en/0.71.0/api.html#custom-components,"DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceremovePAGE ELEMENTSWrite and magicaddText elementsaddData elementsaddChart elementsaddInput widgetsaddMedia elementsaddLayouts and containersaddChat elementsaddStatus elementsaddThird-party componentsopen_in_newAPPLICATION LOGICNavigation and pagesaddExecution flowaddCaching and stateaddConnections and secretsaddCustom componentsaddUtilitiesaddConfigurationaddTOOLSApp testingaddCommand lineaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Develop/API referenceAPI reference Streamlit makes it easy for you to visualize, mutate, and share data. The API reference is organized by activity type, like displaying data or optimizing performance. Each section includes methods associated with the activity type, including examples. Browse our API below and click to learn more about any of our available commands! 🎈 Display almost anything Write and magic st.writeWrite arguments to the app.st.write(""Hello **world**!"") st.write(my_data_frame) st.write(my_mpl_figure) st.write_streamWrite generators or streams to the app with a typewriter effect.st.write_stream(my_generator) st.write_stream(my_llm_stream) MagicAny time Streamlit sees either a variable or literal value on its own line, it automatically writes that to your app using st.write""Hello **world**!"" my_data_frame my_mpl_figure Text elements MarkdownDisplay string formatted as Markdown.st.markdown(""Hello **world**!"") TitleDisplay text in title formatting.st.title(""The app title"") HeaderDisplay text in header formatting.st.header(""This is a header"") SubheaderDisplay text in subheader formatting.st.subheader(""This is a subheader"") CaptionDisplay text in small font.st.caption(""This is written small caption text"") Code blockDisplay a code block with optional syntax highlighting.st.code(""a = 1234"") EchoDisplay some code in the app, then execute it. Useful for tutorials.with st.echo(): st.write('This code will be printed') LaTeXDisplay mathematical expressions formatted as LaTeX.st.latex(""\int a x^2 \,dx"") Preformatted textWrite fixed-width and preformatted text.st.text(""Hello world"") DividerDisplay a horizontal rule.st.divider() Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration! PreviousTagsAdd tags to your Streamlit apps. Created by @gagan3012.st_tags(label='# Enter Keywords:', text='Press enter to add more', value=['Zero', 'One', 'Two'], suggestions=['five', 'six', 'seven', 'eight', 'nine', 'three', 'eleven', 'ten', 'four'], maxtags = 4, key='1') NLUApply text mining on a dataframe. Created by @JohnSnowLabs.nlu.load('sentiment').predict('I love NLU! <3') Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.mention(label=""An awesome Streamlit App"", icon=""streamlit"", url=""https://extras.streamlit.app"",) Annotated textDisplay annotated text in Streamlit apps. Created by @tvst.annotated_text(""This "", (""is"", ""verb""), "" some "", (""annotated"", ""adj""), (""text"", ""noun""), "" for those of "", (""you"", ""pronoun""), "" who "", (""like"", ""verb""), "" this sort of "", (""thing"", ""noun""), ""."") Drawable CanvasProvides a sketching canvas using Fabric.js. Created by @andfanilo.st_canvas(fill_color=""rgba(255, 165, 0, 0.3)"", stroke_width=stroke_width, stroke_color=stroke_color, background_color=bg_color, background_image=Image.open(bg_image) if bg_image else None, update_streamlit=realtime_update, height=150, drawing_mode=drawing_mode, point_display_radius=point_display_radius if drawing_mode == 'point' else 0, key=""canvas"",) TagsAdd tags to your Streamlit apps. Created by @gagan3012.st_tags(label='# Enter Keywords:', text='Press enter to add more', value=['Zero', 'One', 'Two'], suggestions=['five', 'six', 'seven', 'eight', 'nine', 'three', 'eleven', 'ten', 'four'], maxtags = 4, key='1') NLUApply text mining on a dataframe. Created by @JohnSnowLabs.nlu.load('sentiment').predict('I love NLU! <3') Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.mention(label=""An awesome Streamlit App"", icon=""streamlit"", url=""https://extras.streamlit.app"",) Annotated textDisplay annotated text in Streamlit apps. Created by @tvst.annotated_text(""This "", (""is"", ""verb""), "" some "", (""annotated"", ""adj""), (""text"", ""noun""), "" for those of "", (""you"", ""pronoun""), "" who "", (""like"", ""verb""), "" this sort of "", (""thing"", ""noun""), ""."") Drawable CanvasProvides a sketching canvas using Fabric.js. Created by @andfanilo.st_canvas(fill_color=""rgba(255, 165, 0, 0.3)"", stroke_width=stroke_width, stroke_color=stroke_color, background_color=bg_color, background_image=Image.open(bg_image) if bg_image else None, update_streamlit=realtime_update, height=150, drawing_mode=drawing_mode, point_display_radius=point_display_radius if drawing_mode == 'point' else 0, key=""canvas"",) TagsAdd tags to your Streamlit apps. Created by @gagan3012.st_tags(label='# Enter Keywords:', text='Press enter to add more', value=['Zero', 'One', 'Two'], suggestions=['five', 'six', 'seven', 'eight', 'nine', 'three', 'eleven', 'ten', 'four'], maxtags = 4, key='1') NLUApply text mining on a dataframe. Created by @JohnSnowLabs.nlu.load('sentiment').predict('I love NLU! <3') Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.mention(label=""An awesome Streamlit App"", icon=""streamlit"", url=""https://extras.streamlit.app"",) Next Data elements DataframesDisplay a dataframe as an interactive table.st.dataframe(my_data_frame) Data editorDisplay a data editor widget.edited = st.data_editor(df, num_rows=""dynamic"") Column configurationConfigure the display and editing behavior of dataframes and data editors.st.column_config.NumberColumn(""Price (in USD)"", min_value=0, format=""$%d"") Static tablesDisplay a static table.st.table(my_data_frame) MetricsDisplay a metric in big bold font, with an optional indicator of how the metric changed.st.metric(""My metric"", 42, 2) Dicts and JSONDisplay object or string as a pretty-printed JSON string.st.json(my_dict) Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration! PreviousImage CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates value = streamlit_image_coordinates(""https://placekitten.com/200/300"") st.write(value) Plotly EventsMake Plotly charts interactive!. Created by @null-jones.from streamlit_plotly_events import plotly_events fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.metric_cards import style_metric_cards col3.metric(label=""No Change"", value=5000, delta=0) style_metric_cards() Streamlit AggridImplementation of Ag-Grid component for Streamlit. Created by @PablocFonseca.df = pd.DataFrame({'col1': [1, 2, 3], 'col2': [4, 5, 6]}) grid_return = AgGrid(df, editable=True) new_df = grid_return['data'] Streamlit FoliumStreamlit Component for rendering Folium maps. Created by @randyzwitch.m = folium.Map(location=[39.949610, -75.150282], zoom_start=16) folium.Marker([39.949610, -75.150282], popup=""Liberty Bell"", tooltip=""Liberty Bell"").add_to(m) st_data = st_folium(m, width=725) Pandas ProfilingPandas profiling component for Streamlit. Created by @okld.df = pd.read_csv(""https://storage.googleapis.com/tf-datasets/titanic/train.csv"") pr = df.profile_report() st_profile_report(pr) Image CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates value = streamlit_image_coordinates(""https://placekitten.com/200/300"") st.write(value) Plotly EventsMake Plotly charts interactive!. Created by @null-jones.from streamlit_plotly_events import plotly_events fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.metric_cards import style_metric_cards col3.metric(label=""No Change"", value=5000, delta=0) style_metric_cards() Streamlit AggridImplementation of Ag-Grid component for Streamlit. Created by @PablocFonseca.df = pd.DataFrame({'col1': [1, 2, 3], 'col2': [4, 5, 6]}) grid_return = AgGrid(df, editable=True) new_df = grid_return['data'] Streamlit FoliumStreamlit Component for rendering Folium maps. Created by @randyzwitch.m = folium.Map(location=[39.949610, -75.150282], zoom_start=16) folium.Marker([39.949610, -75.150282], popup=""Liberty Bell"", tooltip=""Liberty Bell"").add_to(m) st_data = st_folium(m, width=725) Pandas ProfilingPandas profiling component for Streamlit. Created by @okld.df = pd.read_csv(""https://storage.googleapis.com/tf-datasets/titanic/train.csv"") pr = df.profile_report() st_profile_report(pr) Image CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates value = streamlit_image_coordinates(""https://placekitten.com/200/300"") st.write(value) Plotly EventsMake Plotly charts interactive!. Created by @null-jones.from streamlit_plotly_events import plotly_events fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.metric_cards import style_metric_cards col3.metric(label=""No Change"", value=5000, delta=0) style_metric_cards() Next Chart elements Simple area chartsDisplay an area chart.st.area_chart(my_data_frame) Simple bar chartsDisplay a bar chart.st.bar_chart(my_data_frame) Simple line chartsDisplay a line chart.st.line_chart(my_data_frame) Simple scatter chartsDisplay a line chart.st.scatter_chart(my_data_frame) Scatterplots on mapsDisplay a map with points on it.st.map(my_data_frame) MatplotlibDisplay a matplotlib.pyplot figure.st.pyplot(my_mpl_figure) AltairDisplay a chart using the Altair library.st.altair_chart(my_altair_chart) Vega-LiteDisplay a chart using the Vega-Lite library.st.vega_lite_chart(my_vega_lite_chart) PlotlyDisplay an interactive Plotly chart.st.plotly_chart(my_plotly_chart) BokehDisplay an interactive Bokeh chart.st.bokeh_chart(my_bokeh_chart) PyDeckDisplay a chart using the PyDeck library.st.pydeck_chart(my_pydeck_chart) GraphVizDisplay a graph using the dagre-d3 library.st.graphviz_chart(my_graphviz_spec) Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration! PreviousStreamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl(""https://assets5.lottiefiles.com/packages/lf20_V9t630.json"") st_lottie(lottie_hello, key=""hello"") Plotly EventsMake Plotly charts interactive!. Created by @null-jones.fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.chart += get_annotations_chart(annotations=[(""Mar 01, 2008"", ""Pretty good day for GOOG""), (""Dec 01, 2007"", ""Something's going wrong for GOOG & AAPL""), (""Nov 01, 2008"", ""Market starts again thanks to...""), (""Dec 01, 2009"", ""Small crash for GOOG after...""),],) st.altair_chart(chart, use_container_width=True) PlostA deceptively simple plotting library for Streamlit. Created by @tvst.import plost plost.line_chart(my_dataframe, x='time', y='stock_value', color='stock_name',) HiPlotHigh dimensional Interactive Plotting. Created by @facebookresearch.data = [{'dropout':0.1, 'lr': 0.001, 'loss': 10.0, 'optimizer': 'SGD'}, {'dropout':0.15, 'lr': 0.01, 'loss': 3.5, 'optimizer': 'Adam'}, {'dropout':0.3, 'lr': 0.1, 'loss': 4.5, 'optimizer': 'Adam'}] hip.Experiment.from_iterable(data).display() EChartsHigh dimensional Interactive Plotting. Created by @andfanilo.from streamlit_echarts import st_echarts st_echarts(options=options) Streamlit FoliumStreamlit Component for rendering Folium maps. Created by @randyzwitch.m = folium.Map(location=[39.949610, -75.150282], zoom_start=16) st_data = st_folium(m, width=725) Spacy-StreamlitspaCy building blocks and visualizers for Streamlit apps. Created by @explosion.models = [""en_core_web_sm"", ""en_core_web_md""] spacy_streamlit.visualize(models, ""Sundar Pichai is the CEO of Google."") Streamlit AgraphA Streamlit Graph Vis, based on react-grah-vis. Created by @ChrisDelClea.from streamlit_agraph import agraph, Node, Edge, Config agraph(nodes=nodes, edges=edges, config=config) Streamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl(""https://assets5.lottiefiles.com/packages/lf20_V9t630.json"") st_lottie(lottie_hello, key=""hello"") Plotly EventsMake Plotly charts interactive!. Created by @null-jones.fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.chart += get_annotations_chart(annotations=[(""Mar 01, 2008"", ""Pretty good day for GOOG""), (""Dec 01, 2007"", ""Something's going wrong for GOOG & AAPL""), (""Nov 01, 2008"", ""Market starts again thanks to...""), (""Dec 01, 2009"", ""Small crash for GOOG after...""),],) st.altair_chart(chart, use_container_width=True) PlostA deceptively simple plotting library for Streamlit. Created by @tvst.import plost plost.line_chart(my_dataframe, x='time', y='stock_value', color='stock_name',) HiPlotHigh dimensional Interactive Plotting. Created by @facebookresearch.data = [{'dropout':0.1, 'lr': 0.001, 'loss': 10.0, 'optimizer': 'SGD'}, {'dropout':0.15, 'lr': 0.01, 'loss': 3.5, 'optimizer': 'Adam'}, {'dropout':0.3, 'lr': 0.1, 'loss': 4.5, 'optimizer': 'Adam'}] hip.Experiment.from_iterable(data).display() EChartsHigh dimensional Interactive Plotting. Created by @andfanilo.from streamlit_echarts import st_echarts st_echarts(options=options) Streamlit FoliumStreamlit Component for rendering Folium maps. Created by @randyzwitch.m = folium.Map(location=[39.949610, -75.150282], zoom_start=16) st_data = st_folium(m, width=725) Spacy-StreamlitspaCy building blocks and visualizers for Streamlit apps. Created by @explosion.models = [""en_core_web_sm"", ""en_core_web_md""] spacy_streamlit.visualize(models, ""Sundar Pichai is the CEO of Google."") Streamlit AgraphA Streamlit Graph Vis, based on react-grah-vis. Created by @ChrisDelClea.from streamlit_agraph import agraph, Node, Edge, Config agraph(nodes=nodes, edges=edges, config=config) Streamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl(""https://assets5.lottiefiles.com/packages/lf20_V9t630.json"") st_lottie(lottie_hello, key=""hello"") Plotly EventsMake Plotly charts interactive!. Created by @null-jones.fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.chart += get_annotations_chart(annotations=[(""Mar 01, 2008"", ""Pretty good day for GOOG""), (""Dec 01, 2007"", ""Something's going wrong for GOOG & AAPL""), (""Nov 01, 2008"", ""Market starts again thanks to...""), (""Dec 01, 2009"", ""Small crash for GOOG after...""),],) st.altair_chart(chart, use_container_width=True) Next Input widgets ButtonDisplay a button widget.clicked = st.button(""Click me"") Download buttonDisplay a download button widget.st.download_button(""Download file"", file) Form buttonDisplay a form submit button. For use with st.form.st.form_submit_button(""Sign up"") Link buttonDisplay a link button.st.link_button(""Go to gallery"", url) Page linkDisplay a link to another page in a multipage app.st.page_link(""app.py"", label=""Home"", icon=""🏠"") st.page_link(""pages/profile.py"", label=""My profile"") CheckboxDisplay a checkbox widget.selected = st.checkbox(""I agree"") Color pickerDisplay a color picker widget.color = st.color_picker(""Pick a color"") MultiselectDisplay a multiselect widget. The multiselect widget starts as empty.choices = st.multiselect(""Buy"", [""milk"", ""apples"", ""potatoes""]) RadioDisplay a radio button widget.choice = st.radio(""Pick one"", [""cats"", ""dogs""]) SelectboxDisplay a select widget.choice = st.selectbox(""Pick one"", [""cats"", ""dogs""]) Select-sliderDisplay a slider widget to select items from a list.size = st.select_slider(""Pick a size"", [""S"", ""M"", ""L""]) ToggleDisplay a toggle widget.activated = st.toggle(""Activate"") Number inputDisplay a numeric input widget.choice = st.number_input(""Pick a number"", 0, 10) SliderDisplay a slider widget.number = st.slider(""Pick a number"", 0, 100) Date inputDisplay a date input widget.date = st.date_input(""Your birthday"") Time inputDisplay a time input widget.time = st.time_input(""Meeting time"") Chat inputDisplay a chat input widget.prompt = st.chat_input(""Say something"") if prompt: st.write(f""The user has sent: {prompt}"") Text-areaDisplay a multi-line text input widget.text = st.text_area(""Text to translate"") Text inputDisplay a single-line text input widget.name = st.text_input(""First name"") Data editorDisplay a data editor widget.edited = st.experimental_data_editor(df, num_rows=""dynamic"") File UploaderDisplay a file uploader widget.data = st.file_uploader(""Upload a CSV"") Camera inputDisplay a widget that allows users to upload images directly from a camera.image = st.camera_input(""Take a picture"") Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration! PreviousStreamlit ChatStreamlit Component for a Chatbot UI. Created by @AI-Yash.from streamlit_chat import message message(""My message"") message(""Hello bot!"", is_user=True) # align's the message to the right Streamlit Option MenuSelect a single item from a list of options in a menu. Created by @victoryhb.from streamlit_option_menu import option_menu option_menu(""Main Menu"", [""Home"", 'Settings'], icons=['house', 'gear'], menu_icon=""cast"", default_index=1) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.stoggle import stoggle stoggle( ""Click me!"", """"""🥷 Surprise! Here's some additional content"""""",) Streamlit ElementsCreate a draggable and resizable dashboard in Streamlit. Created by @okls.from streamlit_elements import elements, mui, html with elements(""new_element""): mui.Typography(""Hello world"") TagsAdd tags to your Streamlit apps. Created by @gagan3012.from streamlit_tags import st_tags st_tags(label='# Enter Keywords:', text='Press enter to add more', value=['Zero', 'One', 'Two'], suggestions=['five', 'six', 'seven', 'eight', 'nine', 'three', 'eleven', 'ten', 'four'], maxtags = 4, key='1') StqdmThe simplest way to handle a progress bar in streamlit app. Created by @Wirg.from stqdm import stqdm for _ in stqdm(range(50)): sleep(0.5) TimelineDisplay a Timeline in Streamlit apps using TimelineJS. Created by @innerdoc.from streamlit_timeline import timeline with open('example.json', ""r"") as f: timeline(f.read(), height=800) Camera input liveAlternative for st.camera_input which returns the webcam images live. Created by @blackary.from camera_input_live import camera_input_live image = camera_input_live() st.image(value) Streamlit AceAce editor component for Streamlit. Created by @okld.from streamlit_ace import st_ace content = st_ace() content Streamlit ChatStreamlit Component for a Chatbot UI. Created by @AI-Yash.from streamlit_chat import message message(""My message"") message(""Hello bot!"", is_user=True) # align's the message to the right Streamlit Option MenuSelect a single item from a list of options in a menu. Created by @victoryhb.from streamlit_option_menu import option_menu option_menu(""Main Menu"", [""Home"", 'Settings'], icons=['house', 'gear'], menu_icon=""cast"", default_index=1) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.stoggle import stoggle stoggle( ""Click me!"", """"""🥷 Surprise! Here's some additional content"""""",) Streamlit ElementsCreate a draggable and resizable dashboard in Streamlit. Created by @okls.from streamlit_elements import elements, mui, html with elements(""new_element""): mui.Typography(""Hello world"") TagsAdd tags to your Streamlit apps. Created by @gagan3012.from streamlit_tags import st_tags st_tags(label='# Enter Keywords:', text='Press enter to add more', value=['Zero', 'One', 'Two'], suggestions=['five', 'six', 'seven', 'eight', 'nine', 'three', 'eleven', 'ten', 'four'], maxtags = 4, key='1') StqdmThe simplest way to handle a progress bar in streamlit app. Created by @Wirg.from stqdm import stqdm for _ in stqdm(range(50)): sleep(0.5) TimelineDisplay a Timeline in Streamlit apps using TimelineJS. Created by @innerdoc.from streamlit_timeline import timeline with open('example.json', ""r"") as f: timeline(f.read(), height=800) Camera input liveAlternative for st.camera_input which returns the webcam images live. Created by @blackary.from camera_input_live import camera_input_live image = camera_input_live() st.image(value) Streamlit AceAce editor component for Streamlit. Created by @okld.from streamlit_ace import st_ace content = st_ace() content Streamlit ChatStreamlit Component for a Chatbot UI. Created by @AI-Yash.from streamlit_chat import message message(""My message"") message(""Hello bot!"", is_user=True) # align's the message to the right Streamlit Option MenuSelect a single item from a list of options in a menu. Created by @victoryhb.from streamlit_option_menu import option_menu option_menu(""Main Menu"", [""Home"", 'Settings'], icons=['house', 'gear'], menu_icon=""cast"", default_index=1) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.stoggle import stoggle stoggle( ""Click me!"", """"""🥷 Surprise! Here's some additional content"""""",) Next Media elements ImageDisplay an image or list of images.st.image(numpy_array) st.image(image_bytes) st.image(file) st.image(""https://example.com/myimage.jpg"") AudioDisplay an audio player.st.audio(numpy_array) st.audio(audio_bytes) st.audio(file) st.audio(""https://example.com/myaudio.mp3"", format=""audio/mp3"") VideoDisplay a video player.st.video(numpy_array) st.video(video_bytes) st.video(file) st.video(""https://example.com/myvideo.mp4"", format=""video/mp4"") Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration! PreviousStreamlit CropperA simple image cropper for Streamlit. Created by @turner-anderson.from streamlit_cropper import st_cropper st_cropper(img, realtime_update=realtime_update, box_color=box_color, aspect_ratio=aspect_ratio) Image CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates streamlit_image_coordinates(""https://placekitten.com/200/300"") Streamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl(""https://assets5.lottiefiles.com/packages/lf20_V9t630.json"") st_lottie(lottie_hello, key=""hello"") Streamlit WebrtcHandling and transmitting real-time video/audio streams with Streamlit. Created by @whitphx.from streamlit_webrtc import webrtc_streamer webrtc_streamer(key=""sample"") Drawable CanvasProvides a sketching canvas using Fabric.js. Created by @andfanilo.from streamlit_drawable_canvas import st_canvas st_canvas(fill_color=""rgba(255, 165, 0, 0.3)"", stroke_width=stroke_width, stroke_color=stroke_color, background_color=bg_color, background_image=Image.open(bg_image) if bg_image else None, update_streamlit=realtime_update, height=150, drawing_mode=drawing_mode, point_display_radius=point_display_radius if drawing_mode == 'point' else 0, key=""canvas"",) Image ComparisonCompare images with a slider using JuxtaposeJS. Created by @fcakyon.from streamlit_image_comparison import image_comparison image_comparison(img1=""image1.jpg"", img2=""image2.jpg"",) Streamlit CropperA simple image cropper for Streamlit. Created by @turner-anderson.from streamlit_cropper import st_cropper st_cropper(img, realtime_update=realtime_update, box_color=box_color, aspect_ratio=aspect_ratio) Image CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates streamlit_image_coordinates(""https://placekitten.com/200/300"") Streamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl(""https://assets5.lottiefiles.com/packages/lf20_V9t630.json"") st_lottie(lottie_hello, key=""hello"") Streamlit WebrtcHandling and transmitting real-time video/audio streams with Streamlit. Created by @whitphx.from streamlit_webrtc import webrtc_streamer webrtc_streamer(key=""sample"") Drawable CanvasProvides a sketching canvas using Fabric.js. Created by @andfanilo.from streamlit_drawable_canvas import st_canvas st_canvas(fill_color=""rgba(255, 165, 0, 0.3)"", stroke_width=stroke_width, stroke_color=stroke_color, background_color=bg_color, background_image=Image.open(bg_image) if bg_image else None, update_streamlit=realtime_update, height=150, drawing_mode=drawing_mode, point_display_radius=point_display_radius if drawing_mode == 'point' else 0, key=""canvas"",) Image ComparisonCompare images with a slider using JuxtaposeJS. Created by @fcakyon.from streamlit_image_comparison import image_comparison image_comparison(img1=""image1.jpg"", img2=""image2.jpg"",) Streamlit CropperA simple image cropper for Streamlit. Created by @turner-anderson.from streamlit_cropper import st_cropper st_cropper(img, realtime_update=realtime_update, box_color=box_color, aspect_ratio=aspect_ratio) Image CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates streamlit_image_coordinates(""https://placekitten.com/200/300"") Streamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl(""https://assets5.lottiefiles.com/packages/lf20_V9t630.json"") st_lottie(lottie_hello, key=""hello"") Next Layouts and containers ColumnsInsert containers laid out as side-by-side columns.col1, col2 = st.columns(2) col1.write(""this is column 1"") col2.write(""this is column 2"") ContainerInsert a multi-element container.c = st.container() st.write(""This will show last"") c.write(""This will show first"") c.write(""This will show second"") Modal dialogsInsert a modal dialog that can rerun independently from the rest of the script.@st.experimental_dialog(""Sign up"") def email_form(): name = st.text_input(""Name"") email = st.text_input(""Email"") EmptyInsert a single-element container.c = st.empty() st.write(""This will show last"") c.write(""This will be replaced"") c.write(""This will show first"") ExpanderInsert a multi-element container that can be expanded/collapsed.with st.expander(""Open to see more""): st.write(""This is more content"") PopoverInsert a multi-element popover container that can be opened/closed.with st.popover(""Settings""): st.checkbox(""Show completed"") SidebarDisplay items in a sidebar.st.sidebar.write(""This lives in the sidebar"") st.sidebar.button(""Click me!"") TabsInsert containers separated into tabs.tab1, tab2 = st.tabs([""Tab 1"", ""Tab2""]) tab1.write(""this is tab 1"") tab2.write(""this is tab 2"") Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration!Streamlit ElementsCreate a draggable and resizable dashboard in Streamlit. Created by @okls.from streamlit_elements import elements, mui, html with elements(""new_element""): mui.Typography(""Hello world"") PydanticAuto-generate Streamlit UI from Pydantic Models and Dataclasses. Created by @lukasmasuch.import streamlit_pydantic as sp sp.pydantic_form(key=""my_form"", model=ExampleModel) Streamlit PagesAn experimental version of Streamlit Multi-Page Apps. Created by @blackary.from st_pages import Page, show_pages, add_page_title show_pages([ Page(""streamlit_app.py"", ""Home"", ""🏠""), Page(""other_pages/page2.py"", ""Page 2"", "":books:""), ]) Chat elements Streamlit provides a few commands to help you build conversational apps. These chat elements are designed to be used in conjunction with each other, but you can also use them separately. st.chat_message lets you insert a chat message container into the app so you can display messages from the user or the app. Chat containers can contain other Streamlit elements, including charts, tables, text, and more. st.chat_input lets you display a chat input widget so the user can type in a message. Chat inputDisplay a chat input widget.prompt = st.chat_input(""Say something"") if prompt: st.write(f""The user has sent: {prompt}"") Chat messageInsert a chat message container.import numpy as np with st.chat_message(""user""): st.write(""Hello 👋"") st.line_chart(np.random.randn(30, 3)) Status containerDisplay output of long-running tasks in a container.with st.status('Running'): do_something_slow() st.write_streamWrite generators or streams to the app with a typewriter effect.st.write_stream(my_generator) st.write_stream(my_llm_stream) Status elements Progress barDisplay a progress bar.for i in range(101): st.progress(i) do_something_slow() SpinnerTemporarily displays a message while executing a block of code.with st.spinner(""Please wait...""): do_something_slow() Status containerDisplay output of long-running tasks in a container.with st.status('Running'): do_something_slow() ToastBriefly displays a toast message in the bottom-right corner.st.toast('Butter!', icon='🧈') BalloonsDisplay celebratory balloons!do_something() # Celebrate when all done! st.balloons() SnowflakesDisplay celebratory snowflakes!do_something() # Celebrate when all done! st.snow() Success boxDisplay a success message.st.success(""Match found!"") Info boxDisplay an informational message.st.info(""Dataset is updated every day at midnight."") Warning boxDisplay warning message.st.warning(""Unable to fetch image. Skipping..."") Error boxDisplay error message.st.error(""We encountered an error"") Exception outputDisplay an exception.e = RuntimeError(""This is an exception of type RuntimeError"") st.exception(e) Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration!StqdmThe simplest way to handle a progress bar in streamlit app. Created by @Wirg.from stqdm import stqdm for _ in stqdm(range(50)): sleep(0.5) Custom notification boxA custom notification box with the ability to close it out. Created by @Socvest.from streamlit_custom_notification_box import custom_notification_box styles = {'material-icons':{'color': 'red'}, 'text-icon-link-close-container': {'box-shadow': '#3896de 0px 4px'}, 'notification-text': {'':''}, 'close-button':{'':''}, 'link':{'':''}} custom_notification_box(icon='info', textDisplay='We are almost done with your registration...', externalLink='more info', url='#', styles=styles, key=""foo"") Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.let_it_rain import rain rain(emoji=""🎈"", font_size=54, falling_speed=5, animation_length=""infinite"",) App logic and configuration Navigation and pages Switch pageProgrammatically navigates to a specified page.st.switch_page(""pages/my_page.py"") Page linkDisplay a link to another page in a multipage app.st.page_link(""app.py"", label=""Home"", icon=""🏠"") st.page_link(""pages/profile.py"", label=""My profile"") Execution flow Modal dialogsInsert a modal dialog that can rerun independently from the rest of the script.@st.experimental_dialog(""Sign up"") def email_form(): name = st.text_input(""Name"") email = st.text_input(""Email"") FormsCreate a form that batches elements together with a “Submit"" button.with st.form(key='my_form'): name = st.text_input(""Name"") email = st.text_input(""Email"") st.form_submit_button(""Sign up"") Partial rerunsDefine a fragment to rerun independently from the rest of the script.@st.experimental_fragment(run_every=""10s"") def fragment(): df = get_data() st.line_chart(df) Rerun scriptRerun the script immediately.st.rerun() Stop executionStops execution immediately.st.stop() Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration!AutorefreshForce a refresh without tying up a script. Created by @kmcgrady.from streamlit_autorefresh import st_autorefresh st_autorefresh(interval=2000, limit=100, key=""fizzbuzzcounter"") PydanticAuto-generate Streamlit UI from Pydantic Models and Dataclasses. Created by @lukasmasuch.import streamlit_pydantic as sp sp.pydantic_form(key=""my_form"", model=ExampleModel) Streamlit PagesAn experimental version of Streamlit Multi-Page Apps. Created by @blackary.from st_pages import Page, show_pages, add_page_title show_pages([ Page(""streamlit_app.py"", ""Home"", ""🏠""), Page(""other_pages/page2.py"", ""Page 2"", "":books:""), ]) Caching and state Cache dataFunction decorator to cache functions that return data (e.g. dataframe transforms, database queries, ML inference).@st.cache_data def long_function(param1, param2): # Perform expensive computation here or # fetch data from the web here return data Cache resourceFunction decorator to cache functions that return global resources (e.g. database connections, ML models).@st.cache_resource def init_model(): # Return a global resource here return pipeline( ""sentiment-analysis"", model=""distilbert-base-uncased-finetuned-sst-2-english"" ) Session stateSession state is a way to share variables between reruns, for each user session.st.session_state['key'] = value Query parametersGet, set, or clear the query parameters that are shown in the browser's URL bar.st.query_params[key] = value st.query_params.clear() Connections and databases Setup your connection Create a connectionConnect to a data source or APIconn = st.connection('pets_db', type='sql') pet_owners = conn.query('select * from pet_owners') st.dataframe(pet_owners) Built-in connections SnowflakeConnectionA connection to Snowflake.conn = st.connection('snowflake') SQLConnectionA connection to a SQL database using SQLAlchemy.conn = st.connection('sql') Build your own connections Connection base classBuild your own connection with BaseConnection.class MyConnection(BaseConnection[myconn.MyConnection]): def _connect(self, **kwargs) -> MyConnection: return myconn.connect(**self._secrets, **kwargs) def query(self, query): return self._instance.query(query) Secrets management Secrets singletonAccess secrets from a local TOML file.key = st.secrets[""OpenAI_key""] Secrets fileSave your secrets in a per-project or per-profile TOML file.OpenAI_key = """" Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration!AuthenticatorA secure authentication module to validate user credentials. Created by @mkhorasani.import streamlit_authenticator as stauth authenticator = stauth.Authenticate( config['credentials'], config['cookie']['name'], config['cookie']['key'], config['cookie']['expiry_days'], config['preauthorized']) WS localStorageA simple synchronous way of accessing localStorage from your app. Created by @gagangoku.from streamlit_ws_localstorage import injectWebsocketCode ret = conn.setLocalStorageVal(key='k1', val='v1') st.write('ret: ' + ret) Streamlit Auth0The fastest way to provide comprehensive login inside Streamlit. Created by @conradbez.from auth0_component import login_button user_info = login_button(clientId, domain = domain) st.write(user_info) Custom Components Declare a componentCreate and register a custom component.st.components.v1.declare_component( ""custom_slider"", ""/frontend"", ) HTMLDisplay an HTML string in an iframe.st.components.v1.html( ""

Foo bar.

"" ) iframeLoad a remote URL in an iframe.st.components.v1.iframe( ""docs.streamlit.io"" ) Utilities and user info User infost.experimental_user returns information about the logged-in user of private apps on Streamlit Community Cloud.if st.experimental_user.email == ""foo@corp.com"": st.write(""Welcome back, "", st.experimental_user.email) else: st.write(""You are not authorized to view this page."") Get helpDisplay object’s doc string, nicely formatted.st.help(st.write) st.help(pd.DataFrame) Render HTMLRenders HTML strings to your app.css = """""" """""" st.html(css) Configuration Configuration fileConfigures the default settings for your app.your-project/ ├── .streamlit/ │ └── config.toml └── your_app.py Set page title, favicon, and moreConfigures the default settings of the page.st.set_page_config( page_title=""My app"", page_icon="":shark:"", ) Developer tools App testing st.testing.v1.AppTestst.testing.v1.AppTest simulates a running Streamlit app for testing.from streamlit.testing.v1 import AppTest at = AppTest.from_file(""streamlit_app.py"") at.secrets[""WORD""] = ""Foobar"" at.run() assert not at.exception at.text_input(""word"").input(""Bazbat"").run() assert at.warning[0].value == ""Try again."" AppTest.from_filest.testing.v1.AppTest.from_file initializes a simulated app from a file.from streamlit.testing.v1 import AppTest at = AppTest.from_file(""streamlit_app.py"") at.run() AppTest.from_stringst.testing.v1.AppTest.from_string initializes a simulated app from a string.from streamlit.testing.v1 import AppTest at = AppTest.from_string(app_script_as_string) at.run() AppTest.from_functionst.testing.v1.AppTest.from_function initializes a simulated app from a function.from streamlit.testing.v1 import AppTest at = AppTest.from_function(app_script_as_callable) at.run() BlockA representation of container elements, including: st.chat_message st.columns st.sidebar st.tabs The main body of the app. # at.sidebar returns a Block at.sidebar.button[0].click().run() assert not at.exception ElementThe base class for representation of all elements, including: st.title st.header st.markdown st.dataframe # at.title returns a sequence of Title # Title inherits from Element assert at.title[0].value == ""My awesome app"" ButtonA representation of st.button and st.form_submit_button.at.button[0].click().run() ChatInputA representation of st.chat_input.at.chat_input[0].set_value(""What is Streamlit?"").run() CheckboxA representation of st.checkbox.at.checkbox[0].check().run() ColorPickerA representation of st.color_picker.at.color_picker[0].pick(""#FF4B4B"").run() DateInputA representation of st.date_input.release_date = datetime.date(2023, 10, 26) at.date_input[0].set_value(release_date).run() MultiselectA representation of st.multiselect.at.multiselect[0].select(""New York"").run() NumberInputA representation of st.number_input.at.number_input[0].increment().run() RadioA representation of st.radio.at.radio[0].set_value(""New York"").run() SelectSliderA representation of st.select_slider.at.select_slider[0].set_range(""A"",""C"").run() SelectboxA representation of st.selectbox.at.selectbox[0].select(""New York"").run() SliderA representation of st.slider.at.slider[0].set_range(2,5).run() TextAreaA representation of st.text_area.at.text_area[0].input(""Streamlit is awesome!"").run() TextInputA representation of st.text_input.at.text_input[0].input(""Streamlit"").run() TimeInputA representation of st.time_input.at.time_input[0].increment().run() ToggleA representation of st.toggle.at.toggle[0].set_value(""True"").run() Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration!Pandas ProfilingPandas profiling component for Streamlit. Created by @okld.df = pd.read_csv(""https://storage.googleapis.com/tf-datasets/titanic/train.csv"") pr = df.profile_report() st_profile_report(pr) Streamlit AceAce editor component for Streamlit. Created by @okld.from streamlit_ace import st_ace content = st_ace() content Streamlit AnalyticsTrack & visualize user interactions with your streamlit app. Created by @jrieke.import streamlit_analytics with streamlit_analytics.track(): st.text_input(""Write something"") Previous: ConceptsNext: Write and magicforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy" https://docs.streamlit.io/develop/api-reference/app-testing/st.testing.v1.apptest#apptestlatex,"DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceremovePAGE ELEMENTSWrite and magicaddText elementsaddData elementsaddChart elementsaddInput widgetsaddMedia elementsaddLayouts and containersaddChat elementsaddStatus elementsaddThird-party componentsopen_in_newAPPLICATION LOGICNavigation and pagesaddExecution flowaddCaching and stateaddConnections and secretsaddCustom componentsaddUtilitiesaddConfigurationaddTOOLSApp testingremovest.testing.v1.AppTestTesting element classesCommand lineaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Develop/API reference/App testing/st.testing.v1.AppTest The AppTest class st.testing.v1.AppTestStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA simulated Streamlit app to check the correctness of displayed elements and outputs. An instance of AppTest simulates a running Streamlit app. This class provides methods to set up, manipulate, and inspect the app contents via API instead of a browser UI. It can be used to write automated tests of an app in various scenarios. These can then be run using a tool like pytest. AppTest can be initialized by one of three class methods: st.testing.v1.AppTest.from_file (recommended) st.testing.v1.AppTest.from_string st.testing.v1.AppTest.from_function Once initialized, Session State and widget values can be updated and the script can be run. Unlike an actual live-running Streamlit app, you need to call AppTest.run() explicitly to re-run the app after changing a widget value. Switching pages also requires an explicit, follow-up call to AppTest.run(). AppTest enables developers to build tests on their app as-is, in the familiar python test format, without major refactoring or abstracting out logic to be tested separately from the UI. Tests can run quickly with very low overhead. A typical pattern is to build a suite of tests for an app that ensure consistent functionality as the app evolves, and run the tests locally and/or in a CI environment like Github Actions. Note AppTest only supports testing a single page of an app per instance. For multipage apps, each page will need to be tested separately. No methods exist to programatically switch pages within AppTest. Class description[source] st.testing.v1.AppTest(script_path, *, default_timeout, args=None, kwargs=None) Methods get(element_type) Get elements or widgets of the specified type. run(*, timeout=None) Run the script from the current state. switch_page(page_path) Switch to another page of the app. Attributes secrets (dict[str, Any]) Dictionary of secrets to be used the simulated app. Use dict-like syntax to set secret values for the simulated app. session_state (SafeSessionState) Session State for the simulated app. SafeSessionState object supports read and write operations as usual for Streamlit apps. query_params (dict[str, Any]) Dictionary of query parameters to be used by the simluated app. Use dict-like syntax to set query_params values for the simulated app. button Sequence of all st.button and st.form_submit_button widgets. caption Sequence of all st.caption elements. chat_input Sequence of all st.chat_input widgets. chat_message Sequence of all st.chat_message elements. checkbox Sequence of all st.checkbox widgets. code Sequence of all st.code elements. color_picker Sequence of all st.color_picker widgets. columns Sequence of all columns within st.columns elements. dataframe Sequence of all st.dataframe elements. date_input Sequence of all st.date_input widgets. divider Sequence of all st.divider elements. error Sequence of all st.error elements. exception Sequence of all st.exception elements. expander Sequence of all st.expander elements. header Sequence of all st.header elements. info Sequence of all st.info elements. json Sequence of all st.json elements. latex Sequence of all st.latex elements. main Sequence of elements within the main body of the app. markdown Sequence of all st.markdown elements. metric Sequence of all st.metric elements. multiselect Sequence of all st.multiselect widgets. number_input Sequence of all st.number_input widgets. radio Sequence of all st.radio widgets. select_slider Sequence of all st.select_slider widgets. selectbox Sequence of all st.selectbox widgets. sidebar Sequence of all elements within st.sidebar. slider Sequence of all st.slider widgets. status Sequence of all st.status elements. subheader Sequence of all st.subheader elements. success Sequence of all st.success elements. table Sequence of all st.table elements. tabs Sequence of all tabs within st.tabs elements. text Sequence of all st.text elements. text_area Sequence of all st.text_area widgets. text_input Sequence of all st.text_input widgets. time_input Sequence of all st.time_input widgets. title Sequence of all st.title elements. toast Sequence of all st.toast elements. toggle Sequence of all st.toggle widgets. warning Sequence of all st.warning elements. Initialize a simulated app using AppTest AppTest.from_fileStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeCreate an instance of AppTest to simulate an app page defined within a file. This option is most convenient for CI workflows and testing of published apps. The script must be executable on its own and so must contain all necessary imports. Function signature[source] AppTest.from_file(cls, script_path, *, default_timeout=3) Parameters script_path (str) Path to a script file. The path should be absolute or relative to the file calling .from_file. default_timeout (float) Default time in seconds before a script run is timed out. Can be overridden for individual .run() calls. Returns(AppTest) A simulated Streamlit app for testing. The simulated app can be executed via .run(). AppTest.from_stringStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeCreate an instance of AppTest to simulate an app page defined within a string. This is useful for testing short scripts that fit comfortably as an inline string in the test itself, without having to create a separate file for it. The script must be executable on its own and so must contain all necessary imports. Function signature[source] AppTest.from_string(cls, script, *, default_timeout=3) Parameters script (str) The string contents of the script to be run. default_timeout (float) Default time in seconds before a script run is timed out. Can be overridden for individual .run() calls. Returns(AppTest) A simulated Streamlit app for testing. The simulated app can be executed via .run(). AppTest.from_functionStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeCreate an instance of AppTest to simulate an app page defined within a function. This is similar to AppTest.from_string(), but more convenient to write with IDE assistance. The script must be executable on its own and so must contain all necessary imports. Function signature[source] AppTest.from_function(cls, script, *, default_timeout=3, args=None, kwargs=None) Parameters script (Callable) A function whose body will be used as a script. Must be runnable in isolation, so it must include any necessary imports. default_timeout (float) Default time in seconds before a script run is timed out. Can be overridden for individual .run() calls. args (tuple) An optional tuple of args to pass to the script function. kwargs (dict) An optional dict of kwargs to pass to the script function. Returns(AppTest) A simulated Streamlit app for testing. The simulated app can be executed via .run(). Run an AppTest script AppTest.runStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeRun the script from the current state. This is equivalent to manually rerunning the app or the rerun that occurs upon user interaction. AppTest.run() must be manually called after updating a widget value or switching pages as script reruns do not occur automatically as they do for live-running Streamlit apps. Function signature[source] AppTest.run(*, timeout=None) Parameters timeout (null) The maximum number of seconds to run the script. None means use the default timeout set for the instance of AppTest. Returns(AppTest) self AppTest.switch_pageStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSwitch to another page of the app. This method does not automatically rerun the app. Use a follow-up call to AppTest.run() to obtain the elements on the selected page. Function signature[source] AppTest.switch_page(page_path) Parameters page_path (str) Path of the page to switch to. The path must be relative to the main script's location (e.g. ""pages/my_page.py""). Returns(AppTest) self Get AppTest script elements The main value of AppTest is providing an API to programmatically inspect and interact with the elements and widgets produced by a running Streamlit app. Using the AppTest. properties or AppTest.get() method returns a collection of all the elements or widgets of the specified type that would have been displayed by running the app. Note that you can also retrieve elements within a specific container in the same way - first retrieve the container, then retrieve the elements just in that container. AppTest.getStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeGet elements or widgets of the specified type. This method returns the collection of all elements or widgets of the specified type on the current page. Retrieve a specific element by using its index (order on page) or key lookup. Function signature[source] AppTest.get(element_type) Parameters element_type (str) An element attribute of AppTest. For example, ""button"", ""caption"", or ""chat_input"". Returns(Sequence of Elements) Sequence of elements of the given type. Individual elements can be accessed from a Sequence by index (order on the page). When getting and element_type that is a widget, individual widgets can be accessed by key. For example, at.get(""text"")[0] for the first st.text element or at.get(""slider"")(key=""my_key"") for the st.slider widget with a given key. AppTest.buttonStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.button and st.form_submit_button widgets. Function signature[source] AppTest.button Returns(WidgetList of Button) Sequence of all st.button and st.form_submit_button widgets. Individual widgets can be accessed from a WidgetList by index (order on the page) or key. For example, at.button[0] for the first widget or at.button(key=""my_key"") for a widget with a given key. AppTest.captionStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.caption elements. Function signature[source] AppTest.caption Returns(ElementList of Caption) Sequence of all st.caption elements. Individual elements can be accessed from an ElementList by index (order on the page). For example, at.caption[0] for the first element. Caption is an extension of the Element class. AppTest.chat_inputStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.chat_input widgets. Function signature[source] AppTest.chat_input Returns(WidgetList of ChatInput) Sequence of all st.chat_input widgets. Individual widgets can be accessed from a WidgetList by index (order on the page) or key. For example, at.chat_input[0] for the first widget or at.chat_input(key=""my_key"") for a widget with a given key. AppTest.chat_messageStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.chat_message elements. Function signature[source] AppTest.chat_message Returns(Sequence of ChatMessage) Sequence of all st.chat_message elements. Individual elements can be accessed from an ElementList by index (order on the page). For example, at.chat_message[0] for the first element. ChatMessage is an extension of the Block class. AppTest.checkboxStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.checkbox widgets. Function signature[source] AppTest.checkbox Returns(WidgetList of Checkbox) Sequence of all st.checkbox widgets. Individual widgets can be accessed from a WidgetList by index (order on the page) or key. For example, at.checkbox[0] for the first widget or at.checkbox(key=""my_key"") for a widget with a given key. AppTest.codeStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.code elements. Function signature[source] AppTest.code Returns(ElementList of Code) Sequence of all st.code elements. Individual elements can be accessed from an ElementList by index (order on the page). For example, at.code[0] for the first element. Code is an extension of the Element class. AppTest.color_pickerStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.color_picker widgets. Function signature[source] AppTest.color_picker Returns(WidgetList of ColorPicker) Sequence of all st.color_picker widgets. Individual widgets can be accessed from a WidgetList by index (order on the page) or key. For example, at.color_picker[0] for the first widget or at.color_picker(key=""my_key"") for a widget with a given key. AppTest.columnsStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all columns within st.columns elements. Each column within a single st.columns will be returned as a separate Column in the Sequence. Function signature[source] AppTest.columns Returns(Sequence of Column) Sequence of all columns within st.columns elements. Individual columns can be accessed from an ElementList by index (order on the page). For example, at.columns[0] for the first column. Column is an extension of the Block class. AppTest.dataframeStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.dataframe elements. Function signature[source] AppTest.dataframe Returns(ElementList of Dataframe) Sequence of all st.dataframe elements. Individual elements can be accessed from an ElementList by index (order on the page). For example, at.dataframe[0] for the first element. Dataframe is an extension of the Element class. AppTest.date_inputStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.date_input widgets. Function signature[source] AppTest.date_input Returns(WidgetList of DateInput) Sequence of all st.date_input widgets. Individual widgets can be accessed from a WidgetList by index (order on the page) or key. For example, at.date_input[0] for the first widget or at.date_input(key=""my_key"") for a widget with a given key. AppTest.dividerStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.divider elements. Function signature[source] AppTest.divider Returns(ElementList of Divider) Sequence of all st.divider elements. Individual elements can be accessed from an ElementList by index (order on the page). For example, at.divider[0] for the first element. Divider is an extension of the Element class. AppTest.errorStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.error elements. Function signature[source] AppTest.error Returns(ElementList of Error) Sequence of all st.error elements. Individual elements can be accessed from an ElementList by index (order on the page). For example, at.error[0] for the first element. Error is an extension of the Element class. AppTest.exceptionStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.exception elements. Function signature[source] AppTest.exception Returns(ElementList of Exception) Sequence of all st.exception elements. Individual elements can be accessed from an ElementList by index (order on the page). For example, at.exception[0] for the first element. Exception is an extension of the Element class. AppTest.expanderStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.expander elements. Function signature[source] AppTest.expander Returns(Sequence of Expandable) Sequence of all st.expander elements. Individual elements can be accessed from a Sequence by index (order on the page). For example, at.expander[0] for the first element. Expandable is an extension of the Block class. AppTest.headerStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.header elements. Function signature[source] AppTest.header Returns(ElementList of Header) Sequence of all st.header elements. Individual elements can be accessed from an ElementList by index (order on the page). For example, at.header[0] for the first element. Header is an extension of the Element class. AppTest.infoStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.info elements. Function signature[source] AppTest.info Returns(ElementList of Info) Sequence of all st.info elements. Individual elements can be accessed from an ElementList by index (order on the page). For example, at.info[0] for the first element. Info is an extension of the Element class. AppTest.jsonStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.json elements. Function signature[source] AppTest.json Returns(ElementList of Json) Sequence of all st.json elements. Individual elements can be accessed from an ElementList by index (order on the page). For example, at.json[0] for the first element. Json is an extension of the Element class. AppTest.latexStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.latex elements. Function signature[source] AppTest.latex Returns(ElementList of Latex) Sequence of all st.latex elements. Individual elements can be accessed from an ElementList by index (order on the page). For example, at.latex[0] for the first element. Latex is an extension of the Element class. AppTest.mainStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of elements within the main body of the app. Function signature[source] AppTest.main Returns(Block) A container of elements. Block can be queried for elements in the same manner as AppTest. For example, Block.checkbox will return all st.checkbox within the associated container. AppTest.markdownStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.markdown elements. Function signature[source] AppTest.markdown Returns(ElementList of Markdown) Sequence of all st.markdown elements. Individual elements can be accessed from an ElementList by index (order on the page). For example, at.markdown[0] for the first element. Markdown is an extension of the Element class. AppTest.metricStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.metric elements. Function signature[source] AppTest.metric Returns(ElementList of Metric) Sequence of all st.metric elements. Individual elements can be accessed from an ElementList by index (order on the page). For example, at.metric[0] for the first element. Metric is an extension of the Element class. AppTest.multiselectStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.multiselect widgets. Function signature[source] AppTest.multiselect Returns(WidgetList of Multiselect) Sequence of all st.multiselect widgets. Individual widgets can be accessed from a WidgetList by index (order on the page) or key. For example, at.multiselect[0] for the first widget or at.multiselect(key=""my_key"") for a widget with a given key. AppTest.number_inputStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.number_input widgets. Function signature[source] AppTest.number_input Returns(WidgetList of NumberInput) Sequence of all st.number_input widgets. Individual widgets can be accessed from a WidgetList by index (order on the page) or key. For example, at.number_input[0] for the first widget or at.number_input(key=""my_key"") for a widget with a given key. AppTest.radioStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.radio widgets. Function signature[source] AppTest.radio Returns(WidgetList of Radio) Sequence of all st.radio widgets. Individual widgets can be accessed from a WidgetList by index (order on the page) or key. For example, at.radio[0] for the first widget or at.radio(key=""my_key"") for a widget with a given key. AppTest.select_sliderStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.select_slider widgets. Function signature[source] AppTest.select_slider Returns(WidgetList of SelectSlider) Sequence of all st.select_slider widgets. Individual widgets can be accessed from a WidgetList by index (order on the page) or key. For example, at.select_slider[0] for the first widget or at.select_slider(key=""my_key"") for a widget with a given key. AppTest.selectboxStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.selectbox widgets. Function signature[source] AppTest.selectbox Returns(WidgetList of Selectbox) Sequence of all st.selectbox widgets. Individual widgets can be accessed from a WidgetList by index (order on the page) or key. For example, at.selectbox[0] for the first widget or at.selectbox(key=""my_key"") for a widget with a given key. AppTest.sidebarStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all elements within st.sidebar. Function signature[source] AppTest.sidebar Returns(Block) A container of elements. Block can be queried for elements in the same manner as AppTest. For example, Block.checkbox will return all st.checkbox within the associated container. AppTest.sliderStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.slider widgets. Function signature[source] AppTest.slider Returns(WidgetList of Slider) Sequence of all st.slider widgets. Individual widgets can be accessed from a WidgetList by index (order on the page) or key. For example, at.slider[0] for the first widget or at.slider(key=""my_key"") for a widget with a given key. AppTest.subheaderStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.subheader elements. Function signature[source] AppTest.subheader Returns(ElementList of Subheader) Sequence of all st.subheader elements. Individual elements can be accessed from an ElementList by index (order on the page). For example, at.subheader[0] for the first element. Subheader is an extension of the Element class. AppTest.successStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.success elements. Function signature[source] AppTest.success Returns(ElementList of Success) Sequence of all st.success elements. Individual elements can be accessed from an ElementList by index (order on the page). For example, at.success[0] for the first element. Success is an extension of the Element class. AppTest.statusStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.status elements. Function signature[source] AppTest.status Returns(Sequence of Status) Sequence of all st.status elements. Individual elements can be accessed from a Sequence by index (order on the page). For example, at.status[0] for the first element. Status is an extension of the Block class. AppTest.tableStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.table elements. Function signature[source] AppTest.table Returns(ElementList of Table) Sequence of all st.table elements. Individual elements can be accessed from an ElementList by index (order on the page). For example, at.table[0] for the first element. Table is an extension of the Element class. AppTest.tabsStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all tabs within st.tabs elements. Each tab within a single st.tabs will be returned as a separate Tab in the Sequence. Additionally, the tab labels are forwarded to each Tab element as a property. For example, st.tabs(""A"",""B"") will yield two Tab objects, with Tab.label returning ""A"" and ""B"", respectively. Function signature[source] AppTest.tabs Returns(Sequence of Tab) Sequence of all tabs within st.tabs elements. Individual tabs can be accessed from an ElementList by index (order on the page). For example, at.tabs[0] for the first tab. Tab is an extension of the Block class. AppTest.textStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.text elements. Function signature[source] AppTest.text Returns(ElementList of Text) Sequence of all st.text elements. Individual elements can be accessed from an ElementList by index (order on the page). For example, at.text[0] for the first element. Text is an extension of the Element class. AppTest.text_areaStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.text_area widgets. Function signature[source] AppTest.text_area Returns(WidgetList of TextArea) Sequence of all st.text_area widgets. Individual widgets can be accessed from a WidgetList by index (order on the page) or key. For example, at.text_area[0] for the first widget or at.text_area(key=""my_key"") for a widget with a given key. AppTest.text_inputStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.text_input widgets. Function signature[source] AppTest.text_input Returns(WidgetList of TextInput) Sequence of all st.text_input widgets. Individual widgets can be accessed from a WidgetList by index (order on the page) or key. For example, at.text_input[0] for the first widget or at.text_input(key=""my_key"") for a widget with a given key. AppTest.time_inputStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.time_input widgets. Function signature[source] AppTest.time_input Returns(WidgetList of TimeInput) Sequence of all st.time_input widgets. Individual widgets can be accessed from a WidgetList by index (order on the page) or key. For example, at.time_input[0] for the first widget or at.time_input(key=""my_key"") for a widget with a given key. AppTest.titleStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.title elements. Function signature[source] AppTest.title Returns(ElementList of Title) Sequence of all st.title elements. Individual elements can be accessed from an ElementList by index (order on the page). For example, at.title[0] for the first element. Title is an extension of the Element class. AppTest.toastStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.toast elements. Function signature[source] AppTest.toast Returns(ElementList of Toast) Sequence of all st.toast elements. Individual elements can be accessed from an ElementList by index (order on the page). For example, at.toast[0] for the first element. Toast is an extension of the Element class. AppTest.toggleStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.toggle widgets. Function signature[source] AppTest.toggle Returns(WidgetList of Toggle) Sequence of all st.toggle widgets. Individual widgets can be accessed from a WidgetList by index (order on the page) or key. For example, at.toggle[0] for the first widget or at.toggle(key=""my_key"") for a widget with a given key. AppTest.warningStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.warning elements. Function signature[source] AppTest.warning Returns(ElementList of Warning) Sequence of all st.warning elements. Individual elements can be accessed from an ElementList by index (order on the page). For example, at.warning[0] for the first element. Warning is an extension of the Element class. Previous: App testingNext: Testing element classesforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy" https://docs.streamlit.io/develop/concepts/design/custom-classes#example-what-happens-when-you-define-the-same-class-twice,"DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsremoveCOREArchitecture & executionaddMultipage appsaddApp designremoveAnimate & update elementsButton behavior and examplesDataframesUsing custom classesWorking with timezonesADDITIONALConnections and secretsaddCustom componentsaddConfiguration and themingaddApp testingaddAPI referenceaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Develop/Concepts/App design/Using custom classesUsing custom Python classes in your Streamlit app If you are building a complex Streamlit app or working with existing code, you may have custom Python classes defined in your script. Common examples include the following: Defining a @dataclass to store related data within your app. Defining an Enum class to represent a fixed set of options or values. Defining custom interfaces to external services or databases not covered by st.connection. Because Streamlit reruns your script after every user interaction, custom classes may be redefined multiple times within the same Streamlit session. This may result in unwanted effects, especially with class and instance comparisons. Read on to understand this common pitfall and how to avoid it. We begin by covering some general-purpose patterns you can use for different types of custom classes, and follow with a few more technical details explaining why this matters. Finally, we go into more detail about Using Enum classes specifically, and describe a configuration option which can make them more convenient. Patterns to define your custom classes Pattern 1: Define your class in a separate module This is the recommended, general solution. If possible, move class definitions into their own module file and import them into your app script. As long as you are not editing the file where your class is defined, Streamlit will not re-import it with each rerun. Therefore, if a class is defined in an external file and imported into your script, the class will not be redefined during the session. Example: Move your class definition Try running the following Streamlit app where MyClass is defined within the page's script. isinstance() will return True on the first script run then return False on each rerun thereafter. # app.py import streamlit as st # MyClass gets redefined every time app.py reruns class MyClass: def __init__(self, var1, var2): self.var1 = var1 self.var2 = var2 if ""my_instance"" not in st.session_state: st.session_state.my_instance = MyClass(""foo"", ""bar"") # Displays True on the first run then False on every rerun st.write(isinstance(st.session_state.my_instance, MyClass)) st.button(""Rerun"") If you move the class definition out of app.py into another file, you can make isinstance() consistently return True. Consider the following file structure: myproject/ ├── my_class.py └── app.py # my_class.py class MyClass: def __init__(self, var1, var2): self.var1 = var1 self.var2 = var2 # app.py import streamlit as st from my_class import MyClass # MyClass doesn't get redefined with each rerun if ""my_instance"" not in st.session_state: st.session_state.my_instance = MyClass(""foo"", ""bar"") # Displays True on every rerun st.write(isinstance(st.session_state.my_instance, MyClass)) st.button(""Rerun"") Streamlit only reloads code in imported modules when it detects the code has changed. Thus, if you are actively editing the file where your class is defined, you may need to stop and restart your Streamlit server to avoid an undesirable class redefinition mid-session. Pattern 2: Force your class to compare internal values For classes that store data (like dataclasses), you may be more interested in comparing the internally stored values rather than the class itself. If you define a custom __eq__ method, you can force comparisons to be made on the internally stored values. Example: Define __eq__ Try running the following Streamlit app and observe how the comparison is True on the first run then False on every rerun thereafter. import streamlit as st from dataclasses import dataclass @dataclass class MyDataclass: var1: int var2: float if ""my_dataclass"" not in st.session_state: st.session_state.my_dataclass = MyDataclass(1, 5.5) # Displays True on the first run the False on every rerun st.session_state.my_dataclass == MyDataclass(1, 5.5) st.button(""Rerun"") Since MyDataclass gets redefined with each rerun, the instance stored in Session State will not be equal to any instance defined in a later script run. You can fix this by forcing a comparison of internal values as follows: import streamlit as st from dataclasses import dataclass @dataclass class MyDataclass: var1: int var2: float def __eq__(self, other): # An instance of MyDataclass is equal to another object if the object # contains the same fields with the same values return (self.var1, self.var2) == (other.var1, other.var2) if ""my_dataclass"" not in st.session_state: st.session_state.my_dataclass = MyDataclass(1, 5.5) # Displays True on every rerun st.session_state.my_dataclass == MyDataclass(1, 5.5) st.button(""Rerun"") The default Python __eq__ implementation for a regular class or @dataclass depends on the in-memory ID of the class or class instance. To avoid problems in Streamlit, your custom __eq__ method should not depend the type() of self and other. Pattern 3: Store your class as serialized data Another option for classes that store data is to define serialization and deserialization methods like to_str and from_str for your class. You can use these to store class instance data in st.session_state rather than storing the class instance itself. Similar to pattern 2, this is a way to force comparison of the internal data and bypass the changing in-memory IDs. Example: Save your class instance as a string Using the same example from pattern 2, this can be done as follows: import streamlit as st from dataclasses import dataclass @dataclass class MyDataclass: var1: int var2: float def to_str(self): return f""{self.var1},{self.var2}"" @classmethod def from_str(cls, serial_str): values = serial_str.split("","") var1 = int(values[0]) var2 = float(values[1]) return cls(var1, var2) if ""my_dataclass"" not in st.session_state: st.session_state.my_dataclass = MyDataclass(1, 5.5).to_str() # Displays True on every rerun MyDataclass.from_str(st.session_state.my_dataclass) == MyDataclass(1, 5.5) st.button(""Rerun"") Pattern 4: Use caching to preserve your class For classes that are used as resources (database connections, state managers, APIs), consider using the cached singleton pattern. Use @st.cache_resource to decorate a @staticmethod of your class to generate a single, cached instance of the class. For example: import streamlit as st class MyResource: def __init__(self, api_url: str): self._url = api_url @st.cache_resource(ttl=300) @staticmethod def get_resource_manager(api_url: str): return MyResource(api_url) # This is cached until Session State is cleared or 5 minutes has elapsed. resource_manager = MyResource.get_resource_manager(""http://example.com/api/"") When you use one of Streamlit's caching decorators on a function, Streamlit doesn't use the function object to look up cached values. Instead, Streamlit's caching decorators index return values using the function's qualified name and module. So, even though Streamlit redefines MyResource with each script run, st.cache_resource is unaffected by this. get_resource_manager() will return its cached value with each rerun, until the value expires. Understanding how Python defines and compares classes So what's really happening here? We'll consider a simple example to illustrate why this is a pitfall. Feel free to skip this section if you don't want to deal more details. You can jump ahead to learn about Using Enum classes. Example: What happens when you define the same class twice? Set aside Streamlit for a moment and think about this simple Python script: from dataclasses import dataclass @dataclass class Student: student_id: int name: str Marshall_A = Student(1, ""Marshall"") Marshall_B = Student(1, ""Marshall"") # This is True (because a dataclass will compare two of its instances by value) Marshall_A == Marshall_B # Redefine the class @dataclass class Student: student_id: int name: str Marshall_C = Student(1, ""Marshall"") # This is False Marshall_A == Marshall_C In this example, the dataclass Student is defined twice. All three Marshalls have the same internal values. If you compare Marshall_A and Marshall_B they will be equal because they were both created from the first definition of Student. However, if you compare Marshall_A and Marshall_C they will not be equal because Marshall_C was created from the second definition of Student. Even though both Student dataclasses are defined exactly the same, they have differnt in-memory IDs and are therefore different. What's happening in Streamlit? In Streamlit, you probably don't have the same class written twice in your page script. However, the rerun logic of Streamlit creates the same effect. Let's use the above example for an analogy. If you define a class in one script run and save an instance in Session State, then a later rerun will redefine the class and you may end up comparing a Mashall_C in your rerun to a Marshall_A in Session State. Since widgets rely on Session State under the hood, this is where things can get confusing. How Streamlit widgets store options Several Streamlit UI elements, such as st.selectbox or st.radio, accept multiple-choice options via an options argument. The user of your application can typically select one or more of these options. The selected value is returned by the widget function. For example: number = st.selectbox(""Pick a number, any number"", options=[1, 2, 3]) # number == whatever value the user has selected from the UI. When you call a function like st.selectbox and pass an Iterable to options, the Iterable and current selection are saved into a hidden portion of Session State called the Widget Metadata. When the user of your application interacts with the st.selectbox widget, the broswer sends the index of their selection to your Streamlit server. This index is used to determine which values from the original options list, saved in the Widget Metadata from the previous page execution, are returned to your application. The key detail is that the value returned by st.selectbox (or similar widget function) is from an Iterable saved in Session State during a previous execution of the page, NOT the values passed to options on the current execution. There are a number of architectural reasons why Streamlit is designed this way, which we won't go into here. However, this is how we end up comparing instances of different classes when we think we are comparing instances of the same class. A pathological example The above explanation might be a bit confusing, so here's a pathological example to illustrate the idea. import streamlit as st from dataclasses import dataclass @dataclass class Student: student_id: int name: str Marshall_A = Student(1, ""Marshall"") if ""B"" not in st.session_state: st.session_state.B = Student(1, ""Marshall"") Marshall_B = st.session_state.B options = [Marshall_A,Marshall_B] selected = st.selectbox(""Pick"", options) # This comparison does not return expected results: selected == Marshall_A # This comparison evaluates as expected: selected == Marshall_B As a final note, we used @dataclass in the example for this section to illustrate a point, but in fact it is possible to encounter these same problems with classes, in general. Any class which checks class identity inside of a comparison operator—such as __eq__ or __gt__—can exhibit these issues. Using Enum classes in Streamlit The Enum class from the Python standard library is a powerful way to define custom symbolic names that can be used as options for st.multiselect or st.selectbox in place of str values. For example, you might add the following to your streamlit page: from enum import Enum import streamlit as st # class syntax class Color(Enum): RED = 1 GREEN = 2 BLUE = 3 selected_colors = set(st.multiselect(""Pick colors"", options=Color)) if selected_colors == {Color.RED, Color.GREEN}: st.write(""Hooray, you found the color YELLOW!"") If you're using the latest version of Streamlit, this Streamlit page will work as it appears it should. When a user picks both Color.RED and Color.GREEN, they are shown the special message. However, if you've read the rest of this page you might notice something tricky going on. Specifically, the Enum class Color gets redefined every time this script is run. In Python, if you define two Enum classes with the same class name, members, and values, the classes and their members are still considered unique from each other. This should cause the above if condition to always evaluate to False. In any script rerun, the Color values returned by st.multiselect would be of a different class than the Color defined in that script run. If you run the snippet above with Streamlit version 1.28.0 or less, you will not be able see the special message. Thankfully, as of version 1.29.0, Streamlit introduced a configuration option to greatly simplify the problem. That's where the enabled-by-default enumCoercion configuration option comes in. Understanding the enumCoercion configuration option When enumCoercion is enabled, Streamlit tries to recognize when you are using an element like st.multiselect or st.selectbox with a set of Enum members as options. If Streamlit detects this, it will convert the widget's returned values to members of the Enum class defined in the latest script run. This is something we call automatic Enum coercion. This behavior is configurable via the enumCoercion setting in your Streamlit config.toml file. It is enabled by default, and may be disabled or set to a stricter set of matching criteria. If you find that you still encounter issues with enumCoercion enabled, consider using the custom class patterns described above, such as moving your Enum class definition to a separate module file.Previous: DataframesNext: Working with timezonesforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy" https://docs.streamlit.io/develop/api-reference/caching-and-state/st.experimental_singleton#widget-replay-disabled,"DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceremovePAGE ELEMENTSWrite and magicaddText elementsaddData elementsaddChart elementsaddInput widgetsaddMedia elementsaddLayouts and containersaddChat elementsaddStatus elementsaddThird-party componentsopen_in_newAPPLICATION LOGICNavigation and pagesaddExecution flowaddCaching and stateremovest.cache_datast.cache_resourcest.cachedeletest.session_statest.query_paramsst.experimental_get_query_paramsdeletest.experimental_set_query_paramsdeleteConnections and secretsaddCustom componentsaddUtilitiesaddConfigurationaddTOOLSApp testingaddCommand lineaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Develop/API reference/Caching and state/st.experimental_singletonpriority_highImportantThis is an experimental feature. Experimental features and their APIs may change or be removed at any time. To learn more, click here. st.experimental_singletonStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakedeleteDeprecation noticest.experimental_singleton was deprecated in version 1.18.0. Use st.cache_resource instead. Learn more in Caching.Decorator to cache functions that return global resources (e.g. database connections, ML models). Cached objects are shared across all users, sessions, and reruns. They must be thread-safe because they can be accessed from multiple threads concurrently. If thread safety is an issue, consider using st.session_state to store resources per session instead. You can clear a function's cache with func.clear() or clear the entire cache with st.cache_resource.clear(). To cache data, use st.cache_data instead. Learn more about caching at https://docs.streamlit.io/library/advanced-features/caching. Function signature[source] st.experimental_singleton(func, *, ttl, max_entries, show_spinner, validate, experimental_allow_widgets, hash_funcs=None) Parameters func (callable) The function that creates the cached resource. Streamlit hashes the function's source code. ttl (float, timedelta, str, or None) The maximum time to keep an entry in the cache. Can be one of: None if cache entries should never expire (default). A number specifying the time in seconds. A string specifying the time in a format supported by Pandas's Timedelta constructor, e.g. ""1d"", ""1.5 days"", or ""1h23s"". A timedelta object from Python's built-in datetime library, e.g. timedelta(days=1). max_entries (int or None) The maximum number of entries to keep in the cache, or None for an unbounded cache. When a new entry is added to a full cache, the oldest cached entry will be removed. Defaults to None. show_spinner (bool or str) Enable the spinner. Default is True to show a spinner when there is a ""cache miss"" and the cached resource is being created. If string, value of show_spinner param will be used for spinner text. validate (callable or None) An optional validation function for cached data. validate is called each time the cached value is accessed. It receives the cached value as its only parameter and it must return a boolean. If validate returns False, the current cached value is discarded, and the decorated function is called to compute a new value. This is useful e.g. to check the health of database connections. experimental_allow_widgets (bool) Allow widgets to be used in the cached function. Defaults to False. Support for widgets in cached functions is currently experimental. Setting this parameter to True may lead to excessive memory use since the widget value is treated as an additional input parameter to the cache. We may remove support for this option at any time without notice. hash_funcs (dict or None) Mapping of types or fully qualified names to hash functions. This is used to override the behavior of the hasher inside Streamlit's caching mechanism: when the hasher encounters an object, it will first check to see if its type matches a key in this dict and, if so, will use the provided function to generate a hash for it. See below for an example of how this can be used. Example import streamlit as st @st.cache_resource def get_database_session(url): # Create a database session object that points to the URL. return session s1 = get_database_session(SESSION_URL_1) # Actually executes the function, since this is the first time it was # encountered. s2 = get_database_session(SESSION_URL_1) # Does not execute the function. Instead, returns its previously computed # value. This means that now the connection object in s1 is the same as in s2. s3 = get_database_session(SESSION_URL_2) # This is a different URL, so the function executes. By default, all parameters to a cache_resource function must be hashable. Any parameter whose name begins with _ will not be hashed. You can use this as an ""escape hatch"" for parameters that are not hashable: import streamlit as st @st.cache_resource def get_database_session(_sessionmaker, url): # Create a database connection object that points to the URL. return connection s1 = get_database_session(create_sessionmaker(), DATA_URL_1) # Actually executes the function, since this is the first time it was # encountered. s2 = get_database_session(create_sessionmaker(), DATA_URL_1) # Does not execute the function. Instead, returns its previously computed # value - even though the _sessionmaker parameter was different # in both calls. A cache_resource function's cache can be procedurally cleared: import streamlit as st @st.cache_resource def get_database_session(_sessionmaker, url): # Create a database connection object that points to the URL. return connection fetch_and_clean_data.clear(_sessionmaker, ""https://streamlit.io/"") # Clear the cached entry for the arguments provided. get_database_session.clear() # Clear all cached entries for this function. To override the default hashing behavior, pass a custom hash function. You can do that by mapping a type (e.g. Person) to a hash function (str) like this: import streamlit as st from pydantic import BaseModel class Person(BaseModel): name: str @st.cache_resource(hash_funcs={Person: str}) def get_person_name(person: Person): return person.name Alternatively, you can map the type's fully-qualified name (e.g. ""__main__.Person"") to the hash function instead: import streamlit as st from pydantic import BaseModel class Person(BaseModel): name: str @st.cache_resource(hash_funcs={""__main__.Person"": str}) def get_person_name(person: Person): return person.name st.experimental_singleton.clearStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakedeleteDeprecation noticest.experimental_singleton.clear was deprecated in version 1.18.0. Use st.cache_resource.clear instead. Learn more in Caching.Clear all cache_resource caches. Function signature[source] st.experimental_singleton.clear() Example In the example below, pressing the ""Clear All"" button will clear all singleton caches. i.e. Clears cached singleton objects from all functions decorated with @st.experimental_singleton. import streamlit as st from transformers import BertModel @st.experimental_singleton def get_database_session(url): # Create a database session object that points to the URL. return session @st.experimental_singleton def get_model(model_type): # Create a model of the specified type. return BertModel.from_pretrained(model_type) if st.button(""Clear All""): # Clears all singleton caches: st.experimental_singleton.clear() Validating the cache The @st.experimental_singleton decorator is used to cache the output of a function, so that it only needs to be executed once. This can improve performance in certain situations, such as when a function takes a long time to execute or makes a network request. However, in some cases, the cached output may become invalid over time, such as when a database connection times out. To handle this, the @st.experimental_singleton decorator supports an optional validate parameter, which accepts a validation function that is called each time the cached output is accessed. If the validation function returns False, the cached output is discarded and the decorated function is executed again. Best Practices Use the validate parameter when the cached output may become invalid over time, such as when a database connection or an API key expires. Use the validate parameter judiciously, as it will add an additional overhead of calling the validation function each time the cached output is accessed. Make sure that the validation function is as fast as possible, as it will be called each time the cached output is accessed. Consider to validate cached data periodically, instead of each time it is accessed, to mitigate the performance impact. Handle errors that may occur during validation and provide a fallback mechanism if the validation fails. Replay static st elements in cache-decorated functions Functions decorated with @st.experimental_singleton can contain static st elements. When a cache-decorated function is executed, we record the element and block messages produced, so the elements will appear in the app even when execution of the function is skipped because the result was cached. In the example below, the @st.experimental_singleton decorator is used to cache the execution of the get_model function, that returns a 🤗 Hugging Face Transformers model. Notice the cached function also contains a st.bar_chart command, which will be replayed when the function is skipped because the result was cached. import numpy as np import pandas as pd import streamlit as st from transformers import AutoModel @st.experimental_singleton def get_model(model_type): # Contains a static element st.bar_chart st.bar_chart( np.random.rand(10, 1) ) # This will be recorded and displayed even when the function is skipped # Create a model of the specified type return AutoModel.from_pretrained(model_type) bert_model = get_model(""distilbert-base-uncased"") st.help(bert_model) # Display the model's docstring Supported static st elements in cache-decorated functions include: st.alert st.altair_chart st.area_chart st.audio st.bar_chart st.ballons st.bokeh_chart st.caption st.code st.components.v1.html st.components.v1.iframe st.container st.dataframe st.echo st.empty st.error st.exception st.expander st.experimental_get_query_params st.experimental_set_query_params st.form st.form_submit_button st.graphviz_chart st.help st.image st.info st.json st.latex st.line_chart st.markdown st.metric st.plotly_chart st.progress st.pydeck_chart st.snow st.spinner st.success st.table st.text st.vega_lite_chart st.video st.warning Replay input widgets in cache-decorated functions In addition to static elements, functions decorated with @st.experimental_singleton can also contain input widgets! Replaying input widgets is disabled by default. To enable it, you can set the experimental_allow_widgets parameter for @st.experimental_singleton to True. The example below enables widget replaying, and shows the use of a checkbox widget within a cache-decorated function. import streamlit as st # Enable widget replay @st.experimental_singleton(experimental_allow_widgets=True) def func(): # Contains an input widget st.checkbox(""Works!"") func() If the cache decorated function contains input widgets, but experimental_allow_widgets is set to False or unset, Streamlit will throw a CachedStFunctionWarning, like the one below: import streamlit as st # Widget replay is disabled by default @st.experimental_singleton def func(): # Streamlit will throw a CachedStFunctionWarning st.checkbox(""Doesn't work"") func() How widget replay works Let's demystify how widget replay in cache-decorated functions works and gain a conceptual understanding. Widget values are treated as additional inputs to the function, and are used to determine whether the function should be executed or not. Consider the following example: import streamlit as st @st.experimental_singleton(experimental_allow_widgets=True) def plus_one(x): y = x + 1 if st.checkbox(""Nuke the value 💥""): st.write(""Value was nuked, returning 0"") y = 0 return y st.write(plus_one(2)) The plus_one function takes an integer x as input, and returns x + 1. The function also contains a checkbox widget, which is used to ""nuke"" the value of x. i.e. the return value of plus_one depends on the state of the checkbox: if it is checked, the function returns 0, otherwise it returns 3. In order to know which value the cache should return (in case of a cache hit), Streamlit treats the checkbox state (checked / unchecked) as an additional input to the function plus_one (just like x). If the user checks the checkbox (thereby changing its state), we look up the cache for the same value of x (2) and the same checkbox state (checked). If the cache contains a value for this combination of inputs, we return it. Otherwise, we execute the function and store the result in the cache. Let's now understand how enabling and disabling widget replay changes the behavior of the function. Widget replay disabled Widgets in cached functions throw a CachedStFunctionWarning and are ignored. Other static elements in cached functions replay as expected. Widget replay enabled Widgets in cached functions don't lead to a warning, and are replayed as expected. Interacting with a widget in a cached function will cause the function to be executed again, and the cache to be updated. Widgets in cached functions retain their state across reruns. Each unique combination of widget values is treated as a separate input to the function, and is used to determine whether the function should be executed or not. i.e. Each unique combination of widget values has its own cache entry; the cached function runs the first time and the saved value is used afterwards. Calling a cached function multiple times in one script run with the same arguments triggers a DuplicateWidgetID error. If the arguments to a cached function change, widgets from that function that render again retain their state. Changing the source code of a cached function invalidates the cache. Both st.experimental_singleton and st.experimental_memo support widget replay. Fundamentally, the behavior of a function with (supported) widgets in it doesn't change when it is decorated with @st.experimental_singleton or @st.experimental_memo. The only difference is that the function is only executed when we detect a cache ""miss"". Supported widgets All input widgets are supported in cache-decorated functions. The following is an exhaustive list of supported widgets: st.button st.camera_input st.checkbox st.color_picker st.date_input st.download_button st.file_uploader st.multiselect st.number_input st.radio st.selectbox st.select_slider st.slider st.text_area st.text_input st.time_input Previous: st.experimental_memoNext: st.session_stateforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy" https://docs.streamlit.io/develop/quick-reference/cheat-sheet#placeholders-help-and-options,"DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceaddTutorialsaddQuick referenceremoveCheat sheetRelease notesPre-release featuresRoadmapopen_in_newweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Develop/Quick reference/Cheat sheetStreamlit API cheat sheet This is a summary of the docs, as of Streamlit v1.34.0. Install & Importpip install streamlit streamlit run first_app.py # Import convention >>> import streamlit as st Pre-release featurespip uninstall streamlit pip install streamlit-nightly --upgrade Learn more about experimental featuresCommand linestreamlit --help streamlit run your_script.py streamlit hello streamlit config show streamlit cache clear streamlit docs streamlit --version Magic commands# Magic commands implicitly # call st.write(). ""_This_ is some **Markdown***"" my_variable ""dataframe:"", my_data_frame Display textst.write(""Most objects"") # df, err, func, keras! st.write([""st"", ""is <"", 3]) # see * st.write_stream(my_generator) st.write_stream(my_llm_stream) st.text(""Fixed width text"") st.markdown(""_Markdown_"") # see * st.latex(r"""""" e^{i\pi} + 1 = 0 """""") st.title(""My title"") st.header(""My header"") st.subheader(""My sub"") st.code(""for i in range(8): foo()"") * optional kwarg unsafe_allow_html = True Display datast.dataframe(my_dataframe) st.table(data.iloc[0:10]) st.json({""foo"":""bar"",""fu"":""ba""}) st.metric(""My metric"", 42, 2) Display mediast.image(""./header.png"") st.audio(data) st.video(data) st.video(data, subtitles=""./subs.vtt"") Display chartsst.area_chart(df) st.bar_chart(df) st.line_chart(df) st.map(df) st.scatter_chart(df) st.altair_chart(chart) st.bokeh_chart(fig) st.graphviz_chart(fig) st.plotly_chart(fig) st.pydeck_chart(chart) st.pyplot(fig) st.vega_lite_chart(df) Add widgets to sidebar# Just add it after st.sidebar: >>> a = st.sidebar.radio(""Select one:"", [1, 2]) # Or use ""with"" notation: >>> with st.sidebar: >>> st.radio(""Select one:"", [1, 2]) Columns# Two equal columns: >>> col1, col2 = st.columns(2) >>> col1.write(""This is column 1"") >>> col2.write(""This is column 2"") # Three different columns: >>> col1, col2, col3 = st.columns([3, 1, 1]) # col1 is larger. # You can also use ""with"" notation: >>> with col1: >>> st.radio(""Select one:"", [1, 2]) Tabs# Insert containers separated into tabs: >>> tab1, tab2 = st.tabs([""Tab 1"", ""Tab2""]) >>> tab1.write(""this is tab 1"") >>> tab2.write(""this is tab 2"") # You can also use ""with"" notation: >>> with tab1: >>> st.radio(""Select one:"", [1, 2]) Expandable containers>>> expand = st.expander(""My label"") >>> expand.write(""Inside the expander."") >>> pop = st.popover(""Button label"") >>> pop.checkbox(""Show all"") # You can also use ""with"" notation: >>> with expand: >>> st.radio(""Select one:"", [1, 2]) Control flow# Stop execution immediately: st.stop() # Rerun script immediately: st.rerun() # Navigate to another page: st.switch_page(""pages/my_page.py"") # Group multiple widgets: >>> with st.form(key=""my_form""): >>> username = st.text_input(""Username"") >>> password = st.text_input(""Password"") >>> st.form_submit_button(""Login"") # Define a dialog function >>> @st.experimental_dialog(""Welcome!"") >>> def modal_dialog(): >>> st.write(""Hello"") >>> >>> modal_dialog() # Define a fragment >>> @st.experimental_fragment >>> def fragment_function(): >>> df = get_data() >>> st.line_chart(df) >>> st.button(""Update"") >>> >>> fragment_function() Display interactive widgetsst.button(""Click me"") st.download_button(""Download file"", data) st.link_button(""Go to gallery"", url) st.page_link(""app.py"", label=""Home"") st.data_editor(""Edit data"", data) st.checkbox(""I agree"") st.toggle(""Enable"") st.radio(""Pick one"", [""cats"", ""dogs""]) st.selectbox(""Pick one"", [""cats"", ""dogs""]) st.multiselect(""Buy"", [""milk"", ""apples"", ""potatoes""]) st.slider(""Pick a number"", 0, 100) st.select_slider(""Pick a size"", [""S"", ""M"", ""L""]) st.text_input(""First name"") st.number_input(""Pick a number"", 0, 10) st.text_area(""Text to translate"") st.date_input(""Your birthday"") st.time_input(""Meeting time"") st.file_uploader(""Upload a CSV"") st.camera_input(""Take a picture"") st.color_picker(""Pick a color"") # Use widgets' returned values in variables: >>> for i in range(int(st.number_input(""Num:""))): >>> foo() >>> if st.sidebar.selectbox(""I:"",[""f""]) == ""f"": >>> b() >>> my_slider_val = st.slider(""Quinn Mallory"", 1, 88) >>> st.write(slider_val) # Disable widgets to remove interactivity: >>> st.slider(""Pick a number"", 0, 100, disabled=True) Build chat-based apps# Insert a chat message container. >>> with st.chat_message(""user""): >>> st.write(""Hello 👋"") >>> st.line_chart(np.random.randn(30, 3)) # Display a chat input widget at the bottom of the app. >>> st.chat_input(""Say something"") # Display a chat input widget inline. >>> with st.container(): >>> st.chat_input(""Say something"") Learn how to Build a basic LLM chat appMutate data# Add rows to a dataframe after # showing it. >>> element = st.dataframe(df1) >>> element.add_rows(df2) # Add rows to a chart after # showing it. >>> element = st.line_chart(df1) >>> element.add_rows(df2) Display code>>> with st.echo(): >>> st.write(""Code will be executed and printed"") Placeholders, help, and options# Replace any single element. >>> element = st.empty() >>> element.line_chart(...) >>> element.text_input(...) # Replaces previous. # Insert out of order. >>> elements = st.container() >>> elements.line_chart(...) >>> st.write(""Hello"") >>> elements.text_input(...) # Appears above ""Hello"". st.help(pandas.DataFrame) st.get_option(key) st.set_option(key, value) st.set_page_config(layout=""wide"") st.query_params[key] st.query_params.from_dict(params_dict) st.query_params.get_all(key) st.query_params.clear() st.html(""

Hi!

"") Connect to data sourcesst.connection(""pets_db"", type=""sql"") conn = st.connection(""sql"") conn = st.connection(""snowflake"") >>> class MyConnection(BaseConnection[myconn.MyConnection]): >>> def _connect(self, **kwargs) -> MyConnection: >>> return myconn.connect(**self._secrets, **kwargs) >>> def query(self, query): >>> return self._instance.query(query) Optimize performanceCache data objects# E.g. Dataframe computation, storing downloaded data, etc. >>> @st.cache_data ... def foo(bar): ... # Do something expensive and return data ... return data # Executes foo >>> d1 = foo(ref1) # Does not execute foo # Returns cached item by value, d1 == d2 >>> d2 = foo(ref1) # Different arg, so function foo executes >>> d3 = foo(ref2) # Clear the cached value for foo(ref1) >>> foo.clear(ref1) # Clear all cached entries for this function >>> foo.clear() # Clear values from *all* in-memory or on-disk cached functions >>> st.cache_data.clear() Cache global resources# E.g. TensorFlow session, database connection, etc. >>> @st.cache_resource ... def foo(bar): ... # Create and return a non-data object ... return session # Executes foo >>> s1 = foo(ref1) # Does not execute foo # Returns cached item by reference, s1 == s2 >>> s2 = foo(ref1) # Different arg, so function foo executes >>> s3 = foo(ref2) # Clear the cached value for foo(ref1) >>> foo.clear(ref1) # Clear all cached entries for this function >>> foo.clear() # Clear all global resources from cache >>> st.cache_resource.clear() Deprecated caching>>> @st.cache ... def foo(bar): ... # Do something expensive in here... ... return data >>> # Executes foo >>> d1 = foo(ref1) >>> # Does not execute foo >>> # Returns cached item by reference, d1 == d2 >>> d2 = foo(ref1) >>> # Different arg, so function foo executes >>> d3 = foo(ref2) Display progress and status# Show a spinner during a process >>> with st.spinner(text=""In progress""): >>> time.sleep(3) >>> st.success(""Done"") # Show and update progress bar >>> bar = st.progress(50) >>> time.sleep(3) >>> bar.progress(100) >>> with st.status(""Authenticating..."") as s: >>> time.sleep(2) >>> st.write(""Some long response."") >>> 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 address. >>> if st.user.email == ""jane@email.com"": >>> display_jane_content() >>> elif st.user.email == ""adam@foocorp.io"": >>> display_adam_content() >>> else: >>> st.write(""Please contact us to get access!"") Previous: Quick referenceNext: Release notesforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy" https://docs.streamlit.io/get-started/tutorials/create-an-app#draw-a-histogram,"DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsremoveCreate an appCreate a multipage appcodeDevelopConceptsaddAPI referenceaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Get started/First steps/Create an appCreate an app If you've made it this far, chances are you've installed Streamlit and run through the basics in Basic concepts and Advanced concepts. If not, now is a good time to take a look. The easiest way to learn how to use Streamlit is to try things out yourself. As you read through this guide, test each method. As long as your app is running, every time you add a new element to your script and save, Streamlit's UI will ask if you'd like to rerun the app and view the changes. This allows you to work in a fast interactive loop: you write some code, save it, review the output, write some more, and so on, until you're happy with the results. The goal is to use Streamlit to create an interactive app for your data or model and along the way to use Streamlit to review, debug, perfect, and share your code. In this guide, you're going to use Streamlit's core features to create an interactive app; exploring a public Uber dataset for pickups and drop-offs in New York City. When you're finished, you'll know how to fetch and cache data, draw charts, plot information on a map, and use interactive widgets, like a slider, to filter results. starTipIf you'd like to skip ahead and see everything at once, the complete script is available below. Create your first app Streamlit is more than just a way to make data apps, it’s also a community of creators that share their apps and ideas and help each other make their work better. Please come join us on the community forum. We love to hear your questions, ideas, and help you work through your bugs — stop by today! The first step is to create a new Python script. Let's call it uber_pickups.py. Open uber_pickups.py in your favorite IDE or text editor, then add these lines: import streamlit as st import pandas as pd import numpy as np Every good app has a title, so let's add one: st.title('Uber pickups in NYC') Now it's time to run Streamlit from the command line: streamlit run uber_pickups.py Running a Streamlit app is no different than any other Python script. Whenever you need to view the app, you can use this command. starTipDid you know you can also pass a URL to streamlit run? This is great when combined with GitHub Gists. For example:streamlit run https://raw.githubusercontent.com/streamlit/demo-uber-nyc-pickups/master/streamlit_app.py As usual, the app should automatically open in a new tab in your browser. Fetch some data Now that you have an app, the next thing you'll need to do is fetch the Uber dataset for pickups and drop-offs in New York City. Let's start by writing a function to load the data. Add this code to your script: DATE_COLUMN = 'date/time' DATA_URL = ('https://s3-us-west-2.amazonaws.com/' 'streamlit-demo-data/uber-raw-data-sep14.csv.gz') def load_data(nrows): data = pd.read_csv(DATA_URL, nrows=nrows) lowercase = lambda x: str(x).lower() data.rename(lowercase, axis='columns', inplace=True) data[DATE_COLUMN] = pd.to_datetime(data[DATE_COLUMN]) return data You'll notice that load_data is a plain old function that downloads some data, puts it in a Pandas dataframe, and converts the date column from text to datetime. The function accepts a single parameter (nrows), which specifies the number of rows that you want to load into the dataframe. Now let's test the function and review the output. Below your function, add these lines: # Create a text element and let the reader know the data is loading. data_load_state = st.text('Loading data...') # Load 10,000 rows of data into the dataframe. data = load_data(10000) # Notify the reader that the data was successfully loaded. data_load_state.text('Loading data...done!') You'll see a few buttons in the upper-right corner of your app asking if you'd like to rerun the app. Choose Always rerun, and you'll see your changes automatically each time you save. Ok, that's underwhelming... It turns out that it takes a long time to download data, and load 10,000 lines into a dataframe. Converting the date column into datetime isn’t a quick job either. You don’t want to reload the data each time the app is updated – luckily Streamlit allows you to cache the data. Effortless caching Try adding @st.cache_data before the load_data declaration: @st.cache_data def load_data(nrows): Then save the script, and Streamlit will automatically rerun your app. Since this is the first time you’re running the script with @st.cache_data, you won't see anything change. Let’s tweak your file a little bit more so that you can see the power of caching. Replace the line data_load_state.text('Loading data...done!') with this: data_load_state.text(""Done! (using st.cache_data)"") Now save. See how the line you added appeared immediately? If you take a step back for a second, this is actually quite amazing. Something magical is happening behind the scenes, and it only takes one line of code to activate it. How's it work? Let's take a few minutes to discuss how @st.cache_data actually works. When you mark a function with Streamlit’s cache annotation, it tells Streamlit that whenever the function is called that it should check two things: The input parameters you used for the function call. The code inside the function. If this is the first time Streamlit has seen both these items, with these exact values, and in this exact combination, it runs the function and stores the result in a local cache. The next time the function is called, if the two values haven't changed, then Streamlit knows it can skip executing the function altogether. Instead, it reads the output from the local cache and passes it on to the caller -- like magic. ""But, wait a second,"" you’re saying to yourself, ""this sounds too good to be true. What are the limitations of all this awesomesauce?"" Well, there are a few: Streamlit will only check for changes within the current working directory. If you upgrade a Python library, Streamlit's cache will only notice this if that library is installed inside your working directory. If your function is not deterministic (that is, its output depends on random numbers), or if it pulls data from an external time-varying source (for example, a live stock market ticker service) the cached value will be none-the-wiser. Lastly, you should avoid mutating the output of a function cached with st.cache_data since cached values are stored by reference. While these limitations are important to keep in mind, they tend not to be an issue a surprising amount of the time. Those times, this cache is really transformational. starTipWhenever you have a long-running computation in your code, consider refactoring it so you can use @st.cache_data, if possible. Please read Caching for more details. Now that you know how caching with Streamlit works, let’s get back to the Uber pickup data. Inspect the raw data It's always a good idea to take a look at the raw data you're working with before you start working with it. Let's add a subheader and a printout of the raw data to the app: st.subheader('Raw data') st.write(data) In the Basic concepts guide you learned that st.write will render almost anything you pass to it. In this case, you're passing in a dataframe and it's rendering as an interactive table. st.write tries to do the right thing based on the data type of the input. If it isn't doing what you expect you can use a specialized command like st.dataframe instead. For a full list, see API reference. Draw a histogram Now that you've had a chance to take a look at the dataset and observe what's available, let's take things a step further and draw a histogram to see what Uber's busiest hours are in New York City. To start, let's add a subheader just below the raw data section: st.subheader('Number of pickups by hour') Use NumPy to generate a histogram that breaks down pickup times binned by hour: hist_values = np.histogram( data[DATE_COLUMN].dt.hour, bins=24, range=(0,24))[0] Now, let's use Streamlit's st.bar_chart() method to draw this histogram. st.bar_chart(hist_values) Save your script. This histogram should show up in your app right away. After a quick review, it looks like the busiest time is 17:00 (5 P.M.). To draw this diagram we used Streamlit's native bar_chart() method, but it's important to know that Streamlit supports more complex charting libraries like Altair, Bokeh, Plotly, Matplotlib and more. For a full list, see supported charting libraries. Plot data on a map Using a histogram with Uber's dataset helped us determine what the busiest times are for pickups, but what if we wanted to figure out where pickups were concentrated throughout the city. While you could use a bar chart to show this data, it wouldn't be easy to interpret unless you were intimately familiar with latitudinal and longitudinal coordinates in the city. To show pickup concentration, let's use Streamlit st.map() function to overlay the data on a map of New York City. Add a subheader for the section: st.subheader('Map of all pickups') Use the st.map() function to plot the data: st.map(data) Save your script. The map is fully interactive. Give it a try by panning or zooming in a bit. After drawing your histogram, you determined that the busiest hour for Uber pickups was 17:00. Let's redraw the map to show the concentration of pickups at 17:00. Locate the following code snippet: st.subheader('Map of all pickups') st.map(data) Replace it with: hour_to_filter = 17 filtered_data = data[data[DATE_COLUMN].dt.hour == hour_to_filter] st.subheader(f'Map of all pickups at {hour_to_filter}:00') st.map(filtered_data) You should see the data update instantly. To draw this map we used the st.map function that's built into Streamlit, but if you'd like to visualize complex map data, we encourage you to take a look at the st.pydeck_chart. Filter results with a slider In the last section, when you drew the map, the time used to filter results was hardcoded into the script, but what if we wanted to let a reader dynamically filter the data in real time? Using Streamlit's widgets you can. Let's add a slider to the app with the st.slider() method. Locate hour_to_filter and replace it with this code snippet: hour_to_filter = st.slider('hour', 0, 23, 17) # min: 0h, max: 23h, default: 17h Use the slider and watch the map update in real time. Use a button to toggle data Sliders are just one way to dynamically change the composition of your app. Let's use the st.checkbox function to add a checkbox to your app. We'll use this checkbox to show/hide the raw data table at the top of your app. Locate these lines: st.subheader('Raw data') st.write(data) Replace these lines with the following code: if st.checkbox('Show raw data'): st.subheader('Raw data') st.write(data) We're sure you've got your own ideas. When you're done with this tutorial, check out all the widgets that Streamlit exposes in our API Reference. Let's put it all together That's it, you've made it to the end. Here's the complete script for our interactive app. starTipIf you've skipped ahead, after you've created your script, the command to run Streamlit is streamlit run [app name]. import streamlit as st import pandas as pd import numpy as np st.title('Uber pickups in NYC') DATE_COLUMN = 'date/time' DATA_URL = ('https://s3-us-west-2.amazonaws.com/' 'streamlit-demo-data/uber-raw-data-sep14.csv.gz') @st.cache_data def load_data(nrows): data = pd.read_csv(DATA_URL, nrows=nrows) lowercase = lambda x: str(x).lower() data.rename(lowercase, axis='columns', inplace=True) data[DATE_COLUMN] = pd.to_datetime(data[DATE_COLUMN]) return data data_load_state = st.text('Loading data...') data = load_data(10000) data_load_state.text(""Done! (using st.cache_data)"") if st.checkbox('Show raw data'): st.subheader('Raw data') st.write(data) st.subheader('Number of pickups by hour') hist_values = np.histogram(data[DATE_COLUMN].dt.hour, bins=24, range=(0,24))[0] st.bar_chart(hist_values) # Some number in the range 0-23 hour_to_filter = st.slider('hour', 0, 23, 17) filtered_data = data[data[DATE_COLUMN].dt.hour == hour_to_filter] st.subheader('Map of all pickups at %s:00' % hour_to_filter) st.map(filtered_data) Share your app After you’ve built a Streamlit app, it's time to share it! To show it off to the world you can use Streamlit Community Cloud to deploy, manage, and share your app for free. It works in 3 simple steps: Put your app in a public GitHub repo (and make sure it has a requirements.txt!) Sign into share.streamlit.io Click 'Deploy an app' and then paste in your GitHub URL That's it! 🎈 You now have a publicly deployed app that you can share with the world. Click to learn more about how to use Streamlit Community Cloud. Get help That's it for getting started, now you can go and build your own apps! If you run into difficulties here are a few things you can do. Check out our community forum and post a question Quick help from command line with streamlit help Go through our Knowledge Base for tips, step-by-step tutorials, and articles that answer your questions about creating and deploying Streamlit apps. Read more documentation! Check out: Concepts for things like caching, theming, and adding statefulness to apps. API reference for examples of every Streamlit command. Previous: First stepsNext: Create a multipage appforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy" https://docs.streamlit.io/knowledge-base/using-streamlit/sanity-checks#check-4-is-your-browser-caching-your-app-too-aggressively,"DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Knowledge base/FAQ/Sanity checksSanity checks If you're having problems running your Streamlit app, here are a few things to try out. Check #0: Are you using a Streamlit-supported version of Python? Streamlit will maintain backwards-compatibility with earlier Python versions as practical, guaranteeing compatibility with at least the last three minor versions of Python 3. As new versions of Python are released, we will try to be compatible with the new version as soon as possible, though frequently we are at the mercy of other Python packages to support these new versions as well. Streamlit currently supports versions 3.8, 3.9, 3.10, 3.11, and 3.12 of Python. Check #1: Is Streamlit running? On a Mac or Linux machine, type this on the terminal: ps -Al | grep streamlit If you don't see streamlit run in the output (or streamlit hello, if that's the command you ran) then the Streamlit server is not running. So re-run your command and see if the bug goes away. Check #2: Is this an already-fixed Streamlit bug? We try to fix bugs quickly, so many times a problem will go away when you upgrade Streamlit. So the first thing to try when having an issue is upgrading to the latest version of Streamlit: pip install --upgrade streamlit streamlit version ...and then verify that the version number printed corresponds to the version number displayed on PyPI. Try reproducing the issue now. If not fixed, keep reading on. Check #3: Are you running the correct Streamlit binary? Let's check whether your Python environment is set up correctly. Edit the Streamlit script where you're experiencing your issue, comment everything out, and add these lines instead: import streamlit as st st.write(st.__version__) ...then call streamlit run on your script and make sure it says the same version as above. If not the same version, check out these instructions for some sure-fire ways to set up your environment. Check #4: Is your browser caching your app too aggressively? There are two easy ways to check this: Load your app in a browser then press Ctrl-Shift-R or ⌘-Shift-R to do a hard refresh (Chrome/Firefox). As a test, run Streamlit on another port. This way the browser starts the page with a brand new cache. For that, pass the --server.port argument to Streamlit on the command line: streamlit run my_app.py --server.port=9876 Check #5: Is this a Streamlit regression? If you've upgraded to the latest version of Streamlit and things aren't working, you can downgrade at any time using this command: pip install --upgrade streamlit==1.0.0 ...where 1.0.0 is the version you'd like to downgrade to. See Changelog for a complete list of Streamlit versions. Check #6 [Windows]: Is Python added to your PATH? When installed by downloading from python.org, Python is not automatically added to the Windows system PATH. Because of this, you may get error messages like the following: Command Prompt: C:\Users\streamlit> streamlit hello 'streamlit' is not recognized as an internal or external command, operable program or batch file. PowerShell: PS C:\Users\streamlit> streamlit hello streamlit : The term 'streamlit' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again. At line:1 char:1 + streamlit hello + ~~~~~~~~~ + CategoryInfo : ObjectNotFound: (streamlit:String) [], CommandNotFoundException + FullyQualifiedErrorId : CommandNotFoundException To resolve this issue, add Python to the Windows system PATH. After adding Python to your Windows PATH, you should then be able to follow the instructions in our Get Started section. Check #7 [Windows]: Do you need Build Tools for Visual Studio installed? Streamlit includes pyarrow as an install dependency. Occasionally, when trying to install Streamlit from PyPI, you may see errors such as the following: Using cached pyarrow-1.0.1.tar.gz (1.3 MB) Installing build dependencies ... error ERROR: Command errored out with exit status 1: command: 'c:\users\streamlit\appdata\local\programs\python\python38-32\python.exe' 'c:\users\streamlit\appdata\local\programs\python\python38-32\lib\site-packages\pip' install --ignore-installed --no-user --prefix 'C:\Users\streamlit\AppData\Local\Temp\pip-build-env-s7owjrle\overlay' --no-warn-script-location --no-binary :none: --only-binary :none: -i https://pypi.org/simple -- 'cython >= 0.29' 'numpy==1.14.5; python_version<'""'""'3.8'""'""'' 'numpy==1.16.0; python_version>='""'""'3.8'""'""'' setuptools setuptools_scm wheel cwd: None Complete output (319 lines): Running setup.py install for numpy: finished with status 'error' ERROR: Command errored out with exit status 1: command: 'c:\users\streamlit\appdata\local\programs\python\python38-32\python.exe' -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '""'""'C:\\Users\\streamlit\\AppData\\Local\\Temp\\pip-install-0jwfwx_u\\numpy\\setup.py'""'""'; __file__='""'""'C:\\Users\\streamlit\\AppData\\Local\\Temp\\pip-install-0jwfwx_u\\numpy\\setup.py'""'""';f=getattr(tokenize, '""'""'open'""'""', open)(__file__);code=f.read().replace('""'""'\r\n'""'""', '""'""'\n'""'""');f.close();exec(compile(code, __file__, '""'""'exec'""'""'))' install --record 'C:\Users\streamlit\AppData\Local\Temp\pip-record-eys4l2gc\install-record.txt' --single-version-externally-managed --prefix 'C:\Users\streamlit\AppData\Local\Temp\pip-build-env-s7owjrle\overlay' --compile --install-headers 'C:\Users\streamlit\AppData\Local\Temp\pip-build-env-s7owjrle\overlay\Include\numpy' cwd: C:\Users\streamlit\AppData\Local\Temp\pip-install-0jwfwx_u\numpy\ Complete output (298 lines): blas_opt_info: blas_mkl_info: No module named 'numpy.distutils._msvccompiler' in numpy.distutils; trying from distutils customize MSVCCompiler libraries mkl_rt not found in ['c:\\users\\streamlit\\appdata\\local\\programs\\python\\python38-32\\lib', 'C:\\', 'c:\\users\\streamlit\\appdata\\local\\programs\\python\\python38-32\\libs'] NOT AVAILABLE blis_info: No module named 'numpy.distutils._msvccompiler' in numpy.distutils; trying from distutils customize MSVCCompiler libraries blis not found in ['c:\\users\\streamlit\\appdata\\local\\programs\\python\\python38-32\\lib', 'C:\\', 'c:\\users\\streamlit\\appdata\\local\\programs\\python\\python38-32\\libs'] NOT AVAILABLE # # c:\users\streamlit\appdata\local\programs\python\python38-32\lib\distutils\dist.py:274: UserWarning: Unknown distribution option: 'define_macros' warnings.warn(msg) running install running build running config_cc unifing config_cc, config, build_clib, build_ext, build commands --compiler options running config_fc unifing config_fc, config, build_clib, build_ext, build commands --fcompiler options running build_src build_src building py_modules sources creating build creating build\src.win32-3.8 creating build\src.win32-3.8\numpy creating build\src.win32-3.8\numpy\distutils building library ""npymath"" sources No module named 'numpy.distutils._msvccompiler' in numpy.distutils; trying from distutils error: Microsoft Visual C++ 14.0 is required. Get it with ""Build Tools for Visual Studio"": https://visualstudio.microsoft.com/downloads/ ---------------------------------------- ERROR: Command errored out with exit status 1: 'c:\users\streamlit\appdata\local\programs\python\python38-32\python.exe' -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '""'""'C:\\Users\\streamlit\\AppData\\Local\\Temp\\pip-install-0jwfwx_u\\numpy\\setup.py'""'""'; __file__='""'""'C:\\Users\\streamlit\\AppData\\Local\\Temp\\pip-install-0jwfwx_u\\numpy\\setup.py'""'""';f=getattr(tokenize, '""'""'open'""'""', open)(__file__);code=f.read().replace('""'""'\r\n'""'""', '""'""'\n'""'""');f.close();exec(compile(code, __file__, '""'""'exec'""'""'))' install --record 'C:\Users\streamlit\AppData\Local\Temp\pip-record-eys4l2gc\install-record.txt' --single-version-externally-managed --prefix 'C:\Users\streamlit\AppData\Local\Temp\pip-build-env-s7owjrle\overlay' --compile --install-headers 'C:\Users\streamlit\AppData\Local\Temp\pip-build-env-s7owjrle\overlay\Include\numpy' Check the logs for full command output. ---------------------------------------- This error indicates that Python is trying to compile certain libraries during install, but it cannot find the proper compilers on your system, as reflected by the line error: Microsoft Visual C++ 14.0 is required. Get it with ""Build Tools for Visual Studio"". Installing Build Tools for Visual Studio should resolve this issue.Previous: How do you retrieve the filename of a file uploaded with st.file_uploader?Next: How can I make Streamlit watch for changes in other modules I'm importing in my app?forumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy" https://docs.streamlit.io/develop/api-reference/caching-and-state/st.cache_data#input-widgets,"DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceremovePAGE ELEMENTSWrite and magicaddText elementsaddData elementsaddChart elementsaddInput widgetsaddMedia elementsaddLayouts and containersaddChat elementsaddStatus elementsaddThird-party componentsopen_in_newAPPLICATION LOGICNavigation and pagesaddExecution flowaddCaching and stateremovest.cache_datast.cache_resourcest.cachedeletest.session_statest.query_paramsst.experimental_get_query_paramsdeletest.experimental_set_query_paramsdeleteConnections and secretsaddCustom componentsaddUtilitiesaddConfigurationaddTOOLSApp testingaddCommand lineaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Develop/API reference/Caching and state/st.cache_datastarTipThis page only contains information on the st.cache_data API. For a deeper dive into caching and how to use it, check out Caching. st.cache_dataStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeDecorator to cache functions that return data (e.g. dataframe transforms, database queries, ML inference). Cached objects are stored in ""pickled"" form, which means that the return value of a cached function must be pickleable. Each caller of the cached function gets its own copy of the cached data. You can clear a function's cache with func.clear() or clear the entire cache with st.cache_data.clear(). To cache global resources, use st.cache_resource instead. Learn more about caching at https://docs.streamlit.io/library/advanced-features/caching. Function signature[source] st.cache_data(func=None, *, ttl, max_entries, show_spinner, persist, experimental_allow_widgets, hash_funcs=None) Parameters func (callable) The function to cache. Streamlit hashes the function's source code. ttl (float, timedelta, str, or None) The maximum time to keep an entry in the cache. Can be one of: None if cache entries should never expire (default). A number specifying the time in seconds. A string specifying the time in a format supported by Pandas's Timedelta constructor, e.g. ""1d"", ""1.5 days"", or ""1h23s"". A timedelta object from Python's built-in datetime library, e.g. timedelta(days=1). Note that ttl will be ignored if persist=""disk"" or persist=True. max_entries (int or None) The maximum number of entries to keep in the cache, or None for an unbounded cache. When a new entry is added to a full cache, the oldest cached entry will be removed. Defaults to None. show_spinner (bool or str) Enable the spinner. Default is True to show a spinner when there is a ""cache miss"" and the cached data is being created. If string, value of show_spinner param will be used for spinner text. persist (""disk"", bool, or None) Optional location to persist cached data to. Passing ""disk"" (or True) will persist the cached data to the local disk. None (or False) will disable persistence. The default is None. experimental_allow_widgets (bool) Allow widgets to be used in the cached function. Defaults to False. Support for widgets in cached functions is currently experimental. Setting this parameter to True may lead to excessive memory use since the widget value is treated as an additional input parameter to the cache. We may remove support for this option at any time without notice. hash_funcs (dict or None) Mapping of types or fully qualified names to hash functions. This is used to override the behavior of the hasher inside Streamlit's caching mechanism: when the hasher encounters an object, it will first check to see if its type matches a key in this dict and, if so, will use the provided function to generate a hash for it. See below for an example of how this can be used. Example import streamlit as st @st.cache_data def fetch_and_clean_data(url): # Fetch data from URL here, and then clean it up. return data d1 = fetch_and_clean_data(DATA_URL_1) # Actually executes the function, since this is the first time it was # encountered. d2 = fetch_and_clean_data(DATA_URL_1) # Does not execute the function. Instead, returns its previously computed # value. This means that now the data in d1 is the same as in d2. d3 = fetch_and_clean_data(DATA_URL_2) # This is a different URL, so the function executes. To set the persist parameter, use this command as follows: import streamlit as st @st.cache_data(persist=""disk"") def fetch_and_clean_data(url): # Fetch data from URL here, and then clean it up. return data By default, all parameters to a cached function must be hashable. Any parameter whose name begins with _ will not be hashed. You can use this as an ""escape hatch"" for parameters that are not hashable: import streamlit as st @st.cache_data def fetch_and_clean_data(_db_connection, num_rows): # Fetch data from _db_connection here, and then clean it up. return data connection = make_database_connection() d1 = fetch_and_clean_data(connection, num_rows=10) # Actually executes the function, since this is the first time it was # encountered. another_connection = make_database_connection() d2 = fetch_and_clean_data(another_connection, num_rows=10) # Does not execute the function. Instead, returns its previously computed # value - even though the _database_connection parameter was different # in both calls. A cached function's cache can be procedurally cleared: import streamlit as st @st.cache_data def fetch_and_clean_data(_db_connection, num_rows): # Fetch data from _db_connection here, and then clean it up. return data fetch_and_clean_data.clear(_db_connection, 50) # Clear the cached entry for the arguments provided. fetch_and_clean_data.clear() # Clear all cached entries for this function. To override the default hashing behavior, pass a custom hash function. You can do that by mapping a type (e.g. datetime.datetime) to a hash function (lambda dt: dt.isoformat()) like this: import streamlit as st import datetime @st.cache_data(hash_funcs={datetime.datetime: lambda dt: dt.isoformat()}) def convert_to_utc(dt: datetime.datetime): return dt.astimezone(datetime.timezone.utc) Alternatively, you can map the type's fully-qualified name (e.g. ""datetime.datetime"") to the hash function instead: import streamlit as st import datetime @st.cache_data(hash_funcs={""datetime.datetime"": lambda dt: dt.isoformat()}) def convert_to_utc(dt: datetime.datetime): return dt.astimezone(datetime.timezone.utc) priority_highWarningst.cache_data implicitly uses the pickle module, which is known to be insecure. Anything your cached function returns is pickled and stored, then unpickled on retrieval. Ensure your cached functions return trusted values because it is possible to construct malicious pickle data that will execute arbitrary code during unpickling. Never load data that could have come from an untrusted source in an unsafe mode or that could have been tampered with. Only load data you trust. st.cache_data.clearStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeClear all in-memory and on-disk data caches. Function signature[source] st.cache_data.clear() Example In the example below, pressing the ""Clear All"" button will clear memoized values from all functions decorated with @st.cache_data. import streamlit as st @st.cache_data def square(x): return x**2 @st.cache_data def cube(x): return x**3 if st.button(""Clear All""): # Clear values from *all* all in-memory and on-disk data caches: # i.e. clear values from both square and cube st.cache_data.clear() CachedFunc.clearStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeClear the cached function's associated cache. If no arguments are passed, Streamlit will clear all values cached for the function. If arguments are passed, Streamlit will clear the cached value for these arguments only. Function signature[source] CachedFunc.clear(*args, **kwargs) Parameters *args (Any) Arguments of the cached functions. **kwargs (Any) Keyword arguments of the cached function. Example import streamlit as st import time @st.cache_data def foo(bar): time.sleep(2) st.write(f""Executed foo({bar})."") return bar if st.button(""Clear all cached values for `foo`"", on_click=foo.clear): foo.clear() if st.button(""Clear the cached value of `foo(1)`""): foo.clear(1) foo(1) foo(2) Using Streamlit commands in cached functions Static elements Since version 1.16.0, cached functions can contain Streamlit commands! For example, you can do this: @st.cache_data def get_api_data(): data = api.get(...) st.success(""Fetched data from API!"") # 👈 Show a success message return data As we know, Streamlit only runs this function if it hasn’t been cached before. On this first run, the st.success message will appear in the app. But what happens on subsequent runs? It still shows up! Streamlit realizes that there is an st. command inside the cached function, saves it during the first run, and replays it on subsequent runs. Replaying static elements works for both caching decorators. You can also use this functionality to cache entire parts of your UI: @st.cache_data def show_data(): st.header(""Data analysis"") data = api.get(...) st.success(""Fetched data from API!"") st.write(""Here is a plot of the data:"") st.line_chart(data) st.write(""And here is the raw data:"") st.dataframe(data) Input widgets You can also use interactive input widgets like st.slider or st.text_input in cached functions. Widget replay is an experimental feature at the moment. To enable it, you need to set the experimental_allow_widgets parameter: @st.cache_data(experimental_allow_widgets=True) # 👈 Set the parameter def get_data(): num_rows = st.slider(""Number of rows to get"") # 👈 Add a slider data = api.get(..., num_rows) return data Streamlit treats the slider like an additional input parameter to the cached function. If you change the slider position, Streamlit will see if it has already cached the function for this slider value. If yes, it will return the cached value. If not, it will rerun the function using the new slider value. Using widgets in cached functions is extremely powerful because it lets you cache entire parts of your app. But it can be dangerous! Since Streamlit treats the widget value as an additional input parameter, it can easily lead to excessive memory usage. Imagine your cached function has five sliders and returns a 100 MB DataFrame. Then we’ll add 100 MB to the cache for every permutation of these five slider values – even if the sliders do not influence the returned data! These additions can make your cache explode very quickly. Please be aware of this limitation if you use widgets in cached functions. We recommend using this feature only for isolated parts of your UI where the widgets directly influence the cached return value. priority_highWarningSupport for widgets in cached functions is currently experimental. We may change or remove it anytime without warning. Please use it with care! push_pinNoteTwo widgets are currently not supported in cached functions: st.file_uploader and st.camera_input. We may support them in the future. Feel free to open a GitHub issue if you need them!Previous: Caching and stateNext: st.cache_resourceforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy" https://docs.streamlit.io/deploy/streamlit-community-cloud/deploy-your-app#advanced-settings-for-deployment,"DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudremoveGet startedaddDeploy your appremoveApp dependenciesSecrets managementManage your appaddShare your appaddManage your accountaddTroubleshootingStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Deploy/Streamlit Community Cloud/Deploy your appDeploy your app Streamlit Community Cloud lets you deploy your apps in just one click, and most apps will deploy in only a few minutes. If you don't have an app ready to deploy, fork or clone one from our App gallery — you can find apps for machine learning, data visualization, data exploration, A/B testing and more. You can also fork and deploy samples straight from the New app button. Once you've deployed your app, check out how you can Edit your app with GitHub Codespaces. push_pinNoteIf you want to deploy your app on a different cloud service, check out the Deploy Streamlit apps article in our Knowledge Base. Add your app to GitHub Streamlit Community Cloud launches apps directly from your GitHub repo, so your app code and dependencies need to be on GitHub before you try to deploy your app. For more information on how to specify dependencies, see App dependencies. Your directory structure should look similar to this: your-repository/ ├── your_app.py └── requirements.txt If you are including any custom Configuration or Theming, make sure your config file is saved relative to the root of your repo. Within your repo, your config file should be named .streamlit/config.toml. your-repository/ ├── .streamlit/ │ └── config.toml ├── your_app.py └── requirements.txt priority_highImportantAlthough you can deploy multiple apps from the same repository, there can be only one configuration file. Deploy your app From your workspace at share.streamlit.io, click ""New app"" from the upper-right corner of your workspace. Fill in your repo, branch, and file path. As a shortcut, you can also click ""Paste GitHub URL"" to paste a link directly to your_app.py on GitHub. An app URL with a random hash is prefilled but you can change this to a custom subdomain instead. In the example below, the app would be deployed to https://red-balloon.streamlit.app/. You can always change your subdomain later. See more about Custom subdomains at the end of this page. Advanced settings for deployment push_pinNoteStreamlit Community Cloud supports all released versions of Python that are still receiving security updates. Streamlit Community Cloud defaults to version 3.9. You can select a version of your choice from the ""Python version"" dropdown in the ""Advanced settings"" modal. If an app is running a version of Python that becomes unsupported, it will be forcibly upgraded to the oldest, supported version of Python and may break. (Optional) If you are connecting to a data source or want to specify the Python version for your app, you can do that by clicking ""Advanced settings"" before you deploy the app. Learn more about Secrets management. Watch your app launch Your app is now deploying and you can watch while it launches. Most apps take only a couple of minutes to deploy, but if your app has a lot of dependencies it may take longer to deploy the first time. After the initial deployment, any change that does not touch your dependencies should show up immediately. push_pinNoteThe Streamlit Community Cloud logs on the right hand side of your app are only viewable to users with developer access to your repository. These logs help you debug any issues with the app. Learn more about Streamlit Community Cloud logs. Your app URL That's it — you're done! Your app now has a unique subdomain URL that you can share with others. Read more about how to Share your app with viewers. Unique subdomains If the ""Custom subdomain (optional)"" field is blank when you deploy your app, a URL is assigned following a structure based on your GitHub repo. The URL begins with your GitHub username or organization owning your repo, followed by your repo name, app path, and a short hash. If you deploy from a branch other than main or master, the URL also includes the branch name. https://[GitHub username or organization]-[repo name]-[app path]-[branch name]-[short hash].streamlit.app For example, this is an app deployed from the streamlit organization. The repo is demo-self-driving and the app name is streamlit_app.py in the root directory. The branch name is master and therefore not included. https://streamlit-demo-self-driving-streamlit-app-8jya0g.streamlit.app Custom subdomains Setting a custom subdomain makes it much easier to share your app since you can choose something memorable. Whether you set a custom subdomain during deployment or later, your app's URL will appear as: https://.streamlit.app To view or customize your app subdomain from the dashboard: Click the overflow icon (more_vert) to the app's right and select ""Settings"". View the ""General"" tab in the App settings modal. Your app's unique subdomain will appear here. Pick a custom subdomain between 6 and 63 characters in length for your app's URL and hit ""Save"". It's that simple! You can then access your app by visiting your customized URL 🎉. If a custom subdomain is not available (e.g. because it's already taken), you'll see an error message like this: Previous: Get startedNext: App dependenciesforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy" https://docs.streamlit.io/develop/api-reference/#built-in-connections,"DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceremovePAGE ELEMENTSWrite and magicaddText elementsaddData elementsaddChart elementsaddInput widgetsaddMedia elementsaddLayouts and containersaddChat elementsaddStatus elementsaddThird-party componentsopen_in_newAPPLICATION LOGICNavigation and pagesaddExecution flowaddCaching and stateaddConnections and secretsaddCustom componentsaddUtilitiesaddConfigurationaddTOOLSApp testingaddCommand lineaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Develop/API referenceAPI reference Streamlit makes it easy for you to visualize, mutate, and share data. The API reference is organized by activity type, like displaying data or optimizing performance. Each section includes methods associated with the activity type, including examples. Browse our API below and click to learn more about any of our available commands! 🎈 Display almost anything Write and magic st.writeWrite arguments to the app.st.write(""Hello **world**!"") st.write(my_data_frame) st.write(my_mpl_figure) st.write_streamWrite generators or streams to the app with a typewriter effect.st.write_stream(my_generator) st.write_stream(my_llm_stream) MagicAny time Streamlit sees either a variable or literal value on its own line, it automatically writes that to your app using st.write""Hello **world**!"" my_data_frame my_mpl_figure Text elements MarkdownDisplay string formatted as Markdown.st.markdown(""Hello **world**!"") TitleDisplay text in title formatting.st.title(""The app title"") HeaderDisplay text in header formatting.st.header(""This is a header"") SubheaderDisplay text in subheader formatting.st.subheader(""This is a subheader"") CaptionDisplay text in small font.st.caption(""This is written small caption text"") Code blockDisplay a code block with optional syntax highlighting.st.code(""a = 1234"") EchoDisplay some code in the app, then execute it. Useful for tutorials.with st.echo(): st.write('This code will be printed') LaTeXDisplay mathematical expressions formatted as LaTeX.st.latex(""\int a x^2 \,dx"") Preformatted textWrite fixed-width and preformatted text.st.text(""Hello world"") DividerDisplay a horizontal rule.st.divider() Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration! PreviousTagsAdd tags to your Streamlit apps. Created by @gagan3012.st_tags(label='# Enter Keywords:', text='Press enter to add more', value=['Zero', 'One', 'Two'], suggestions=['five', 'six', 'seven', 'eight', 'nine', 'three', 'eleven', 'ten', 'four'], maxtags = 4, key='1') NLUApply text mining on a dataframe. Created by @JohnSnowLabs.nlu.load('sentiment').predict('I love NLU! <3') Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.mention(label=""An awesome Streamlit App"", icon=""streamlit"", url=""https://extras.streamlit.app"",) Annotated textDisplay annotated text in Streamlit apps. Created by @tvst.annotated_text(""This "", (""is"", ""verb""), "" some "", (""annotated"", ""adj""), (""text"", ""noun""), "" for those of "", (""you"", ""pronoun""), "" who "", (""like"", ""verb""), "" this sort of "", (""thing"", ""noun""), ""."") Drawable CanvasProvides a sketching canvas using Fabric.js. Created by @andfanilo.st_canvas(fill_color=""rgba(255, 165, 0, 0.3)"", stroke_width=stroke_width, stroke_color=stroke_color, background_color=bg_color, background_image=Image.open(bg_image) if bg_image else None, update_streamlit=realtime_update, height=150, drawing_mode=drawing_mode, point_display_radius=point_display_radius if drawing_mode == 'point' else 0, key=""canvas"",) TagsAdd tags to your Streamlit apps. Created by @gagan3012.st_tags(label='# Enter Keywords:', text='Press enter to add more', value=['Zero', 'One', 'Two'], suggestions=['five', 'six', 'seven', 'eight', 'nine', 'three', 'eleven', 'ten', 'four'], maxtags = 4, key='1') NLUApply text mining on a dataframe. Created by @JohnSnowLabs.nlu.load('sentiment').predict('I love NLU! <3') Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.mention(label=""An awesome Streamlit App"", icon=""streamlit"", url=""https://extras.streamlit.app"",) Annotated textDisplay annotated text in Streamlit apps. Created by @tvst.annotated_text(""This "", (""is"", ""verb""), "" some "", (""annotated"", ""adj""), (""text"", ""noun""), "" for those of "", (""you"", ""pronoun""), "" who "", (""like"", ""verb""), "" this sort of "", (""thing"", ""noun""), ""."") Drawable CanvasProvides a sketching canvas using Fabric.js. Created by @andfanilo.st_canvas(fill_color=""rgba(255, 165, 0, 0.3)"", stroke_width=stroke_width, stroke_color=stroke_color, background_color=bg_color, background_image=Image.open(bg_image) if bg_image else None, update_streamlit=realtime_update, height=150, drawing_mode=drawing_mode, point_display_radius=point_display_radius if drawing_mode == 'point' else 0, key=""canvas"",) TagsAdd tags to your Streamlit apps. Created by @gagan3012.st_tags(label='# Enter Keywords:', text='Press enter to add more', value=['Zero', 'One', 'Two'], suggestions=['five', 'six', 'seven', 'eight', 'nine', 'three', 'eleven', 'ten', 'four'], maxtags = 4, key='1') NLUApply text mining on a dataframe. Created by @JohnSnowLabs.nlu.load('sentiment').predict('I love NLU! <3') Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.mention(label=""An awesome Streamlit App"", icon=""streamlit"", url=""https://extras.streamlit.app"",) Next Data elements DataframesDisplay a dataframe as an interactive table.st.dataframe(my_data_frame) Data editorDisplay a data editor widget.edited = st.data_editor(df, num_rows=""dynamic"") Column configurationConfigure the display and editing behavior of dataframes and data editors.st.column_config.NumberColumn(""Price (in USD)"", min_value=0, format=""$%d"") Static tablesDisplay a static table.st.table(my_data_frame) MetricsDisplay a metric in big bold font, with an optional indicator of how the metric changed.st.metric(""My metric"", 42, 2) Dicts and JSONDisplay object or string as a pretty-printed JSON string.st.json(my_dict) Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration! PreviousImage CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates value = streamlit_image_coordinates(""https://placekitten.com/200/300"") st.write(value) Plotly EventsMake Plotly charts interactive!. Created by @null-jones.from streamlit_plotly_events import plotly_events fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.metric_cards import style_metric_cards col3.metric(label=""No Change"", value=5000, delta=0) style_metric_cards() Streamlit AggridImplementation of Ag-Grid component for Streamlit. Created by @PablocFonseca.df = pd.DataFrame({'col1': [1, 2, 3], 'col2': [4, 5, 6]}) grid_return = AgGrid(df, editable=True) new_df = grid_return['data'] Streamlit FoliumStreamlit Component for rendering Folium maps. Created by @randyzwitch.m = folium.Map(location=[39.949610, -75.150282], zoom_start=16) folium.Marker([39.949610, -75.150282], popup=""Liberty Bell"", tooltip=""Liberty Bell"").add_to(m) st_data = st_folium(m, width=725) Pandas ProfilingPandas profiling component for Streamlit. Created by @okld.df = pd.read_csv(""https://storage.googleapis.com/tf-datasets/titanic/train.csv"") pr = df.profile_report() st_profile_report(pr) Image CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates value = streamlit_image_coordinates(""https://placekitten.com/200/300"") st.write(value) Plotly EventsMake Plotly charts interactive!. Created by @null-jones.from streamlit_plotly_events import plotly_events fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.metric_cards import style_metric_cards col3.metric(label=""No Change"", value=5000, delta=0) style_metric_cards() Streamlit AggridImplementation of Ag-Grid component for Streamlit. Created by @PablocFonseca.df = pd.DataFrame({'col1': [1, 2, 3], 'col2': [4, 5, 6]}) grid_return = AgGrid(df, editable=True) new_df = grid_return['data'] Streamlit FoliumStreamlit Component for rendering Folium maps. Created by @randyzwitch.m = folium.Map(location=[39.949610, -75.150282], zoom_start=16) folium.Marker([39.949610, -75.150282], popup=""Liberty Bell"", tooltip=""Liberty Bell"").add_to(m) st_data = st_folium(m, width=725) Pandas ProfilingPandas profiling component for Streamlit. Created by @okld.df = pd.read_csv(""https://storage.googleapis.com/tf-datasets/titanic/train.csv"") pr = df.profile_report() st_profile_report(pr) Image CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates value = streamlit_image_coordinates(""https://placekitten.com/200/300"") st.write(value) Plotly EventsMake Plotly charts interactive!. Created by @null-jones.from streamlit_plotly_events import plotly_events fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.metric_cards import style_metric_cards col3.metric(label=""No Change"", value=5000, delta=0) style_metric_cards() Next Chart elements Simple area chartsDisplay an area chart.st.area_chart(my_data_frame) Simple bar chartsDisplay a bar chart.st.bar_chart(my_data_frame) Simple line chartsDisplay a line chart.st.line_chart(my_data_frame) Simple scatter chartsDisplay a line chart.st.scatter_chart(my_data_frame) Scatterplots on mapsDisplay a map with points on it.st.map(my_data_frame) MatplotlibDisplay a matplotlib.pyplot figure.st.pyplot(my_mpl_figure) AltairDisplay a chart using the Altair library.st.altair_chart(my_altair_chart) Vega-LiteDisplay a chart using the Vega-Lite library.st.vega_lite_chart(my_vega_lite_chart) PlotlyDisplay an interactive Plotly chart.st.plotly_chart(my_plotly_chart) BokehDisplay an interactive Bokeh chart.st.bokeh_chart(my_bokeh_chart) PyDeckDisplay a chart using the PyDeck library.st.pydeck_chart(my_pydeck_chart) GraphVizDisplay a graph using the dagre-d3 library.st.graphviz_chart(my_graphviz_spec) Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration! PreviousStreamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl(""https://assets5.lottiefiles.com/packages/lf20_V9t630.json"") st_lottie(lottie_hello, key=""hello"") Plotly EventsMake Plotly charts interactive!. Created by @null-jones.fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.chart += get_annotations_chart(annotations=[(""Mar 01, 2008"", ""Pretty good day for GOOG""), (""Dec 01, 2007"", ""Something's going wrong for GOOG & AAPL""), (""Nov 01, 2008"", ""Market starts again thanks to...""), (""Dec 01, 2009"", ""Small crash for GOOG after...""),],) st.altair_chart(chart, use_container_width=True) PlostA deceptively simple plotting library for Streamlit. Created by @tvst.import plost plost.line_chart(my_dataframe, x='time', y='stock_value', color='stock_name',) HiPlotHigh dimensional Interactive Plotting. Created by @facebookresearch.data = [{'dropout':0.1, 'lr': 0.001, 'loss': 10.0, 'optimizer': 'SGD'}, {'dropout':0.15, 'lr': 0.01, 'loss': 3.5, 'optimizer': 'Adam'}, {'dropout':0.3, 'lr': 0.1, 'loss': 4.5, 'optimizer': 'Adam'}] hip.Experiment.from_iterable(data).display() EChartsHigh dimensional Interactive Plotting. Created by @andfanilo.from streamlit_echarts import st_echarts st_echarts(options=options) Streamlit FoliumStreamlit Component for rendering Folium maps. Created by @randyzwitch.m = folium.Map(location=[39.949610, -75.150282], zoom_start=16) st_data = st_folium(m, width=725) Spacy-StreamlitspaCy building blocks and visualizers for Streamlit apps. Created by @explosion.models = [""en_core_web_sm"", ""en_core_web_md""] spacy_streamlit.visualize(models, ""Sundar Pichai is the CEO of Google."") Streamlit AgraphA Streamlit Graph Vis, based on react-grah-vis. Created by @ChrisDelClea.from streamlit_agraph import agraph, Node, Edge, Config agraph(nodes=nodes, edges=edges, config=config) Streamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl(""https://assets5.lottiefiles.com/packages/lf20_V9t630.json"") st_lottie(lottie_hello, key=""hello"") Plotly EventsMake Plotly charts interactive!. Created by @null-jones.fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.chart += get_annotations_chart(annotations=[(""Mar 01, 2008"", ""Pretty good day for GOOG""), (""Dec 01, 2007"", ""Something's going wrong for GOOG & AAPL""), (""Nov 01, 2008"", ""Market starts again thanks to...""), (""Dec 01, 2009"", ""Small crash for GOOG after...""),],) st.altair_chart(chart, use_container_width=True) PlostA deceptively simple plotting library for Streamlit. Created by @tvst.import plost plost.line_chart(my_dataframe, x='time', y='stock_value', color='stock_name',) HiPlotHigh dimensional Interactive Plotting. Created by @facebookresearch.data = [{'dropout':0.1, 'lr': 0.001, 'loss': 10.0, 'optimizer': 'SGD'}, {'dropout':0.15, 'lr': 0.01, 'loss': 3.5, 'optimizer': 'Adam'}, {'dropout':0.3, 'lr': 0.1, 'loss': 4.5, 'optimizer': 'Adam'}] hip.Experiment.from_iterable(data).display() EChartsHigh dimensional Interactive Plotting. Created by @andfanilo.from streamlit_echarts import st_echarts st_echarts(options=options) Streamlit FoliumStreamlit Component for rendering Folium maps. Created by @randyzwitch.m = folium.Map(location=[39.949610, -75.150282], zoom_start=16) st_data = st_folium(m, width=725) Spacy-StreamlitspaCy building blocks and visualizers for Streamlit apps. Created by @explosion.models = [""en_core_web_sm"", ""en_core_web_md""] spacy_streamlit.visualize(models, ""Sundar Pichai is the CEO of Google."") Streamlit AgraphA Streamlit Graph Vis, based on react-grah-vis. Created by @ChrisDelClea.from streamlit_agraph import agraph, Node, Edge, Config agraph(nodes=nodes, edges=edges, config=config) Streamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl(""https://assets5.lottiefiles.com/packages/lf20_V9t630.json"") st_lottie(lottie_hello, key=""hello"") Plotly EventsMake Plotly charts interactive!. Created by @null-jones.fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.chart += get_annotations_chart(annotations=[(""Mar 01, 2008"", ""Pretty good day for GOOG""), (""Dec 01, 2007"", ""Something's going wrong for GOOG & AAPL""), (""Nov 01, 2008"", ""Market starts again thanks to...""), (""Dec 01, 2009"", ""Small crash for GOOG after...""),],) st.altair_chart(chart, use_container_width=True) Next Input widgets ButtonDisplay a button widget.clicked = st.button(""Click me"") Download buttonDisplay a download button widget.st.download_button(""Download file"", file) Form buttonDisplay a form submit button. For use with st.form.st.form_submit_button(""Sign up"") Link buttonDisplay a link button.st.link_button(""Go to gallery"", url) Page linkDisplay a link to another page in a multipage app.st.page_link(""app.py"", label=""Home"", icon=""🏠"") st.page_link(""pages/profile.py"", label=""My profile"") CheckboxDisplay a checkbox widget.selected = st.checkbox(""I agree"") Color pickerDisplay a color picker widget.color = st.color_picker(""Pick a color"") MultiselectDisplay a multiselect widget. The multiselect widget starts as empty.choices = st.multiselect(""Buy"", [""milk"", ""apples"", ""potatoes""]) RadioDisplay a radio button widget.choice = st.radio(""Pick one"", [""cats"", ""dogs""]) SelectboxDisplay a select widget.choice = st.selectbox(""Pick one"", [""cats"", ""dogs""]) Select-sliderDisplay a slider widget to select items from a list.size = st.select_slider(""Pick a size"", [""S"", ""M"", ""L""]) ToggleDisplay a toggle widget.activated = st.toggle(""Activate"") Number inputDisplay a numeric input widget.choice = st.number_input(""Pick a number"", 0, 10) SliderDisplay a slider widget.number = st.slider(""Pick a number"", 0, 100) Date inputDisplay a date input widget.date = st.date_input(""Your birthday"") Time inputDisplay a time input widget.time = st.time_input(""Meeting time"") Chat inputDisplay a chat input widget.prompt = st.chat_input(""Say something"") if prompt: st.write(f""The user has sent: {prompt}"") Text-areaDisplay a multi-line text input widget.text = st.text_area(""Text to translate"") Text inputDisplay a single-line text input widget.name = st.text_input(""First name"") Data editorDisplay a data editor widget.edited = st.experimental_data_editor(df, num_rows=""dynamic"") File UploaderDisplay a file uploader widget.data = st.file_uploader(""Upload a CSV"") Camera inputDisplay a widget that allows users to upload images directly from a camera.image = st.camera_input(""Take a picture"") Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration! PreviousStreamlit ChatStreamlit Component for a Chatbot UI. Created by @AI-Yash.from streamlit_chat import message message(""My message"") message(""Hello bot!"", is_user=True) # align's the message to the right Streamlit Option MenuSelect a single item from a list of options in a menu. Created by @victoryhb.from streamlit_option_menu import option_menu option_menu(""Main Menu"", [""Home"", 'Settings'], icons=['house', 'gear'], menu_icon=""cast"", default_index=1) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.stoggle import stoggle stoggle( ""Click me!"", """"""🥷 Surprise! Here's some additional content"""""",) Streamlit ElementsCreate a draggable and resizable dashboard in Streamlit. Created by @okls.from streamlit_elements import elements, mui, html with elements(""new_element""): mui.Typography(""Hello world"") TagsAdd tags to your Streamlit apps. Created by @gagan3012.from streamlit_tags import st_tags st_tags(label='# Enter Keywords:', text='Press enter to add more', value=['Zero', 'One', 'Two'], suggestions=['five', 'six', 'seven', 'eight', 'nine', 'three', 'eleven', 'ten', 'four'], maxtags = 4, key='1') StqdmThe simplest way to handle a progress bar in streamlit app. Created by @Wirg.from stqdm import stqdm for _ in stqdm(range(50)): sleep(0.5) TimelineDisplay a Timeline in Streamlit apps using TimelineJS. Created by @innerdoc.from streamlit_timeline import timeline with open('example.json', ""r"") as f: timeline(f.read(), height=800) Camera input liveAlternative for st.camera_input which returns the webcam images live. Created by @blackary.from camera_input_live import camera_input_live image = camera_input_live() st.image(value) Streamlit AceAce editor component for Streamlit. Created by @okld.from streamlit_ace import st_ace content = st_ace() content Streamlit ChatStreamlit Component for a Chatbot UI. Created by @AI-Yash.from streamlit_chat import message message(""My message"") message(""Hello bot!"", is_user=True) # align's the message to the right Streamlit Option MenuSelect a single item from a list of options in a menu. Created by @victoryhb.from streamlit_option_menu import option_menu option_menu(""Main Menu"", [""Home"", 'Settings'], icons=['house', 'gear'], menu_icon=""cast"", default_index=1) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.stoggle import stoggle stoggle( ""Click me!"", """"""🥷 Surprise! Here's some additional content"""""",) Streamlit ElementsCreate a draggable and resizable dashboard in Streamlit. Created by @okls.from streamlit_elements import elements, mui, html with elements(""new_element""): mui.Typography(""Hello world"") TagsAdd tags to your Streamlit apps. Created by @gagan3012.from streamlit_tags import st_tags st_tags(label='# Enter Keywords:', text='Press enter to add more', value=['Zero', 'One', 'Two'], suggestions=['five', 'six', 'seven', 'eight', 'nine', 'three', 'eleven', 'ten', 'four'], maxtags = 4, key='1') StqdmThe simplest way to handle a progress bar in streamlit app. Created by @Wirg.from stqdm import stqdm for _ in stqdm(range(50)): sleep(0.5) TimelineDisplay a Timeline in Streamlit apps using TimelineJS. Created by @innerdoc.from streamlit_timeline import timeline with open('example.json', ""r"") as f: timeline(f.read(), height=800) Camera input liveAlternative for st.camera_input which returns the webcam images live. Created by @blackary.from camera_input_live import camera_input_live image = camera_input_live() st.image(value) Streamlit AceAce editor component for Streamlit. Created by @okld.from streamlit_ace import st_ace content = st_ace() content Streamlit ChatStreamlit Component for a Chatbot UI. Created by @AI-Yash.from streamlit_chat import message message(""My message"") message(""Hello bot!"", is_user=True) # align's the message to the right Streamlit Option MenuSelect a single item from a list of options in a menu. Created by @victoryhb.from streamlit_option_menu import option_menu option_menu(""Main Menu"", [""Home"", 'Settings'], icons=['house', 'gear'], menu_icon=""cast"", default_index=1) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.stoggle import stoggle stoggle( ""Click me!"", """"""🥷 Surprise! Here's some additional content"""""",) Next Media elements ImageDisplay an image or list of images.st.image(numpy_array) st.image(image_bytes) st.image(file) st.image(""https://example.com/myimage.jpg"") AudioDisplay an audio player.st.audio(numpy_array) st.audio(audio_bytes) st.audio(file) st.audio(""https://example.com/myaudio.mp3"", format=""audio/mp3"") VideoDisplay a video player.st.video(numpy_array) st.video(video_bytes) st.video(file) st.video(""https://example.com/myvideo.mp4"", format=""video/mp4"") Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration! PreviousStreamlit CropperA simple image cropper for Streamlit. Created by @turner-anderson.from streamlit_cropper import st_cropper st_cropper(img, realtime_update=realtime_update, box_color=box_color, aspect_ratio=aspect_ratio) Image CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates streamlit_image_coordinates(""https://placekitten.com/200/300"") Streamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl(""https://assets5.lottiefiles.com/packages/lf20_V9t630.json"") st_lottie(lottie_hello, key=""hello"") Streamlit WebrtcHandling and transmitting real-time video/audio streams with Streamlit. Created by @whitphx.from streamlit_webrtc import webrtc_streamer webrtc_streamer(key=""sample"") Drawable CanvasProvides a sketching canvas using Fabric.js. Created by @andfanilo.from streamlit_drawable_canvas import st_canvas st_canvas(fill_color=""rgba(255, 165, 0, 0.3)"", stroke_width=stroke_width, stroke_color=stroke_color, background_color=bg_color, background_image=Image.open(bg_image) if bg_image else None, update_streamlit=realtime_update, height=150, drawing_mode=drawing_mode, point_display_radius=point_display_radius if drawing_mode == 'point' else 0, key=""canvas"",) Image ComparisonCompare images with a slider using JuxtaposeJS. Created by @fcakyon.from streamlit_image_comparison import image_comparison image_comparison(img1=""image1.jpg"", img2=""image2.jpg"",) Streamlit CropperA simple image cropper for Streamlit. Created by @turner-anderson.from streamlit_cropper import st_cropper st_cropper(img, realtime_update=realtime_update, box_color=box_color, aspect_ratio=aspect_ratio) Image CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates streamlit_image_coordinates(""https://placekitten.com/200/300"") Streamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl(""https://assets5.lottiefiles.com/packages/lf20_V9t630.json"") st_lottie(lottie_hello, key=""hello"") Streamlit WebrtcHandling and transmitting real-time video/audio streams with Streamlit. Created by @whitphx.from streamlit_webrtc import webrtc_streamer webrtc_streamer(key=""sample"") Drawable CanvasProvides a sketching canvas using Fabric.js. Created by @andfanilo.from streamlit_drawable_canvas import st_canvas st_canvas(fill_color=""rgba(255, 165, 0, 0.3)"", stroke_width=stroke_width, stroke_color=stroke_color, background_color=bg_color, background_image=Image.open(bg_image) if bg_image else None, update_streamlit=realtime_update, height=150, drawing_mode=drawing_mode, point_display_radius=point_display_radius if drawing_mode == 'point' else 0, key=""canvas"",) Image ComparisonCompare images with a slider using JuxtaposeJS. Created by @fcakyon.from streamlit_image_comparison import image_comparison image_comparison(img1=""image1.jpg"", img2=""image2.jpg"",) Streamlit CropperA simple image cropper for Streamlit. Created by @turner-anderson.from streamlit_cropper import st_cropper st_cropper(img, realtime_update=realtime_update, box_color=box_color, aspect_ratio=aspect_ratio) Image CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates streamlit_image_coordinates(""https://placekitten.com/200/300"") Streamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl(""https://assets5.lottiefiles.com/packages/lf20_V9t630.json"") st_lottie(lottie_hello, key=""hello"") Next Layouts and containers ColumnsInsert containers laid out as side-by-side columns.col1, col2 = st.columns(2) col1.write(""this is column 1"") col2.write(""this is column 2"") ContainerInsert a multi-element container.c = st.container() st.write(""This will show last"") c.write(""This will show first"") c.write(""This will show second"") Modal dialogsInsert a modal dialog that can rerun independently from the rest of the script.@st.experimental_dialog(""Sign up"") def email_form(): name = st.text_input(""Name"") email = st.text_input(""Email"") EmptyInsert a single-element container.c = st.empty() st.write(""This will show last"") c.write(""This will be replaced"") c.write(""This will show first"") ExpanderInsert a multi-element container that can be expanded/collapsed.with st.expander(""Open to see more""): st.write(""This is more content"") PopoverInsert a multi-element popover container that can be opened/closed.with st.popover(""Settings""): st.checkbox(""Show completed"") SidebarDisplay items in a sidebar.st.sidebar.write(""This lives in the sidebar"") st.sidebar.button(""Click me!"") TabsInsert containers separated into tabs.tab1, tab2 = st.tabs([""Tab 1"", ""Tab2""]) tab1.write(""this is tab 1"") tab2.write(""this is tab 2"") Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration!Streamlit ElementsCreate a draggable and resizable dashboard in Streamlit. Created by @okls.from streamlit_elements import elements, mui, html with elements(""new_element""): mui.Typography(""Hello world"") PydanticAuto-generate Streamlit UI from Pydantic Models and Dataclasses. Created by @lukasmasuch.import streamlit_pydantic as sp sp.pydantic_form(key=""my_form"", model=ExampleModel) Streamlit PagesAn experimental version of Streamlit Multi-Page Apps. Created by @blackary.from st_pages import Page, show_pages, add_page_title show_pages([ Page(""streamlit_app.py"", ""Home"", ""🏠""), Page(""other_pages/page2.py"", ""Page 2"", "":books:""), ]) Chat elements Streamlit provides a few commands to help you build conversational apps. These chat elements are designed to be used in conjunction with each other, but you can also use them separately. st.chat_message lets you insert a chat message container into the app so you can display messages from the user or the app. Chat containers can contain other Streamlit elements, including charts, tables, text, and more. st.chat_input lets you display a chat input widget so the user can type in a message. Chat inputDisplay a chat input widget.prompt = st.chat_input(""Say something"") if prompt: st.write(f""The user has sent: {prompt}"") Chat messageInsert a chat message container.import numpy as np with st.chat_message(""user""): st.write(""Hello 👋"") st.line_chart(np.random.randn(30, 3)) Status containerDisplay output of long-running tasks in a container.with st.status('Running'): do_something_slow() st.write_streamWrite generators or streams to the app with a typewriter effect.st.write_stream(my_generator) st.write_stream(my_llm_stream) Status elements Progress barDisplay a progress bar.for i in range(101): st.progress(i) do_something_slow() SpinnerTemporarily displays a message while executing a block of code.with st.spinner(""Please wait...""): do_something_slow() Status containerDisplay output of long-running tasks in a container.with st.status('Running'): do_something_slow() ToastBriefly displays a toast message in the bottom-right corner.st.toast('Butter!', icon='🧈') BalloonsDisplay celebratory balloons!do_something() # Celebrate when all done! st.balloons() SnowflakesDisplay celebratory snowflakes!do_something() # Celebrate when all done! st.snow() Success boxDisplay a success message.st.success(""Match found!"") Info boxDisplay an informational message.st.info(""Dataset is updated every day at midnight."") Warning boxDisplay warning message.st.warning(""Unable to fetch image. Skipping..."") Error boxDisplay error message.st.error(""We encountered an error"") Exception outputDisplay an exception.e = RuntimeError(""This is an exception of type RuntimeError"") st.exception(e) Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration!StqdmThe simplest way to handle a progress bar in streamlit app. Created by @Wirg.from stqdm import stqdm for _ in stqdm(range(50)): sleep(0.5) Custom notification boxA custom notification box with the ability to close it out. Created by @Socvest.from streamlit_custom_notification_box import custom_notification_box styles = {'material-icons':{'color': 'red'}, 'text-icon-link-close-container': {'box-shadow': '#3896de 0px 4px'}, 'notification-text': {'':''}, 'close-button':{'':''}, 'link':{'':''}} custom_notification_box(icon='info', textDisplay='We are almost done with your registration...', externalLink='more info', url='#', styles=styles, key=""foo"") Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.let_it_rain import rain rain(emoji=""🎈"", font_size=54, falling_speed=5, animation_length=""infinite"",) App logic and configuration Navigation and pages Switch pageProgrammatically navigates to a specified page.st.switch_page(""pages/my_page.py"") Page linkDisplay a link to another page in a multipage app.st.page_link(""app.py"", label=""Home"", icon=""🏠"") st.page_link(""pages/profile.py"", label=""My profile"") Execution flow Modal dialogsInsert a modal dialog that can rerun independently from the rest of the script.@st.experimental_dialog(""Sign up"") def email_form(): name = st.text_input(""Name"") email = st.text_input(""Email"") FormsCreate a form that batches elements together with a “Submit"" button.with st.form(key='my_form'): name = st.text_input(""Name"") email = st.text_input(""Email"") st.form_submit_button(""Sign up"") Partial rerunsDefine a fragment to rerun independently from the rest of the script.@st.experimental_fragment(run_every=""10s"") def fragment(): df = get_data() st.line_chart(df) Rerun scriptRerun the script immediately.st.rerun() Stop executionStops execution immediately.st.stop() Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration!AutorefreshForce a refresh without tying up a script. Created by @kmcgrady.from streamlit_autorefresh import st_autorefresh st_autorefresh(interval=2000, limit=100, key=""fizzbuzzcounter"") PydanticAuto-generate Streamlit UI from Pydantic Models and Dataclasses. Created by @lukasmasuch.import streamlit_pydantic as sp sp.pydantic_form(key=""my_form"", model=ExampleModel) Streamlit PagesAn experimental version of Streamlit Multi-Page Apps. Created by @blackary.from st_pages import Page, show_pages, add_page_title show_pages([ Page(""streamlit_app.py"", ""Home"", ""🏠""), Page(""other_pages/page2.py"", ""Page 2"", "":books:""), ]) Caching and state Cache dataFunction decorator to cache functions that return data (e.g. dataframe transforms, database queries, ML inference).@st.cache_data def long_function(param1, param2): # Perform expensive computation here or # fetch data from the web here return data Cache resourceFunction decorator to cache functions that return global resources (e.g. database connections, ML models).@st.cache_resource def init_model(): # Return a global resource here return pipeline( ""sentiment-analysis"", model=""distilbert-base-uncased-finetuned-sst-2-english"" ) Session stateSession state is a way to share variables between reruns, for each user session.st.session_state['key'] = value Query parametersGet, set, or clear the query parameters that are shown in the browser's URL bar.st.query_params[key] = value st.query_params.clear() Connections and databases Setup your connection Create a connectionConnect to a data source or APIconn = st.connection('pets_db', type='sql') pet_owners = conn.query('select * from pet_owners') st.dataframe(pet_owners) Built-in connections SnowflakeConnectionA connection to Snowflake.conn = st.connection('snowflake') SQLConnectionA connection to a SQL database using SQLAlchemy.conn = st.connection('sql') Build your own connections Connection base classBuild your own connection with BaseConnection.class MyConnection(BaseConnection[myconn.MyConnection]): def _connect(self, **kwargs) -> MyConnection: return myconn.connect(**self._secrets, **kwargs) def query(self, query): return self._instance.query(query) Secrets management Secrets singletonAccess secrets from a local TOML file.key = st.secrets[""OpenAI_key""] Secrets fileSave your secrets in a per-project or per-profile TOML file.OpenAI_key = """" Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration!AuthenticatorA secure authentication module to validate user credentials. Created by @mkhorasani.import streamlit_authenticator as stauth authenticator = stauth.Authenticate( config['credentials'], config['cookie']['name'], config['cookie']['key'], config['cookie']['expiry_days'], config['preauthorized']) WS localStorageA simple synchronous way of accessing localStorage from your app. Created by @gagangoku.from streamlit_ws_localstorage import injectWebsocketCode ret = conn.setLocalStorageVal(key='k1', val='v1') st.write('ret: ' + ret) Streamlit Auth0The fastest way to provide comprehensive login inside Streamlit. Created by @conradbez.from auth0_component import login_button user_info = login_button(clientId, domain = domain) st.write(user_info) Custom Components Declare a componentCreate and register a custom component.st.components.v1.declare_component( ""custom_slider"", ""/frontend"", ) HTMLDisplay an HTML string in an iframe.st.components.v1.html( ""

Foo bar.

"" ) iframeLoad a remote URL in an iframe.st.components.v1.iframe( ""docs.streamlit.io"" ) Utilities and user info User infost.experimental_user returns information about the logged-in user of private apps on Streamlit Community Cloud.if st.experimental_user.email == ""foo@corp.com"": st.write(""Welcome back, "", st.experimental_user.email) else: st.write(""You are not authorized to view this page."") Get helpDisplay object’s doc string, nicely formatted.st.help(st.write) st.help(pd.DataFrame) Render HTMLRenders HTML strings to your app.css = """""" """""" st.html(css) Configuration Configuration fileConfigures the default settings for your app.your-project/ ├── .streamlit/ │ └── config.toml └── your_app.py Set page title, favicon, and moreConfigures the default settings of the page.st.set_page_config( page_title=""My app"", page_icon="":shark:"", ) Developer tools App testing st.testing.v1.AppTestst.testing.v1.AppTest simulates a running Streamlit app for testing.from streamlit.testing.v1 import AppTest at = AppTest.from_file(""streamlit_app.py"") at.secrets[""WORD""] = ""Foobar"" at.run() assert not at.exception at.text_input(""word"").input(""Bazbat"").run() assert at.warning[0].value == ""Try again."" AppTest.from_filest.testing.v1.AppTest.from_file initializes a simulated app from a file.from streamlit.testing.v1 import AppTest at = AppTest.from_file(""streamlit_app.py"") at.run() AppTest.from_stringst.testing.v1.AppTest.from_string initializes a simulated app from a string.from streamlit.testing.v1 import AppTest at = AppTest.from_string(app_script_as_string) at.run() AppTest.from_functionst.testing.v1.AppTest.from_function initializes a simulated app from a function.from streamlit.testing.v1 import AppTest at = AppTest.from_function(app_script_as_callable) at.run() BlockA representation of container elements, including: st.chat_message st.columns st.sidebar st.tabs The main body of the app. # at.sidebar returns a Block at.sidebar.button[0].click().run() assert not at.exception ElementThe base class for representation of all elements, including: st.title st.header st.markdown st.dataframe # at.title returns a sequence of Title # Title inherits from Element assert at.title[0].value == ""My awesome app"" ButtonA representation of st.button and st.form_submit_button.at.button[0].click().run() ChatInputA representation of st.chat_input.at.chat_input[0].set_value(""What is Streamlit?"").run() CheckboxA representation of st.checkbox.at.checkbox[0].check().run() ColorPickerA representation of st.color_picker.at.color_picker[0].pick(""#FF4B4B"").run() DateInputA representation of st.date_input.release_date = datetime.date(2023, 10, 26) at.date_input[0].set_value(release_date).run() MultiselectA representation of st.multiselect.at.multiselect[0].select(""New York"").run() NumberInputA representation of st.number_input.at.number_input[0].increment().run() RadioA representation of st.radio.at.radio[0].set_value(""New York"").run() SelectSliderA representation of st.select_slider.at.select_slider[0].set_range(""A"",""C"").run() SelectboxA representation of st.selectbox.at.selectbox[0].select(""New York"").run() SliderA representation of st.slider.at.slider[0].set_range(2,5).run() TextAreaA representation of st.text_area.at.text_area[0].input(""Streamlit is awesome!"").run() TextInputA representation of st.text_input.at.text_input[0].input(""Streamlit"").run() TimeInputA representation of st.time_input.at.time_input[0].increment().run() ToggleA representation of st.toggle.at.toggle[0].set_value(""True"").run() Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration!Pandas ProfilingPandas profiling component for Streamlit. Created by @okld.df = pd.read_csv(""https://storage.googleapis.com/tf-datasets/titanic/train.csv"") pr = df.profile_report() st_profile_report(pr) Streamlit AceAce editor component for Streamlit. Created by @okld.from streamlit_ace import st_ace content = st_ace() content Streamlit AnalyticsTrack & visualize user interactions with your streamlit app. Created by @jrieke.import streamlit_analytics with streamlit_analytics.track(): st.text_input(""Write something"") Previous: ConceptsNext: Write and magicforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy" https://docs.streamlit.io/develop/concepts/design/buttons#show-a-temporary-message-with-a-button,"DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsremoveCOREArchitecture & executionaddMultipage appsaddApp designremoveAnimate & update elementsButton behavior and examplesDataframesUsing custom classesWorking with timezonesADDITIONALConnections and secretsaddCustom componentsaddConfiguration and themingaddApp testingaddAPI referenceaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Develop/Concepts/App design/Button behavior and examplesButton behavior and examples Summary Buttons created with st.button do not retain state. They return True on the script rerun resulting from their click and immediately return to False on the next script rerun. If a displayed element is nested inside if st.button('Click me'):, the element will be visible when the button is clicked and disappear as soon as the user takes their next action. This is because the script reruns and the button return value becomes False. In this guide, we will illustrate the use of buttons and explain common misconceptions. Read on to see a variety of examples that expand on st.button using st.session_state. Anti-patterns are included at the end. Go ahead and pull up your favorite code editor so you can streamlit run the examples as you read. Check out Streamlit's Basic concepts if you haven't run your own Streamlit scripts yet. When to use if st.button() When code is conditioned on a button's value, it will execute once in response to the button being clicked and not again (until the button is clicked again). Good to nest inside buttons: Transient messages that immediately disappear. Once-per-click processes that saves data to session state, a file, or a database. Bad to nest inside buttons: Displayed items that should persist as the user continues. Other widgets which cause the script to rerun when used. Processes that neither modify session state nor write to a file/database.* * This can be appropriate when disposable results are desired. If you have a ""Validate"" button, that could be a process conditioned directly on a button. It could be used to create an alert to say 'Valid' or 'Invalid' with no need to keep that info. Common logic with buttons Show a temporary message with a button If you want to give the user a quick button to check if an entry is valid, but not keep that check displayed as the user continues. In this example, a user can click a button to check if their animal string is in the animal_shelter list. When the user clicks ""Check availability"" they will see ""We have that animal!"" or ""We don't have that animal."" If they change the animal in st.text_input, the script reruns and the message disappears until they click ""Check availability"" again. import streamlit as st animal_shelter = ['cat', 'dog', 'rabbit', 'bird'] animal = st.text_input('Type an animal') if st.button('Check availability'): have_it = animal.lower() in animal_shelter 'We have that animal!' if have_it else 'We don\'t have that animal.' Note: The above example uses magic to render the message on the frontend. Stateful button If you want a clicked button to continue to be True, create a value in st.session_state and use the button to set that value to True in a callback. import streamlit as st if 'clicked' not in st.session_state: st.session_state.clicked = False def click_button(): st.session_state.clicked = True st.button('Click me', on_click=click_button) if st.session_state.clicked: # The message and nested widget will remain on the page st.write('Button clicked!') st.slider('Select a value') Toggle button If you want a button to work like a toggle switch, consider using st.checkbox. Otherwise, you can use a button with a callback function to reverse a boolean value saved in st.session_state. In this example, we use st.button to toggle another widget on and off. By displaying st.slider conditionally on a value in st.session_state, the user can interact with the slider without it disappearing. import streamlit as st if 'button' not in st.session_state: st.session_state.button = False def click_button(): st.session_state.button = not st.session_state.button st.button('Click me', on_click=click_button) if st.session_state.button: # The message and nested widget will remain on the page st.write('Button is on!') st.slider('Select a value') else: st.write('Button is off!') Alternatively, you can use the value in st.session_state on the slider's disabled parameter. import streamlit as st if 'button' not in st.session_state: st.session_state.button = False def click_button(): st.session_state.button = not st.session_state.button st.button('Click me', on_click=click_button) st.slider('Select a value', disabled=st.session_state.button) Buttons to continue or control stages of a process Another alternative to nesting content inside a button is to use a value in st.session_state that designates the ""step"" or ""stage"" of a process. In this example, we have four stages in our script: Before the user begins. User enters their name. User chooses a color. User gets a thank-you message. A button at the beginning advances the stage from 0 to 1. A button at the end resets the stage from 3 to 0. The other widgets used in stage 1 and 2 have callbacks to set the stage. If you have a process with dependant steps and want to keep previous stages visible, such a callback forces a user to retrace subsequent stages if they change an earlier widget. import streamlit as st if 'stage' not in st.session_state: st.session_state.stage = 0 def set_state(i): st.session_state.stage = i if st.session_state.stage == 0: st.button('Begin', on_click=set_state, args=[1]) if st.session_state.stage >= 1: name = st.text_input('Name', on_change=set_state, args=[2]) if st.session_state.stage >= 2: st.write(f'Hello {name}!') color = st.selectbox( 'Pick a Color', [None, 'red', 'orange', 'green', 'blue', 'violet'], on_change=set_state, args=[3] ) if color is None: set_state(2) if st.session_state.stage >= 3: st.write(f':{color}[Thank you!]') st.button('Start Over', on_click=set_state, args=[0]) Buttons to modify st.session_state If you modify st.session_state inside of a button, you must consider where that button is within the script. A slight problem In this example, we access st.session_state.name both before and after the buttons which modify it. When a button (""Jane"" or ""John"") is clicked, the script reruns. The info displayed before the buttons lags behind the info written after the button. The data in st.session_state before the button is not updated. When the script executes the button function, that is when the conditional code to update st.session_state creates the change. Thus, this change is reflected after the button. import streamlit as st import pandas as pd if 'name' not in st.session_state: st.session_state['name'] = 'John Doe' st.header(st.session_state['name']) if st.button('Jane'): st.session_state['name'] = 'Jane Doe' if st.button('John'): st.session_state['name'] = 'John Doe' st.header(st.session_state['name']) Logic used in a callback Callbacks are a clean way to modify st.session_state. Callbacks are executed as a prefix to the script rerunning, so the position of the button relative to accessing data is not important. import streamlit as st import pandas as pd if 'name' not in st.session_state: st.session_state['name'] = 'John Doe' def change_name(name): st.session_state['name'] = name st.header(st.session_state['name']) st.button('Jane', on_click=change_name, args=['Jane Doe']) st.button('John', on_click=change_name, args=['John Doe']) st.header(st.session_state['name']) Logic nested in a button with a rerun Although callbacks are often preferred to avoid extra reruns, our first 'John Doe'/'Jane Doe' example can be modified by adding st.rerun instead. If you need to acces data in st.session_state before the button that modifies it, you can include st.rerun to rerun the script after the change has been committed. This means the script will rerun twice when a button is clicked. import streamlit as st import pandas as pd if 'name' not in st.session_state: st.session_state['name'] = 'John Doe' st.header(st.session_state['name']) if st.button('Jane'): st.session_state['name'] = 'Jane Doe' st.rerun() if st.button('John'): st.session_state['name'] = 'John Doe' st.rerun() st.header(st.session_state['name']) Buttons to modify or reset other widgets When a button is used to modify or reset another widget, it is the same as the above examples to modify st.session_state. However, an extra consideration exists: you cannot modify a key-value pair in st.session_state if the widget with that key has already been rendered on the page for the current script run. priority_highImportantDon't do this!import streamlit as st st.text_input('Name', key='name') # These buttons will error because their nested code changes # a widget's state after that widget within the script. if st.button('Clear name'): st.session_state.name = '' if st.button('Streamlit!'): st.session_state.name = ('Streamlit') Option 1: Use a key for the button and put the logic before the widget If you assign a key to a button, you can condition code on a button's state by using its value in st.session_state. This means that logic depending on your button can be in your script before that button. In the following example, we use the .get() method on st.session_state because the keys for the buttons will not exist when the script runs for the first time. The .get() method will return False if it can't find the key. Otherwise, it will return the value of the key. import streamlit as st # Use the get method since the keys won't be in session_state # on the first script run if st.session_state.get('clear'): st.session_state['name'] = '' if st.session_state.get('streamlit'): st.session_state['name'] = 'Streamlit' st.text_input('Name', key='name') st.button('Clear name', key='clear') st.button('Streamlit!', key='streamlit') Option 2: Use a callback import streamlit as st st.text_input('Name', key='name') def set_name(name): st.session_state.name = name st.button('Clear name', on_click=set_name, args=['']) st.button('Streamlit!', on_click=set_name, args=['Streamlit']) Option 3: Use containers By using st.container you can have widgets appear in different orders in your script and frontend view (webpage). import streamlit as st begin = st.container() if st.button('Clear name'): st.session_state.name = '' if st.button('Streamlit!'): st.session_state.name = ('Streamlit') # The widget is second in logic, but first in display begin.text_input('Name', key='name') Buttons to add other widgets dynamically When dynamically adding widgets to the page, make sure to use an index to keep the keys unique and avoid a DuplicateWidgetID error. In this example, we define a function display_input_row which renders a row of widgets. That function accepts an index as a parameter. The widgets rendered by display_input_row use index within their keys so that dispaly_input_row can be executed multiple times on a single script rerun without repeating any widget keys. import streamlit as st def display_input_row(index): left, middle, right = st.columns(3) left.text_input('First', key=f'first_{index}') middle.text_input('Middle', key=f'middle_{index}') right.text_input('Last', key=f'last_{index}') if 'rows' not in st.session_state: st.session_state['rows'] = 0 def increase_rows(): st.session_state['rows'] += 1 st.button('Add person', on_click=increase_rows) for i in range(st.session_state['rows']): display_input_row(i) # Show the results st.subheader('People') for i in range(st.session_state['rows']): st.write( f'Person {i+1}:', st.session_state[f'first_{i}'], st.session_state[f'middle_{i}'], st.session_state[f'last_{i}'] ) Buttons to handle expensive or file-writing processes When you have expensive processes, set them to run upon clicking a button and save the results into st.session_state. This allows you to keep accessing the results of the process without re-executing it unnecessarily. This is especially helpful for processes that save to disk or write to a database. In this example, we have an expensive_process that depends on two parameters: option and add. Functionally, add changes the output, but option does not—option is there to provide a parameter import streamlit as st import pandas as pd import time def expensive_process(option, add): with st.spinner('Processing...'): time.sleep(5) df = pd.DataFrame({'A': [1, 2, 3], 'B': [4, 5, 6], 'C':[7, 8, 9]}) + add return (df, add) cols = st.columns(2) option = cols[0].selectbox('Select a number', options=['1', '2', '3']) add = cols[1].number_input('Add a number', min_value=0, max_value=10) if 'processed' not in st.session_state: st.session_state.processed = {} # Process and save results if st.button('Process'): result = expensive_process(option, add) st.session_state.processed[option] = result if option in st.session_state.processed: st.write(f'Option {option} processed with add {add}') st.write(st.session_state.processed[option][0]) Astute observers may think, ""This feels a little like caching."" We are only saving results relative to one parameter, but the pattern could easily be expanded to save results relative to both parameters. In that sense, yes, it has some similarities to caching, but also some important differences. When you save results in st.session_state, the results are only available to the current user in their current session. If you use st.cache_data instead, the results are available to all users across all sessions. Furthermore, if you want to update a saved result, you have to clear all saved results for that function to do so. Anti-patterns Here are some simplified examples of how buttons can go wrong. Be on the lookout for these common mistakes. Buttons nested inside buttons import streamlit as st if st.button('Button 1'): st.write('Button 1 was clicked') if st.button('Button 2'): # This will never be executed. st.write('Button 2 was clicked') Other widgets nested inside buttons import streamlit as st if st.button('Sign up'): name = st.text_input('Name') if name: # This will never be executed. st.success(f'Welcome {name}') Nesting a process inside a button without saving to session state import streamlit as st import pandas as pd file = st.file_uploader(""Upload a file"", type=""csv"") if st.button('Get data'): df = pd.read_csv(file) # This display will go away with the user's next action. st.write(df) if st.button('Save'): # This will always error. df.to_csv('data.csv') Previous: Animate & update elementsNext: DataframesforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy" https://docs.streamlit.io/knowledge-base/deploy/invoking-python-subprocess-deployed-streamlit-app#invoking-a-python-subprocess-in-a-deployed-streamlit-app,"DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Knowledge base/Deployment issues/Invoking a Python subprocess in a deployed Streamlit appInvoking a Python subprocess in a deployed Streamlit app Problem Let's suppose you want to invoke a subprocess to run a Python script script.py in your deployed Streamlit app streamlit_app.py. For example, the machine learning library Ludwig is run using a command-line interface, or maybe you want to run a bash script or similar type of process from Python. You have tried the following, but run into dependency issues for script.py, even though you have specified your Python dependencies in a requirements file: # streamlit_app.py import streamlit as st import subprocess subprocess.run([""python"", ""script.py""]) Solution When you run the above code block, you will get the version of Python that is on the system path—not necessarily the Python executable installed in the virtual environment that the Streamlit code is running under. The solution is to detect the Python executable directly with sys.executable: # streamlit_app.py import streamlit as st import subprocess import sys subprocess.run([f""{sys.executable}"", ""script.py""]) This ensures that script.py is running under the same Python executable as your Streamlit code—where your Python dependencies are installed. Relevant links https://stackoverflow.com/questions/69947867/run-portion-of-python-code-in-parallel-from-a-streamlit-app/69948545#69948545 https://discuss.streamlit.io/t/modulenotfounderror-no-module-named-cv2-streamlit/18319/3?u=snehankekre https://docs.python.org/3/library/sys.html#sys.executable Previous: How do I increase the upload limit of st.file_uploader on Streamlit Community Cloud?Next: Organizing your apps with workspaces on Streamlit Community CloudforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy" https://docs.streamlit.io/get-started/fundamentals/additional-features#custom-components,"DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsremoveBasic conceptsAdvanced conceptsAdditional featuresSummaryFirst stepsaddcodeDevelopConceptsaddAPI referenceaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Get started/Fundamentals/Additional featuresAdditional Streamlit features So you've read all about Streamlit's Basic concepts and gotten a taste of caching and Session State in Advanced concepts. But what about the bells and whistles? Here's a quick look at some extra features to take your app to the next level. Theming Streamlit supports Light and Dark themes out of the box. Streamlit will first check if the user viewing an app has a Light or Dark mode preference set by their operating system and browser. If so, then that preference will be used. Otherwise, the Light theme is applied by default. You can also change the active theme from ""⋮"" → ""Settings"". Want to add your own theme to an app? The ""Settings"" menu has a theme editor accessible by clicking on ""Edit active theme"". You can use this editor to try out different colors and see your app update live. When you're happy with your work, themes can be saved by setting config options in the [theme] config section. After you've defined a theme for your app, it will appear as ""Custom Theme"" in the theme selector and will be applied by default instead of the included Light and Dark themes. More information about the options available when defining a theme can be found in the theme option documentation. push_pinNoteThe theme editor menu is available only in local development. If you've deployed your app using Streamlit Community Cloud, the ""Edit active theme"" button will no longer be displayed in the ""Settings"" menu. starTipAnother way to experiment with different theme colors is to turn on the ""Run on save"" option, edit your config.toml file, and watch as your app reruns with the new theme colors applied. Pages As apps grow large, it becomes useful to organize them into multiple pages. This makes the app easier to manage as a developer and easier to navigate as a user. Streamlit provides a frictionless way to create multipage apps. We designed this feature so that building a multipage app is as easy as building a single-page app! Just add more pages to an existing app as follows: In the folder containing your main script, create a new pages folder. Let’s say your main script is named main_page.py. Add new .py files in the pages folder to add more pages to your app. Run streamlit run main_page.py as usual. That’s it! The main_page.py script will now correspond to the main page of your app. And you’ll see the other scripts from the pages folder in the sidebar page selector. The pages are listed according to filename (without file extensions and disregarding underscores). For example: main_page.pyimport streamlit as st st.markdown(""# Main page 🎈"") st.sidebar.markdown(""# Main page 🎈"") pages/page_2.pyimport streamlit as st st.markdown(""# Page 2 ❄️"") st.sidebar.markdown(""# Page 2 ❄️"") pages/page_3.pyimport streamlit as st st.markdown(""# Page 3 🎉"") st.sidebar.markdown(""# Page 3 🎉"") Now run streamlit run main_page.py and view your shiny new multipage app! Our documentation on Multipage apps teaches you how to add pages to your app, including how to define pages, structure and run multipage apps, and navigate between pages. Once you understand the basics, create your first multipage app! Custom components If you can't find the right component within the Streamlit library, try out custom components to extend Streamlit's built-in functionality. Explore and browse through popular, community-created components in the Components gallery. If you dabble in frontend development, you can build your own custom component with Streamlit's components API. Static file serving As you learned in Streamlit fundamentals, Streamlit runs a server that clients connect to. That means viewers of your app don't have direct access to the files which are local to your app. Most of the time, this doesn't matter because Streamlt commands handle that for you. When you use st.image() your Streamlit server will access the file and handle the necessary hosting so your app viewers can see it. However, if you want a direct URL to an image or file you'll need to host it. This requires setting the correct configuration and placing your hosted files in a directory named static. For example, your project could look like: your-project/ ├── static/ │ └── my_hosted-image.png └── streamlit_app.py To learn more, read our guide on Static file serving. App testing Good development hygeine includes testing your code. Automated testing allows you to write higher quality code, faster! Streamlit has a built-in testing framework that let's you build tests easily. Use your favorite testing framework to run your tests. We like pytest. When you test a Streamlit app, you simulate running the app, declare user input, and inspect the results. You can use GitHub workflows to automate your tests and get instant alerts about breaking changes. Learn more in our guide to App testing.Previous: Advanced conceptsNext: SummaryforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy" https://docs.streamlit.io/en/0.72.0/api.html#chat-elements,"DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceremovePAGE ELEMENTSWrite and magicaddText elementsaddData elementsaddChart elementsaddInput widgetsaddMedia elementsaddLayouts and containersaddChat elementsaddStatus elementsaddThird-party componentsopen_in_newAPPLICATION LOGICNavigation and pagesaddExecution flowaddCaching and stateaddConnections and secretsaddCustom componentsaddUtilitiesaddConfigurationaddTOOLSApp testingaddCommand lineaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Develop/API referenceAPI reference Streamlit makes it easy for you to visualize, mutate, and share data. The API reference is organized by activity type, like displaying data or optimizing performance. Each section includes methods associated with the activity type, including examples. Browse our API below and click to learn more about any of our available commands! 🎈 Display almost anything Write and magic st.writeWrite arguments to the app.st.write(""Hello **world**!"") st.write(my_data_frame) st.write(my_mpl_figure) st.write_streamWrite generators or streams to the app with a typewriter effect.st.write_stream(my_generator) st.write_stream(my_llm_stream) MagicAny time Streamlit sees either a variable or literal value on its own line, it automatically writes that to your app using st.write""Hello **world**!"" my_data_frame my_mpl_figure Text elements MarkdownDisplay string formatted as Markdown.st.markdown(""Hello **world**!"") TitleDisplay text in title formatting.st.title(""The app title"") HeaderDisplay text in header formatting.st.header(""This is a header"") SubheaderDisplay text in subheader formatting.st.subheader(""This is a subheader"") CaptionDisplay text in small font.st.caption(""This is written small caption text"") Code blockDisplay a code block with optional syntax highlighting.st.code(""a = 1234"") EchoDisplay some code in the app, then execute it. Useful for tutorials.with st.echo(): st.write('This code will be printed') LaTeXDisplay mathematical expressions formatted as LaTeX.st.latex(""\int a x^2 \,dx"") Preformatted textWrite fixed-width and preformatted text.st.text(""Hello world"") DividerDisplay a horizontal rule.st.divider() Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration! PreviousTagsAdd tags to your Streamlit apps. Created by @gagan3012.st_tags(label='# Enter Keywords:', text='Press enter to add more', value=['Zero', 'One', 'Two'], suggestions=['five', 'six', 'seven', 'eight', 'nine', 'three', 'eleven', 'ten', 'four'], maxtags = 4, key='1') NLUApply text mining on a dataframe. Created by @JohnSnowLabs.nlu.load('sentiment').predict('I love NLU! <3') Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.mention(label=""An awesome Streamlit App"", icon=""streamlit"", url=""https://extras.streamlit.app"",) Annotated textDisplay annotated text in Streamlit apps. Created by @tvst.annotated_text(""This "", (""is"", ""verb""), "" some "", (""annotated"", ""adj""), (""text"", ""noun""), "" for those of "", (""you"", ""pronoun""), "" who "", (""like"", ""verb""), "" this sort of "", (""thing"", ""noun""), ""."") Drawable CanvasProvides a sketching canvas using Fabric.js. Created by @andfanilo.st_canvas(fill_color=""rgba(255, 165, 0, 0.3)"", stroke_width=stroke_width, stroke_color=stroke_color, background_color=bg_color, background_image=Image.open(bg_image) if bg_image else None, update_streamlit=realtime_update, height=150, drawing_mode=drawing_mode, point_display_radius=point_display_radius if drawing_mode == 'point' else 0, key=""canvas"",) TagsAdd tags to your Streamlit apps. Created by @gagan3012.st_tags(label='# Enter Keywords:', text='Press enter to add more', value=['Zero', 'One', 'Two'], suggestions=['five', 'six', 'seven', 'eight', 'nine', 'three', 'eleven', 'ten', 'four'], maxtags = 4, key='1') NLUApply text mining on a dataframe. Created by @JohnSnowLabs.nlu.load('sentiment').predict('I love NLU! <3') Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.mention(label=""An awesome Streamlit App"", icon=""streamlit"", url=""https://extras.streamlit.app"",) Annotated textDisplay annotated text in Streamlit apps. Created by @tvst.annotated_text(""This "", (""is"", ""verb""), "" some "", (""annotated"", ""adj""), (""text"", ""noun""), "" for those of "", (""you"", ""pronoun""), "" who "", (""like"", ""verb""), "" this sort of "", (""thing"", ""noun""), ""."") Drawable CanvasProvides a sketching canvas using Fabric.js. Created by @andfanilo.st_canvas(fill_color=""rgba(255, 165, 0, 0.3)"", stroke_width=stroke_width, stroke_color=stroke_color, background_color=bg_color, background_image=Image.open(bg_image) if bg_image else None, update_streamlit=realtime_update, height=150, drawing_mode=drawing_mode, point_display_radius=point_display_radius if drawing_mode == 'point' else 0, key=""canvas"",) TagsAdd tags to your Streamlit apps. Created by @gagan3012.st_tags(label='# Enter Keywords:', text='Press enter to add more', value=['Zero', 'One', 'Two'], suggestions=['five', 'six', 'seven', 'eight', 'nine', 'three', 'eleven', 'ten', 'four'], maxtags = 4, key='1') NLUApply text mining on a dataframe. Created by @JohnSnowLabs.nlu.load('sentiment').predict('I love NLU! <3') Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.mention(label=""An awesome Streamlit App"", icon=""streamlit"", url=""https://extras.streamlit.app"",) Next Data elements DataframesDisplay a dataframe as an interactive table.st.dataframe(my_data_frame) Data editorDisplay a data editor widget.edited = st.data_editor(df, num_rows=""dynamic"") Column configurationConfigure the display and editing behavior of dataframes and data editors.st.column_config.NumberColumn(""Price (in USD)"", min_value=0, format=""$%d"") Static tablesDisplay a static table.st.table(my_data_frame) MetricsDisplay a metric in big bold font, with an optional indicator of how the metric changed.st.metric(""My metric"", 42, 2) Dicts and JSONDisplay object or string as a pretty-printed JSON string.st.json(my_dict) Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration! PreviousImage CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates value = streamlit_image_coordinates(""https://placekitten.com/200/300"") st.write(value) Plotly EventsMake Plotly charts interactive!. Created by @null-jones.from streamlit_plotly_events import plotly_events fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.metric_cards import style_metric_cards col3.metric(label=""No Change"", value=5000, delta=0) style_metric_cards() Streamlit AggridImplementation of Ag-Grid component for Streamlit. Created by @PablocFonseca.df = pd.DataFrame({'col1': [1, 2, 3], 'col2': [4, 5, 6]}) grid_return = AgGrid(df, editable=True) new_df = grid_return['data'] Streamlit FoliumStreamlit Component for rendering Folium maps. Created by @randyzwitch.m = folium.Map(location=[39.949610, -75.150282], zoom_start=16) folium.Marker([39.949610, -75.150282], popup=""Liberty Bell"", tooltip=""Liberty Bell"").add_to(m) st_data = st_folium(m, width=725) Pandas ProfilingPandas profiling component for Streamlit. Created by @okld.df = pd.read_csv(""https://storage.googleapis.com/tf-datasets/titanic/train.csv"") pr = df.profile_report() st_profile_report(pr) Image CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates value = streamlit_image_coordinates(""https://placekitten.com/200/300"") st.write(value) Plotly EventsMake Plotly charts interactive!. Created by @null-jones.from streamlit_plotly_events import plotly_events fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.metric_cards import style_metric_cards col3.metric(label=""No Change"", value=5000, delta=0) style_metric_cards() Streamlit AggridImplementation of Ag-Grid component for Streamlit. Created by @PablocFonseca.df = pd.DataFrame({'col1': [1, 2, 3], 'col2': [4, 5, 6]}) grid_return = AgGrid(df, editable=True) new_df = grid_return['data'] Streamlit FoliumStreamlit Component for rendering Folium maps. Created by @randyzwitch.m = folium.Map(location=[39.949610, -75.150282], zoom_start=16) folium.Marker([39.949610, -75.150282], popup=""Liberty Bell"", tooltip=""Liberty Bell"").add_to(m) st_data = st_folium(m, width=725) Pandas ProfilingPandas profiling component for Streamlit. Created by @okld.df = pd.read_csv(""https://storage.googleapis.com/tf-datasets/titanic/train.csv"") pr = df.profile_report() st_profile_report(pr) Image CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates value = streamlit_image_coordinates(""https://placekitten.com/200/300"") st.write(value) Plotly EventsMake Plotly charts interactive!. Created by @null-jones.from streamlit_plotly_events import plotly_events fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.metric_cards import style_metric_cards col3.metric(label=""No Change"", value=5000, delta=0) style_metric_cards() Next Chart elements Simple area chartsDisplay an area chart.st.area_chart(my_data_frame) Simple bar chartsDisplay a bar chart.st.bar_chart(my_data_frame) Simple line chartsDisplay a line chart.st.line_chart(my_data_frame) Simple scatter chartsDisplay a line chart.st.scatter_chart(my_data_frame) Scatterplots on mapsDisplay a map with points on it.st.map(my_data_frame) MatplotlibDisplay a matplotlib.pyplot figure.st.pyplot(my_mpl_figure) AltairDisplay a chart using the Altair library.st.altair_chart(my_altair_chart) Vega-LiteDisplay a chart using the Vega-Lite library.st.vega_lite_chart(my_vega_lite_chart) PlotlyDisplay an interactive Plotly chart.st.plotly_chart(my_plotly_chart) BokehDisplay an interactive Bokeh chart.st.bokeh_chart(my_bokeh_chart) PyDeckDisplay a chart using the PyDeck library.st.pydeck_chart(my_pydeck_chart) GraphVizDisplay a graph using the dagre-d3 library.st.graphviz_chart(my_graphviz_spec) Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration! PreviousStreamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl(""https://assets5.lottiefiles.com/packages/lf20_V9t630.json"") st_lottie(lottie_hello, key=""hello"") Plotly EventsMake Plotly charts interactive!. Created by @null-jones.fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.chart += get_annotations_chart(annotations=[(""Mar 01, 2008"", ""Pretty good day for GOOG""), (""Dec 01, 2007"", ""Something's going wrong for GOOG & AAPL""), (""Nov 01, 2008"", ""Market starts again thanks to...""), (""Dec 01, 2009"", ""Small crash for GOOG after...""),],) st.altair_chart(chart, use_container_width=True) PlostA deceptively simple plotting library for Streamlit. Created by @tvst.import plost plost.line_chart(my_dataframe, x='time', y='stock_value', color='stock_name',) HiPlotHigh dimensional Interactive Plotting. Created by @facebookresearch.data = [{'dropout':0.1, 'lr': 0.001, 'loss': 10.0, 'optimizer': 'SGD'}, {'dropout':0.15, 'lr': 0.01, 'loss': 3.5, 'optimizer': 'Adam'}, {'dropout':0.3, 'lr': 0.1, 'loss': 4.5, 'optimizer': 'Adam'}] hip.Experiment.from_iterable(data).display() EChartsHigh dimensional Interactive Plotting. Created by @andfanilo.from streamlit_echarts import st_echarts st_echarts(options=options) Streamlit FoliumStreamlit Component for rendering Folium maps. Created by @randyzwitch.m = folium.Map(location=[39.949610, -75.150282], zoom_start=16) st_data = st_folium(m, width=725) Spacy-StreamlitspaCy building blocks and visualizers for Streamlit apps. Created by @explosion.models = [""en_core_web_sm"", ""en_core_web_md""] spacy_streamlit.visualize(models, ""Sundar Pichai is the CEO of Google."") Streamlit AgraphA Streamlit Graph Vis, based on react-grah-vis. Created by @ChrisDelClea.from streamlit_agraph import agraph, Node, Edge, Config agraph(nodes=nodes, edges=edges, config=config) Streamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl(""https://assets5.lottiefiles.com/packages/lf20_V9t630.json"") st_lottie(lottie_hello, key=""hello"") Plotly EventsMake Plotly charts interactive!. Created by @null-jones.fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.chart += get_annotations_chart(annotations=[(""Mar 01, 2008"", ""Pretty good day for GOOG""), (""Dec 01, 2007"", ""Something's going wrong for GOOG & AAPL""), (""Nov 01, 2008"", ""Market starts again thanks to...""), (""Dec 01, 2009"", ""Small crash for GOOG after...""),],) st.altair_chart(chart, use_container_width=True) PlostA deceptively simple plotting library for Streamlit. Created by @tvst.import plost plost.line_chart(my_dataframe, x='time', y='stock_value', color='stock_name',) HiPlotHigh dimensional Interactive Plotting. Created by @facebookresearch.data = [{'dropout':0.1, 'lr': 0.001, 'loss': 10.0, 'optimizer': 'SGD'}, {'dropout':0.15, 'lr': 0.01, 'loss': 3.5, 'optimizer': 'Adam'}, {'dropout':0.3, 'lr': 0.1, 'loss': 4.5, 'optimizer': 'Adam'}] hip.Experiment.from_iterable(data).display() EChartsHigh dimensional Interactive Plotting. Created by @andfanilo.from streamlit_echarts import st_echarts st_echarts(options=options) Streamlit FoliumStreamlit Component for rendering Folium maps. Created by @randyzwitch.m = folium.Map(location=[39.949610, -75.150282], zoom_start=16) st_data = st_folium(m, width=725) Spacy-StreamlitspaCy building blocks and visualizers for Streamlit apps. Created by @explosion.models = [""en_core_web_sm"", ""en_core_web_md""] spacy_streamlit.visualize(models, ""Sundar Pichai is the CEO of Google."") Streamlit AgraphA Streamlit Graph Vis, based on react-grah-vis. Created by @ChrisDelClea.from streamlit_agraph import agraph, Node, Edge, Config agraph(nodes=nodes, edges=edges, config=config) Streamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl(""https://assets5.lottiefiles.com/packages/lf20_V9t630.json"") st_lottie(lottie_hello, key=""hello"") Plotly EventsMake Plotly charts interactive!. Created by @null-jones.fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.chart += get_annotations_chart(annotations=[(""Mar 01, 2008"", ""Pretty good day for GOOG""), (""Dec 01, 2007"", ""Something's going wrong for GOOG & AAPL""), (""Nov 01, 2008"", ""Market starts again thanks to...""), (""Dec 01, 2009"", ""Small crash for GOOG after...""),],) st.altair_chart(chart, use_container_width=True) Next Input widgets ButtonDisplay a button widget.clicked = st.button(""Click me"") Download buttonDisplay a download button widget.st.download_button(""Download file"", file) Form buttonDisplay a form submit button. For use with st.form.st.form_submit_button(""Sign up"") Link buttonDisplay a link button.st.link_button(""Go to gallery"", url) Page linkDisplay a link to another page in a multipage app.st.page_link(""app.py"", label=""Home"", icon=""🏠"") st.page_link(""pages/profile.py"", label=""My profile"") CheckboxDisplay a checkbox widget.selected = st.checkbox(""I agree"") Color pickerDisplay a color picker widget.color = st.color_picker(""Pick a color"") MultiselectDisplay a multiselect widget. The multiselect widget starts as empty.choices = st.multiselect(""Buy"", [""milk"", ""apples"", ""potatoes""]) RadioDisplay a radio button widget.choice = st.radio(""Pick one"", [""cats"", ""dogs""]) SelectboxDisplay a select widget.choice = st.selectbox(""Pick one"", [""cats"", ""dogs""]) Select-sliderDisplay a slider widget to select items from a list.size = st.select_slider(""Pick a size"", [""S"", ""M"", ""L""]) ToggleDisplay a toggle widget.activated = st.toggle(""Activate"") Number inputDisplay a numeric input widget.choice = st.number_input(""Pick a number"", 0, 10) SliderDisplay a slider widget.number = st.slider(""Pick a number"", 0, 100) Date inputDisplay a date input widget.date = st.date_input(""Your birthday"") Time inputDisplay a time input widget.time = st.time_input(""Meeting time"") Chat inputDisplay a chat input widget.prompt = st.chat_input(""Say something"") if prompt: st.write(f""The user has sent: {prompt}"") Text-areaDisplay a multi-line text input widget.text = st.text_area(""Text to translate"") Text inputDisplay a single-line text input widget.name = st.text_input(""First name"") Data editorDisplay a data editor widget.edited = st.experimental_data_editor(df, num_rows=""dynamic"") File UploaderDisplay a file uploader widget.data = st.file_uploader(""Upload a CSV"") Camera inputDisplay a widget that allows users to upload images directly from a camera.image = st.camera_input(""Take a picture"") Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration! PreviousStreamlit ChatStreamlit Component for a Chatbot UI. Created by @AI-Yash.from streamlit_chat import message message(""My message"") message(""Hello bot!"", is_user=True) # align's the message to the right Streamlit Option MenuSelect a single item from a list of options in a menu. Created by @victoryhb.from streamlit_option_menu import option_menu option_menu(""Main Menu"", [""Home"", 'Settings'], icons=['house', 'gear'], menu_icon=""cast"", default_index=1) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.stoggle import stoggle stoggle( ""Click me!"", """"""🥷 Surprise! Here's some additional content"""""",) Streamlit ElementsCreate a draggable and resizable dashboard in Streamlit. Created by @okls.from streamlit_elements import elements, mui, html with elements(""new_element""): mui.Typography(""Hello world"") TagsAdd tags to your Streamlit apps. Created by @gagan3012.from streamlit_tags import st_tags st_tags(label='# Enter Keywords:', text='Press enter to add more', value=['Zero', 'One', 'Two'], suggestions=['five', 'six', 'seven', 'eight', 'nine', 'three', 'eleven', 'ten', 'four'], maxtags = 4, key='1') StqdmThe simplest way to handle a progress bar in streamlit app. Created by @Wirg.from stqdm import stqdm for _ in stqdm(range(50)): sleep(0.5) TimelineDisplay a Timeline in Streamlit apps using TimelineJS. Created by @innerdoc.from streamlit_timeline import timeline with open('example.json', ""r"") as f: timeline(f.read(), height=800) Camera input liveAlternative for st.camera_input which returns the webcam images live. Created by @blackary.from camera_input_live import camera_input_live image = camera_input_live() st.image(value) Streamlit AceAce editor component for Streamlit. Created by @okld.from streamlit_ace import st_ace content = st_ace() content Streamlit ChatStreamlit Component for a Chatbot UI. Created by @AI-Yash.from streamlit_chat import message message(""My message"") message(""Hello bot!"", is_user=True) # align's the message to the right Streamlit Option MenuSelect a single item from a list of options in a menu. Created by @victoryhb.from streamlit_option_menu import option_menu option_menu(""Main Menu"", [""Home"", 'Settings'], icons=['house', 'gear'], menu_icon=""cast"", default_index=1) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.stoggle import stoggle stoggle( ""Click me!"", """"""🥷 Surprise! Here's some additional content"""""",) Streamlit ElementsCreate a draggable and resizable dashboard in Streamlit. Created by @okls.from streamlit_elements import elements, mui, html with elements(""new_element""): mui.Typography(""Hello world"") TagsAdd tags to your Streamlit apps. Created by @gagan3012.from streamlit_tags import st_tags st_tags(label='# Enter Keywords:', text='Press enter to add more', value=['Zero', 'One', 'Two'], suggestions=['five', 'six', 'seven', 'eight', 'nine', 'three', 'eleven', 'ten', 'four'], maxtags = 4, key='1') StqdmThe simplest way to handle a progress bar in streamlit app. Created by @Wirg.from stqdm import stqdm for _ in stqdm(range(50)): sleep(0.5) TimelineDisplay a Timeline in Streamlit apps using TimelineJS. Created by @innerdoc.from streamlit_timeline import timeline with open('example.json', ""r"") as f: timeline(f.read(), height=800) Camera input liveAlternative for st.camera_input which returns the webcam images live. Created by @blackary.from camera_input_live import camera_input_live image = camera_input_live() st.image(value) Streamlit AceAce editor component for Streamlit. Created by @okld.from streamlit_ace import st_ace content = st_ace() content Streamlit ChatStreamlit Component for a Chatbot UI. Created by @AI-Yash.from streamlit_chat import message message(""My message"") message(""Hello bot!"", is_user=True) # align's the message to the right Streamlit Option MenuSelect a single item from a list of options in a menu. Created by @victoryhb.from streamlit_option_menu import option_menu option_menu(""Main Menu"", [""Home"", 'Settings'], icons=['house', 'gear'], menu_icon=""cast"", default_index=1) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.stoggle import stoggle stoggle( ""Click me!"", """"""🥷 Surprise! Here's some additional content"""""",) Next Media elements ImageDisplay an image or list of images.st.image(numpy_array) st.image(image_bytes) st.image(file) st.image(""https://example.com/myimage.jpg"") AudioDisplay an audio player.st.audio(numpy_array) st.audio(audio_bytes) st.audio(file) st.audio(""https://example.com/myaudio.mp3"", format=""audio/mp3"") VideoDisplay a video player.st.video(numpy_array) st.video(video_bytes) st.video(file) st.video(""https://example.com/myvideo.mp4"", format=""video/mp4"") Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration! PreviousStreamlit CropperA simple image cropper for Streamlit. Created by @turner-anderson.from streamlit_cropper import st_cropper st_cropper(img, realtime_update=realtime_update, box_color=box_color, aspect_ratio=aspect_ratio) Image CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates streamlit_image_coordinates(""https://placekitten.com/200/300"") Streamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl(""https://assets5.lottiefiles.com/packages/lf20_V9t630.json"") st_lottie(lottie_hello, key=""hello"") Streamlit WebrtcHandling and transmitting real-time video/audio streams with Streamlit. Created by @whitphx.from streamlit_webrtc import webrtc_streamer webrtc_streamer(key=""sample"") Drawable CanvasProvides a sketching canvas using Fabric.js. Created by @andfanilo.from streamlit_drawable_canvas import st_canvas st_canvas(fill_color=""rgba(255, 165, 0, 0.3)"", stroke_width=stroke_width, stroke_color=stroke_color, background_color=bg_color, background_image=Image.open(bg_image) if bg_image else None, update_streamlit=realtime_update, height=150, drawing_mode=drawing_mode, point_display_radius=point_display_radius if drawing_mode == 'point' else 0, key=""canvas"",) Image ComparisonCompare images with a slider using JuxtaposeJS. Created by @fcakyon.from streamlit_image_comparison import image_comparison image_comparison(img1=""image1.jpg"", img2=""image2.jpg"",) Streamlit CropperA simple image cropper for Streamlit. Created by @turner-anderson.from streamlit_cropper import st_cropper st_cropper(img, realtime_update=realtime_update, box_color=box_color, aspect_ratio=aspect_ratio) Image CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates streamlit_image_coordinates(""https://placekitten.com/200/300"") Streamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl(""https://assets5.lottiefiles.com/packages/lf20_V9t630.json"") st_lottie(lottie_hello, key=""hello"") Streamlit WebrtcHandling and transmitting real-time video/audio streams with Streamlit. Created by @whitphx.from streamlit_webrtc import webrtc_streamer webrtc_streamer(key=""sample"") Drawable CanvasProvides a sketching canvas using Fabric.js. Created by @andfanilo.from streamlit_drawable_canvas import st_canvas st_canvas(fill_color=""rgba(255, 165, 0, 0.3)"", stroke_width=stroke_width, stroke_color=stroke_color, background_color=bg_color, background_image=Image.open(bg_image) if bg_image else None, update_streamlit=realtime_update, height=150, drawing_mode=drawing_mode, point_display_radius=point_display_radius if drawing_mode == 'point' else 0, key=""canvas"",) Image ComparisonCompare images with a slider using JuxtaposeJS. Created by @fcakyon.from streamlit_image_comparison import image_comparison image_comparison(img1=""image1.jpg"", img2=""image2.jpg"",) Streamlit CropperA simple image cropper for Streamlit. Created by @turner-anderson.from streamlit_cropper import st_cropper st_cropper(img, realtime_update=realtime_update, box_color=box_color, aspect_ratio=aspect_ratio) Image CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates streamlit_image_coordinates(""https://placekitten.com/200/300"") Streamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl(""https://assets5.lottiefiles.com/packages/lf20_V9t630.json"") st_lottie(lottie_hello, key=""hello"") Next Layouts and containers ColumnsInsert containers laid out as side-by-side columns.col1, col2 = st.columns(2) col1.write(""this is column 1"") col2.write(""this is column 2"") ContainerInsert a multi-element container.c = st.container() st.write(""This will show last"") c.write(""This will show first"") c.write(""This will show second"") Modal dialogsInsert a modal dialog that can rerun independently from the rest of the script.@st.experimental_dialog(""Sign up"") def email_form(): name = st.text_input(""Name"") email = st.text_input(""Email"") EmptyInsert a single-element container.c = st.empty() st.write(""This will show last"") c.write(""This will be replaced"") c.write(""This will show first"") ExpanderInsert a multi-element container that can be expanded/collapsed.with st.expander(""Open to see more""): st.write(""This is more content"") PopoverInsert a multi-element popover container that can be opened/closed.with st.popover(""Settings""): st.checkbox(""Show completed"") SidebarDisplay items in a sidebar.st.sidebar.write(""This lives in the sidebar"") st.sidebar.button(""Click me!"") TabsInsert containers separated into tabs.tab1, tab2 = st.tabs([""Tab 1"", ""Tab2""]) tab1.write(""this is tab 1"") tab2.write(""this is tab 2"") Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration!Streamlit ElementsCreate a draggable and resizable dashboard in Streamlit. Created by @okls.from streamlit_elements import elements, mui, html with elements(""new_element""): mui.Typography(""Hello world"") PydanticAuto-generate Streamlit UI from Pydantic Models and Dataclasses. Created by @lukasmasuch.import streamlit_pydantic as sp sp.pydantic_form(key=""my_form"", model=ExampleModel) Streamlit PagesAn experimental version of Streamlit Multi-Page Apps. Created by @blackary.from st_pages import Page, show_pages, add_page_title show_pages([ Page(""streamlit_app.py"", ""Home"", ""🏠""), Page(""other_pages/page2.py"", ""Page 2"", "":books:""), ]) Chat elements Streamlit provides a few commands to help you build conversational apps. These chat elements are designed to be used in conjunction with each other, but you can also use them separately. st.chat_message lets you insert a chat message container into the app so you can display messages from the user or the app. Chat containers can contain other Streamlit elements, including charts, tables, text, and more. st.chat_input lets you display a chat input widget so the user can type in a message. Chat inputDisplay a chat input widget.prompt = st.chat_input(""Say something"") if prompt: st.write(f""The user has sent: {prompt}"") Chat messageInsert a chat message container.import numpy as np with st.chat_message(""user""): st.write(""Hello 👋"") st.line_chart(np.random.randn(30, 3)) Status containerDisplay output of long-running tasks in a container.with st.status('Running'): do_something_slow() st.write_streamWrite generators or streams to the app with a typewriter effect.st.write_stream(my_generator) st.write_stream(my_llm_stream) Status elements Progress barDisplay a progress bar.for i in range(101): st.progress(i) do_something_slow() SpinnerTemporarily displays a message while executing a block of code.with st.spinner(""Please wait...""): do_something_slow() Status containerDisplay output of long-running tasks in a container.with st.status('Running'): do_something_slow() ToastBriefly displays a toast message in the bottom-right corner.st.toast('Butter!', icon='🧈') BalloonsDisplay celebratory balloons!do_something() # Celebrate when all done! st.balloons() SnowflakesDisplay celebratory snowflakes!do_something() # Celebrate when all done! st.snow() Success boxDisplay a success message.st.success(""Match found!"") Info boxDisplay an informational message.st.info(""Dataset is updated every day at midnight."") Warning boxDisplay warning message.st.warning(""Unable to fetch image. Skipping..."") Error boxDisplay error message.st.error(""We encountered an error"") Exception outputDisplay an exception.e = RuntimeError(""This is an exception of type RuntimeError"") st.exception(e) Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration!StqdmThe simplest way to handle a progress bar in streamlit app. Created by @Wirg.from stqdm import stqdm for _ in stqdm(range(50)): sleep(0.5) Custom notification boxA custom notification box with the ability to close it out. Created by @Socvest.from streamlit_custom_notification_box import custom_notification_box styles = {'material-icons':{'color': 'red'}, 'text-icon-link-close-container': {'box-shadow': '#3896de 0px 4px'}, 'notification-text': {'':''}, 'close-button':{'':''}, 'link':{'':''}} custom_notification_box(icon='info', textDisplay='We are almost done with your registration...', externalLink='more info', url='#', styles=styles, key=""foo"") Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.let_it_rain import rain rain(emoji=""🎈"", font_size=54, falling_speed=5, animation_length=""infinite"",) App logic and configuration Navigation and pages Switch pageProgrammatically navigates to a specified page.st.switch_page(""pages/my_page.py"") Page linkDisplay a link to another page in a multipage app.st.page_link(""app.py"", label=""Home"", icon=""🏠"") st.page_link(""pages/profile.py"", label=""My profile"") Execution flow Modal dialogsInsert a modal dialog that can rerun independently from the rest of the script.@st.experimental_dialog(""Sign up"") def email_form(): name = st.text_input(""Name"") email = st.text_input(""Email"") FormsCreate a form that batches elements together with a “Submit"" button.with st.form(key='my_form'): name = st.text_input(""Name"") email = st.text_input(""Email"") st.form_submit_button(""Sign up"") Partial rerunsDefine a fragment to rerun independently from the rest of the script.@st.experimental_fragment(run_every=""10s"") def fragment(): df = get_data() st.line_chart(df) Rerun scriptRerun the script immediately.st.rerun() Stop executionStops execution immediately.st.stop() Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration!AutorefreshForce a refresh without tying up a script. Created by @kmcgrady.from streamlit_autorefresh import st_autorefresh st_autorefresh(interval=2000, limit=100, key=""fizzbuzzcounter"") PydanticAuto-generate Streamlit UI from Pydantic Models and Dataclasses. Created by @lukasmasuch.import streamlit_pydantic as sp sp.pydantic_form(key=""my_form"", model=ExampleModel) Streamlit PagesAn experimental version of Streamlit Multi-Page Apps. Created by @blackary.from st_pages import Page, show_pages, add_page_title show_pages([ Page(""streamlit_app.py"", ""Home"", ""🏠""), Page(""other_pages/page2.py"", ""Page 2"", "":books:""), ]) Caching and state Cache dataFunction decorator to cache functions that return data (e.g. dataframe transforms, database queries, ML inference).@st.cache_data def long_function(param1, param2): # Perform expensive computation here or # fetch data from the web here return data Cache resourceFunction decorator to cache functions that return global resources (e.g. database connections, ML models).@st.cache_resource def init_model(): # Return a global resource here return pipeline( ""sentiment-analysis"", model=""distilbert-base-uncased-finetuned-sst-2-english"" ) Session stateSession state is a way to share variables between reruns, for each user session.st.session_state['key'] = value Query parametersGet, set, or clear the query parameters that are shown in the browser's URL bar.st.query_params[key] = value st.query_params.clear() Connections and databases Setup your connection Create a connectionConnect to a data source or APIconn = st.connection('pets_db', type='sql') pet_owners = conn.query('select * from pet_owners') st.dataframe(pet_owners) Built-in connections SnowflakeConnectionA connection to Snowflake.conn = st.connection('snowflake') SQLConnectionA connection to a SQL database using SQLAlchemy.conn = st.connection('sql') Build your own connections Connection base classBuild your own connection with BaseConnection.class MyConnection(BaseConnection[myconn.MyConnection]): def _connect(self, **kwargs) -> MyConnection: return myconn.connect(**self._secrets, **kwargs) def query(self, query): return self._instance.query(query) Secrets management Secrets singletonAccess secrets from a local TOML file.key = st.secrets[""OpenAI_key""] Secrets fileSave your secrets in a per-project or per-profile TOML file.OpenAI_key = """" Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration!AuthenticatorA secure authentication module to validate user credentials. Created by @mkhorasani.import streamlit_authenticator as stauth authenticator = stauth.Authenticate( config['credentials'], config['cookie']['name'], config['cookie']['key'], config['cookie']['expiry_days'], config['preauthorized']) WS localStorageA simple synchronous way of accessing localStorage from your app. Created by @gagangoku.from streamlit_ws_localstorage import injectWebsocketCode ret = conn.setLocalStorageVal(key='k1', val='v1') st.write('ret: ' + ret) Streamlit Auth0The fastest way to provide comprehensive login inside Streamlit. Created by @conradbez.from auth0_component import login_button user_info = login_button(clientId, domain = domain) st.write(user_info) Custom Components Declare a componentCreate and register a custom component.st.components.v1.declare_component( ""custom_slider"", ""/frontend"", ) HTMLDisplay an HTML string in an iframe.st.components.v1.html( ""

Foo bar.

"" ) iframeLoad a remote URL in an iframe.st.components.v1.iframe( ""docs.streamlit.io"" ) Utilities and user info User infost.experimental_user returns information about the logged-in user of private apps on Streamlit Community Cloud.if st.experimental_user.email == ""foo@corp.com"": st.write(""Welcome back, "", st.experimental_user.email) else: st.write(""You are not authorized to view this page."") Get helpDisplay object’s doc string, nicely formatted.st.help(st.write) st.help(pd.DataFrame) Render HTMLRenders HTML strings to your app.css = """""" """""" st.html(css) Configuration Configuration fileConfigures the default settings for your app.your-project/ ├── .streamlit/ │ └── config.toml └── your_app.py Set page title, favicon, and moreConfigures the default settings of the page.st.set_page_config( page_title=""My app"", page_icon="":shark:"", ) Developer tools App testing st.testing.v1.AppTestst.testing.v1.AppTest simulates a running Streamlit app for testing.from streamlit.testing.v1 import AppTest at = AppTest.from_file(""streamlit_app.py"") at.secrets[""WORD""] = ""Foobar"" at.run() assert not at.exception at.text_input(""word"").input(""Bazbat"").run() assert at.warning[0].value == ""Try again."" AppTest.from_filest.testing.v1.AppTest.from_file initializes a simulated app from a file.from streamlit.testing.v1 import AppTest at = AppTest.from_file(""streamlit_app.py"") at.run() AppTest.from_stringst.testing.v1.AppTest.from_string initializes a simulated app from a string.from streamlit.testing.v1 import AppTest at = AppTest.from_string(app_script_as_string) at.run() AppTest.from_functionst.testing.v1.AppTest.from_function initializes a simulated app from a function.from streamlit.testing.v1 import AppTest at = AppTest.from_function(app_script_as_callable) at.run() BlockA representation of container elements, including: st.chat_message st.columns st.sidebar st.tabs The main body of the app. # at.sidebar returns a Block at.sidebar.button[0].click().run() assert not at.exception ElementThe base class for representation of all elements, including: st.title st.header st.markdown st.dataframe # at.title returns a sequence of Title # Title inherits from Element assert at.title[0].value == ""My awesome app"" ButtonA representation of st.button and st.form_submit_button.at.button[0].click().run() ChatInputA representation of st.chat_input.at.chat_input[0].set_value(""What is Streamlit?"").run() CheckboxA representation of st.checkbox.at.checkbox[0].check().run() ColorPickerA representation of st.color_picker.at.color_picker[0].pick(""#FF4B4B"").run() DateInputA representation of st.date_input.release_date = datetime.date(2023, 10, 26) at.date_input[0].set_value(release_date).run() MultiselectA representation of st.multiselect.at.multiselect[0].select(""New York"").run() NumberInputA representation of st.number_input.at.number_input[0].increment().run() RadioA representation of st.radio.at.radio[0].set_value(""New York"").run() SelectSliderA representation of st.select_slider.at.select_slider[0].set_range(""A"",""C"").run() SelectboxA representation of st.selectbox.at.selectbox[0].select(""New York"").run() SliderA representation of st.slider.at.slider[0].set_range(2,5).run() TextAreaA representation of st.text_area.at.text_area[0].input(""Streamlit is awesome!"").run() TextInputA representation of st.text_input.at.text_input[0].input(""Streamlit"").run() TimeInputA representation of st.time_input.at.time_input[0].increment().run() ToggleA representation of st.toggle.at.toggle[0].set_value(""True"").run() Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration!Pandas ProfilingPandas profiling component for Streamlit. Created by @okld.df = pd.read_csv(""https://storage.googleapis.com/tf-datasets/titanic/train.csv"") pr = df.profile_report() st_profile_report(pr) Streamlit AceAce editor component for Streamlit. Created by @okld.from streamlit_ace import st_ace content = st_ace() content Streamlit AnalyticsTrack & visualize user interactions with your streamlit app. Created by @jrieke.import streamlit_analytics with streamlit_analytics.track(): st.text_input(""Write something"") Previous: ConceptsNext: Write and magicforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy" https://docs.streamlit.io/en/0.75.0/api.html#utilities-and-user-info,"DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceremovePAGE ELEMENTSWrite and magicaddText elementsaddData elementsaddChart elementsaddInput widgetsaddMedia elementsaddLayouts and containersaddChat elementsaddStatus elementsaddThird-party componentsopen_in_newAPPLICATION LOGICNavigation and pagesaddExecution flowaddCaching and stateaddConnections and secretsaddCustom componentsaddUtilitiesaddConfigurationaddTOOLSApp testingaddCommand lineaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Develop/API referenceAPI reference Streamlit makes it easy for you to visualize, mutate, and share data. The API reference is organized by activity type, like displaying data or optimizing performance. Each section includes methods associated with the activity type, including examples. Browse our API below and click to learn more about any of our available commands! 🎈 Display almost anything Write and magic st.writeWrite arguments to the app.st.write(""Hello **world**!"") st.write(my_data_frame) st.write(my_mpl_figure) st.write_streamWrite generators or streams to the app with a typewriter effect.st.write_stream(my_generator) st.write_stream(my_llm_stream) MagicAny time Streamlit sees either a variable or literal value on its own line, it automatically writes that to your app using st.write""Hello **world**!"" my_data_frame my_mpl_figure Text elements MarkdownDisplay string formatted as Markdown.st.markdown(""Hello **world**!"") TitleDisplay text in title formatting.st.title(""The app title"") HeaderDisplay text in header formatting.st.header(""This is a header"") SubheaderDisplay text in subheader formatting.st.subheader(""This is a subheader"") CaptionDisplay text in small font.st.caption(""This is written small caption text"") Code blockDisplay a code block with optional syntax highlighting.st.code(""a = 1234"") EchoDisplay some code in the app, then execute it. Useful for tutorials.with st.echo(): st.write('This code will be printed') LaTeXDisplay mathematical expressions formatted as LaTeX.st.latex(""\int a x^2 \,dx"") Preformatted textWrite fixed-width and preformatted text.st.text(""Hello world"") DividerDisplay a horizontal rule.st.divider() Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration! PreviousTagsAdd tags to your Streamlit apps. Created by @gagan3012.st_tags(label='# Enter Keywords:', text='Press enter to add more', value=['Zero', 'One', 'Two'], suggestions=['five', 'six', 'seven', 'eight', 'nine', 'three', 'eleven', 'ten', 'four'], maxtags = 4, key='1') NLUApply text mining on a dataframe. Created by @JohnSnowLabs.nlu.load('sentiment').predict('I love NLU! <3') Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.mention(label=""An awesome Streamlit App"", icon=""streamlit"", url=""https://extras.streamlit.app"",) Annotated textDisplay annotated text in Streamlit apps. Created by @tvst.annotated_text(""This "", (""is"", ""verb""), "" some "", (""annotated"", ""adj""), (""text"", ""noun""), "" for those of "", (""you"", ""pronoun""), "" who "", (""like"", ""verb""), "" this sort of "", (""thing"", ""noun""), ""."") Drawable CanvasProvides a sketching canvas using Fabric.js. Created by @andfanilo.st_canvas(fill_color=""rgba(255, 165, 0, 0.3)"", stroke_width=stroke_width, stroke_color=stroke_color, background_color=bg_color, background_image=Image.open(bg_image) if bg_image else None, update_streamlit=realtime_update, height=150, drawing_mode=drawing_mode, point_display_radius=point_display_radius if drawing_mode == 'point' else 0, key=""canvas"",) TagsAdd tags to your Streamlit apps. Created by @gagan3012.st_tags(label='# Enter Keywords:', text='Press enter to add more', value=['Zero', 'One', 'Two'], suggestions=['five', 'six', 'seven', 'eight', 'nine', 'three', 'eleven', 'ten', 'four'], maxtags = 4, key='1') NLUApply text mining on a dataframe. Created by @JohnSnowLabs.nlu.load('sentiment').predict('I love NLU! <3') Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.mention(label=""An awesome Streamlit App"", icon=""streamlit"", url=""https://extras.streamlit.app"",) Annotated textDisplay annotated text in Streamlit apps. Created by @tvst.annotated_text(""This "", (""is"", ""verb""), "" some "", (""annotated"", ""adj""), (""text"", ""noun""), "" for those of "", (""you"", ""pronoun""), "" who "", (""like"", ""verb""), "" this sort of "", (""thing"", ""noun""), ""."") Drawable CanvasProvides a sketching canvas using Fabric.js. Created by @andfanilo.st_canvas(fill_color=""rgba(255, 165, 0, 0.3)"", stroke_width=stroke_width, stroke_color=stroke_color, background_color=bg_color, background_image=Image.open(bg_image) if bg_image else None, update_streamlit=realtime_update, height=150, drawing_mode=drawing_mode, point_display_radius=point_display_radius if drawing_mode == 'point' else 0, key=""canvas"",) TagsAdd tags to your Streamlit apps. Created by @gagan3012.st_tags(label='# Enter Keywords:', text='Press enter to add more', value=['Zero', 'One', 'Two'], suggestions=['five', 'six', 'seven', 'eight', 'nine', 'three', 'eleven', 'ten', 'four'], maxtags = 4, key='1') NLUApply text mining on a dataframe. Created by @JohnSnowLabs.nlu.load('sentiment').predict('I love NLU! <3') Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.mention(label=""An awesome Streamlit App"", icon=""streamlit"", url=""https://extras.streamlit.app"",) Next Data elements DataframesDisplay a dataframe as an interactive table.st.dataframe(my_data_frame) Data editorDisplay a data editor widget.edited = st.data_editor(df, num_rows=""dynamic"") Column configurationConfigure the display and editing behavior of dataframes and data editors.st.column_config.NumberColumn(""Price (in USD)"", min_value=0, format=""$%d"") Static tablesDisplay a static table.st.table(my_data_frame) MetricsDisplay a metric in big bold font, with an optional indicator of how the metric changed.st.metric(""My metric"", 42, 2) Dicts and JSONDisplay object or string as a pretty-printed JSON string.st.json(my_dict) Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration! PreviousImage CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates value = streamlit_image_coordinates(""https://placekitten.com/200/300"") st.write(value) Plotly EventsMake Plotly charts interactive!. Created by @null-jones.from streamlit_plotly_events import plotly_events fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.metric_cards import style_metric_cards col3.metric(label=""No Change"", value=5000, delta=0) style_metric_cards() Streamlit AggridImplementation of Ag-Grid component for Streamlit. Created by @PablocFonseca.df = pd.DataFrame({'col1': [1, 2, 3], 'col2': [4, 5, 6]}) grid_return = AgGrid(df, editable=True) new_df = grid_return['data'] Streamlit FoliumStreamlit Component for rendering Folium maps. Created by @randyzwitch.m = folium.Map(location=[39.949610, -75.150282], zoom_start=16) folium.Marker([39.949610, -75.150282], popup=""Liberty Bell"", tooltip=""Liberty Bell"").add_to(m) st_data = st_folium(m, width=725) Pandas ProfilingPandas profiling component for Streamlit. Created by @okld.df = pd.read_csv(""https://storage.googleapis.com/tf-datasets/titanic/train.csv"") pr = df.profile_report() st_profile_report(pr) Image CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates value = streamlit_image_coordinates(""https://placekitten.com/200/300"") st.write(value) Plotly EventsMake Plotly charts interactive!. Created by @null-jones.from streamlit_plotly_events import plotly_events fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.metric_cards import style_metric_cards col3.metric(label=""No Change"", value=5000, delta=0) style_metric_cards() Streamlit AggridImplementation of Ag-Grid component for Streamlit. Created by @PablocFonseca.df = pd.DataFrame({'col1': [1, 2, 3], 'col2': [4, 5, 6]}) grid_return = AgGrid(df, editable=True) new_df = grid_return['data'] Streamlit FoliumStreamlit Component for rendering Folium maps. Created by @randyzwitch.m = folium.Map(location=[39.949610, -75.150282], zoom_start=16) folium.Marker([39.949610, -75.150282], popup=""Liberty Bell"", tooltip=""Liberty Bell"").add_to(m) st_data = st_folium(m, width=725) Pandas ProfilingPandas profiling component for Streamlit. Created by @okld.df = pd.read_csv(""https://storage.googleapis.com/tf-datasets/titanic/train.csv"") pr = df.profile_report() st_profile_report(pr) Image CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates value = streamlit_image_coordinates(""https://placekitten.com/200/300"") st.write(value) Plotly EventsMake Plotly charts interactive!. Created by @null-jones.from streamlit_plotly_events import plotly_events fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.metric_cards import style_metric_cards col3.metric(label=""No Change"", value=5000, delta=0) style_metric_cards() Next Chart elements Simple area chartsDisplay an area chart.st.area_chart(my_data_frame) Simple bar chartsDisplay a bar chart.st.bar_chart(my_data_frame) Simple line chartsDisplay a line chart.st.line_chart(my_data_frame) Simple scatter chartsDisplay a line chart.st.scatter_chart(my_data_frame) Scatterplots on mapsDisplay a map with points on it.st.map(my_data_frame) MatplotlibDisplay a matplotlib.pyplot figure.st.pyplot(my_mpl_figure) AltairDisplay a chart using the Altair library.st.altair_chart(my_altair_chart) Vega-LiteDisplay a chart using the Vega-Lite library.st.vega_lite_chart(my_vega_lite_chart) PlotlyDisplay an interactive Plotly chart.st.plotly_chart(my_plotly_chart) BokehDisplay an interactive Bokeh chart.st.bokeh_chart(my_bokeh_chart) PyDeckDisplay a chart using the PyDeck library.st.pydeck_chart(my_pydeck_chart) GraphVizDisplay a graph using the dagre-d3 library.st.graphviz_chart(my_graphviz_spec) Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration! PreviousStreamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl(""https://assets5.lottiefiles.com/packages/lf20_V9t630.json"") st_lottie(lottie_hello, key=""hello"") Plotly EventsMake Plotly charts interactive!. Created by @null-jones.fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.chart += get_annotations_chart(annotations=[(""Mar 01, 2008"", ""Pretty good day for GOOG""), (""Dec 01, 2007"", ""Something's going wrong for GOOG & AAPL""), (""Nov 01, 2008"", ""Market starts again thanks to...""), (""Dec 01, 2009"", ""Small crash for GOOG after...""),],) st.altair_chart(chart, use_container_width=True) PlostA deceptively simple plotting library for Streamlit. Created by @tvst.import plost plost.line_chart(my_dataframe, x='time', y='stock_value', color='stock_name',) HiPlotHigh dimensional Interactive Plotting. Created by @facebookresearch.data = [{'dropout':0.1, 'lr': 0.001, 'loss': 10.0, 'optimizer': 'SGD'}, {'dropout':0.15, 'lr': 0.01, 'loss': 3.5, 'optimizer': 'Adam'}, {'dropout':0.3, 'lr': 0.1, 'loss': 4.5, 'optimizer': 'Adam'}] hip.Experiment.from_iterable(data).display() EChartsHigh dimensional Interactive Plotting. Created by @andfanilo.from streamlit_echarts import st_echarts st_echarts(options=options) Streamlit FoliumStreamlit Component for rendering Folium maps. Created by @randyzwitch.m = folium.Map(location=[39.949610, -75.150282], zoom_start=16) st_data = st_folium(m, width=725) Spacy-StreamlitspaCy building blocks and visualizers for Streamlit apps. Created by @explosion.models = [""en_core_web_sm"", ""en_core_web_md""] spacy_streamlit.visualize(models, ""Sundar Pichai is the CEO of Google."") Streamlit AgraphA Streamlit Graph Vis, based on react-grah-vis. Created by @ChrisDelClea.from streamlit_agraph import agraph, Node, Edge, Config agraph(nodes=nodes, edges=edges, config=config) Streamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl(""https://assets5.lottiefiles.com/packages/lf20_V9t630.json"") st_lottie(lottie_hello, key=""hello"") Plotly EventsMake Plotly charts interactive!. Created by @null-jones.fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.chart += get_annotations_chart(annotations=[(""Mar 01, 2008"", ""Pretty good day for GOOG""), (""Dec 01, 2007"", ""Something's going wrong for GOOG & AAPL""), (""Nov 01, 2008"", ""Market starts again thanks to...""), (""Dec 01, 2009"", ""Small crash for GOOG after...""),],) st.altair_chart(chart, use_container_width=True) PlostA deceptively simple plotting library for Streamlit. Created by @tvst.import plost plost.line_chart(my_dataframe, x='time', y='stock_value', color='stock_name',) HiPlotHigh dimensional Interactive Plotting. Created by @facebookresearch.data = [{'dropout':0.1, 'lr': 0.001, 'loss': 10.0, 'optimizer': 'SGD'}, {'dropout':0.15, 'lr': 0.01, 'loss': 3.5, 'optimizer': 'Adam'}, {'dropout':0.3, 'lr': 0.1, 'loss': 4.5, 'optimizer': 'Adam'}] hip.Experiment.from_iterable(data).display() EChartsHigh dimensional Interactive Plotting. Created by @andfanilo.from streamlit_echarts import st_echarts st_echarts(options=options) Streamlit FoliumStreamlit Component for rendering Folium maps. Created by @randyzwitch.m = folium.Map(location=[39.949610, -75.150282], zoom_start=16) st_data = st_folium(m, width=725) Spacy-StreamlitspaCy building blocks and visualizers for Streamlit apps. Created by @explosion.models = [""en_core_web_sm"", ""en_core_web_md""] spacy_streamlit.visualize(models, ""Sundar Pichai is the CEO of Google."") Streamlit AgraphA Streamlit Graph Vis, based on react-grah-vis. Created by @ChrisDelClea.from streamlit_agraph import agraph, Node, Edge, Config agraph(nodes=nodes, edges=edges, config=config) Streamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl(""https://assets5.lottiefiles.com/packages/lf20_V9t630.json"") st_lottie(lottie_hello, key=""hello"") Plotly EventsMake Plotly charts interactive!. Created by @null-jones.fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.chart += get_annotations_chart(annotations=[(""Mar 01, 2008"", ""Pretty good day for GOOG""), (""Dec 01, 2007"", ""Something's going wrong for GOOG & AAPL""), (""Nov 01, 2008"", ""Market starts again thanks to...""), (""Dec 01, 2009"", ""Small crash for GOOG after...""),],) st.altair_chart(chart, use_container_width=True) Next Input widgets ButtonDisplay a button widget.clicked = st.button(""Click me"") Download buttonDisplay a download button widget.st.download_button(""Download file"", file) Form buttonDisplay a form submit button. For use with st.form.st.form_submit_button(""Sign up"") Link buttonDisplay a link button.st.link_button(""Go to gallery"", url) Page linkDisplay a link to another page in a multipage app.st.page_link(""app.py"", label=""Home"", icon=""🏠"") st.page_link(""pages/profile.py"", label=""My profile"") CheckboxDisplay a checkbox widget.selected = st.checkbox(""I agree"") Color pickerDisplay a color picker widget.color = st.color_picker(""Pick a color"") MultiselectDisplay a multiselect widget. The multiselect widget starts as empty.choices = st.multiselect(""Buy"", [""milk"", ""apples"", ""potatoes""]) RadioDisplay a radio button widget.choice = st.radio(""Pick one"", [""cats"", ""dogs""]) SelectboxDisplay a select widget.choice = st.selectbox(""Pick one"", [""cats"", ""dogs""]) Select-sliderDisplay a slider widget to select items from a list.size = st.select_slider(""Pick a size"", [""S"", ""M"", ""L""]) ToggleDisplay a toggle widget.activated = st.toggle(""Activate"") Number inputDisplay a numeric input widget.choice = st.number_input(""Pick a number"", 0, 10) SliderDisplay a slider widget.number = st.slider(""Pick a number"", 0, 100) Date inputDisplay a date input widget.date = st.date_input(""Your birthday"") Time inputDisplay a time input widget.time = st.time_input(""Meeting time"") Chat inputDisplay a chat input widget.prompt = st.chat_input(""Say something"") if prompt: st.write(f""The user has sent: {prompt}"") Text-areaDisplay a multi-line text input widget.text = st.text_area(""Text to translate"") Text inputDisplay a single-line text input widget.name = st.text_input(""First name"") Data editorDisplay a data editor widget.edited = st.experimental_data_editor(df, num_rows=""dynamic"") File UploaderDisplay a file uploader widget.data = st.file_uploader(""Upload a CSV"") Camera inputDisplay a widget that allows users to upload images directly from a camera.image = st.camera_input(""Take a picture"") Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration! PreviousStreamlit ChatStreamlit Component for a Chatbot UI. Created by @AI-Yash.from streamlit_chat import message message(""My message"") message(""Hello bot!"", is_user=True) # align's the message to the right Streamlit Option MenuSelect a single item from a list of options in a menu. Created by @victoryhb.from streamlit_option_menu import option_menu option_menu(""Main Menu"", [""Home"", 'Settings'], icons=['house', 'gear'], menu_icon=""cast"", default_index=1) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.stoggle import stoggle stoggle( ""Click me!"", """"""🥷 Surprise! Here's some additional content"""""",) Streamlit ElementsCreate a draggable and resizable dashboard in Streamlit. Created by @okls.from streamlit_elements import elements, mui, html with elements(""new_element""): mui.Typography(""Hello world"") TagsAdd tags to your Streamlit apps. Created by @gagan3012.from streamlit_tags import st_tags st_tags(label='# Enter Keywords:', text='Press enter to add more', value=['Zero', 'One', 'Two'], suggestions=['five', 'six', 'seven', 'eight', 'nine', 'three', 'eleven', 'ten', 'four'], maxtags = 4, key='1') StqdmThe simplest way to handle a progress bar in streamlit app. Created by @Wirg.from stqdm import stqdm for _ in stqdm(range(50)): sleep(0.5) TimelineDisplay a Timeline in Streamlit apps using TimelineJS. Created by @innerdoc.from streamlit_timeline import timeline with open('example.json', ""r"") as f: timeline(f.read(), height=800) Camera input liveAlternative for st.camera_input which returns the webcam images live. Created by @blackary.from camera_input_live import camera_input_live image = camera_input_live() st.image(value) Streamlit AceAce editor component for Streamlit. Created by @okld.from streamlit_ace import st_ace content = st_ace() content Streamlit ChatStreamlit Component for a Chatbot UI. Created by @AI-Yash.from streamlit_chat import message message(""My message"") message(""Hello bot!"", is_user=True) # align's the message to the right Streamlit Option MenuSelect a single item from a list of options in a menu. Created by @victoryhb.from streamlit_option_menu import option_menu option_menu(""Main Menu"", [""Home"", 'Settings'], icons=['house', 'gear'], menu_icon=""cast"", default_index=1) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.stoggle import stoggle stoggle( ""Click me!"", """"""🥷 Surprise! Here's some additional content"""""",) Streamlit ElementsCreate a draggable and resizable dashboard in Streamlit. Created by @okls.from streamlit_elements import elements, mui, html with elements(""new_element""): mui.Typography(""Hello world"") TagsAdd tags to your Streamlit apps. Created by @gagan3012.from streamlit_tags import st_tags st_tags(label='# Enter Keywords:', text='Press enter to add more', value=['Zero', 'One', 'Two'], suggestions=['five', 'six', 'seven', 'eight', 'nine', 'three', 'eleven', 'ten', 'four'], maxtags = 4, key='1') StqdmThe simplest way to handle a progress bar in streamlit app. Created by @Wirg.from stqdm import stqdm for _ in stqdm(range(50)): sleep(0.5) TimelineDisplay a Timeline in Streamlit apps using TimelineJS. Created by @innerdoc.from streamlit_timeline import timeline with open('example.json', ""r"") as f: timeline(f.read(), height=800) Camera input liveAlternative for st.camera_input which returns the webcam images live. Created by @blackary.from camera_input_live import camera_input_live image = camera_input_live() st.image(value) Streamlit AceAce editor component for Streamlit. Created by @okld.from streamlit_ace import st_ace content = st_ace() content Streamlit ChatStreamlit Component for a Chatbot UI. Created by @AI-Yash.from streamlit_chat import message message(""My message"") message(""Hello bot!"", is_user=True) # align's the message to the right Streamlit Option MenuSelect a single item from a list of options in a menu. Created by @victoryhb.from streamlit_option_menu import option_menu option_menu(""Main Menu"", [""Home"", 'Settings'], icons=['house', 'gear'], menu_icon=""cast"", default_index=1) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.stoggle import stoggle stoggle( ""Click me!"", """"""🥷 Surprise! Here's some additional content"""""",) Next Media elements ImageDisplay an image or list of images.st.image(numpy_array) st.image(image_bytes) st.image(file) st.image(""https://example.com/myimage.jpg"") AudioDisplay an audio player.st.audio(numpy_array) st.audio(audio_bytes) st.audio(file) st.audio(""https://example.com/myaudio.mp3"", format=""audio/mp3"") VideoDisplay a video player.st.video(numpy_array) st.video(video_bytes) st.video(file) st.video(""https://example.com/myvideo.mp4"", format=""video/mp4"") Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration! PreviousStreamlit CropperA simple image cropper for Streamlit. Created by @turner-anderson.from streamlit_cropper import st_cropper st_cropper(img, realtime_update=realtime_update, box_color=box_color, aspect_ratio=aspect_ratio) Image CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates streamlit_image_coordinates(""https://placekitten.com/200/300"") Streamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl(""https://assets5.lottiefiles.com/packages/lf20_V9t630.json"") st_lottie(lottie_hello, key=""hello"") Streamlit WebrtcHandling and transmitting real-time video/audio streams with Streamlit. Created by @whitphx.from streamlit_webrtc import webrtc_streamer webrtc_streamer(key=""sample"") Drawable CanvasProvides a sketching canvas using Fabric.js. Created by @andfanilo.from streamlit_drawable_canvas import st_canvas st_canvas(fill_color=""rgba(255, 165, 0, 0.3)"", stroke_width=stroke_width, stroke_color=stroke_color, background_color=bg_color, background_image=Image.open(bg_image) if bg_image else None, update_streamlit=realtime_update, height=150, drawing_mode=drawing_mode, point_display_radius=point_display_radius if drawing_mode == 'point' else 0, key=""canvas"",) Image ComparisonCompare images with a slider using JuxtaposeJS. Created by @fcakyon.from streamlit_image_comparison import image_comparison image_comparison(img1=""image1.jpg"", img2=""image2.jpg"",) Streamlit CropperA simple image cropper for Streamlit. Created by @turner-anderson.from streamlit_cropper import st_cropper st_cropper(img, realtime_update=realtime_update, box_color=box_color, aspect_ratio=aspect_ratio) Image CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates streamlit_image_coordinates(""https://placekitten.com/200/300"") Streamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl(""https://assets5.lottiefiles.com/packages/lf20_V9t630.json"") st_lottie(lottie_hello, key=""hello"") Streamlit WebrtcHandling and transmitting real-time video/audio streams with Streamlit. Created by @whitphx.from streamlit_webrtc import webrtc_streamer webrtc_streamer(key=""sample"") Drawable CanvasProvides a sketching canvas using Fabric.js. Created by @andfanilo.from streamlit_drawable_canvas import st_canvas st_canvas(fill_color=""rgba(255, 165, 0, 0.3)"", stroke_width=stroke_width, stroke_color=stroke_color, background_color=bg_color, background_image=Image.open(bg_image) if bg_image else None, update_streamlit=realtime_update, height=150, drawing_mode=drawing_mode, point_display_radius=point_display_radius if drawing_mode == 'point' else 0, key=""canvas"",) Image ComparisonCompare images with a slider using JuxtaposeJS. Created by @fcakyon.from streamlit_image_comparison import image_comparison image_comparison(img1=""image1.jpg"", img2=""image2.jpg"",) Streamlit CropperA simple image cropper for Streamlit. Created by @turner-anderson.from streamlit_cropper import st_cropper st_cropper(img, realtime_update=realtime_update, box_color=box_color, aspect_ratio=aspect_ratio) Image CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates streamlit_image_coordinates(""https://placekitten.com/200/300"") Streamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl(""https://assets5.lottiefiles.com/packages/lf20_V9t630.json"") st_lottie(lottie_hello, key=""hello"") Next Layouts and containers ColumnsInsert containers laid out as side-by-side columns.col1, col2 = st.columns(2) col1.write(""this is column 1"") col2.write(""this is column 2"") ContainerInsert a multi-element container.c = st.container() st.write(""This will show last"") c.write(""This will show first"") c.write(""This will show second"") Modal dialogsInsert a modal dialog that can rerun independently from the rest of the script.@st.experimental_dialog(""Sign up"") def email_form(): name = st.text_input(""Name"") email = st.text_input(""Email"") EmptyInsert a single-element container.c = st.empty() st.write(""This will show last"") c.write(""This will be replaced"") c.write(""This will show first"") ExpanderInsert a multi-element container that can be expanded/collapsed.with st.expander(""Open to see more""): st.write(""This is more content"") PopoverInsert a multi-element popover container that can be opened/closed.with st.popover(""Settings""): st.checkbox(""Show completed"") SidebarDisplay items in a sidebar.st.sidebar.write(""This lives in the sidebar"") st.sidebar.button(""Click me!"") TabsInsert containers separated into tabs.tab1, tab2 = st.tabs([""Tab 1"", ""Tab2""]) tab1.write(""this is tab 1"") tab2.write(""this is tab 2"") Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration!Streamlit ElementsCreate a draggable and resizable dashboard in Streamlit. Created by @okls.from streamlit_elements import elements, mui, html with elements(""new_element""): mui.Typography(""Hello world"") PydanticAuto-generate Streamlit UI from Pydantic Models and Dataclasses. Created by @lukasmasuch.import streamlit_pydantic as sp sp.pydantic_form(key=""my_form"", model=ExampleModel) Streamlit PagesAn experimental version of Streamlit Multi-Page Apps. Created by @blackary.from st_pages import Page, show_pages, add_page_title show_pages([ Page(""streamlit_app.py"", ""Home"", ""🏠""), Page(""other_pages/page2.py"", ""Page 2"", "":books:""), ]) Chat elements Streamlit provides a few commands to help you build conversational apps. These chat elements are designed to be used in conjunction with each other, but you can also use them separately. st.chat_message lets you insert a chat message container into the app so you can display messages from the user or the app. Chat containers can contain other Streamlit elements, including charts, tables, text, and more. st.chat_input lets you display a chat input widget so the user can type in a message. Chat inputDisplay a chat input widget.prompt = st.chat_input(""Say something"") if prompt: st.write(f""The user has sent: {prompt}"") Chat messageInsert a chat message container.import numpy as np with st.chat_message(""user""): st.write(""Hello 👋"") st.line_chart(np.random.randn(30, 3)) Status containerDisplay output of long-running tasks in a container.with st.status('Running'): do_something_slow() st.write_streamWrite generators or streams to the app with a typewriter effect.st.write_stream(my_generator) st.write_stream(my_llm_stream) Status elements Progress barDisplay a progress bar.for i in range(101): st.progress(i) do_something_slow() SpinnerTemporarily displays a message while executing a block of code.with st.spinner(""Please wait...""): do_something_slow() Status containerDisplay output of long-running tasks in a container.with st.status('Running'): do_something_slow() ToastBriefly displays a toast message in the bottom-right corner.st.toast('Butter!', icon='🧈') BalloonsDisplay celebratory balloons!do_something() # Celebrate when all done! st.balloons() SnowflakesDisplay celebratory snowflakes!do_something() # Celebrate when all done! st.snow() Success boxDisplay a success message.st.success(""Match found!"") Info boxDisplay an informational message.st.info(""Dataset is updated every day at midnight."") Warning boxDisplay warning message.st.warning(""Unable to fetch image. Skipping..."") Error boxDisplay error message.st.error(""We encountered an error"") Exception outputDisplay an exception.e = RuntimeError(""This is an exception of type RuntimeError"") st.exception(e) Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration!StqdmThe simplest way to handle a progress bar in streamlit app. Created by @Wirg.from stqdm import stqdm for _ in stqdm(range(50)): sleep(0.5) Custom notification boxA custom notification box with the ability to close it out. Created by @Socvest.from streamlit_custom_notification_box import custom_notification_box styles = {'material-icons':{'color': 'red'}, 'text-icon-link-close-container': {'box-shadow': '#3896de 0px 4px'}, 'notification-text': {'':''}, 'close-button':{'':''}, 'link':{'':''}} custom_notification_box(icon='info', textDisplay='We are almost done with your registration...', externalLink='more info', url='#', styles=styles, key=""foo"") Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.let_it_rain import rain rain(emoji=""🎈"", font_size=54, falling_speed=5, animation_length=""infinite"",) App logic and configuration Navigation and pages Switch pageProgrammatically navigates to a specified page.st.switch_page(""pages/my_page.py"") Page linkDisplay a link to another page in a multipage app.st.page_link(""app.py"", label=""Home"", icon=""🏠"") st.page_link(""pages/profile.py"", label=""My profile"") Execution flow Modal dialogsInsert a modal dialog that can rerun independently from the rest of the script.@st.experimental_dialog(""Sign up"") def email_form(): name = st.text_input(""Name"") email = st.text_input(""Email"") FormsCreate a form that batches elements together with a “Submit"" button.with st.form(key='my_form'): name = st.text_input(""Name"") email = st.text_input(""Email"") st.form_submit_button(""Sign up"") Partial rerunsDefine a fragment to rerun independently from the rest of the script.@st.experimental_fragment(run_every=""10s"") def fragment(): df = get_data() st.line_chart(df) Rerun scriptRerun the script immediately.st.rerun() Stop executionStops execution immediately.st.stop() Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration!AutorefreshForce a refresh without tying up a script. Created by @kmcgrady.from streamlit_autorefresh import st_autorefresh st_autorefresh(interval=2000, limit=100, key=""fizzbuzzcounter"") PydanticAuto-generate Streamlit UI from Pydantic Models and Dataclasses. Created by @lukasmasuch.import streamlit_pydantic as sp sp.pydantic_form(key=""my_form"", model=ExampleModel) Streamlit PagesAn experimental version of Streamlit Multi-Page Apps. Created by @blackary.from st_pages import Page, show_pages, add_page_title show_pages([ Page(""streamlit_app.py"", ""Home"", ""🏠""), Page(""other_pages/page2.py"", ""Page 2"", "":books:""), ]) Caching and state Cache dataFunction decorator to cache functions that return data (e.g. dataframe transforms, database queries, ML inference).@st.cache_data def long_function(param1, param2): # Perform expensive computation here or # fetch data from the web here return data Cache resourceFunction decorator to cache functions that return global resources (e.g. database connections, ML models).@st.cache_resource def init_model(): # Return a global resource here return pipeline( ""sentiment-analysis"", model=""distilbert-base-uncased-finetuned-sst-2-english"" ) Session stateSession state is a way to share variables between reruns, for each user session.st.session_state['key'] = value Query parametersGet, set, or clear the query parameters that are shown in the browser's URL bar.st.query_params[key] = value st.query_params.clear() Connections and databases Setup your connection Create a connectionConnect to a data source or APIconn = st.connection('pets_db', type='sql') pet_owners = conn.query('select * from pet_owners') st.dataframe(pet_owners) Built-in connections SnowflakeConnectionA connection to Snowflake.conn = st.connection('snowflake') SQLConnectionA connection to a SQL database using SQLAlchemy.conn = st.connection('sql') Build your own connections Connection base classBuild your own connection with BaseConnection.class MyConnection(BaseConnection[myconn.MyConnection]): def _connect(self, **kwargs) -> MyConnection: return myconn.connect(**self._secrets, **kwargs) def query(self, query): return self._instance.query(query) Secrets management Secrets singletonAccess secrets from a local TOML file.key = st.secrets[""OpenAI_key""] Secrets fileSave your secrets in a per-project or per-profile TOML file.OpenAI_key = """" Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration!AuthenticatorA secure authentication module to validate user credentials. Created by @mkhorasani.import streamlit_authenticator as stauth authenticator = stauth.Authenticate( config['credentials'], config['cookie']['name'], config['cookie']['key'], config['cookie']['expiry_days'], config['preauthorized']) WS localStorageA simple synchronous way of accessing localStorage from your app. Created by @gagangoku.from streamlit_ws_localstorage import injectWebsocketCode ret = conn.setLocalStorageVal(key='k1', val='v1') st.write('ret: ' + ret) Streamlit Auth0The fastest way to provide comprehensive login inside Streamlit. Created by @conradbez.from auth0_component import login_button user_info = login_button(clientId, domain = domain) st.write(user_info) Custom Components Declare a componentCreate and register a custom component.st.components.v1.declare_component( ""custom_slider"", ""/frontend"", ) HTMLDisplay an HTML string in an iframe.st.components.v1.html( ""

Foo bar.

"" ) iframeLoad a remote URL in an iframe.st.components.v1.iframe( ""docs.streamlit.io"" ) Utilities and user info User infost.experimental_user returns information about the logged-in user of private apps on Streamlit Community Cloud.if st.experimental_user.email == ""foo@corp.com"": st.write(""Welcome back, "", st.experimental_user.email) else: st.write(""You are not authorized to view this page."") Get helpDisplay object’s doc string, nicely formatted.st.help(st.write) st.help(pd.DataFrame) Render HTMLRenders HTML strings to your app.css = """""" """""" st.html(css) Configuration Configuration fileConfigures the default settings for your app.your-project/ ├── .streamlit/ │ └── config.toml └── your_app.py Set page title, favicon, and moreConfigures the default settings of the page.st.set_page_config( page_title=""My app"", page_icon="":shark:"", ) Developer tools App testing st.testing.v1.AppTestst.testing.v1.AppTest simulates a running Streamlit app for testing.from streamlit.testing.v1 import AppTest at = AppTest.from_file(""streamlit_app.py"") at.secrets[""WORD""] = ""Foobar"" at.run() assert not at.exception at.text_input(""word"").input(""Bazbat"").run() assert at.warning[0].value == ""Try again."" AppTest.from_filest.testing.v1.AppTest.from_file initializes a simulated app from a file.from streamlit.testing.v1 import AppTest at = AppTest.from_file(""streamlit_app.py"") at.run() AppTest.from_stringst.testing.v1.AppTest.from_string initializes a simulated app from a string.from streamlit.testing.v1 import AppTest at = AppTest.from_string(app_script_as_string) at.run() AppTest.from_functionst.testing.v1.AppTest.from_function initializes a simulated app from a function.from streamlit.testing.v1 import AppTest at = AppTest.from_function(app_script_as_callable) at.run() BlockA representation of container elements, including: st.chat_message st.columns st.sidebar st.tabs The main body of the app. # at.sidebar returns a Block at.sidebar.button[0].click().run() assert not at.exception ElementThe base class for representation of all elements, including: st.title st.header st.markdown st.dataframe # at.title returns a sequence of Title # Title inherits from Element assert at.title[0].value == ""My awesome app"" ButtonA representation of st.button and st.form_submit_button.at.button[0].click().run() ChatInputA representation of st.chat_input.at.chat_input[0].set_value(""What is Streamlit?"").run() CheckboxA representation of st.checkbox.at.checkbox[0].check().run() ColorPickerA representation of st.color_picker.at.color_picker[0].pick(""#FF4B4B"").run() DateInputA representation of st.date_input.release_date = datetime.date(2023, 10, 26) at.date_input[0].set_value(release_date).run() MultiselectA representation of st.multiselect.at.multiselect[0].select(""New York"").run() NumberInputA representation of st.number_input.at.number_input[0].increment().run() RadioA representation of st.radio.at.radio[0].set_value(""New York"").run() SelectSliderA representation of st.select_slider.at.select_slider[0].set_range(""A"",""C"").run() SelectboxA representation of st.selectbox.at.selectbox[0].select(""New York"").run() SliderA representation of st.slider.at.slider[0].set_range(2,5).run() TextAreaA representation of st.text_area.at.text_area[0].input(""Streamlit is awesome!"").run() TextInputA representation of st.text_input.at.text_input[0].input(""Streamlit"").run() TimeInputA representation of st.time_input.at.time_input[0].increment().run() ToggleA representation of st.toggle.at.toggle[0].set_value(""True"").run() Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration!Pandas ProfilingPandas profiling component for Streamlit. Created by @okld.df = pd.read_csv(""https://storage.googleapis.com/tf-datasets/titanic/train.csv"") pr = df.profile_report() st_profile_report(pr) Streamlit AceAce editor component for Streamlit. Created by @okld.from streamlit_ace import st_ace content = st_ace() content Streamlit AnalyticsTrack & visualize user interactions with your streamlit app. Created by @jrieke.import streamlit_analytics with streamlit_analytics.track(): st.text_input(""Write something"") Previous: ConceptsNext: Write and magicforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy" https://docs.streamlit.io/knowledge-base/deploy/share-apps-with-viewers-outside-organization#share-your-app-on-social-media,"DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudremoveGet startedaddDeploy your appaddManage your appaddShare your appremoveEmbed your appSearch indexabilityShare previewsManage your accountaddTroubleshootingStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Deploy/Streamlit Community Cloud/Share your appShare your app Now that your app is deployed you can easily share it and collaborate on it. But first, let's take a moment and do a little joy dance for getting that app deployed! 🕺💃 Your app is now live at a fixed URL, so go wild and share it with whomever you want. Your app will inherit permissions from your GitHub repo, meaning that if your repo is private your app will be private and if your repo is public your app will be public. If you want to change that you can simply do so from the app settings menu. You are only allowed one private app at a time. If you've deployed from a private repository, you will have to make that app public or delete it before you can deploy another app from a private repository. Only developers can change your app between public and private. Make your app public or private Share your public app Share your private app Make your app public or private If you deployed your app from a public repository, your app will be public by default. If you deployed your app from a private repository, you will need to make the app public if you want to freely share it with the community at large. Set privacy from your app settings Access your App settings and go to the ""Sharing"" section. Set your app's privacy under ""Who can view this app."" Select ""This app is public and searchable"" to make your app public. Select ""Only specific people can view this app"" to make your app private. Set privacy from the share button From your app at .streamlit.app, click ""Share"" in the upper-right corner. Toggle your app between public and private by clicking ""Make this app public"". Share your public app Once your app is public, just give anyone your app's URL and they view it! Streamlit Community Cloud has several convenient shortcuts for sharing your app. Share your app on social media From your app at .streamlit.app, click ""Share"" in the upper-right corner. Click ""Social"" to access convenient social media share buttons. starTipUse the social media sharing buttons to post your app on our forum! We'd love to see what you make and perhaps feature your app as our app of the month. 💖 Invite viewers by email Whether your app is public or private, you can send an email invite to your app directly from Streamlit Community Cloud. This grants the viewer access to analytics for all your public apps and the ability to invite other viewers to your workspace. Developers and invited viewers are identified by their email in analytics instead of appearing anonymously (if they view any of your apps while logged in). Read more about viewers in App analytics. From your app at .streamlit.app, click ""Share"" in the upper-right corner. Enter an email address and click ""Invite"". Invited users will get a direct link to your app in their inbox. Copy your app's URL You can convenitiently copy your app's URL from the share menu or from your workspace. From your app click ""Share"" in the upper-right corner then click ""Copy link"". From your workspace click the overflow menu icon (more_vert) then click ""Copy URL"". Add a badge to your GitHub repository To help others find and play with your Streamlit app, you can add Streamlit's GitHub badge to your repo. Below is an enlarged example of what the badge looks like. Clicking on the badge takes you to—in this case—Streamlit's Roadmap. Once you deploy your app, you can embed this badge right into your GitHub README.md by adding the following Markdown: [![Streamlit App](https://static.streamlit.io/badges/streamlit_badge_black_white.svg)](https://.streamlit.app) push_pinNoteBe sure to replace https://.streamlit.app with the URL of your deployed app! Share your private app By default an app deployed from a private repository will be private to the developers in the workspace. A private app will not be visible to anyone else unless you grant them explicit permission. You can grant permission by adding them as a developer on GitHub or by adding them as a viewer on Streamlit Community Cloud. Once you have added someone's email address to your app's viewer list, that person will be able to sign in and view your private app. If their email is associated to a Google account, they will be able to sign in with Google OAuth. Otherwise, they will be able to sign in with single-use, emailed links. Streamlit sends an email invitation with a link to your app every time you invite someone. priority_highImportantWhen you add a viewer to any app in your workspace, they are granted access to analytics for that app as well as analytics for all your public apps. They can also pass these permissions to others by inviting more viewers. All viewers and developers in your workspace are identified by their email in analytics. Furthermore, their emails show in analytics for every app in your workspace and not just apps they are explicitly invited to. Read more about viewers in App analytics Invite viewers from the share button From your app at .streamlit.app, click ""Share"" in the upper-right corner. Enter the email to send an invitation to and click ""Invite"". Invited users appear in the list below. Invited users will get a direct link to your app in their inbox. To remove a viewer, simply access the share menu as above and click the close next to their name. Invite viewers from your app settings Access your App settings and go to the ""Sharing"" section. Add or remove users from the list of viewers. Click ""Save"". Previous: Manage your appNext: Embed your appforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy" https://docs.streamlit.io/knowledge-base/deploy/sign-in-without-sso#sign-in-with-google,"DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudremoveGet startedaddDeploy your appaddManage your appaddShare your appaddManage your accountremoveSign in & sign outWorkspace settingsManage your GitHub connectionUpdate your emailDelete your accountTroubleshootingStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Deploy/Streamlit Community Cloud/Manage your account/Sign in & sign outSign in & sign out Once you've created your account, you can sign in to share.streamlit.io and follow the steps below. Sign in with Google Visit share.streamlit.io and click ""Continue with Google"". Enter your Google account credentials. If your account is already linked to GitHub, you may be immediately prompted to sign in with GitHub. Once you have signed in, you can Explore your workspace!. 🎈 Sign in with GitHub Visit share.streamlit.io and click ""Continue with GitHub"". Enter your GitHub credentials. Once you have signed in to GitHub, you can Explore your workspace!. 🎈 Sign in with Email Visit share.streamlit.io and enter the email you used to create your Streamlit Community Cloud account. Click ""Continue with email"". You will see a confirmation message asking you to check your email. Check your inbox for an email with the subject ""Sign in to Streamlit Cloud"". Click the link in the email to sign in to Streamlit Community Cloud. Note that this link will expire in 15 minutes and can only be used once. Once you click the link in your email, you can Explore your workspace!. 🎈 Sign out of your account From your workspace, click on your workspace name in the upper-right corner. Click ""Sign out"". Previous: Manage your accountNext: Workspace settingsforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy" https://docs.streamlit.io/deploy/tutorials/kubernetes#introduction,"DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsremoveDockerKubernetesschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Deploy/Other platforms/KubernetesDeploy Streamlit using Kubernetes Introduction So you have an amazing app and you want to start sharing it with other people, what do you do? You have a few options. First, where do you want to run your Streamlit app, and how do you want to access it? On your corporate network - Most corporate networks are closed to the outside world. You typically use a VPN to log onto your corporate network and access resources there. You could run your Streamlit app on a server in your corporate network for security reasons, to ensure that only folks internal to your company can access it. On the cloud - If you'd like to access your Streamlit app from outside of a corporate network, or share your app with folks outside of your home network or laptop, you might choose this option. In this case, it'll depend on your hosting provider. We have community-submitted guides from Heroku, AWS, and other providers. Wherever you decide to deploy your app, you will first need to containerize it. This guide walks you through using Kubernetes to deploy your app. If you prefer Docker see Deploy Streamlit using Docker. Prerequisites Install Docker Engine Install the gcloud CLI Install Docker Engine If you haven't already done so, install Docker on your server. Docker provides .deb and .rpm packages from many Linux distributions, including: Debian Ubuntu Verify that Docker Engine is installed correctly by running the hello-world Docker image: sudo docker run hello-world starTipFollow Docker's official post-installation steps for Linux to run Docker as a non-root user, so that you don't have to preface the docker command with sudo. Install the gcloud CLI In this guide, we will orchestrate Docker containers with Kubernetes and host docker images on the Google Container Registry (GCR). As GCR is a Google-supported Docker registry, we need to register gcloud as the Docker credential helper. Follow the official documentation to Install the gcloud CLI and initialize it. Create a Docker container We need to create a docker container which contains all the dependencies and the application code. Below you can see the entrypoint, i.e. the command run when the container starts, and the Dockerfile definition. Create an entrypoint script Create a run.sh script containing the following: #!/bin/bash APP_PID= stopRunningProcess() { # Based on https://linuxconfig.org/how-to-propagate-a-signal-to-child-processes-from-a-bash-script if test ! ""${APP_PID}"" = '' && ps -p ${APP_PID} > /dev/null ; then > /proc/1/fd/1 echo ""Stopping ${COMMAND_PATH} which is running with process ID ${APP_PID}"" kill -TERM ${APP_PID} > /proc/1/fd/1 echo ""Waiting for ${COMMAND_PATH} to process SIGTERM signal"" wait ${APP_PID} > /proc/1/fd/1 echo ""All processes have stopped running"" else > /proc/1/fd/1 echo ""${COMMAND_PATH} was not started when the signal was sent or it has already been stopped"" fi } trap stopRunningProcess EXIT TERM source ${VIRTUAL_ENV}/bin/activate streamlit run ${HOME}/app/streamlit_app.py & APP_ID=${!} wait ${APP_ID} Create a Dockerfile Docker builds images by reading the instructions from a Dockerfile. A Dockerfile is a text document that contains all the commands a user could call on the command line to assemble an image. Learn more in the Dockerfile reference. The docker build command builds an image from a Dockerfile. The docker run command first creates a container over the specified image, and then starts it using the specified command. Here's an example Dockerfile that you can add to the root of your directory. FROM python:3.8-slim RUN groupadd --gid 1000 appuser \ && useradd --uid 1000 --gid 1000 -ms /bin/bash appuser RUN pip3 install --no-cache-dir --upgrade \ pip \ virtualenv RUN apt-get update && apt-get install -y \ build-essential \ software-properties-common \ git USER appuser WORKDIR /home/appuser RUN git clone https://github.com/streamlit/streamlit-example.git app ENV VIRTUAL_ENV=/home/appuser/venv RUN virtualenv ${VIRTUAL_ENV} RUN . ${VIRTUAL_ENV}/bin/activate && pip install -r app/requirements.txt EXPOSE 8501 COPY run.sh /home/appuser ENTRYPOINT [""./run.sh""] priority_highImportantAs mentioned in Development flow, for Streamlit version 1.10.0 and higher, Streamlit apps cannot be run from the root directory of Linux distributions. Your main script should live in a directory other than the root directory. If you try to run a Streamlit app from the root directory, Streamlit will throw a FileNotFoundError: [Errno 2] No such file or directory error. For more information, see GitHub issue #5239.If you are using Streamlit version 1.10.0 or higher, you must set the WORKDIR to a directory other than the root directory. For example, you can set the WORKDIR to /home/appuser as shown in the example Dockerfile above. Build a Docker image Put the above files (run.sh and Dockerfile) in the same folder and build the docker image: docker build --platform linux/amd64 -t gcr.io/$GCP_PROJECT_ID/k8s-streamlit:test . priority_highImportantReplace $GCP_PROJECT_ID in the above command with the name of your Google Cloud project. Upload the Docker image to a container registry The next step is to upload the Docker image to a container registry. In this example, we will use the Google Container Registry (GCR). Start by enabling the Container Registry API. Sign in to Google Cloud and navigate to your project’s Container Registry and click Enable. We can now build the Docker image from the previous step and push it to our project’s GCR. Be sure to replace $GCP_PROJECT_ID in the docker push command with the name of your project: gcloud auth configure-docker docker push gcr.io/$GCP_PROJECT_ID/k8s-streamlit:test Create a Kubernetes deployment For this step you will need a: Running Kubernetes service Custom domain for which you can generate a TLS certificate DNS service where you can configure your custom domain to point to the application IP As the image was uploaded to the container registry in the previous step, we can run it in Kubernetes using the below configurations. Install and run Kubernetes Make sure your Kubernetes client, kubectl, is installed and running on your machine. Configure a Google OAuth Client and oauth2-proxy For configuring the Google OAuth Client, please see Google Auth Provider. Configure oauth2-proxy to use the desired OAuth Provider Configuration and update the oath2-proxy config in the config map. The below configuration contains a ouath2-proxy sidecar container which handles the authentication with Google. You can learn more from the oauth2-proxy repository. Create a Kubernetes configuration file Create a YAML configuration file named k8s-streamlit.yaml: apiVersion: v1 kind: ConfigMap metadata: name: streamlit-configmap data: oauth2-proxy.cfg: |- http_address = ""0.0.0.0:4180"" upstreams = [""http://127.0.0.1:8501/""] email_domains = [""*""] client_id = """" client_secret = """" cookie_secret = ""<16, 24, or 32 bytes>"" redirect_url = --- apiVersion: apps/v1 kind: Deployment metadata: name: streamlit-deployment labels: app: streamlit spec: replicas: 1 selector: matchLabels: app: streamlit template: metadata: labels: app: streamlit spec: containers: - name: oauth2-proxy image: quay.io/oauth2-proxy/oauth2-proxy:v7.2.0 args: [""--config"", ""/etc/oauth2-proxy/oauth2-proxy.cfg""] ports: - containerPort: 4180 livenessProbe: httpGet: path: /ping port: 4180 scheme: HTTP readinessProbe: httpGet: path: /ping port: 4180 scheme: HTTP volumeMounts: - mountPath: ""/etc/oauth2-proxy"" name: oauth2-config - name: streamlit image: gcr.io/GCP_PROJECT_ID/k8s-streamlit:test imagePullPolicy: Always ports: - containerPort: 8501 livenessProbe: httpGet: path: /_stcore/health port: 8501 scheme: HTTP timeoutSeconds: 1 readinessProbe: httpGet: path: /_stcore/health port: 8501 scheme: HTTP timeoutSeconds: 1 resources: limits: cpu: 1 memory: 2Gi requests: cpu: 100m memory: 745Mi volumes: - name: oauth2-config configMap: name: streamlit-configmap --- apiVersion: v1 kind: Service metadata: name: streamlit-service spec: type: LoadBalancer selector: app: streamlit ports: - name: streamlit-port protocol: TCP port: 80 targetPort: 4180 priority_highImportantWhile the above configurations can be copied verbatim, you will have to configure the oauth2-proxy yourself and use the correct GOOGLE_CLIENT_ID, GOOGLE_CLIENT_ID, GCP_PROJECT_ID, and REDIRECT_URL. Now create the configuration from the file in Kubernetes with the kubectl create command: kubctl create -f k8s-streamlit.yaml Set up TLS support Since you are using the Google authentication, you will need to set up TLS support. Find out how in TLS Configuration. Verify the deployment Once the deployment and the service are created, we need to wait a couple of minutes for the public IP address to become available. We can check when that is ready by running: kubectl get service streamlit-service -o jsonpath='{.status.loadBalancer.ingress[0].ip}' After the public IP is assigned, you will need to configure in your DNS service an A record pointing to the above IP address.Previous: DockerNext: Knowledge baseforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy" https://docs.streamlit.io/knowledge-base/dependencies/install-package-not-pypi-conda-available-github#specify-a-tag,"DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Knowledge base/Installing dependencies/How to install a package not on PyPI or Conda but available on GitHubHow to install a package not on PyPI/Conda but available on GitHub Overview Are you trying to deploy your app to Streamlit Community Cloud, but don't know how to specify a Python dependency in your requirements file that is available on a public GitHub repo but not any package index like PyPI or Conda? If so, continue reading to find out how! Let's suppose you want to install SomePackage and its Python dependencies from GitHub, a hosting service for the popular version control system (VCS) Git. And suppose SomePackage is found at the the following URL: https://github.com/SomePackage.git. pip (via requirements.txt) supports installing from GitHub. This support requires a working executable to be available (for Git). It is used through a URL prefix: git+. Specify the GitHub web URL To install SomePackage, innclude the following in your requirements.txt file: git+https://github.com/SomePackage#egg=SomePackage You can even specify a ""git ref"" such as branch name, a commit hash or a tag name, as shown in the examples below. Specify a Git branch name Install SomePackage by specifying a branch name such as main, master, develop, etc, in requirements.txt: git+https://github.com/SomePackage.git@main#egg=SomePackage Specify a commit hash Install SomePackage by specifying a commit hash in requirements.txt: git+https://github.com/SomePackage.git@eb40b4ff6f7c5c1e4366cgfg0671291bge918#egg=SomePackage Specify a tag Install SomePackage by specifying a tag in requirements.txt: git+https://github.com/SomePackage.git@v1.1.0#egg=SomePackage Limitations It is currently not possible to install private packages from private GitHub repos using the URI form: git+https://{token}@github.com/user/project.git@{version} where version is a tag, a branch, or a commit. And token is a personal access token with read only permissions. Streamlit Community Cloud only supports installing public packages from public GitHub repos.Previous: Installing dependenciesNext: ImportError libGL.so.1 cannot open shared object file No such file or directoryforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy" https://docs.streamlit.io/develop/tutorials/databases/tableau,"DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceaddTutorialsremoveExecution flowaddConnect to data sourcesremoveAWS S3BigQueryDeta BaseFirestoreopen_in_newGoogle Cloud StorageMicrosoft SQL ServerMongoDBMySQLNeonPostgreSQLPrivate Google SheetPublic Google SheetSnowflakeSupabaseTableauTiDBTigerGraphMultipage appsaddWork with LLMsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Develop/Tutorials/Connect to data sources/TableauConnect Streamlit to Tableau Introduction This guide explains how to securely access data on Tableau from Streamlit Community Cloud. It uses the tableauserverclient library and Streamlit's Secrets management. Create a Tableau site push_pinNoteIf you already have a database that you want to use, feel free to skip to the next step. For simplicity, we are using the cloud version of Tableau here but this guide works equally well for self-hosted deployments. First, sign up for Tableau Online or log in. Create a workbook or run one of the example workbooks under ""Dashboard Starters"". Create personal access tokens While the Tableau API allows authentication via username and password, you should use personal access tokens for a production app. Go to your Tableau Online homepage, create an access token and note down the token name and secret. push_pinNotePersonal access tokens will expire if not used after 15 consecutive days. Add token to your local app secrets Your local Streamlit app will read secrets from a file .streamlit/secrets.toml in your app's root directory. Create this file if it doesn't exist yet and add your token, the site name you created during setup, and the URL of your Tableau server like below: # .streamlit/secrets.toml [tableau] token_name = ""xxx"" token_secret = ""xxx"" server_url = ""https://abc01.online.tableau.com/"" site_id = ""streamlitexample"" # in your site's URL behind the server_url priority_highImportantAdd this file to .gitignore and don't commit it to your GitHub repo! Copy your app secrets to the cloud As the secrets.toml file above is not committed to GitHub, you need to pass its content to your deployed app (on Streamlit Community Cloud) separately. Go to the app dashboard and in the app's dropdown menu, click on Edit Secrets. Copy the content of secrets.toml into the text area. More information is available at Secrets management. Add tableauserverclient to your requirements file Add the tableauserverclient package to your requirements.txt file, preferably pinning its version (replace x.x.x with the version you want installed): # requirements.txt tableauserverclient==x.x.x Write your Streamlit app Copy the code below to your Streamlit app and run it. Note that this code just shows a few options of data you can get – explore the tableauserverclient library to find more! # streamlit_app.py import streamlit as st import tableauserverclient as TSC # Set up connection. tableau_auth = TSC.PersonalAccessTokenAuth( st.secrets[""tableau""][""token_name""], st.secrets[""tableau""][""personal_access_token""], st.secrets[""tableau""][""site_id""], ) server = TSC.Server(st.secrets[""tableau""][""server_url""], use_server_version=True) # Get various data. # Explore the tableauserverclient library for more options. # Uses st.cache_data to only rerun when the query changes or after 10 min. @st.cache_data(ttl=600) def run_query(): with server.auth.sign_in(tableau_auth): # Get all workbooks. workbooks, pagination_item = server.workbooks.get() workbooks_names = [w.name for w in workbooks] # Get views for first workbook. server.workbooks.populate_views(workbooks[0]) views_names = [v.name for v in workbooks[0].views] # Get image & CSV for first view of first workbook. view_item = workbooks[0].views[0] server.views.populate_image(view_item) server.views.populate_csv(view_item) view_name = view_item.name view_image = view_item.image # `view_item.csv` is a list of binary objects, convert to str. view_csv = b"""".join(view_item.csv).decode(""utf-8"") return workbooks_names, views_names, view_name, view_image, view_csv workbooks_names, views_names, view_name, view_image, view_csv = run_query() # Print results. st.subheader(""📓 Workbooks"") st.write(""Found the following workbooks:"", "", "".join(workbooks_names)) st.subheader(""👁️ Views"") st.write( f""Workbook *{workbooks_names[0]}* has the following views:"", "", "".join(views_names), ) st.subheader(""🖼️ Image"") st.write(f""Here's what view *{view_name}* looks like:"") st.image(view_image, width=300) st.subheader(""📊 Data"") st.write(f""And here's the data for view *{view_name}*:"") st.write(pd.read_csv(StringIO(view_csv))) See st.cache_data above? Without it, Streamlit would run the query every time the app reruns (e.g. on a widget interaction). With st.cache_data, it only runs when the query changes or after 10 minutes (that's what ttl is for). Watch out: If your database updates more frequently, you should adapt ttl or remove caching so viewers always see the latest data. Learn more in Caching. If everything worked out, your app should look like this (can differ based on your workbooks): Previous: SupabaseNext: TiDBforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy" https://docs.streamlit.io/develop/api-reference/caching-and-state/st.experimental_singleton#replay-static-st-elements-in-cache-decorated-functions,"DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceremovePAGE ELEMENTSWrite and magicaddText elementsaddData elementsaddChart elementsaddInput widgetsaddMedia elementsaddLayouts and containersaddChat elementsaddStatus elementsaddThird-party componentsopen_in_newAPPLICATION LOGICNavigation and pagesaddExecution flowaddCaching and stateremovest.cache_datast.cache_resourcest.cachedeletest.session_statest.query_paramsst.experimental_get_query_paramsdeletest.experimental_set_query_paramsdeleteConnections and secretsaddCustom componentsaddUtilitiesaddConfigurationaddTOOLSApp testingaddCommand lineaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Develop/API reference/Caching and state/st.experimental_singletonpriority_highImportantThis is an experimental feature. Experimental features and their APIs may change or be removed at any time. To learn more, click here. st.experimental_singletonStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakedeleteDeprecation noticest.experimental_singleton was deprecated in version 1.18.0. Use st.cache_resource instead. Learn more in Caching.Decorator to cache functions that return global resources (e.g. database connections, ML models). Cached objects are shared across all users, sessions, and reruns. They must be thread-safe because they can be accessed from multiple threads concurrently. If thread safety is an issue, consider using st.session_state to store resources per session instead. You can clear a function's cache with func.clear() or clear the entire cache with st.cache_resource.clear(). To cache data, use st.cache_data instead. Learn more about caching at https://docs.streamlit.io/library/advanced-features/caching. Function signature[source] st.experimental_singleton(func, *, ttl, max_entries, show_spinner, validate, experimental_allow_widgets, hash_funcs=None) Parameters func (callable) The function that creates the cached resource. Streamlit hashes the function's source code. ttl (float, timedelta, str, or None) The maximum time to keep an entry in the cache. Can be one of: None if cache entries should never expire (default). A number specifying the time in seconds. A string specifying the time in a format supported by Pandas's Timedelta constructor, e.g. ""1d"", ""1.5 days"", or ""1h23s"". A timedelta object from Python's built-in datetime library, e.g. timedelta(days=1). max_entries (int or None) The maximum number of entries to keep in the cache, or None for an unbounded cache. When a new entry is added to a full cache, the oldest cached entry will be removed. Defaults to None. show_spinner (bool or str) Enable the spinner. Default is True to show a spinner when there is a ""cache miss"" and the cached resource is being created. If string, value of show_spinner param will be used for spinner text. validate (callable or None) An optional validation function for cached data. validate is called each time the cached value is accessed. It receives the cached value as its only parameter and it must return a boolean. If validate returns False, the current cached value is discarded, and the decorated function is called to compute a new value. This is useful e.g. to check the health of database connections. experimental_allow_widgets (bool) Allow widgets to be used in the cached function. Defaults to False. Support for widgets in cached functions is currently experimental. Setting this parameter to True may lead to excessive memory use since the widget value is treated as an additional input parameter to the cache. We may remove support for this option at any time without notice. hash_funcs (dict or None) Mapping of types or fully qualified names to hash functions. This is used to override the behavior of the hasher inside Streamlit's caching mechanism: when the hasher encounters an object, it will first check to see if its type matches a key in this dict and, if so, will use the provided function to generate a hash for it. See below for an example of how this can be used. Example import streamlit as st @st.cache_resource def get_database_session(url): # Create a database session object that points to the URL. return session s1 = get_database_session(SESSION_URL_1) # Actually executes the function, since this is the first time it was # encountered. s2 = get_database_session(SESSION_URL_1) # Does not execute the function. Instead, returns its previously computed # value. This means that now the connection object in s1 is the same as in s2. s3 = get_database_session(SESSION_URL_2) # This is a different URL, so the function executes. By default, all parameters to a cache_resource function must be hashable. Any parameter whose name begins with _ will not be hashed. You can use this as an ""escape hatch"" for parameters that are not hashable: import streamlit as st @st.cache_resource def get_database_session(_sessionmaker, url): # Create a database connection object that points to the URL. return connection s1 = get_database_session(create_sessionmaker(), DATA_URL_1) # Actually executes the function, since this is the first time it was # encountered. s2 = get_database_session(create_sessionmaker(), DATA_URL_1) # Does not execute the function. Instead, returns its previously computed # value - even though the _sessionmaker parameter was different # in both calls. A cache_resource function's cache can be procedurally cleared: import streamlit as st @st.cache_resource def get_database_session(_sessionmaker, url): # Create a database connection object that points to the URL. return connection fetch_and_clean_data.clear(_sessionmaker, ""https://streamlit.io/"") # Clear the cached entry for the arguments provided. get_database_session.clear() # Clear all cached entries for this function. To override the default hashing behavior, pass a custom hash function. You can do that by mapping a type (e.g. Person) to a hash function (str) like this: import streamlit as st from pydantic import BaseModel class Person(BaseModel): name: str @st.cache_resource(hash_funcs={Person: str}) def get_person_name(person: Person): return person.name Alternatively, you can map the type's fully-qualified name (e.g. ""__main__.Person"") to the hash function instead: import streamlit as st from pydantic import BaseModel class Person(BaseModel): name: str @st.cache_resource(hash_funcs={""__main__.Person"": str}) def get_person_name(person: Person): return person.name st.experimental_singleton.clearStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakedeleteDeprecation noticest.experimental_singleton.clear was deprecated in version 1.18.0. Use st.cache_resource.clear instead. Learn more in Caching.Clear all cache_resource caches. Function signature[source] st.experimental_singleton.clear() Example In the example below, pressing the ""Clear All"" button will clear all singleton caches. i.e. Clears cached singleton objects from all functions decorated with @st.experimental_singleton. import streamlit as st from transformers import BertModel @st.experimental_singleton def get_database_session(url): # Create a database session object that points to the URL. return session @st.experimental_singleton def get_model(model_type): # Create a model of the specified type. return BertModel.from_pretrained(model_type) if st.button(""Clear All""): # Clears all singleton caches: st.experimental_singleton.clear() Validating the cache The @st.experimental_singleton decorator is used to cache the output of a function, so that it only needs to be executed once. This can improve performance in certain situations, such as when a function takes a long time to execute or makes a network request. However, in some cases, the cached output may become invalid over time, such as when a database connection times out. To handle this, the @st.experimental_singleton decorator supports an optional validate parameter, which accepts a validation function that is called each time the cached output is accessed. If the validation function returns False, the cached output is discarded and the decorated function is executed again. Best Practices Use the validate parameter when the cached output may become invalid over time, such as when a database connection or an API key expires. Use the validate parameter judiciously, as it will add an additional overhead of calling the validation function each time the cached output is accessed. Make sure that the validation function is as fast as possible, as it will be called each time the cached output is accessed. Consider to validate cached data periodically, instead of each time it is accessed, to mitigate the performance impact. Handle errors that may occur during validation and provide a fallback mechanism if the validation fails. Replay static st elements in cache-decorated functions Functions decorated with @st.experimental_singleton can contain static st elements. When a cache-decorated function is executed, we record the element and block messages produced, so the elements will appear in the app even when execution of the function is skipped because the result was cached. In the example below, the @st.experimental_singleton decorator is used to cache the execution of the get_model function, that returns a 🤗 Hugging Face Transformers model. Notice the cached function also contains a st.bar_chart command, which will be replayed when the function is skipped because the result was cached. import numpy as np import pandas as pd import streamlit as st from transformers import AutoModel @st.experimental_singleton def get_model(model_type): # Contains a static element st.bar_chart st.bar_chart( np.random.rand(10, 1) ) # This will be recorded and displayed even when the function is skipped # Create a model of the specified type return AutoModel.from_pretrained(model_type) bert_model = get_model(""distilbert-base-uncased"") st.help(bert_model) # Display the model's docstring Supported static st elements in cache-decorated functions include: st.alert st.altair_chart st.area_chart st.audio st.bar_chart st.ballons st.bokeh_chart st.caption st.code st.components.v1.html st.components.v1.iframe st.container st.dataframe st.echo st.empty st.error st.exception st.expander st.experimental_get_query_params st.experimental_set_query_params st.form st.form_submit_button st.graphviz_chart st.help st.image st.info st.json st.latex st.line_chart st.markdown st.metric st.plotly_chart st.progress st.pydeck_chart st.snow st.spinner st.success st.table st.text st.vega_lite_chart st.video st.warning Replay input widgets in cache-decorated functions In addition to static elements, functions decorated with @st.experimental_singleton can also contain input widgets! Replaying input widgets is disabled by default. To enable it, you can set the experimental_allow_widgets parameter for @st.experimental_singleton to True. The example below enables widget replaying, and shows the use of a checkbox widget within a cache-decorated function. import streamlit as st # Enable widget replay @st.experimental_singleton(experimental_allow_widgets=True) def func(): # Contains an input widget st.checkbox(""Works!"") func() If the cache decorated function contains input widgets, but experimental_allow_widgets is set to False or unset, Streamlit will throw a CachedStFunctionWarning, like the one below: import streamlit as st # Widget replay is disabled by default @st.experimental_singleton def func(): # Streamlit will throw a CachedStFunctionWarning st.checkbox(""Doesn't work"") func() How widget replay works Let's demystify how widget replay in cache-decorated functions works and gain a conceptual understanding. Widget values are treated as additional inputs to the function, and are used to determine whether the function should be executed or not. Consider the following example: import streamlit as st @st.experimental_singleton(experimental_allow_widgets=True) def plus_one(x): y = x + 1 if st.checkbox(""Nuke the value 💥""): st.write(""Value was nuked, returning 0"") y = 0 return y st.write(plus_one(2)) The plus_one function takes an integer x as input, and returns x + 1. The function also contains a checkbox widget, which is used to ""nuke"" the value of x. i.e. the return value of plus_one depends on the state of the checkbox: if it is checked, the function returns 0, otherwise it returns 3. In order to know which value the cache should return (in case of a cache hit), Streamlit treats the checkbox state (checked / unchecked) as an additional input to the function plus_one (just like x). If the user checks the checkbox (thereby changing its state), we look up the cache for the same value of x (2) and the same checkbox state (checked). If the cache contains a value for this combination of inputs, we return it. Otherwise, we execute the function and store the result in the cache. Let's now understand how enabling and disabling widget replay changes the behavior of the function. Widget replay disabled Widgets in cached functions throw a CachedStFunctionWarning and are ignored. Other static elements in cached functions replay as expected. Widget replay enabled Widgets in cached functions don't lead to a warning, and are replayed as expected. Interacting with a widget in a cached function will cause the function to be executed again, and the cache to be updated. Widgets in cached functions retain their state across reruns. Each unique combination of widget values is treated as a separate input to the function, and is used to determine whether the function should be executed or not. i.e. Each unique combination of widget values has its own cache entry; the cached function runs the first time and the saved value is used afterwards. Calling a cached function multiple times in one script run with the same arguments triggers a DuplicateWidgetID error. If the arguments to a cached function change, widgets from that function that render again retain their state. Changing the source code of a cached function invalidates the cache. Both st.experimental_singleton and st.experimental_memo support widget replay. Fundamentally, the behavior of a function with (supported) widgets in it doesn't change when it is decorated with @st.experimental_singleton or @st.experimental_memo. The only difference is that the function is only executed when we detect a cache ""miss"". Supported widgets All input widgets are supported in cache-decorated functions. The following is an exhaustive list of supported widgets: st.button st.camera_input st.checkbox st.color_picker st.date_input st.download_button st.file_uploader st.multiselect st.number_input st.radio st.selectbox st.select_slider st.slider st.text_area st.text_input st.time_input Previous: st.experimental_memoNext: st.session_stateforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy" https://docs.streamlit.io/develop/api-reference/connections/st.connections.experimentalbaseconnection#stconnectionsexperimentalbaseconnection,"DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceremovePAGE ELEMENTSWrite and magicaddText elementsaddData elementsaddChart elementsaddInput widgetsaddMedia elementsaddLayouts and containersaddChat elementsaddStatus elementsaddThird-party componentsopen_in_newAPPLICATION LOGICNavigation and pagesaddExecution flowaddCaching and stateaddConnections and secretsremoveSECRETSst.secretssecrets.tomlCONNECTIONSst.connectionSnowflakeConnectionSQLConnectionBaseConnectionSnowparkConnectiondeleteCustom componentsaddUtilitiesaddConfigurationaddTOOLSApp testingaddCommand lineaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Develop/API reference/Connections and secrets/ExperimentalBaseConnectionpriority_highImportantThis is an experimental feature. Experimental features and their APIs may change or be removed at any time. To learn more, click here. starTipThis page only contains information on the st.connections.ExperimentalBaseConnection class. For a deeper dive into creating and managing data connections within Streamlit apps, read Connecting to data. st.connections.ExperimentalBaseConnectionStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakedeleteDeprecation noticest.connections.ExperimentalBaseConnection was deprecated in version 1.28.0. Use st.connections.BaseConnection instead.The abstract base class that all Streamlit Connections must inherit from. This base class provides connection authors with a standardized way to hook into the st.connection() factory function: connection authors are required to provide an implementation for the abstract method _connect in their subclasses. Additionally, it also provides a few methods/properties designed to make implementation of connections more convenient. See the docstrings for each of the methods of this class for more information Note While providing an implementation of _connect is technically all that's required to define a valid connection, connections should also provide the user with context-specific ways of interacting with the underlying connection object. For example, the first-party SQLConnection provides a query() method for reads and a session property for more complex operations. Class description[source] st.connections.ExperimentalBaseConnection(connection_name, **kwargs) Methods reset() Reset this connection so that it gets reinitialized the next time it's used. st.connections.ExperimentalBaseConnection.resetStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in Snowflakepriority_highWarningThis method did not exist in version 1.34.0 of Streamlit.Previous: SnowparkConnectionNext: Custom componentsforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy" https://docs.streamlit.io/knowledge-base/using-streamlit/how-to-get-row-selections#example,"DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Knowledge base/FAQ/How do I get dataframe row selections from a user?How do I get dataframe row-selections from a user? At the moment, st.dataframe and st.data_editor do not natively support passing user-selected rows to the Python backend. We are working to support this in the future. For now, if you need to get row-selections from a user, you can accomplish this by adding an extra Checkbox column) to your dataframe and using st.data_editor. You can use this extra column to collect a user's selection(s). Example In the following example, we define a function which accepts a dataframe and returns the rows selected by a user. Within the function, the dataframe is copied to prevent mutating it. We insert a temporary ""Select"" column into the copied dataframe before passing the copied data into st.data_editor. We have disabled editing for all other columns, but you can make them editable if desired. After filtering the dataframe and dropping the temporary column, our function returns the selected rows. import streamlit as st import numpy as np import pandas as pd df = pd.DataFrame( { ""Animal"": [""Lion"", ""Elephant"", ""Giraffe"", ""Monkey"", ""Zebra""], ""Habitat"": [""Savanna"", ""Forest"", ""Savanna"", ""Forest"", ""Savanna""], ""Lifespan (years)"": [15, 60, 25, 20, 25], ""Average weight (kg)"": [190, 5000, 800, 10, 350], } ) def dataframe_with_selections(df): df_with_selections = df.copy() df_with_selections.insert(0, ""Select"", False) # Get dataframe row-selections from user with st.data_editor edited_df = st.data_editor( df_with_selections, hide_index=True, column_config={""Select"": st.column_config.CheckboxColumn(required=True)}, disabled=df.columns, ) # Filter the dataframe using the temporary column, then drop the column selected_rows = edited_df[edited_df.Select] return selected_rows.drop('Select', axis=1) selection = dataframe_with_selections(df) st.write(""Your selection:"") st.write(selection) Previous: How to download a Pandas DataFrame as a CSV?Next: How do I upgrade to the latest version of Streamlit?forumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy" https://docs.streamlit.io/knowledge-base/dependencies/install-package-not-pypi-conda-available-github#overview,"DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Knowledge base/Installing dependencies/How to install a package not on PyPI or Conda but available on GitHubHow to install a package not on PyPI/Conda but available on GitHub Overview Are you trying to deploy your app to Streamlit Community Cloud, but don't know how to specify a Python dependency in your requirements file that is available on a public GitHub repo but not any package index like PyPI or Conda? If so, continue reading to find out how! Let's suppose you want to install SomePackage and its Python dependencies from GitHub, a hosting service for the popular version control system (VCS) Git. And suppose SomePackage is found at the the following URL: https://github.com/SomePackage.git. pip (via requirements.txt) supports installing from GitHub. This support requires a working executable to be available (for Git). It is used through a URL prefix: git+. Specify the GitHub web URL To install SomePackage, innclude the following in your requirements.txt file: git+https://github.com/SomePackage#egg=SomePackage You can even specify a ""git ref"" such as branch name, a commit hash or a tag name, as shown in the examples below. Specify a Git branch name Install SomePackage by specifying a branch name such as main, master, develop, etc, in requirements.txt: git+https://github.com/SomePackage.git@main#egg=SomePackage Specify a commit hash Install SomePackage by specifying a commit hash in requirements.txt: git+https://github.com/SomePackage.git@eb40b4ff6f7c5c1e4366cgfg0671291bge918#egg=SomePackage Specify a tag Install SomePackage by specifying a tag in requirements.txt: git+https://github.com/SomePackage.git@v1.1.0#egg=SomePackage Limitations It is currently not possible to install private packages from private GitHub repos using the URI form: git+https://{token}@github.com/user/project.git@{version} where version is a tag, a branch, or a commit. And token is a personal access token with read only permissions. Streamlit Community Cloud only supports installing public packages from public GitHub repos.Previous: Installing dependenciesNext: ImportError libGL.so.1 cannot open shared object file No such file or directoryforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy" https://docs.streamlit.io/develop/tutorials/databases/tigergraph#copy-your-app-secrets-to-the-cloud,"DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceaddTutorialsremoveExecution flowaddConnect to data sourcesremoveAWS S3BigQueryDeta BaseFirestoreopen_in_newGoogle Cloud StorageMicrosoft SQL ServerMongoDBMySQLNeonPostgreSQLPrivate Google SheetPublic Google SheetSnowflakeSupabaseTableauTiDBTigerGraphMultipage appsaddWork with LLMsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Develop/Tutorials/Connect to data sources/TigerGraphConnect Streamlit to TigerGraph Introduction This guide explains how to securely access a TigerGraph database from Streamlit Community Cloud. It uses the pyTigerGraph library and Streamlit's Secrets management. Create a TigerGraph Cloud Database First, follow the official tutorials to create a TigerGraph instance in TigerGraph Cloud, either as a blog or a video. Note your username, password, and subdomain. For this tutorial, we will be using the COVID-19 starter kit. When setting up your solution, select the “COVID-19 Analysis"" option. Once it is started, ensure your data is downloaded and queries are installed. Add username and password to your local app secrets Your local Streamlit app will read secrets from a file .streamlit/secrets.toml in your app’s root directory. Create this file if it doesn’t exist yet and add your TigerGraph Cloud instance username, password, graph name, and subdomain as shown below: # .streamlit/secrets.toml [tigergraph] host = ""https://xxx.i.tgcloud.io/"" username = ""xxx"" password = ""xxx"" graphname = ""xxx"" priority_highImportantAdd this file to .gitignore and don't commit it to your GitHub repo! Copy your app secrets to the cloud As the secrets.toml file above is not committed to GitHub, you need to pass its content to your deployed app (on Streamlit Community Cloud) separately. Go to the app dashboard and in the app's dropdown menu, click on Edit Secrets. Copy the content of secrets.toml into the text area. More information is available at Secrets management. Add PyTigerGraph to your requirements file Add the pyTigerGraph package to your requirements.txt file, preferably pinning its version (replace x.x.x with the version you want installed): # requirements.txt pyTigerGraph==x.x.x Write your Streamlit app Copy the code below to your Streamlit app and run it. Make sure to adapt the name of your graph and query. # streamlit_app.py import streamlit as st import pyTigerGraph as tg # Initialize connection. conn = tg.TigerGraphConnection(**st.secrets[""tigergraph""]) conn.apiToken = conn.getToken(conn.createSecret()) # Pull data from the graph by running the ""mostDirectInfections"" query. # Uses st.cache_data to only rerun when the query changes or after 10 min. @st.cache_data(ttl=600) def get_data(): most_infections = conn.runInstalledQuery(""mostDirectInfections"")[0][""Answer""][0] return most_infections[""v_id""], most_infections[""attributes""] items = get_data() # Print results. st.title(f""Patient {items[0]} has the most direct infections"") for key, val in items[1].items(): st.write(f""Patient {items[0]}'s {key} is {val}."") See st.cache_data above? Without it, Streamlit would run the query every time the app reruns (e.g. on a widget interaction). With st.cache_data, it only runs when the query changes or after 10 minutes (that's what ttl is for). Watch out: If your database updates more frequently, you should adapt ttl or remove caching so viewers always see the latest data. Learn more in Caching. If everything worked out (and you used the example data we created above), your app should look like this: Previous: TiDBNext: Multipage appsforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy" https://docs.streamlit.io/deploy/streamlit-community-cloud/get-started/quickstart#stop-or-delete-your-codespace,"DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudremoveGet startedremoveQuickstartCreate your accountConnect your GitHub accountExplore your workspaceFork and edit a public appTrust and securityDeploy your appaddManage your appaddShare your appaddManage your accountaddTroubleshootingStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Deploy/Streamlit Community Cloud/Get started/QuickstartQuickstart This is a concise set of steps to create your Streamlit Community Cloud account, deploy a sample app, and start editing it with GitHub Codespaces. For other options and complete explanations, start with Create your account. You will be signing in to your Google and GitHub accounts during this process. If you do not already have these accounts, you can create them before you begin. If you do not want to use a Google account, you can create your account with any email. Sign up for Streamlit Community Cloud Go to share.streamlit.io/signup. Click ""Continue with Google"". Enter your Google credentials and follow Google's authentication prompts. After authenticating with Google, click ""Connect GitHub account"". Enter your GitHub credentials and follow GitHub's authentication prompts. Click ""Authorize streamlit"". To finish, fill in your information and click ""Continue"" at the bottom of the screen. You will be taken to your Streamlit workspace. If you see a warning icon (warning) next to ""Settings"" in the upper-right corner, this will be addressed in the next steps. Create a new app with GitHub Codespaces Click the down arrow (expand_more) to expand the options under ""New App"". Click ""Create new app with GitHub Codespaces"". You will be prompted that ""Streamlit is requesting additional permissions"". Click ""Authorize streamlit"". The Streamlit Hello repository will be forked to your GitHub account. Fill in a repository name and click ""Create!"" Click ""Create new codespace"" to confirm the creation of a codespace on your GitHub account. Read more about GitHub Codespaces the learn about monthly limits for free use and paid plans. Wait for GitHub to set up your codespace. GitHub will automatically execute the commands to launch your Streamlit app within your codespace. Your app will be visible in a ""Simple Browser"" on the right. This may take a minute to complete from when your codespace first appears on screen. Edit your app in GitHub Codespaces Go to the app's main file (Hello.py) and add some text to the title in st.write(). Try typing "":balloon:"" at the beginning. Files are automatically saved in your codespace with each edit. Click ""Always rerun"" in the upper-right corner of your app to automatically rerun with each edit. See your edits and keep going! Stop or delete your codespace When you are done, remember to stop your codespace on GitHub to avoid any undesired use of your capacity. Go to github.com/codespaces. At the bottom of the page, all your codespaces are listed. Click the overflow menu icon (more_horiz) for your codespace. Click ""Stop codespace"" if you'd like to return to your work later. Otherwise, click ""Delete."" Congratulations! You just deployed an app to Streamlit Community Cloud. 🎉 Head back to your workspace at share.streamlit.io/ and deploy another Streamlit app. Previous: Get startedNext: Create your accountforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy" https://docs.streamlit.io/develop/tutorials/llms#build-llm-apps,"DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceaddTutorialsremoveExecution flowaddConnect to data sourcesaddMultipage appsaddWork with LLMsremoveBuild a basic LLM chat appBuild an LLM app using LangChainQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Develop/Tutorials/Work with LLMsBuild LLM apps Build a basic chat appBuild a simple OpenAI chat app to get started with Streamlit's chat elements.Build an LLM app using LangChainBuild a chat app using the LangChain framework with OpenAI.Previous: Multipage appsNext: Build a basic LLM chat appforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy" https://docs.streamlit.io/develop/tutorials/databases/aws-s3#copy-your-app-secrets-to-the-cloud,"DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceaddTutorialsremoveExecution flowaddConnect to data sourcesremoveAWS S3BigQueryDeta BaseFirestoreopen_in_newGoogle Cloud StorageMicrosoft SQL ServerMongoDBMySQLNeonPostgreSQLPrivate Google SheetPublic Google SheetSnowflakeSupabaseTableauTiDBTigerGraphMultipage appsaddWork with LLMsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Develop/Tutorials/Connect to data sources/AWS S3Connect Streamlit to AWS S3 Introduction This guide explains how to securely access files on AWS S3 from Streamlit Community Cloud. It uses Streamlit FilesConnection, the s3fs library and optionally Streamlit's Secrets management. Create an S3 bucket and add a file push_pinNoteIf you already have a bucket that you want to use, feel free to skip to the next step. First, sign up for AWS or log in. Go to the S3 console and create a new bucket: Navigate to the upload section of your new bucket: And note down the ""AWS Region"" for later. In this example, it's us-east-1, but it may differ for you. Next, upload the following CSV file, which contains some example data: myfile.csv Create access keys Go to the AWS console, create access keys as shown below and copy the ""Access Key ID"" and ""Secret Access Key"": starTipAccess keys created as a root user have wide-ranging permissions. In order to make your AWS account more secure, you should consider creating an IAM account with restricted permissions and using its access keys. More information here. Set up your AWS credentials locally Streamlit FilesConnection and s3fs will read and use your existing AWS credentials and configuration if available - such as from an ~/.aws/credentials file or environment variables. If you don't already have this set up, or plan to host the app on Streamlit Community Cloud, you should specify the credentials from a file .streamlit/secrets.toml in your app's root directory or your home directory. Create this file if it doesn't exist yet and add to it the access key ID, access key secret, and the AWS default region you noted down earlier, as shown below: # .streamlit/secrets.toml AWS_ACCESS_KEY_ID = ""xxx"" AWS_SECRET_ACCESS_KEY = ""xxx"" AWS_DEFAULT_REGION = ""xxx"" priority_highImportantBe sure to replace xxx above with the values you noted down earlier, and add this file to .gitignore so you don't commit it to your GitHub repo! Copy your app secrets to the cloud To host your app on Streamlit Community Cloud, you will need to pass your credentials to your deployed app via secrets. Go to the app dashboard and in the app's dropdown menu, click on Edit Secrets. Copy the content of secrets.toml above into the text area. More information is available at Secrets management. Add FilesConnection and s3fs to your requirements file Add the FilesConnection and s3fs packages to your requirements.txt file, preferably pinning the versions (replace x.x.x with the version you want installed): # requirements.txt s3fs==x.x.x st-files-connection Write your Streamlit app Copy the code below to your Streamlit app and run it. Make sure to adapt the name of your bucket and file. Note that Streamlit automatically turns the access keys from your secrets file into environment variables, where s3fs searches for them by default. # streamlit_app.py import streamlit as st from st_files_connection import FilesConnection # Create connection object and retrieve file contents. # Specify input format is a csv and to cache the result for 600 seconds. conn = st.connection('s3', type=FilesConnection) df = conn.read(""testbucket-jrieke/myfile.csv"", input_format=""csv"", ttl=600) # Print results. for row in df.itertuples(): st.write(f""{row.Owner} has a :{row.Pet}:"") See st.connection above? This handles secrets retrieval, setup, result caching and retries. By default, read() results are cached without expiring. In this case, we set ttl=600 to ensure the file contents is cached for no longer than 10 minutes. You can also set ttl=0 to disable caching. Learn more in Caching. If everything worked out (and you used the example file given above), your app should look like this: Previous: Connect to data sourcesNext: BigQueryforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy" https://docs.streamlit.io/develop/api-reference/data/st.dataframe#configuring-columns,"DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceremovePAGE ELEMENTSWrite and magicaddText elementsaddData elementsremovest.dataframest.data_editorst.column_configaddst.tablest.metricst.jsonChart elementsaddInput widgetsaddMedia elementsaddLayouts and containersaddChat elementsaddStatus elementsaddThird-party componentsopen_in_newAPPLICATION LOGICNavigation and pagesaddExecution flowaddCaching and stateaddConnections and secretsaddCustom componentsaddUtilitiesaddConfigurationaddTOOLSApp testingaddCommand lineaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Develop/API reference/Data elements/st.dataframestarTipThis page only contains information on the st.dataframe API. For an overview of working with dataframes read Dataframes. If you want to let users interactively edit dataframes, check out st.data_editor. st.dataframeStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeDisplay a dataframe as an interactive table. This command works with dataframes from Pandas, PyArrow, Snowpark, and PySpark. It can also display several other types that can be converted to dataframes, e.g. numpy arrays, lists, sets and dictionaries. Function signature[source] st.dataframe(data=None, width=None, height=None, *, use_container_width=False, hide_index=None, column_order=None, column_config=None) Parameters data (pandas.DataFrame, pandas.Series, pandas.Styler, pandas.Index, pyarrow.Table, numpy.ndarray, pyspark.sql.DataFrame, snowflake.snowpark.dataframe.DataFrame, snowflake.snowpark.table.Table, Iterable, dict, or None) The data to display. If 'data' is a pandas.Styler, it will be used to style its underlying DataFrame. Streamlit supports custom cell values and colors. It does not support some of the more exotic pandas styling features, like bar charts, hovering, and captions. width (int or None) Desired width of the dataframe expressed in pixels. If None, the width will be automatically calculated based on the column content. height (int or None) Desired height of the dataframe expressed in pixels. If None, a default height is used. use_container_width (bool) If True, set the dataframe width to the width of the parent container. This takes precedence over the width argument. hide_index (bool or None) Whether to hide the index column(s). If None (default), the visibility of index columns is automatically determined based on the data. column_order (Iterable of str or None) Specifies the display order of columns. This also affects which columns are visible. For example, column_order=(""col2"", ""col1"") will display 'col2' first, followed by 'col1', and will hide all other non-index columns. If None (default), the order is inherited from the original data structure. column_config (dict or None) Configures how columns are displayed, e.g. their title, visibility, type, or format. This needs to be a dictionary where each key is a column name and the value is one of: None to hide the column. A string to set the display label of the column. One of the column types defined under st.column_config, e.g. st.column_config.NumberColumn(""Dollar values”, format=”$ %d"") to show a column as dollar amounts. See more info on the available column types and config options here. To configure the index column(s), use _index as the column name. Examples import streamlit as st import pandas as pd import numpy as np df = pd.DataFrame(np.random.randn(50, 20), columns=(""col %d"" % i for i in range(20))) st.dataframe(df) # Same as st.write(df) Built with Streamlit 🎈Fullscreen open_in_new You can also pass a Pandas Styler object to change the style of the rendered DataFrame: import streamlit as st import pandas as pd import numpy as np df = pd.DataFrame(np.random.randn(10, 20), columns=(""col %d"" % i for i in range(20))) st.dataframe(df.style.highlight_max(axis=0)) Built with Streamlit 🎈Fullscreen open_in_new Or you can customize the dataframe via column_config, hide_index, or column_order: import random import pandas as pd import streamlit as st df = pd.DataFrame( { ""name"": [""Roadmap"", ""Extras"", ""Issues""], ""url"": [""https://roadmap.streamlit.app"", ""https://extras.streamlit.app"", ""https://issues.streamlit.app""], ""stars"": [random.randint(0, 1000) for _ in range(3)], ""views_history"": [[random.randint(0, 5000) for _ in range(30)] for _ in range(3)], } ) st.dataframe( df, column_config={ ""name"": ""App name"", ""stars"": st.column_config.NumberColumn( ""Github Stars"", help=""Number of stars on GitHub"", format=""%d ⭐"", ), ""url"": st.column_config.LinkColumn(""App URL""), ""views_history"": st.column_config.LineChartColumn( ""Views (past 30 days)"", y_min=0, y_max=5000 ), }, hide_index=True, ) Built with Streamlit 🎈Fullscreen open_in_new st.dataframe supports the use_container_width parameter to stretch across the full container width: import pandas as pd import streamlit as st # Cache the dataframe so it's only loaded once @st.cache_data def load_data(): return pd.DataFrame( { ""first column"": [1, 2, 3, 4], ""second column"": [10, 20, 30, 40], } ) # Boolean to resize the dataframe, stored as a session state variable st.checkbox(""Use container width"", value=False, key=""use_container_width"") df = load_data() # Display the dataframe and allow the user to stretch the dataframe # across the full width of the container, based on the checkbox value st.dataframe(df, use_container_width=st.session_state.use_container_width) Built with Streamlit 🎈Fullscreen open_in_new element.add_rowsStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeConcatenate a dataframe to the bottom of the current one. Function signature[source] element.add_rows(data=None, **kwargs) Parameters data (pandas.DataFrame, pandas.Styler, pyarrow.Table, numpy.ndarray, pyspark.sql.DataFrame, snowflake.snowpark.dataframe.DataFrame, Iterable, dict, or None) Table to concat. Optional. **kwargs (pandas.DataFrame, numpy.ndarray, Iterable, dict, or None) The named dataset to concat. Optional. You can only pass in 1 dataset (including the one in the data parameter). Example import streamlit as st import pandas as pd import numpy as np df1 = pd.DataFrame(np.random.randn(50, 20), columns=(""col %d"" % i for i in range(20))) my_table = st.table(df1) df2 = pd.DataFrame(np.random.randn(50, 20), columns=(""col %d"" % i for i in range(20))) my_table.add_rows(df2) # Now the table shown in the Streamlit app contains the data for # df1 followed by the data for df2. You can do the same thing with plots. For example, if you want to add more data to a line chart: # Assuming df1 and df2 from the example above still exist... my_chart = st.line_chart(df1) my_chart.add_rows(df2) # Now the chart shown in the Streamlit app contains the data for # df1 followed by the data for df2. And for plots whose datasets are named, you can pass the data with a keyword argument where the key is the name: my_chart = st.vega_lite_chart({ 'mark': 'line', 'encoding': {'x': 'a', 'y': 'b'}, 'datasets': { 'some_fancy_name': df1, # <-- named dataset }, 'data': {'name': 'some_fancy_name'}, }), my_chart.add_rows(some_fancy_name=df2) # <-- name used as keyword Interactivity Dataframes displayed with st.dataframe are interactive. End users can sort, resize, search, and copy data to their clipboard. For on overview of features, read our Dataframes guide. Configuring columns You can configure the display and editing behavior of columns in st.dataframe and st.data_editor via the Column configuration API. We have developed the API to let you add images, charts, and clickable URLs in dataframe and data editor columns. Additionally, you can make individual columns editable, set columns as categorical and specify which options they can take, hide the index of the dataframe, and much more. Built with Streamlit 🎈Fullscreen open_in_newPrevious: Data elementsNext: st.data_editorforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy" https://docs.streamlit.io/en/0.68.0/api.html#status-elements,"DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceremovePAGE ELEMENTSWrite and magicaddText elementsaddData elementsaddChart elementsaddInput widgetsaddMedia elementsaddLayouts and containersaddChat elementsaddStatus elementsaddThird-party componentsopen_in_newAPPLICATION LOGICNavigation and pagesaddExecution flowaddCaching and stateaddConnections and secretsaddCustom componentsaddUtilitiesaddConfigurationaddTOOLSApp testingaddCommand lineaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Develop/API referenceAPI reference Streamlit makes it easy for you to visualize, mutate, and share data. The API reference is organized by activity type, like displaying data or optimizing performance. Each section includes methods associated with the activity type, including examples. Browse our API below and click to learn more about any of our available commands! 🎈 Display almost anything Write and magic st.writeWrite arguments to the app.st.write(""Hello **world**!"") st.write(my_data_frame) st.write(my_mpl_figure) st.write_streamWrite generators or streams to the app with a typewriter effect.st.write_stream(my_generator) st.write_stream(my_llm_stream) MagicAny time Streamlit sees either a variable or literal value on its own line, it automatically writes that to your app using st.write""Hello **world**!"" my_data_frame my_mpl_figure Text elements MarkdownDisplay string formatted as Markdown.st.markdown(""Hello **world**!"") TitleDisplay text in title formatting.st.title(""The app title"") HeaderDisplay text in header formatting.st.header(""This is a header"") SubheaderDisplay text in subheader formatting.st.subheader(""This is a subheader"") CaptionDisplay text in small font.st.caption(""This is written small caption text"") Code blockDisplay a code block with optional syntax highlighting.st.code(""a = 1234"") EchoDisplay some code in the app, then execute it. Useful for tutorials.with st.echo(): st.write('This code will be printed') LaTeXDisplay mathematical expressions formatted as LaTeX.st.latex(""\int a x^2 \,dx"") Preformatted textWrite fixed-width and preformatted text.st.text(""Hello world"") DividerDisplay a horizontal rule.st.divider() Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration! PreviousTagsAdd tags to your Streamlit apps. Created by @gagan3012.st_tags(label='# Enter Keywords:', text='Press enter to add more', value=['Zero', 'One', 'Two'], suggestions=['five', 'six', 'seven', 'eight', 'nine', 'three', 'eleven', 'ten', 'four'], maxtags = 4, key='1') NLUApply text mining on a dataframe. Created by @JohnSnowLabs.nlu.load('sentiment').predict('I love NLU! <3') Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.mention(label=""An awesome Streamlit App"", icon=""streamlit"", url=""https://extras.streamlit.app"",) Annotated textDisplay annotated text in Streamlit apps. Created by @tvst.annotated_text(""This "", (""is"", ""verb""), "" some "", (""annotated"", ""adj""), (""text"", ""noun""), "" for those of "", (""you"", ""pronoun""), "" who "", (""like"", ""verb""), "" this sort of "", (""thing"", ""noun""), ""."") Drawable CanvasProvides a sketching canvas using Fabric.js. Created by @andfanilo.st_canvas(fill_color=""rgba(255, 165, 0, 0.3)"", stroke_width=stroke_width, stroke_color=stroke_color, background_color=bg_color, background_image=Image.open(bg_image) if bg_image else None, update_streamlit=realtime_update, height=150, drawing_mode=drawing_mode, point_display_radius=point_display_radius if drawing_mode == 'point' else 0, key=""canvas"",) TagsAdd tags to your Streamlit apps. Created by @gagan3012.st_tags(label='# Enter Keywords:', text='Press enter to add more', value=['Zero', 'One', 'Two'], suggestions=['five', 'six', 'seven', 'eight', 'nine', 'three', 'eleven', 'ten', 'four'], maxtags = 4, key='1') NLUApply text mining on a dataframe. Created by @JohnSnowLabs.nlu.load('sentiment').predict('I love NLU! <3') Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.mention(label=""An awesome Streamlit App"", icon=""streamlit"", url=""https://extras.streamlit.app"",) Annotated textDisplay annotated text in Streamlit apps. Created by @tvst.annotated_text(""This "", (""is"", ""verb""), "" some "", (""annotated"", ""adj""), (""text"", ""noun""), "" for those of "", (""you"", ""pronoun""), "" who "", (""like"", ""verb""), "" this sort of "", (""thing"", ""noun""), ""."") Drawable CanvasProvides a sketching canvas using Fabric.js. Created by @andfanilo.st_canvas(fill_color=""rgba(255, 165, 0, 0.3)"", stroke_width=stroke_width, stroke_color=stroke_color, background_color=bg_color, background_image=Image.open(bg_image) if bg_image else None, update_streamlit=realtime_update, height=150, drawing_mode=drawing_mode, point_display_radius=point_display_radius if drawing_mode == 'point' else 0, key=""canvas"",) TagsAdd tags to your Streamlit apps. Created by @gagan3012.st_tags(label='# Enter Keywords:', text='Press enter to add more', value=['Zero', 'One', 'Two'], suggestions=['five', 'six', 'seven', 'eight', 'nine', 'three', 'eleven', 'ten', 'four'], maxtags = 4, key='1') NLUApply text mining on a dataframe. Created by @JohnSnowLabs.nlu.load('sentiment').predict('I love NLU! <3') Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.mention(label=""An awesome Streamlit App"", icon=""streamlit"", url=""https://extras.streamlit.app"",) Next Data elements DataframesDisplay a dataframe as an interactive table.st.dataframe(my_data_frame) Data editorDisplay a data editor widget.edited = st.data_editor(df, num_rows=""dynamic"") Column configurationConfigure the display and editing behavior of dataframes and data editors.st.column_config.NumberColumn(""Price (in USD)"", min_value=0, format=""$%d"") Static tablesDisplay a static table.st.table(my_data_frame) MetricsDisplay a metric in big bold font, with an optional indicator of how the metric changed.st.metric(""My metric"", 42, 2) Dicts and JSONDisplay object or string as a pretty-printed JSON string.st.json(my_dict) Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration! PreviousImage CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates value = streamlit_image_coordinates(""https://placekitten.com/200/300"") st.write(value) Plotly EventsMake Plotly charts interactive!. Created by @null-jones.from streamlit_plotly_events import plotly_events fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.metric_cards import style_metric_cards col3.metric(label=""No Change"", value=5000, delta=0) style_metric_cards() Streamlit AggridImplementation of Ag-Grid component for Streamlit. Created by @PablocFonseca.df = pd.DataFrame({'col1': [1, 2, 3], 'col2': [4, 5, 6]}) grid_return = AgGrid(df, editable=True) new_df = grid_return['data'] Streamlit FoliumStreamlit Component for rendering Folium maps. Created by @randyzwitch.m = folium.Map(location=[39.949610, -75.150282], zoom_start=16) folium.Marker([39.949610, -75.150282], popup=""Liberty Bell"", tooltip=""Liberty Bell"").add_to(m) st_data = st_folium(m, width=725) Pandas ProfilingPandas profiling component for Streamlit. Created by @okld.df = pd.read_csv(""https://storage.googleapis.com/tf-datasets/titanic/train.csv"") pr = df.profile_report() st_profile_report(pr) Image CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates value = streamlit_image_coordinates(""https://placekitten.com/200/300"") st.write(value) Plotly EventsMake Plotly charts interactive!. Created by @null-jones.from streamlit_plotly_events import plotly_events fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.metric_cards import style_metric_cards col3.metric(label=""No Change"", value=5000, delta=0) style_metric_cards() Streamlit AggridImplementation of Ag-Grid component for Streamlit. Created by @PablocFonseca.df = pd.DataFrame({'col1': [1, 2, 3], 'col2': [4, 5, 6]}) grid_return = AgGrid(df, editable=True) new_df = grid_return['data'] Streamlit FoliumStreamlit Component for rendering Folium maps. Created by @randyzwitch.m = folium.Map(location=[39.949610, -75.150282], zoom_start=16) folium.Marker([39.949610, -75.150282], popup=""Liberty Bell"", tooltip=""Liberty Bell"").add_to(m) st_data = st_folium(m, width=725) Pandas ProfilingPandas profiling component for Streamlit. Created by @okld.df = pd.read_csv(""https://storage.googleapis.com/tf-datasets/titanic/train.csv"") pr = df.profile_report() st_profile_report(pr) Image CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates value = streamlit_image_coordinates(""https://placekitten.com/200/300"") st.write(value) Plotly EventsMake Plotly charts interactive!. Created by @null-jones.from streamlit_plotly_events import plotly_events fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.metric_cards import style_metric_cards col3.metric(label=""No Change"", value=5000, delta=0) style_metric_cards() Next Chart elements Simple area chartsDisplay an area chart.st.area_chart(my_data_frame) Simple bar chartsDisplay a bar chart.st.bar_chart(my_data_frame) Simple line chartsDisplay a line chart.st.line_chart(my_data_frame) Simple scatter chartsDisplay a line chart.st.scatter_chart(my_data_frame) Scatterplots on mapsDisplay a map with points on it.st.map(my_data_frame) MatplotlibDisplay a matplotlib.pyplot figure.st.pyplot(my_mpl_figure) AltairDisplay a chart using the Altair library.st.altair_chart(my_altair_chart) Vega-LiteDisplay a chart using the Vega-Lite library.st.vega_lite_chart(my_vega_lite_chart) PlotlyDisplay an interactive Plotly chart.st.plotly_chart(my_plotly_chart) BokehDisplay an interactive Bokeh chart.st.bokeh_chart(my_bokeh_chart) PyDeckDisplay a chart using the PyDeck library.st.pydeck_chart(my_pydeck_chart) GraphVizDisplay a graph using the dagre-d3 library.st.graphviz_chart(my_graphviz_spec) Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration! PreviousStreamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl(""https://assets5.lottiefiles.com/packages/lf20_V9t630.json"") st_lottie(lottie_hello, key=""hello"") Plotly EventsMake Plotly charts interactive!. Created by @null-jones.fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.chart += get_annotations_chart(annotations=[(""Mar 01, 2008"", ""Pretty good day for GOOG""), (""Dec 01, 2007"", ""Something's going wrong for GOOG & AAPL""), (""Nov 01, 2008"", ""Market starts again thanks to...""), (""Dec 01, 2009"", ""Small crash for GOOG after...""),],) st.altair_chart(chart, use_container_width=True) PlostA deceptively simple plotting library for Streamlit. Created by @tvst.import plost plost.line_chart(my_dataframe, x='time', y='stock_value', color='stock_name',) HiPlotHigh dimensional Interactive Plotting. Created by @facebookresearch.data = [{'dropout':0.1, 'lr': 0.001, 'loss': 10.0, 'optimizer': 'SGD'}, {'dropout':0.15, 'lr': 0.01, 'loss': 3.5, 'optimizer': 'Adam'}, {'dropout':0.3, 'lr': 0.1, 'loss': 4.5, 'optimizer': 'Adam'}] hip.Experiment.from_iterable(data).display() EChartsHigh dimensional Interactive Plotting. Created by @andfanilo.from streamlit_echarts import st_echarts st_echarts(options=options) Streamlit FoliumStreamlit Component for rendering Folium maps. Created by @randyzwitch.m = folium.Map(location=[39.949610, -75.150282], zoom_start=16) st_data = st_folium(m, width=725) Spacy-StreamlitspaCy building blocks and visualizers for Streamlit apps. Created by @explosion.models = [""en_core_web_sm"", ""en_core_web_md""] spacy_streamlit.visualize(models, ""Sundar Pichai is the CEO of Google."") Streamlit AgraphA Streamlit Graph Vis, based on react-grah-vis. Created by @ChrisDelClea.from streamlit_agraph import agraph, Node, Edge, Config agraph(nodes=nodes, edges=edges, config=config) Streamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl(""https://assets5.lottiefiles.com/packages/lf20_V9t630.json"") st_lottie(lottie_hello, key=""hello"") Plotly EventsMake Plotly charts interactive!. Created by @null-jones.fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.chart += get_annotations_chart(annotations=[(""Mar 01, 2008"", ""Pretty good day for GOOG""), (""Dec 01, 2007"", ""Something's going wrong for GOOG & AAPL""), (""Nov 01, 2008"", ""Market starts again thanks to...""), (""Dec 01, 2009"", ""Small crash for GOOG after...""),],) st.altair_chart(chart, use_container_width=True) PlostA deceptively simple plotting library for Streamlit. Created by @tvst.import plost plost.line_chart(my_dataframe, x='time', y='stock_value', color='stock_name',) HiPlotHigh dimensional Interactive Plotting. Created by @facebookresearch.data = [{'dropout':0.1, 'lr': 0.001, 'loss': 10.0, 'optimizer': 'SGD'}, {'dropout':0.15, 'lr': 0.01, 'loss': 3.5, 'optimizer': 'Adam'}, {'dropout':0.3, 'lr': 0.1, 'loss': 4.5, 'optimizer': 'Adam'}] hip.Experiment.from_iterable(data).display() EChartsHigh dimensional Interactive Plotting. Created by @andfanilo.from streamlit_echarts import st_echarts st_echarts(options=options) Streamlit FoliumStreamlit Component for rendering Folium maps. Created by @randyzwitch.m = folium.Map(location=[39.949610, -75.150282], zoom_start=16) st_data = st_folium(m, width=725) Spacy-StreamlitspaCy building blocks and visualizers for Streamlit apps. Created by @explosion.models = [""en_core_web_sm"", ""en_core_web_md""] spacy_streamlit.visualize(models, ""Sundar Pichai is the CEO of Google."") Streamlit AgraphA Streamlit Graph Vis, based on react-grah-vis. Created by @ChrisDelClea.from streamlit_agraph import agraph, Node, Edge, Config agraph(nodes=nodes, edges=edges, config=config) Streamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl(""https://assets5.lottiefiles.com/packages/lf20_V9t630.json"") st_lottie(lottie_hello, key=""hello"") Plotly EventsMake Plotly charts interactive!. Created by @null-jones.fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.chart += get_annotations_chart(annotations=[(""Mar 01, 2008"", ""Pretty good day for GOOG""), (""Dec 01, 2007"", ""Something's going wrong for GOOG & AAPL""), (""Nov 01, 2008"", ""Market starts again thanks to...""), (""Dec 01, 2009"", ""Small crash for GOOG after...""),],) st.altair_chart(chart, use_container_width=True) Next Input widgets ButtonDisplay a button widget.clicked = st.button(""Click me"") Download buttonDisplay a download button widget.st.download_button(""Download file"", file) Form buttonDisplay a form submit button. For use with st.form.st.form_submit_button(""Sign up"") Link buttonDisplay a link button.st.link_button(""Go to gallery"", url) Page linkDisplay a link to another page in a multipage app.st.page_link(""app.py"", label=""Home"", icon=""🏠"") st.page_link(""pages/profile.py"", label=""My profile"") CheckboxDisplay a checkbox widget.selected = st.checkbox(""I agree"") Color pickerDisplay a color picker widget.color = st.color_picker(""Pick a color"") MultiselectDisplay a multiselect widget. The multiselect widget starts as empty.choices = st.multiselect(""Buy"", [""milk"", ""apples"", ""potatoes""]) RadioDisplay a radio button widget.choice = st.radio(""Pick one"", [""cats"", ""dogs""]) SelectboxDisplay a select widget.choice = st.selectbox(""Pick one"", [""cats"", ""dogs""]) Select-sliderDisplay a slider widget to select items from a list.size = st.select_slider(""Pick a size"", [""S"", ""M"", ""L""]) ToggleDisplay a toggle widget.activated = st.toggle(""Activate"") Number inputDisplay a numeric input widget.choice = st.number_input(""Pick a number"", 0, 10) SliderDisplay a slider widget.number = st.slider(""Pick a number"", 0, 100) Date inputDisplay a date input widget.date = st.date_input(""Your birthday"") Time inputDisplay a time input widget.time = st.time_input(""Meeting time"") Chat inputDisplay a chat input widget.prompt = st.chat_input(""Say something"") if prompt: st.write(f""The user has sent: {prompt}"") Text-areaDisplay a multi-line text input widget.text = st.text_area(""Text to translate"") Text inputDisplay a single-line text input widget.name = st.text_input(""First name"") Data editorDisplay a data editor widget.edited = st.experimental_data_editor(df, num_rows=""dynamic"") File UploaderDisplay a file uploader widget.data = st.file_uploader(""Upload a CSV"") Camera inputDisplay a widget that allows users to upload images directly from a camera.image = st.camera_input(""Take a picture"") Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration! PreviousStreamlit ChatStreamlit Component for a Chatbot UI. Created by @AI-Yash.from streamlit_chat import message message(""My message"") message(""Hello bot!"", is_user=True) # align's the message to the right Streamlit Option MenuSelect a single item from a list of options in a menu. Created by @victoryhb.from streamlit_option_menu import option_menu option_menu(""Main Menu"", [""Home"", 'Settings'], icons=['house', 'gear'], menu_icon=""cast"", default_index=1) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.stoggle import stoggle stoggle( ""Click me!"", """"""🥷 Surprise! Here's some additional content"""""",) Streamlit ElementsCreate a draggable and resizable dashboard in Streamlit. Created by @okls.from streamlit_elements import elements, mui, html with elements(""new_element""): mui.Typography(""Hello world"") TagsAdd tags to your Streamlit apps. Created by @gagan3012.from streamlit_tags import st_tags st_tags(label='# Enter Keywords:', text='Press enter to add more', value=['Zero', 'One', 'Two'], suggestions=['five', 'six', 'seven', 'eight', 'nine', 'three', 'eleven', 'ten', 'four'], maxtags = 4, key='1') StqdmThe simplest way to handle a progress bar in streamlit app. Created by @Wirg.from stqdm import stqdm for _ in stqdm(range(50)): sleep(0.5) TimelineDisplay a Timeline in Streamlit apps using TimelineJS. Created by @innerdoc.from streamlit_timeline import timeline with open('example.json', ""r"") as f: timeline(f.read(), height=800) Camera input liveAlternative for st.camera_input which returns the webcam images live. Created by @blackary.from camera_input_live import camera_input_live image = camera_input_live() st.image(value) Streamlit AceAce editor component for Streamlit. Created by @okld.from streamlit_ace import st_ace content = st_ace() content Streamlit ChatStreamlit Component for a Chatbot UI. Created by @AI-Yash.from streamlit_chat import message message(""My message"") message(""Hello bot!"", is_user=True) # align's the message to the right Streamlit Option MenuSelect a single item from a list of options in a menu. Created by @victoryhb.from streamlit_option_menu import option_menu option_menu(""Main Menu"", [""Home"", 'Settings'], icons=['house', 'gear'], menu_icon=""cast"", default_index=1) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.stoggle import stoggle stoggle( ""Click me!"", """"""🥷 Surprise! Here's some additional content"""""",) Streamlit ElementsCreate a draggable and resizable dashboard in Streamlit. Created by @okls.from streamlit_elements import elements, mui, html with elements(""new_element""): mui.Typography(""Hello world"") TagsAdd tags to your Streamlit apps. Created by @gagan3012.from streamlit_tags import st_tags st_tags(label='# Enter Keywords:', text='Press enter to add more', value=['Zero', 'One', 'Two'], suggestions=['five', 'six', 'seven', 'eight', 'nine', 'three', 'eleven', 'ten', 'four'], maxtags = 4, key='1') StqdmThe simplest way to handle a progress bar in streamlit app. Created by @Wirg.from stqdm import stqdm for _ in stqdm(range(50)): sleep(0.5) TimelineDisplay a Timeline in Streamlit apps using TimelineJS. Created by @innerdoc.from streamlit_timeline import timeline with open('example.json', ""r"") as f: timeline(f.read(), height=800) Camera input liveAlternative for st.camera_input which returns the webcam images live. Created by @blackary.from camera_input_live import camera_input_live image = camera_input_live() st.image(value) Streamlit AceAce editor component for Streamlit. Created by @okld.from streamlit_ace import st_ace content = st_ace() content Streamlit ChatStreamlit Component for a Chatbot UI. Created by @AI-Yash.from streamlit_chat import message message(""My message"") message(""Hello bot!"", is_user=True) # align's the message to the right Streamlit Option MenuSelect a single item from a list of options in a menu. Created by @victoryhb.from streamlit_option_menu import option_menu option_menu(""Main Menu"", [""Home"", 'Settings'], icons=['house', 'gear'], menu_icon=""cast"", default_index=1) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.stoggle import stoggle stoggle( ""Click me!"", """"""🥷 Surprise! Here's some additional content"""""",) Next Media elements ImageDisplay an image or list of images.st.image(numpy_array) st.image(image_bytes) st.image(file) st.image(""https://example.com/myimage.jpg"") AudioDisplay an audio player.st.audio(numpy_array) st.audio(audio_bytes) st.audio(file) st.audio(""https://example.com/myaudio.mp3"", format=""audio/mp3"") VideoDisplay a video player.st.video(numpy_array) st.video(video_bytes) st.video(file) st.video(""https://example.com/myvideo.mp4"", format=""video/mp4"") Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration! PreviousStreamlit CropperA simple image cropper for Streamlit. Created by @turner-anderson.from streamlit_cropper import st_cropper st_cropper(img, realtime_update=realtime_update, box_color=box_color, aspect_ratio=aspect_ratio) Image CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates streamlit_image_coordinates(""https://placekitten.com/200/300"") Streamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl(""https://assets5.lottiefiles.com/packages/lf20_V9t630.json"") st_lottie(lottie_hello, key=""hello"") Streamlit WebrtcHandling and transmitting real-time video/audio streams with Streamlit. Created by @whitphx.from streamlit_webrtc import webrtc_streamer webrtc_streamer(key=""sample"") Drawable CanvasProvides a sketching canvas using Fabric.js. Created by @andfanilo.from streamlit_drawable_canvas import st_canvas st_canvas(fill_color=""rgba(255, 165, 0, 0.3)"", stroke_width=stroke_width, stroke_color=stroke_color, background_color=bg_color, background_image=Image.open(bg_image) if bg_image else None, update_streamlit=realtime_update, height=150, drawing_mode=drawing_mode, point_display_radius=point_display_radius if drawing_mode == 'point' else 0, key=""canvas"",) Image ComparisonCompare images with a slider using JuxtaposeJS. Created by @fcakyon.from streamlit_image_comparison import image_comparison image_comparison(img1=""image1.jpg"", img2=""image2.jpg"",) Streamlit CropperA simple image cropper for Streamlit. Created by @turner-anderson.from streamlit_cropper import st_cropper st_cropper(img, realtime_update=realtime_update, box_color=box_color, aspect_ratio=aspect_ratio) Image CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates streamlit_image_coordinates(""https://placekitten.com/200/300"") Streamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl(""https://assets5.lottiefiles.com/packages/lf20_V9t630.json"") st_lottie(lottie_hello, key=""hello"") Streamlit WebrtcHandling and transmitting real-time video/audio streams with Streamlit. Created by @whitphx.from streamlit_webrtc import webrtc_streamer webrtc_streamer(key=""sample"") Drawable CanvasProvides a sketching canvas using Fabric.js. Created by @andfanilo.from streamlit_drawable_canvas import st_canvas st_canvas(fill_color=""rgba(255, 165, 0, 0.3)"", stroke_width=stroke_width, stroke_color=stroke_color, background_color=bg_color, background_image=Image.open(bg_image) if bg_image else None, update_streamlit=realtime_update, height=150, drawing_mode=drawing_mode, point_display_radius=point_display_radius if drawing_mode == 'point' else 0, key=""canvas"",) Image ComparisonCompare images with a slider using JuxtaposeJS. Created by @fcakyon.from streamlit_image_comparison import image_comparison image_comparison(img1=""image1.jpg"", img2=""image2.jpg"",) Streamlit CropperA simple image cropper for Streamlit. Created by @turner-anderson.from streamlit_cropper import st_cropper st_cropper(img, realtime_update=realtime_update, box_color=box_color, aspect_ratio=aspect_ratio) Image CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates streamlit_image_coordinates(""https://placekitten.com/200/300"") Streamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl(""https://assets5.lottiefiles.com/packages/lf20_V9t630.json"") st_lottie(lottie_hello, key=""hello"") Next Layouts and containers ColumnsInsert containers laid out as side-by-side columns.col1, col2 = st.columns(2) col1.write(""this is column 1"") col2.write(""this is column 2"") ContainerInsert a multi-element container.c = st.container() st.write(""This will show last"") c.write(""This will show first"") c.write(""This will show second"") Modal dialogsInsert a modal dialog that can rerun independently from the rest of the script.@st.experimental_dialog(""Sign up"") def email_form(): name = st.text_input(""Name"") email = st.text_input(""Email"") EmptyInsert a single-element container.c = st.empty() st.write(""This will show last"") c.write(""This will be replaced"") c.write(""This will show first"") ExpanderInsert a multi-element container that can be expanded/collapsed.with st.expander(""Open to see more""): st.write(""This is more content"") PopoverInsert a multi-element popover container that can be opened/closed.with st.popover(""Settings""): st.checkbox(""Show completed"") SidebarDisplay items in a sidebar.st.sidebar.write(""This lives in the sidebar"") st.sidebar.button(""Click me!"") TabsInsert containers separated into tabs.tab1, tab2 = st.tabs([""Tab 1"", ""Tab2""]) tab1.write(""this is tab 1"") tab2.write(""this is tab 2"") Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration!Streamlit ElementsCreate a draggable and resizable dashboard in Streamlit. Created by @okls.from streamlit_elements import elements, mui, html with elements(""new_element""): mui.Typography(""Hello world"") PydanticAuto-generate Streamlit UI from Pydantic Models and Dataclasses. Created by @lukasmasuch.import streamlit_pydantic as sp sp.pydantic_form(key=""my_form"", model=ExampleModel) Streamlit PagesAn experimental version of Streamlit Multi-Page Apps. Created by @blackary.from st_pages import Page, show_pages, add_page_title show_pages([ Page(""streamlit_app.py"", ""Home"", ""🏠""), Page(""other_pages/page2.py"", ""Page 2"", "":books:""), ]) Chat elements Streamlit provides a few commands to help you build conversational apps. These chat elements are designed to be used in conjunction with each other, but you can also use them separately. st.chat_message lets you insert a chat message container into the app so you can display messages from the user or the app. Chat containers can contain other Streamlit elements, including charts, tables, text, and more. st.chat_input lets you display a chat input widget so the user can type in a message. Chat inputDisplay a chat input widget.prompt = st.chat_input(""Say something"") if prompt: st.write(f""The user has sent: {prompt}"") Chat messageInsert a chat message container.import numpy as np with st.chat_message(""user""): st.write(""Hello 👋"") st.line_chart(np.random.randn(30, 3)) Status containerDisplay output of long-running tasks in a container.with st.status('Running'): do_something_slow() st.write_streamWrite generators or streams to the app with a typewriter effect.st.write_stream(my_generator) st.write_stream(my_llm_stream) Status elements Progress barDisplay a progress bar.for i in range(101): st.progress(i) do_something_slow() SpinnerTemporarily displays a message while executing a block of code.with st.spinner(""Please wait...""): do_something_slow() Status containerDisplay output of long-running tasks in a container.with st.status('Running'): do_something_slow() ToastBriefly displays a toast message in the bottom-right corner.st.toast('Butter!', icon='🧈') BalloonsDisplay celebratory balloons!do_something() # Celebrate when all done! st.balloons() SnowflakesDisplay celebratory snowflakes!do_something() # Celebrate when all done! st.snow() Success boxDisplay a success message.st.success(""Match found!"") Info boxDisplay an informational message.st.info(""Dataset is updated every day at midnight."") Warning boxDisplay warning message.st.warning(""Unable to fetch image. Skipping..."") Error boxDisplay error message.st.error(""We encountered an error"") Exception outputDisplay an exception.e = RuntimeError(""This is an exception of type RuntimeError"") st.exception(e) Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration!StqdmThe simplest way to handle a progress bar in streamlit app. Created by @Wirg.from stqdm import stqdm for _ in stqdm(range(50)): sleep(0.5) Custom notification boxA custom notification box with the ability to close it out. Created by @Socvest.from streamlit_custom_notification_box import custom_notification_box styles = {'material-icons':{'color': 'red'}, 'text-icon-link-close-container': {'box-shadow': '#3896de 0px 4px'}, 'notification-text': {'':''}, 'close-button':{'':''}, 'link':{'':''}} custom_notification_box(icon='info', textDisplay='We are almost done with your registration...', externalLink='more info', url='#', styles=styles, key=""foo"") Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.let_it_rain import rain rain(emoji=""🎈"", font_size=54, falling_speed=5, animation_length=""infinite"",) App logic and configuration Navigation and pages Switch pageProgrammatically navigates to a specified page.st.switch_page(""pages/my_page.py"") Page linkDisplay a link to another page in a multipage app.st.page_link(""app.py"", label=""Home"", icon=""🏠"") st.page_link(""pages/profile.py"", label=""My profile"") Execution flow Modal dialogsInsert a modal dialog that can rerun independently from the rest of the script.@st.experimental_dialog(""Sign up"") def email_form(): name = st.text_input(""Name"") email = st.text_input(""Email"") FormsCreate a form that batches elements together with a “Submit"" button.with st.form(key='my_form'): name = st.text_input(""Name"") email = st.text_input(""Email"") st.form_submit_button(""Sign up"") Partial rerunsDefine a fragment to rerun independently from the rest of the script.@st.experimental_fragment(run_every=""10s"") def fragment(): df = get_data() st.line_chart(df) Rerun scriptRerun the script immediately.st.rerun() Stop executionStops execution immediately.st.stop() Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration!AutorefreshForce a refresh without tying up a script. Created by @kmcgrady.from streamlit_autorefresh import st_autorefresh st_autorefresh(interval=2000, limit=100, key=""fizzbuzzcounter"") PydanticAuto-generate Streamlit UI from Pydantic Models and Dataclasses. Created by @lukasmasuch.import streamlit_pydantic as sp sp.pydantic_form(key=""my_form"", model=ExampleModel) Streamlit PagesAn experimental version of Streamlit Multi-Page Apps. Created by @blackary.from st_pages import Page, show_pages, add_page_title show_pages([ Page(""streamlit_app.py"", ""Home"", ""🏠""), Page(""other_pages/page2.py"", ""Page 2"", "":books:""), ]) Caching and state Cache dataFunction decorator to cache functions that return data (e.g. dataframe transforms, database queries, ML inference).@st.cache_data def long_function(param1, param2): # Perform expensive computation here or # fetch data from the web here return data Cache resourceFunction decorator to cache functions that return global resources (e.g. database connections, ML models).@st.cache_resource def init_model(): # Return a global resource here return pipeline( ""sentiment-analysis"", model=""distilbert-base-uncased-finetuned-sst-2-english"" ) Session stateSession state is a way to share variables between reruns, for each user session.st.session_state['key'] = value Query parametersGet, set, or clear the query parameters that are shown in the browser's URL bar.st.query_params[key] = value st.query_params.clear() Connections and databases Setup your connection Create a connectionConnect to a data source or APIconn = st.connection('pets_db', type='sql') pet_owners = conn.query('select * from pet_owners') st.dataframe(pet_owners) Built-in connections SnowflakeConnectionA connection to Snowflake.conn = st.connection('snowflake') SQLConnectionA connection to a SQL database using SQLAlchemy.conn = st.connection('sql') Build your own connections Connection base classBuild your own connection with BaseConnection.class MyConnection(BaseConnection[myconn.MyConnection]): def _connect(self, **kwargs) -> MyConnection: return myconn.connect(**self._secrets, **kwargs) def query(self, query): return self._instance.query(query) Secrets management Secrets singletonAccess secrets from a local TOML file.key = st.secrets[""OpenAI_key""] Secrets fileSave your secrets in a per-project or per-profile TOML file.OpenAI_key = """" Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration!AuthenticatorA secure authentication module to validate user credentials. Created by @mkhorasani.import streamlit_authenticator as stauth authenticator = stauth.Authenticate( config['credentials'], config['cookie']['name'], config['cookie']['key'], config['cookie']['expiry_days'], config['preauthorized']) WS localStorageA simple synchronous way of accessing localStorage from your app. Created by @gagangoku.from streamlit_ws_localstorage import injectWebsocketCode ret = conn.setLocalStorageVal(key='k1', val='v1') st.write('ret: ' + ret) Streamlit Auth0The fastest way to provide comprehensive login inside Streamlit. Created by @conradbez.from auth0_component import login_button user_info = login_button(clientId, domain = domain) st.write(user_info) Custom Components Declare a componentCreate and register a custom component.st.components.v1.declare_component( ""custom_slider"", ""/frontend"", ) HTMLDisplay an HTML string in an iframe.st.components.v1.html( ""

Foo bar.

"" ) iframeLoad a remote URL in an iframe.st.components.v1.iframe( ""docs.streamlit.io"" ) Utilities and user info User infost.experimental_user returns information about the logged-in user of private apps on Streamlit Community Cloud.if st.experimental_user.email == ""foo@corp.com"": st.write(""Welcome back, "", st.experimental_user.email) else: st.write(""You are not authorized to view this page."") Get helpDisplay object’s doc string, nicely formatted.st.help(st.write) st.help(pd.DataFrame) Render HTMLRenders HTML strings to your app.css = """""" """""" st.html(css) Configuration Configuration fileConfigures the default settings for your app.your-project/ ├── .streamlit/ │ └── config.toml └── your_app.py Set page title, favicon, and moreConfigures the default settings of the page.st.set_page_config( page_title=""My app"", page_icon="":shark:"", ) Developer tools App testing st.testing.v1.AppTestst.testing.v1.AppTest simulates a running Streamlit app for testing.from streamlit.testing.v1 import AppTest at = AppTest.from_file(""streamlit_app.py"") at.secrets[""WORD""] = ""Foobar"" at.run() assert not at.exception at.text_input(""word"").input(""Bazbat"").run() assert at.warning[0].value == ""Try again."" AppTest.from_filest.testing.v1.AppTest.from_file initializes a simulated app from a file.from streamlit.testing.v1 import AppTest at = AppTest.from_file(""streamlit_app.py"") at.run() AppTest.from_stringst.testing.v1.AppTest.from_string initializes a simulated app from a string.from streamlit.testing.v1 import AppTest at = AppTest.from_string(app_script_as_string) at.run() AppTest.from_functionst.testing.v1.AppTest.from_function initializes a simulated app from a function.from streamlit.testing.v1 import AppTest at = AppTest.from_function(app_script_as_callable) at.run() BlockA representation of container elements, including: st.chat_message st.columns st.sidebar st.tabs The main body of the app. # at.sidebar returns a Block at.sidebar.button[0].click().run() assert not at.exception ElementThe base class for representation of all elements, including: st.title st.header st.markdown st.dataframe # at.title returns a sequence of Title # Title inherits from Element assert at.title[0].value == ""My awesome app"" ButtonA representation of st.button and st.form_submit_button.at.button[0].click().run() ChatInputA representation of st.chat_input.at.chat_input[0].set_value(""What is Streamlit?"").run() CheckboxA representation of st.checkbox.at.checkbox[0].check().run() ColorPickerA representation of st.color_picker.at.color_picker[0].pick(""#FF4B4B"").run() DateInputA representation of st.date_input.release_date = datetime.date(2023, 10, 26) at.date_input[0].set_value(release_date).run() MultiselectA representation of st.multiselect.at.multiselect[0].select(""New York"").run() NumberInputA representation of st.number_input.at.number_input[0].increment().run() RadioA representation of st.radio.at.radio[0].set_value(""New York"").run() SelectSliderA representation of st.select_slider.at.select_slider[0].set_range(""A"",""C"").run() SelectboxA representation of st.selectbox.at.selectbox[0].select(""New York"").run() SliderA representation of st.slider.at.slider[0].set_range(2,5).run() TextAreaA representation of st.text_area.at.text_area[0].input(""Streamlit is awesome!"").run() TextInputA representation of st.text_input.at.text_input[0].input(""Streamlit"").run() TimeInputA representation of st.time_input.at.time_input[0].increment().run() ToggleA representation of st.toggle.at.toggle[0].set_value(""True"").run() Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration!Pandas ProfilingPandas profiling component for Streamlit. Created by @okld.df = pd.read_csv(""https://storage.googleapis.com/tf-datasets/titanic/train.csv"") pr = df.profile_report() st_profile_report(pr) Streamlit AceAce editor component for Streamlit. Created by @okld.from streamlit_ace import st_ace content = st_ace() content Streamlit AnalyticsTrack & visualize user interactions with your streamlit app. Created by @jrieke.import streamlit_analytics with streamlit_analytics.track(): st.text_input(""Write something"") Previous: ConceptsNext: Write and magicforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy" https://docs.streamlit.io/develop/api-reference/execution-flow#execution-flow,"DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceremovePAGE ELEMENTSWrite and magicaddText elementsaddData elementsaddChart elementsaddInput widgetsaddMedia elementsaddLayouts and containersaddChat elementsaddStatus elementsaddThird-party componentsopen_in_newAPPLICATION LOGICNavigation and pagesaddExecution flowremovest.dialogst.formst.form_submit_buttonst.fragmentst.rerunst.stopCaching and stateaddConnections and secretsaddCustom componentsaddUtilitiesaddConfigurationaddTOOLSApp testingaddCommand lineaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Develop/API reference/Execution flowExecution flow Change execution By default, Streamlit apps execute the script entirely, but we allow some functionality to handle control flow in your applications. Modal dialogsInsert a modal dialog that can rerun independently from the rest of the script.@st.experimental_dialog(""Sign up"") def email_form(): name = st.text_input(""Name"") email = st.text_input(""Email"") Partial rerunsDefine a fragment to rerun independently from the rest of the script.@st.experimental_fragment(run_every=""10s"") def fragment(): df = get_data() st.line_chart(df) Rerun scriptRerun the script immediately.st.rerun() Stop executionStops execution immediately.st.stop() Group multiple widgets By default, Streamlit reruns your script everytime a user interacts with your app. However, sometimes it's a better user experience to wait until a group of related widgets is filled before actually rerunning the script. That's what st.form is for! FormsCreate a form that batches elements together with a “Submit"" button.with st.form(key='my_form'): name = st.text_input(""Name"") email = st.text_input(""Email"") st.form_submit_button(""Sign up"") Form submit buttonDisplay a form submit button.with st.form(key='my_form'): name = st.text_input(""Name"") email = st.text_input(""Email"") st.form_submit_button(""Sign up"") Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration!AutorefreshForce a refresh without tying up a script. Created by @kmcgrady.from streamlit_autorefresh import st_autorefresh st_autorefresh(interval=2000, limit=100, key=""fizzbuzzcounter"") PydanticAuto-generate Streamlit UI from Pydantic Models and Dataclasses. Created by @lukasmasuch.import streamlit_pydantic as sp sp.pydantic_form(key=""my_form"", model=ExampleModel) Streamlit PagesAn experimental version of Streamlit Multi-Page Apps. Created by @blackary.from st_pages import Page, show_pages, add_page_title show_pages([ Page(""streamlit_app.py"", ""Home"", ""🏠""), Page(""other_pages/page2.py"", ""Page 2"", "":books:""), ]) Previous: Navigation and pagesNext: st.dialogforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy" https://docs.streamlit.io/develop/concepts/architecture/fragments#fragments-vs-caching,"DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsremoveCOREArchitecture & executionremoveRunning your appStreamlit's architectureThe app chromeCachingSession StateFormsFragmentsWidget behaviorMultipage appsaddApp designaddADDITIONALConnections and secretsaddCustom componentsaddConfiguration and themingaddApp testingaddAPI referenceaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Develop/Concepts/Architecture & execution/FragmentsWorking with fragments and partial reruns Reruns are a central part of every Streamlit app. When users interact with widgets, your script reruns from top to bottom, and your app's frontend is updated. Streamlit provides several features to help you develop your app within this execution model. Streamlit version 1.33.0 introduced fragments to allow rerunning a portion of your code instead of your full script. As your app grows larger and more complex, these partial reruns help your app be efficient and performant. Fragments give you finer, easy-to-understand control over your app's execution flow. Before you read about fragments, we recommend having a basic understanding of caching, Session State, and forms. Use cases for fragments Fragments are versatile and applicable to a wide variety of circumstances. Here are just a few, common scenarios where fragments are useful: Your app has multiple visualizations and each one takes time to load, but you have a filter input that only updates one of them. You have a dynamic form that doesn't need to update the rest of your app (until the form is complete). You want to automatically update a single component or group of components to stream data. Defining and calling a fragment Streamlit provides a decorator (st.experimental_fragment) to turn any function into a fragment function. When you call a fragment function that contains a widget function, a user triggers a partial rerun instead of a full rerun when they interact with that fragment's widget. During a partial rerun, your fragment function is re-executed. Anything within the main body of your fragment is updated on the frontend, while the rest of your app remains the same. We'll describe fragments written across multiple containers later on. Here is a basic example of defining and calling a fragment function. Just like with caching, remember to call your function after defining it. import streamlit as st @st.experimental_fragment def fragment_function(): if st.button(""Hi!""): st.write(""Hi back!"") fragment_function() If you want the main body of your fragment to appear in the sidebar or another container, call your fragment function inside a context manager. with st.sidebar: fragment_function() Partial rerun execution flow Consider the following code with the explanation and diagram below. import streamlit as st st.title(""My Awesome App"") @st.experimental_fragment() def toggle_and_text(): cols = st.columns(2) cols[0].toggle(""Toggle"") cols[1].text_area(""Enter text"") @st.experimental_fragment() def filter_and_file(): cols = st.columns(2) cols[0].checkbox(""Filter"") cols[1].file_uploader(""Upload image"") toggle_and_text() cols = st.columns(2) cols[0].selectbox(""Select"", [1,2,3], None) cols[1].button(""Update"") filter_and_file() When a user interacts with an input widget inside a fragment, only the fragment reruns instead of the full script. When a user interacts with an input widget outside a fragment, the full script reruns as usual. If you run the code above, the full script will run top to bottom on your app's initial load. If you flip the toggle button in your running app, the first fragment (toggle_and_text()) will rerun, redrawing the toggle and text area while leaving everything else unchanged. If you click the checkbox, the second fragment (filter_and_file()) will rerun and consequently redraw the checkbox and file uploader. Everything else remains unchanged. Finally, if you click the update button, the full script will rerun, and Streamlit will redraw everything. Fragment return values and interacting with the rest of your app Streamlit ignores fragment return values during fragment reruns, so defining return values for your fragment functions is not recommended. Instead, if your fragment needs to share data with the rest of your app, use Session State. Fragments are just functions in your script, so they can access Session State, imported modules, and other Streamlit elements like containers. If your fragment writes to any container created outside of itself, note the following difference in behavior: Elements drawn in the main body of your fragment are cleared and redrawn in place during a fragment rerun. Repeated fragment reruns will not cause additional elements to appear. Elements drawn to containers outside the main body of fragment will not be cleared with each fragment rerun. Instead, Streamlit will draw them additively and these elements will accumulate until the next full-script rerun. To prevent elements from accumulating in outside containers, use st.empty containers. For a related tutorial, see Create a fragment across multiple containers. If you need to trigger a full-script rerun from inside a fragment, call st.rerun. For a related tutorial, see Trigger a full-script rerun from inside a fragment. Automate fragment reruns st.experimental_fragment includes a convenient run_every parameter that causes the fragment to rerun automatically at the specified time interval. These reruns are in addition to any reruns (fragment or full-script) triggered by your user. The automatic fragment reruns will continue even if your user is not interacting with your app. This is a great way to show a live data stream or status on a running background job, efficiently updating your rendered data and only your rendered data. @st.experimental_fragment(run_every=""10s"") def auto_function(): # This will update every 10 seconds! df = get_latest_updates() st.line_chart(df) auto_function() For a related tutorial, see Start and stop a streaming fragment. Compare fragments to other Streamlit features Fragments vs forms Here is a comparison between fragments and forms: Forms allow users to interact with widgets without rerunning your app. Streamlit does not send user actions within a form to your app's Python backend until the form is submitted. Widgets within a form can not dynamically update other widgets (in or out of the form) in real-time. Fragments run independently from the rest of your code. As your users interact with fragment widgets, their actions are immediately processed by your app's Python backend and your fragment code is rerun. Widgets within a fragment can dynamically update other widgets within the same fragment in real-time. A form batches user input without interaction between any widgets. A fragment immediately processes user input but limits the scope of the rerun. Fragments vs callbacks Here is a comparison between fragments and callbacks: Callbacks allow you to execute a function at the beginning of a script rerun. A callback is a single prefix to your script rerun. Fragments allow you to rerun a portion of your script. A fragment is a repeatable postfix to your script, running each time a user interacts with a fragment widget, or automatically in sequence when run_every is set. When callbacks render elements to your page, they are rendered before the rest of your page elements. When fragments render elements to your page, they are updated with each fragment rerun (unless they are written to containers outside of the fragment, in which case they accumulate there). Fragments vs custom components Here is a comparison between fragments and custom components: Components are custom frontend code that can interact with the Python code, native elements, and widgets in your Streamlit app. Custom components extend what’s possible with Streamlit. They follow the normal Streamlit execution flow. Fragments are parts of your app that can rerun independently of the full app. Fragments can be composed of multiple Streamlit elements, widgets, or any Python code. A fragment can include one or more custom components. A custom component could not easily include a fragment! Fragments vs caching Here is a comparison between fragments and caching: Caching: allows you to skip over a function and return a previously computed value. When you use caching, you execute everything except the cached function (if you've already run it before). Fragments: allow you to freeze most of your app and just execute the fragment. When you use fragments, you execute only the fragment (when triggering a fragment rerun). Caching saves you from unnecessarily running a piece of your app while the rest runs. Fragments save you from running your full app when you only want to run one piece. Limitations and unsupported behavior Fragments can't detect a change in input values. It is best to use Session State for dynamic input and output for fragment functions. Calling fragments within fragments is unsupported. Using caching and fragments on the same function is unsupported. Previous: FormsNext: Widget behaviorforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy" https://docs.streamlit.io/develop/concepts/configuration,"DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsremoveCOREArchitecture & executionaddMultipage appsaddApp designaddADDITIONALConnections and secretsaddCustom componentsaddConfiguration and themingremoveConfiguration optionsHTTPS supportServing static filesCustomize your themeApp testingaddAPI referenceaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Develop/Concepts/Configuration and themingConfigure and customize your app Configuration optionsUnderstand they types of options available to you through Streamlit configuration.HTTPS supportUnderstand how to configure SSL and TLS for your Streamlit app.Static file servingUnderstand how to host files alongside your app to make them accessible by URL. Use this if you want to point to files with raw HTML.ThemingUnderstand how to use the theming configuration options to customize the color and appearance of your app.Previous: Custom componentsNext: Configuration optionsforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy" https://docs.streamlit.io/develop/api-reference/widgets#other-input-elements,"DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceremovePAGE ELEMENTSWrite and magicaddText elementsaddData elementsaddChart elementsaddInput widgetsremoveBUTTONSst.buttonst.download_buttonst.form_submit_buttonlinkst.link_buttonst.page_linkSELECTIONSst.checkboxst.color_pickerst.multiselectst.radiost.selectboxst.select_sliderst.toggleNUMERICst.number_inputst.sliderDATE & TIMEst.date_inputst.time_inputTEXTst.chat_inputlinkst.text_areast.text_inputMEDIA & FILESst.camera_inputst.data_editorlinkst.file_uploaderMedia elementsaddLayouts and containersaddChat elementsaddStatus elementsaddThird-party componentsopen_in_newAPPLICATION LOGICNavigation and pagesaddExecution flowaddCaching and stateaddConnections and secretsaddCustom componentsaddUtilitiesaddConfigurationaddTOOLSApp testingaddCommand lineaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Develop/API reference/Input widgetsInput widgets With widgets, Streamlit allows you to bake interactivity directly into your apps with buttons, sliders, text inputs, and more. Button elements ButtonDisplay a button widget.clicked = st.button(""Click me"") Download buttonDisplay a download button widget.st.download_button(""Download file"", file) Form buttonDisplay a form submit button. For use with st.form.st.form_submit_button(""Sign up"") Link buttonDisplay a link button.st.link_button(""Go to gallery"", url) Page linkDisplay a link to another page in a multipage app.st.page_link(""app.py"", label=""Home"", icon=""🏠"") st.page_link(""pages/profile.py"", label=""My profile"") Selection elements CheckboxDisplay a checkbox widget.selected = st.checkbox(""I agree"") ToggleDisplay a toggle widget.activated = st.toggle(""Activate"") RadioDisplay a radio button widget.choice = st.radio(""Pick one"", [""cats"", ""dogs""]) SelectboxDisplay a select widget.choice = st.selectbox(""Pick one"", [""cats"", ""dogs""]) MultiselectDisplay a multiselect widget. The multiselect widget starts as empty.choices = st.multiselect(""Buy"", [""milk"", ""apples"", ""potatoes""]) Select sliderDisplay a slider widget to select items from a list.size = st.select_slider(""Pick a size"", [""S"", ""M"", ""L""]) Color pickerDisplay a color picker widget.color = st.color_picker(""Pick a color"") Numeric input elements Number inputDisplay a numeric input widget.choice = st.number_input(""Pick a number"", 0, 10) SliderDisplay a slider widget.number = st.slider(""Pick a number"", 0, 100) Date and time input elements Date inputDisplay a date input widget.date = st.date_input(""Your birthday"") Time inputDisplay a time input widget.time = st.time_input(""Meeting time"") Text input elements Text inputDisplay a single-line text input widget.name = st.text_input(""First name"") Text areaDisplay a multi-line text input widget.text = st.text_area(""Text to translate"") Chat inputDisplay a chat input widget.prompt = st.chat_input(""Say something"") if prompt: st.write(f""The user has sent: {prompt}"") Other input elements Data editorDisplay a data editor widget.edited = st.experimental_data_editor(df, num_rows=""dynamic"") File uploaderDisplay a file uploader widget.data = st.file_uploader(""Upload a CSV"") Camera inputDisplay a widget that allows users to upload images directly from a camera.image = st.camera_input(""Take a picture"") Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration! PreviousStreamlit ChatStreamlit Component for a Chatbot UI. Created by @AI-Yash.from streamlit_chat import message message(""My message"") message(""Hello bot!"", is_user=True) # align's the message to the right Streamlit Option MenuSelect a single item from a list of options in a menu. Created by @victoryhb.from streamlit_option_menu import option_menu option_menu(""Main Menu"", [""Home"", 'Settings'], icons=['house', 'gear'], menu_icon=""cast"", default_index=1) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.stoggle import stoggle stoggle( ""Click me!"", """"""🥷 Surprise! Here's some additional content"""""",) Streamlit ElementsCreate a draggable and resizable dashboard in Streamlit. Created by @okls.from streamlit_elements import elements, mui, html with elements(""new_element""): mui.Typography(""Hello world"") TagsAdd tags to your Streamlit apps. Created by @gagan3012.from streamlit_tags import st_tags st_tags(label='# Enter Keywords:', text='Press enter to add more', value=['Zero', 'One', 'Two'], suggestions=['five', 'six', 'seven', 'eight', 'nine', 'three', 'eleven', 'ten', 'four'], maxtags = 4, key='1') StqdmThe simplest way to handle a progress bar in streamlit app. Created by @Wirg.from stqdm import stqdm for _ in stqdm(range(50)): sleep(0.5) TimelineDisplay a Timeline in Streamlit apps using TimelineJS. Created by @innerdoc.from streamlit_timeline import timeline with open('example.json', ""r"") as f: timeline(f.read(), height=800) Camera input liveAlternative for st.camera_input which returns the webcam images live. Created by @blackary.from camera_input_live import camera_input_live image = camera_input_live() st.image(value) Streamlit AceAce editor component for Streamlit. Created by @okld.from streamlit_ace import st_ace content = st_ace() content Streamlit ChatStreamlit Component for a Chatbot UI. Created by @AI-Yash.from streamlit_chat import message message(""My message"") message(""Hello bot!"", is_user=True) # align's the message to the right Streamlit Option MenuSelect a single item from a list of options in a menu. Created by @victoryhb.from streamlit_option_menu import option_menu option_menu(""Main Menu"", [""Home"", 'Settings'], icons=['house', 'gear'], menu_icon=""cast"", default_index=1) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.stoggle import stoggle stoggle( ""Click me!"", """"""🥷 Surprise! Here's some additional content"""""",) Streamlit ElementsCreate a draggable and resizable dashboard in Streamlit. Created by @okls.from streamlit_elements import elements, mui, html with elements(""new_element""): mui.Typography(""Hello world"") TagsAdd tags to your Streamlit apps. Created by @gagan3012.from streamlit_tags import st_tags st_tags(label='# Enter Keywords:', text='Press enter to add more', value=['Zero', 'One', 'Two'], suggestions=['five', 'six', 'seven', 'eight', 'nine', 'three', 'eleven', 'ten', 'four'], maxtags = 4, key='1') StqdmThe simplest way to handle a progress bar in streamlit app. Created by @Wirg.from stqdm import stqdm for _ in stqdm(range(50)): sleep(0.5) TimelineDisplay a Timeline in Streamlit apps using TimelineJS. Created by @innerdoc.from streamlit_timeline import timeline with open('example.json', ""r"") as f: timeline(f.read(), height=800) Camera input liveAlternative for st.camera_input which returns the webcam images live. Created by @blackary.from camera_input_live import camera_input_live image = camera_input_live() st.image(value) Streamlit AceAce editor component for Streamlit. Created by @okld.from streamlit_ace import st_ace content = st_ace() content Streamlit ChatStreamlit Component for a Chatbot UI. Created by @AI-Yash.from streamlit_chat import message message(""My message"") message(""Hello bot!"", is_user=True) # align's the message to the right Streamlit Option MenuSelect a single item from a list of options in a menu. Created by @victoryhb.from streamlit_option_menu import option_menu option_menu(""Main Menu"", [""Home"", 'Settings'], icons=['house', 'gear'], menu_icon=""cast"", default_index=1) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.stoggle import stoggle stoggle( ""Click me!"", """"""🥷 Surprise! Here's some additional content"""""",) NextPrevious: Chart elementsNext: st.buttonforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy" https://docs.streamlit.io/develop/concepts/architecture/forms,"DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsremoveCOREArchitecture & executionremoveRunning your appStreamlit's architectureThe app chromeCachingSession StateFormsFragmentsWidget behaviorMultipage appsaddApp designaddADDITIONALConnections and secretsaddCustom componentsaddConfiguration and themingaddApp testingaddAPI referenceaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Develop/Concepts/Architecture & execution/FormsUsing forms When you don't want to rerun your script with each input made by a user, st.form is here to help! Forms make it easy to batch user input into a single rerun. This guide to using forms provides examples and explains how users interact with forms. Example In the following example, a user can set multiple parameters to update the map. As the user changes the parameters, the script will not rerun and the map will not update. When the user submits the form with the button labeled ""Update map"", the script reruns and the map updates. If at any time the user clicks ""Generate new points"" which is outside of the form, the script will rerun. If the user has any unsubmitted changes within the form, these will not be sent with the rerun. All changes made to a form will only be sent to the Python backend when the form itself is submitted. View source codeexpand_moreimport streamlit as st import pandas as pd import numpy as np def get_data(): df = pd.DataFrame({ ""lat"": np.random.randn(200) / 50 + 37.76, ""lon"": np.random.randn(200) / 50 + -122.4, ""team"": ['A','B']*100 }) return df if st.button('Generate new points'): st.session_state.df = get_data() if 'df' not in st.session_state: st.session_state.df = get_data() df = st.session_state.df with st.form(""my_form""): header = st.columns([1,2,2]) header[0].subheader('Color') header[1].subheader('Opacity') header[2].subheader('Size') row1 = st.columns([1,2,2]) colorA = row1[0].color_picker('Team A', '#0000FF') opacityA = row1[1].slider('A opacity', 20, 100, 50, label_visibility='hidden') sizeA = row1[2].slider('A size', 50, 200, 100, step=10, label_visibility='hidden') row2 = st.columns([1,2,2]) colorB = row2[0].color_picker('Team B', '#FF0000') opacityB = row2[1].slider('B opacity', 20, 100, 50, label_visibility='hidden') sizeB = row2[2].slider('B size', 50, 200, 100, step=10, label_visibility='hidden') st.form_submit_button('Update map') alphaA = int(opacityA*255/100) alphaB = int(opacityB*255/100) df['color'] = np.where(df.team=='A',colorA+f'{alphaA:02x}',colorB+f'{alphaB:02x}') df['size'] = np.where(df.team=='A',sizeA, sizeB) st.map(df, size='size', color='color') Built with Streamlit 🎈Fullscreen open_in_new User interaction If a widget is not in a form, that widget will trigger a script rerun whenever a user changes its value. For widgets with keyed input (st.number_input, st.text_input, st.text_area), a new value triggers a rerun when the user clicks or tabs out of the widget. A user can also submit a change by pressing Enter while thier cursor is active in the widget. On the other hand if a widget is inside of a form, the script will not rerun when a user clicks or tabs out of that widget. For widgets inside a form, the script will rerun when the form is submitted and all widgets within the form will send their updated values to the Python backend. A user can submit a form using Enter on their keyboard if their cursor active in a widget that accepts keyed input. Within st.number_input and st.text_input a user presses Enter to submit the form. Within st.text_area a user presses Ctrl+Enter/⌘+Enter to submit the form. Widget values Before a form is submitted, all widgets within that form will have default values, just like widgets outside of a form have default values. import streamlit as st with st.form(""my_form""): st.write(""Inside the form"") my_number = st.slider('Pick a number', 1, 10) my_color = st.selectbox('Pick a color', ['red','orange','green','blue','violet']) st.form_submit_button('Submit my picks') # This is outside the form st.write(my_number) st.write(my_color) Built with Streamlit 🎈Fullscreen open_in_new Forms are containers When st.form is called, a container is created on the frontend. You can write to that container like you do with other container elements. That is, you can use Python's with statement as shown in the example above, or you can assign the form container to a variable and call methods on it directly. Additionally, you can place st.form_submit_button anywhere in the form container. import streamlit as st animal = st.form('my_animal') # This is writing directly to the main body. Since the form container is # defined above, this will appear below everything written in the form. sound = st.selectbox('Sounds like', ['meow','woof','squeak','tweet']) # These methods called on the form container, so they appear inside the form. submit = animal.form_submit_button(f'Say it with {sound}!') sentence = animal.text_input('Your sentence:', 'Where\'s the tuna?') say_it = sentence.rstrip('.,!?') + f', {sound}!' if submit: animal.subheader(say_it) else: animal.subheader(' ') Built with Streamlit 🎈Fullscreen open_in_new Processing form submissions The purpose of a form is to override the default behavior of Streamlit which reruns a script as soon as the user makes a change. For widgets outside of a form, the logical flow is: The user changes a widget's value on the frontend. The widget's value in st.session_state and in the Python backend (server) is updated. The script rerun begins. If the widget has a callback, it is executed as a prefix to the page rerun. When the updated widget's function is executed during the rerun, it outputs the new value. For widgets inside a form, any changes made by a user (step 1) do not get passed to the Python backend (step 2) until the form is submitted. Furthermore, the only widget inside a form that can have a callback function is the st.form_submit_button. If you need to execute a process using newly submitted values, you have three major patterns for doing so. Execute the process after the form If you need to execute a one-time process as a result of a form submission, you can condition that process on the st.form_submit_button and execute it after the form. If you need results from your process to display above the form, you can use containers to control where the form displays relative to your output. import streamlit as st col1,col2 = st.columns([1,2]) col1.title('Sum:') with st.form('addition'): a = st.number_input('a') b = st.number_input('b') submit = st.form_submit_button('add') if submit: col2.title(f'{a+b:.2f}') Built with Streamlit 🎈Fullscreen open_in_new Use a callback with session state You can use a callback to execute a process as a prefix to the script rerunning. priority_highImportantWhen processing newly updated values within a callback, do not pass those values to the callback directly through the args or kwargs parameters. You need to assign a key to any widget whose value you use within the callback. If you look up the value of that widget from st.session_state within the body of the callback, you will be able to access the newly submitted value. See the example below. import streamlit as st if 'sum' not in st.session_state: st.session_state.sum = '' def sum(): result = st.session_state.a + st.session_state.b st.session_state.sum = result col1,col2 = st.columns(2) col1.title('Sum:') if isinstance(st.session_state.sum, float): col2.title(f'{st.session_state.sum:.2f}') with st.form('addition'): st.number_input('a', key = 'a') st.number_input('b', key = 'b') st.form_submit_button('add', on_click=sum) Built with Streamlit 🎈Fullscreen open_in_new Use st.rerun If your process affects content above your form, another alternative is using an extra rerun. This can be less resource-efficient though, and may be less desirable that the above options. import streamlit as st if 'sum' not in st.session_state: st.session_state.sum = '' col1,col2 = st.columns(2) col1.title('Sum:') if isinstance(st.session_state.sum, float): col2.title(f'{st.session_state.sum:.2f}') with st.form('addition'): a = st.number_input('a') b = st.number_input('b') submit = st.form_submit_button('add') # The value of st.session_state.sum is updated at the end of the script rerun, # so the displayed value at the top in col2 does not show the new sum. Trigger # a second rerun when the form is submitted to update the value above. st.session_state.sum = a + b if submit: st.rerun() Built with Streamlit 🎈Fullscreen open_in_new Limitations Every form must contain a st.form_submit_button. st.button and st.download_button cannot be added to a form. st.form cannot be embedded inside another st.form. Callback functions can only be assigned to st.form_submit_button within a form; no other widgets in a form can have a callback. Interdependent widgets within a form are unlikely to be particularly useful. If you pass widget1's value into widget2 when they are both inside a form, then widget2 will only update when the form is submitted. Previous: Session StateNext: FragmentsforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy" https://docs.streamlit.io/develop/tutorials/databases/bigquery#add-the-key-file-to-your-local-app-secrets,"DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceaddTutorialsremoveExecution flowaddConnect to data sourcesremoveAWS S3BigQueryDeta BaseFirestoreopen_in_newGoogle Cloud StorageMicrosoft SQL ServerMongoDBMySQLNeonPostgreSQLPrivate Google SheetPublic Google SheetSnowflakeSupabaseTableauTiDBTigerGraphMultipage appsaddWork with LLMsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Develop/Tutorials/Connect to data sources/BigQueryConnect Streamlit to Google BigQuery Introduction This guide explains how to securely access a BigQuery database from Streamlit Community Cloud. It uses the google-cloud-bigquery library and Streamlit's Secrets management. Create a BigQuery database push_pinNoteIf you already have a database that you want to use, feel free to skip to the next step. For this example, we will use one of the sample datasets from BigQuery (namely the shakespeare table). If you want to create a new dataset instead, follow Google's quickstart guide. Enable the BigQuery API Programmatic access to BigQuery is controlled through Google Cloud Platform. Create an account or sign in and head over to the APIs & Services dashboard (select or create a project if asked). As shown below, search for the BigQuery API and enable it: Create a service account & key file To use the BigQuery API from Streamlit Community Cloud, you need a Google Cloud Platform service account (a special account type for programmatic data access). Go to the Service Accounts page and create an account with the Viewer permission (this will let the account access data but not change it): push_pinNoteIf the button CREATE SERVICE ACCOUNT is gray, you don't have the correct permissions. Ask the admin of your Google Cloud project for help. After clicking DONE, you should be back on the service accounts overview. Create a JSON key file for the new account and download it: Add the key file to your local app secrets Your local Streamlit app will read secrets from a file .streamlit/secrets.toml in your app's root directory. Create this file if it doesn't exist yet and add the content of the key file you just downloaded to it as shown below: # .streamlit/secrets.toml [gcp_service_account] type = ""service_account"" project_id = ""xxx"" private_key_id = ""xxx"" private_key = ""xxx"" client_email = ""xxx"" client_id = ""xxx"" auth_uri = ""https://accounts.google.com/o/oauth2/auth"" token_uri = ""https://oauth2.googleapis.com/token"" auth_provider_x509_cert_url = ""https://www.googleapis.com/oauth2/v1/certs"" client_x509_cert_url = ""xxx"" priority_highImportantAdd this file to .gitignore and don't commit it to your GitHub repo! Copy your app secrets to the cloud As the secrets.toml file above is not committed to GitHub, you need to pass its content to your deployed app (on Streamlit Community Cloud) separately. Go to the app dashboard and in the app's dropdown menu, click on Edit Secrets. Copy the content of secrets.toml into the text area. More information is available at Secrets management. Add google-cloud-bigquery to your requirements file Add the google-cloud-bigquery package to your requirements.txt file, preferably pinning its version (replace x.x.x with the version want installed): # requirements.txt google-cloud-bigquery==x.x.x Write your Streamlit app Copy the code below to your Streamlit app and run it. Make sure to adapt the query if you don't use the sample table. # streamlit_app.py import streamlit as st from google.oauth2 import service_account from google.cloud import bigquery # Create API client. credentials = service_account.Credentials.from_service_account_info( st.secrets[""gcp_service_account""] ) client = bigquery.Client(credentials=credentials) # Perform query. # Uses st.cache_data to only rerun when the query changes or after 10 min. @st.cache_data(ttl=600) def run_query(query): query_job = client.query(query) rows_raw = query_job.result() # Convert to list of dicts. Required for st.cache_data to hash the return value. rows = [dict(row) for row in rows_raw] return rows rows = run_query(""SELECT word FROM `bigquery-public-data.samples.shakespeare` LIMIT 10"") # Print results. st.write(""Some wise words from Shakespeare:"") for row in rows: st.write(""✍️ "" + row['word']) See st.cache_data above? Without it, Streamlit would run the query every time the app reruns (e.g. on a widget interaction). With st.cache_data, it only runs when the query changes or after 10 minutes (that's what ttl is for). Watch out: If your database updates more frequently, you should adapt ttl or remove caching so viewers always see the latest data. Learn more in Caching. Alternatively, you can use pandas to read from BigQuery right into a dataframe! Follow all the above steps, install the pandas-gbq library (don't forget to add it to requirements.txt!), and call pandas.read_gbq(query, credentials=credentials). More info in the pandas docs. If everything worked out (and you used the sample table), your app should look like this: Previous: AWS S3Next: Deta BaseforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy" https://docs.streamlit.io/knowledge-base/deploy/authentication-without-sso#option-2-individual-password-for-each-user,"DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Knowledge base/Deployment issues/Authentication without SSOAuthentication without SSO Introduction Want to secure your Streamlit app with passwords, but cannot implement single sign-on? We got you covered! This guide shows you two simple techniques for adding basic authentication to your Streamlit app, using Secrets management. priority_highWarningWhile this technique adds some level of security, it is NOT comparable to proper authentication with an SSO provider. Option 1: One global password for all users This is the easiest option! Your app will ask for a password that's shared between all users. It will be stored in the app secrets using Secrets management. If you want to change this password or revoke a user's access, you will need to change it for everyone. If you want to have one password per user instead, jump to Option 2 below. Step 1: Add the password to your local app secrets Your local Streamlit app will read secrets from a file .streamlit/secrets.toml in your app's root dir. Create this file if it doesn't exist yet and add your password to it as shown below: # .streamlit/secrets.toml password = ""streamlit123"" priority_highImportantBe sure to add this file to your .gitignore so you don't commit your secrets! Step 2: Copy your app secrets to the cloud As the secrets.toml file above is not committed to GitHub, you need to pass its content to your deployed app (on Streamlit Community Cloud) separately. Go to the app dashboard and in the app's dropdown menu, click on Edit Secrets. Copy the content of secrets.toml into the text area. More information is available at Secrets management. Step 3: Ask for the password in your Streamlit app Copy the code below to your Streamlit app, insert your normal app code below the check_password() function call at the bottom, and run it: # streamlit_app.py import hmac import streamlit as st def check_password(): """"""Returns `True` if the user had the correct password."""""" def password_entered(): """"""Checks whether a password entered by the user is correct."""""" if hmac.compare_digest(st.session_state[""password""], st.secrets[""password""]): st.session_state[""password_correct""] = True del st.session_state[""password""] # Don't store the password. else: st.session_state[""password_correct""] = False # Return True if the password is validated. if st.session_state.get(""password_correct"", False): return True # Show input for password. st.text_input( ""Password"", type=""password"", on_change=password_entered, key=""password"" ) if ""password_correct"" in st.session_state: st.error(""😕 Password incorrect"") return False if not check_password(): st.stop() # Do not continue if check_password is not True. # Main Streamlit app starts here st.write(""Here goes your normal Streamlit app..."") st.button(""Click me"") If everything worked out, your app should look like this: Option 2: Individual password for each user This option allows you to set a username and password for each user of your app. Like in Option 1, both values will be stored in the app secrets using Secrets management. Step 1: Add usernames & passwords to your local app secrets Your local Streamlit app will read secrets from a file .streamlit/secrets.toml in your app's root dir. Create this file if it doesn't exist yet and add the usernames & password to it as shown below: # .streamlit/secrets.toml [passwords] # Follow the rule: username = ""password"" alice_foo = ""streamlit123"" bob_bar = ""mycrazypw"" priority_highImportantBe sure to add this file to your .gitignore so you don't commit your secrets! Alternatively, you could set up and manage usernames & passwords via a spreadsheet or database. To use secrets to securely connect to Google Sheets, AWS, and other data providers, read our tutorials on how to Connect Streamlit to data sources. Step 2: Copy your app secrets to the cloud As the secrets.toml file above is not committed to GitHub, you need to pass its content to your deployed app (on Streamlit Community Cloud) separately. Go to the app dashboard and in the app's dropdown menu, click on Edit Secrets. Copy the content of secrets.toml into the text area. More information is available at Secrets management. Step 3: Ask for username & password in your Streamlit app Copy the code below to your Streamlit app, insert your normal app code below the check_password() function call at the bottom, and run it: # streamlit_app.py import hmac import streamlit as st def check_password(): """"""Returns `True` if the user had a correct password."""""" def login_form(): """"""Form with widgets to collect user information"""""" with st.form(""Credentials""): st.text_input(""Username"", key=""username"") st.text_input(""Password"", type=""password"", key=""password"") st.form_submit_button(""Log in"", on_click=password_entered) def password_entered(): """"""Checks whether a password entered by the user is correct."""""" if st.session_state[""username""] in st.secrets[ ""passwords"" ] and hmac.compare_digest( st.session_state[""password""], st.secrets.passwords[st.session_state[""username""]], ): st.session_state[""password_correct""] = True del st.session_state[""password""] # Don't store the username or password. del st.session_state[""username""] else: st.session_state[""password_correct""] = False # Return True if the username + password is validated. if st.session_state.get(""password_correct"", False): return True # Show inputs for username + password. login_form() if ""password_correct"" in st.session_state: st.error(""😕 User not known or password incorrect"") return False if not check_password(): st.stop() # Main Streamlit app starts here st.write(""Here goes your normal Streamlit app..."") st.button(""Click me"") If everything worked out, your app should look like this: Previous: Deployment issuesNext: How can I deploy multiple Streamlit apps on different subdomains?forumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy" https://docs.streamlit.io/develop/api-reference/caching-and-state#manage-state,"DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceremovePAGE ELEMENTSWrite and magicaddText elementsaddData elementsaddChart elementsaddInput widgetsaddMedia elementsaddLayouts and containersaddChat elementsaddStatus elementsaddThird-party componentsopen_in_newAPPLICATION LOGICNavigation and pagesaddExecution flowaddCaching and stateremovest.cache_datast.cache_resourcest.cachedeletest.session_statest.query_paramsst.experimental_get_query_paramsdeletest.experimental_set_query_paramsdeleteConnections and secretsaddCustom componentsaddUtilitiesaddConfigurationaddTOOLSApp testingaddCommand lineaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Develop/API reference/Caching and stateCaching and state Optimize performance and add statefulness to your app! Caching Streamlit provides powerful cache primitives for data and global resources. They allow your app to stay performant even when loading data from the web, manipulating large datasets, or performing expensive computations. Cache dataFunction decorator to cache functions that return data (e.g. dataframe transforms, database queries, ML inference).@st.cache_data def long_function(param1, param2): # Perform expensive computation here or # fetch data from the web here return data Cache resourceFunction decorator to cache functions that return global resources (e.g. database connections, ML models).@st.cache_resource def init_model(): # Return a global resource here return pipeline( ""sentiment-analysis"", model=""distilbert-base-uncased-finetuned-sst-2-english"" ) Manage state Streamlit re-executes your script with each user interaction. Widgets have built-in statefulness between reruns, but Session State lets you do more! Session StateSave data between reruns and across pages.st.session_state[""foo""] = ""bar"" Query parametersGet, set, or clear the query parameters that are shown in the browser's URL bar.st.query_params[key] = value st.query_params.clear() Deprecated commands delete This command was deprecated in version 1.18.0. Use st.cache_data or st.cache_resource instead. CachingFunction decorator to memoize function executions.@st.cache(ttl=3600) def run_long_computation(arg1, arg2): # Do stuff here return computation_output delete This command was deprecated in version 1.18.0. Use st.cache_data instead. MemoExperimental function decorator to memoize function executions.@st.experimental_memo def fetch_and_clean_data(url): # Fetch data from URL here, and then clean it up. return data delete This command was deprecated in version 1.18.0. Use st.cache_resource instead. SingletonExperimental function decorator to store singleton objects.@st.experimental_singleton def get_database_session(url): # Create a database session object that points to the URL. return session deleteGet query parametersGet query parameters that are shown in the browser's URL bar.param_dict = st.experimental_get_query_params() deleteSet query parametersSet query parameters that are shown in the browser's URL bar.st.experimental_set_query_params( {""show_all""=True, ""selected""=[""asia"", ""america""]} ) Previous: Execution flowNext: st.cache_dataforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy" https://docs.streamlit.io/en/0.68.0/api.html#caching-and-state,"DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceremovePAGE ELEMENTSWrite and magicaddText elementsaddData elementsaddChart elementsaddInput widgetsaddMedia elementsaddLayouts and containersaddChat elementsaddStatus elementsaddThird-party componentsopen_in_newAPPLICATION LOGICNavigation and pagesaddExecution flowaddCaching and stateaddConnections and secretsaddCustom componentsaddUtilitiesaddConfigurationaddTOOLSApp testingaddCommand lineaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Develop/API referenceAPI reference Streamlit makes it easy for you to visualize, mutate, and share data. The API reference is organized by activity type, like displaying data or optimizing performance. Each section includes methods associated with the activity type, including examples. Browse our API below and click to learn more about any of our available commands! 🎈 Display almost anything Write and magic st.writeWrite arguments to the app.st.write(""Hello **world**!"") st.write(my_data_frame) st.write(my_mpl_figure) st.write_streamWrite generators or streams to the app with a typewriter effect.st.write_stream(my_generator) st.write_stream(my_llm_stream) MagicAny time Streamlit sees either a variable or literal value on its own line, it automatically writes that to your app using st.write""Hello **world**!"" my_data_frame my_mpl_figure Text elements MarkdownDisplay string formatted as Markdown.st.markdown(""Hello **world**!"") TitleDisplay text in title formatting.st.title(""The app title"") HeaderDisplay text in header formatting.st.header(""This is a header"") SubheaderDisplay text in subheader formatting.st.subheader(""This is a subheader"") CaptionDisplay text in small font.st.caption(""This is written small caption text"") Code blockDisplay a code block with optional syntax highlighting.st.code(""a = 1234"") EchoDisplay some code in the app, then execute it. Useful for tutorials.with st.echo(): st.write('This code will be printed') LaTeXDisplay mathematical expressions formatted as LaTeX.st.latex(""\int a x^2 \,dx"") Preformatted textWrite fixed-width and preformatted text.st.text(""Hello world"") DividerDisplay a horizontal rule.st.divider() Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration! PreviousTagsAdd tags to your Streamlit apps. Created by @gagan3012.st_tags(label='# Enter Keywords:', text='Press enter to add more', value=['Zero', 'One', 'Two'], suggestions=['five', 'six', 'seven', 'eight', 'nine', 'three', 'eleven', 'ten', 'four'], maxtags = 4, key='1') NLUApply text mining on a dataframe. Created by @JohnSnowLabs.nlu.load('sentiment').predict('I love NLU! <3') Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.mention(label=""An awesome Streamlit App"", icon=""streamlit"", url=""https://extras.streamlit.app"",) Annotated textDisplay annotated text in Streamlit apps. Created by @tvst.annotated_text(""This "", (""is"", ""verb""), "" some "", (""annotated"", ""adj""), (""text"", ""noun""), "" for those of "", (""you"", ""pronoun""), "" who "", (""like"", ""verb""), "" this sort of "", (""thing"", ""noun""), ""."") Drawable CanvasProvides a sketching canvas using Fabric.js. Created by @andfanilo.st_canvas(fill_color=""rgba(255, 165, 0, 0.3)"", stroke_width=stroke_width, stroke_color=stroke_color, background_color=bg_color, background_image=Image.open(bg_image) if bg_image else None, update_streamlit=realtime_update, height=150, drawing_mode=drawing_mode, point_display_radius=point_display_radius if drawing_mode == 'point' else 0, key=""canvas"",) TagsAdd tags to your Streamlit apps. Created by @gagan3012.st_tags(label='# Enter Keywords:', text='Press enter to add more', value=['Zero', 'One', 'Two'], suggestions=['five', 'six', 'seven', 'eight', 'nine', 'three', 'eleven', 'ten', 'four'], maxtags = 4, key='1') NLUApply text mining on a dataframe. Created by @JohnSnowLabs.nlu.load('sentiment').predict('I love NLU! <3') Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.mention(label=""An awesome Streamlit App"", icon=""streamlit"", url=""https://extras.streamlit.app"",) Annotated textDisplay annotated text in Streamlit apps. Created by @tvst.annotated_text(""This "", (""is"", ""verb""), "" some "", (""annotated"", ""adj""), (""text"", ""noun""), "" for those of "", (""you"", ""pronoun""), "" who "", (""like"", ""verb""), "" this sort of "", (""thing"", ""noun""), ""."") Drawable CanvasProvides a sketching canvas using Fabric.js. Created by @andfanilo.st_canvas(fill_color=""rgba(255, 165, 0, 0.3)"", stroke_width=stroke_width, stroke_color=stroke_color, background_color=bg_color, background_image=Image.open(bg_image) if bg_image else None, update_streamlit=realtime_update, height=150, drawing_mode=drawing_mode, point_display_radius=point_display_radius if drawing_mode == 'point' else 0, key=""canvas"",) TagsAdd tags to your Streamlit apps. Created by @gagan3012.st_tags(label='# Enter Keywords:', text='Press enter to add more', value=['Zero', 'One', 'Two'], suggestions=['five', 'six', 'seven', 'eight', 'nine', 'three', 'eleven', 'ten', 'four'], maxtags = 4, key='1') NLUApply text mining on a dataframe. Created by @JohnSnowLabs.nlu.load('sentiment').predict('I love NLU! <3') Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.mention(label=""An awesome Streamlit App"", icon=""streamlit"", url=""https://extras.streamlit.app"",) Next Data elements DataframesDisplay a dataframe as an interactive table.st.dataframe(my_data_frame) Data editorDisplay a data editor widget.edited = st.data_editor(df, num_rows=""dynamic"") Column configurationConfigure the display and editing behavior of dataframes and data editors.st.column_config.NumberColumn(""Price (in USD)"", min_value=0, format=""$%d"") Static tablesDisplay a static table.st.table(my_data_frame) MetricsDisplay a metric in big bold font, with an optional indicator of how the metric changed.st.metric(""My metric"", 42, 2) Dicts and JSONDisplay object or string as a pretty-printed JSON string.st.json(my_dict) Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration! PreviousImage CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates value = streamlit_image_coordinates(""https://placekitten.com/200/300"") st.write(value) Plotly EventsMake Plotly charts interactive!. Created by @null-jones.from streamlit_plotly_events import plotly_events fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.metric_cards import style_metric_cards col3.metric(label=""No Change"", value=5000, delta=0) style_metric_cards() Streamlit AggridImplementation of Ag-Grid component for Streamlit. Created by @PablocFonseca.df = pd.DataFrame({'col1': [1, 2, 3], 'col2': [4, 5, 6]}) grid_return = AgGrid(df, editable=True) new_df = grid_return['data'] Streamlit FoliumStreamlit Component for rendering Folium maps. Created by @randyzwitch.m = folium.Map(location=[39.949610, -75.150282], zoom_start=16) folium.Marker([39.949610, -75.150282], popup=""Liberty Bell"", tooltip=""Liberty Bell"").add_to(m) st_data = st_folium(m, width=725) Pandas ProfilingPandas profiling component for Streamlit. Created by @okld.df = pd.read_csv(""https://storage.googleapis.com/tf-datasets/titanic/train.csv"") pr = df.profile_report() st_profile_report(pr) Image CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates value = streamlit_image_coordinates(""https://placekitten.com/200/300"") st.write(value) Plotly EventsMake Plotly charts interactive!. Created by @null-jones.from streamlit_plotly_events import plotly_events fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.metric_cards import style_metric_cards col3.metric(label=""No Change"", value=5000, delta=0) style_metric_cards() Streamlit AggridImplementation of Ag-Grid component for Streamlit. Created by @PablocFonseca.df = pd.DataFrame({'col1': [1, 2, 3], 'col2': [4, 5, 6]}) grid_return = AgGrid(df, editable=True) new_df = grid_return['data'] Streamlit FoliumStreamlit Component for rendering Folium maps. Created by @randyzwitch.m = folium.Map(location=[39.949610, -75.150282], zoom_start=16) folium.Marker([39.949610, -75.150282], popup=""Liberty Bell"", tooltip=""Liberty Bell"").add_to(m) st_data = st_folium(m, width=725) Pandas ProfilingPandas profiling component for Streamlit. Created by @okld.df = pd.read_csv(""https://storage.googleapis.com/tf-datasets/titanic/train.csv"") pr = df.profile_report() st_profile_report(pr) Image CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates value = streamlit_image_coordinates(""https://placekitten.com/200/300"") st.write(value) Plotly EventsMake Plotly charts interactive!. Created by @null-jones.from streamlit_plotly_events import plotly_events fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.metric_cards import style_metric_cards col3.metric(label=""No Change"", value=5000, delta=0) style_metric_cards() Next Chart elements Simple area chartsDisplay an area chart.st.area_chart(my_data_frame) Simple bar chartsDisplay a bar chart.st.bar_chart(my_data_frame) Simple line chartsDisplay a line chart.st.line_chart(my_data_frame) Simple scatter chartsDisplay a line chart.st.scatter_chart(my_data_frame) Scatterplots on mapsDisplay a map with points on it.st.map(my_data_frame) MatplotlibDisplay a matplotlib.pyplot figure.st.pyplot(my_mpl_figure) AltairDisplay a chart using the Altair library.st.altair_chart(my_altair_chart) Vega-LiteDisplay a chart using the Vega-Lite library.st.vega_lite_chart(my_vega_lite_chart) PlotlyDisplay an interactive Plotly chart.st.plotly_chart(my_plotly_chart) BokehDisplay an interactive Bokeh chart.st.bokeh_chart(my_bokeh_chart) PyDeckDisplay a chart using the PyDeck library.st.pydeck_chart(my_pydeck_chart) GraphVizDisplay a graph using the dagre-d3 library.st.graphviz_chart(my_graphviz_spec) Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration! PreviousStreamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl(""https://assets5.lottiefiles.com/packages/lf20_V9t630.json"") st_lottie(lottie_hello, key=""hello"") Plotly EventsMake Plotly charts interactive!. Created by @null-jones.fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.chart += get_annotations_chart(annotations=[(""Mar 01, 2008"", ""Pretty good day for GOOG""), (""Dec 01, 2007"", ""Something's going wrong for GOOG & AAPL""), (""Nov 01, 2008"", ""Market starts again thanks to...""), (""Dec 01, 2009"", ""Small crash for GOOG after...""),],) st.altair_chart(chart, use_container_width=True) PlostA deceptively simple plotting library for Streamlit. Created by @tvst.import plost plost.line_chart(my_dataframe, x='time', y='stock_value', color='stock_name',) HiPlotHigh dimensional Interactive Plotting. Created by @facebookresearch.data = [{'dropout':0.1, 'lr': 0.001, 'loss': 10.0, 'optimizer': 'SGD'}, {'dropout':0.15, 'lr': 0.01, 'loss': 3.5, 'optimizer': 'Adam'}, {'dropout':0.3, 'lr': 0.1, 'loss': 4.5, 'optimizer': 'Adam'}] hip.Experiment.from_iterable(data).display() EChartsHigh dimensional Interactive Plotting. Created by @andfanilo.from streamlit_echarts import st_echarts st_echarts(options=options) Streamlit FoliumStreamlit Component for rendering Folium maps. Created by @randyzwitch.m = folium.Map(location=[39.949610, -75.150282], zoom_start=16) st_data = st_folium(m, width=725) Spacy-StreamlitspaCy building blocks and visualizers for Streamlit apps. Created by @explosion.models = [""en_core_web_sm"", ""en_core_web_md""] spacy_streamlit.visualize(models, ""Sundar Pichai is the CEO of Google."") Streamlit AgraphA Streamlit Graph Vis, based on react-grah-vis. Created by @ChrisDelClea.from streamlit_agraph import agraph, Node, Edge, Config agraph(nodes=nodes, edges=edges, config=config) Streamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl(""https://assets5.lottiefiles.com/packages/lf20_V9t630.json"") st_lottie(lottie_hello, key=""hello"") Plotly EventsMake Plotly charts interactive!. Created by @null-jones.fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.chart += get_annotations_chart(annotations=[(""Mar 01, 2008"", ""Pretty good day for GOOG""), (""Dec 01, 2007"", ""Something's going wrong for GOOG & AAPL""), (""Nov 01, 2008"", ""Market starts again thanks to...""), (""Dec 01, 2009"", ""Small crash for GOOG after...""),],) st.altair_chart(chart, use_container_width=True) PlostA deceptively simple plotting library for Streamlit. Created by @tvst.import plost plost.line_chart(my_dataframe, x='time', y='stock_value', color='stock_name',) HiPlotHigh dimensional Interactive Plotting. Created by @facebookresearch.data = [{'dropout':0.1, 'lr': 0.001, 'loss': 10.0, 'optimizer': 'SGD'}, {'dropout':0.15, 'lr': 0.01, 'loss': 3.5, 'optimizer': 'Adam'}, {'dropout':0.3, 'lr': 0.1, 'loss': 4.5, 'optimizer': 'Adam'}] hip.Experiment.from_iterable(data).display() EChartsHigh dimensional Interactive Plotting. Created by @andfanilo.from streamlit_echarts import st_echarts st_echarts(options=options) Streamlit FoliumStreamlit Component for rendering Folium maps. Created by @randyzwitch.m = folium.Map(location=[39.949610, -75.150282], zoom_start=16) st_data = st_folium(m, width=725) Spacy-StreamlitspaCy building blocks and visualizers for Streamlit apps. Created by @explosion.models = [""en_core_web_sm"", ""en_core_web_md""] spacy_streamlit.visualize(models, ""Sundar Pichai is the CEO of Google."") Streamlit AgraphA Streamlit Graph Vis, based on react-grah-vis. Created by @ChrisDelClea.from streamlit_agraph import agraph, Node, Edge, Config agraph(nodes=nodes, edges=edges, config=config) Streamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl(""https://assets5.lottiefiles.com/packages/lf20_V9t630.json"") st_lottie(lottie_hello, key=""hello"") Plotly EventsMake Plotly charts interactive!. Created by @null-jones.fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.chart += get_annotations_chart(annotations=[(""Mar 01, 2008"", ""Pretty good day for GOOG""), (""Dec 01, 2007"", ""Something's going wrong for GOOG & AAPL""), (""Nov 01, 2008"", ""Market starts again thanks to...""), (""Dec 01, 2009"", ""Small crash for GOOG after...""),],) st.altair_chart(chart, use_container_width=True) Next Input widgets ButtonDisplay a button widget.clicked = st.button(""Click me"") Download buttonDisplay a download button widget.st.download_button(""Download file"", file) Form buttonDisplay a form submit button. For use with st.form.st.form_submit_button(""Sign up"") Link buttonDisplay a link button.st.link_button(""Go to gallery"", url) Page linkDisplay a link to another page in a multipage app.st.page_link(""app.py"", label=""Home"", icon=""🏠"") st.page_link(""pages/profile.py"", label=""My profile"") CheckboxDisplay a checkbox widget.selected = st.checkbox(""I agree"") Color pickerDisplay a color picker widget.color = st.color_picker(""Pick a color"") MultiselectDisplay a multiselect widget. The multiselect widget starts as empty.choices = st.multiselect(""Buy"", [""milk"", ""apples"", ""potatoes""]) RadioDisplay a radio button widget.choice = st.radio(""Pick one"", [""cats"", ""dogs""]) SelectboxDisplay a select widget.choice = st.selectbox(""Pick one"", [""cats"", ""dogs""]) Select-sliderDisplay a slider widget to select items from a list.size = st.select_slider(""Pick a size"", [""S"", ""M"", ""L""]) ToggleDisplay a toggle widget.activated = st.toggle(""Activate"") Number inputDisplay a numeric input widget.choice = st.number_input(""Pick a number"", 0, 10) SliderDisplay a slider widget.number = st.slider(""Pick a number"", 0, 100) Date inputDisplay a date input widget.date = st.date_input(""Your birthday"") Time inputDisplay a time input widget.time = st.time_input(""Meeting time"") Chat inputDisplay a chat input widget.prompt = st.chat_input(""Say something"") if prompt: st.write(f""The user has sent: {prompt}"") Text-areaDisplay a multi-line text input widget.text = st.text_area(""Text to translate"") Text inputDisplay a single-line text input widget.name = st.text_input(""First name"") Data editorDisplay a data editor widget.edited = st.experimental_data_editor(df, num_rows=""dynamic"") File UploaderDisplay a file uploader widget.data = st.file_uploader(""Upload a CSV"") Camera inputDisplay a widget that allows users to upload images directly from a camera.image = st.camera_input(""Take a picture"") Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration! PreviousStreamlit ChatStreamlit Component for a Chatbot UI. Created by @AI-Yash.from streamlit_chat import message message(""My message"") message(""Hello bot!"", is_user=True) # align's the message to the right Streamlit Option MenuSelect a single item from a list of options in a menu. Created by @victoryhb.from streamlit_option_menu import option_menu option_menu(""Main Menu"", [""Home"", 'Settings'], icons=['house', 'gear'], menu_icon=""cast"", default_index=1) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.stoggle import stoggle stoggle( ""Click me!"", """"""🥷 Surprise! Here's some additional content"""""",) Streamlit ElementsCreate a draggable and resizable dashboard in Streamlit. Created by @okls.from streamlit_elements import elements, mui, html with elements(""new_element""): mui.Typography(""Hello world"") TagsAdd tags to your Streamlit apps. Created by @gagan3012.from streamlit_tags import st_tags st_tags(label='# Enter Keywords:', text='Press enter to add more', value=['Zero', 'One', 'Two'], suggestions=['five', 'six', 'seven', 'eight', 'nine', 'three', 'eleven', 'ten', 'four'], maxtags = 4, key='1') StqdmThe simplest way to handle a progress bar in streamlit app. Created by @Wirg.from stqdm import stqdm for _ in stqdm(range(50)): sleep(0.5) TimelineDisplay a Timeline in Streamlit apps using TimelineJS. Created by @innerdoc.from streamlit_timeline import timeline with open('example.json', ""r"") as f: timeline(f.read(), height=800) Camera input liveAlternative for st.camera_input which returns the webcam images live. Created by @blackary.from camera_input_live import camera_input_live image = camera_input_live() st.image(value) Streamlit AceAce editor component for Streamlit. Created by @okld.from streamlit_ace import st_ace content = st_ace() content Streamlit ChatStreamlit Component for a Chatbot UI. Created by @AI-Yash.from streamlit_chat import message message(""My message"") message(""Hello bot!"", is_user=True) # align's the message to the right Streamlit Option MenuSelect a single item from a list of options in a menu. Created by @victoryhb.from streamlit_option_menu import option_menu option_menu(""Main Menu"", [""Home"", 'Settings'], icons=['house', 'gear'], menu_icon=""cast"", default_index=1) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.stoggle import stoggle stoggle( ""Click me!"", """"""🥷 Surprise! Here's some additional content"""""",) Streamlit ElementsCreate a draggable and resizable dashboard in Streamlit. Created by @okls.from streamlit_elements import elements, mui, html with elements(""new_element""): mui.Typography(""Hello world"") TagsAdd tags to your Streamlit apps. Created by @gagan3012.from streamlit_tags import st_tags st_tags(label='# Enter Keywords:', text='Press enter to add more', value=['Zero', 'One', 'Two'], suggestions=['five', 'six', 'seven', 'eight', 'nine', 'three', 'eleven', 'ten', 'four'], maxtags = 4, key='1') StqdmThe simplest way to handle a progress bar in streamlit app. Created by @Wirg.from stqdm import stqdm for _ in stqdm(range(50)): sleep(0.5) TimelineDisplay a Timeline in Streamlit apps using TimelineJS. Created by @innerdoc.from streamlit_timeline import timeline with open('example.json', ""r"") as f: timeline(f.read(), height=800) Camera input liveAlternative for st.camera_input which returns the webcam images live. Created by @blackary.from camera_input_live import camera_input_live image = camera_input_live() st.image(value) Streamlit AceAce editor component for Streamlit. Created by @okld.from streamlit_ace import st_ace content = st_ace() content Streamlit ChatStreamlit Component for a Chatbot UI. Created by @AI-Yash.from streamlit_chat import message message(""My message"") message(""Hello bot!"", is_user=True) # align's the message to the right Streamlit Option MenuSelect a single item from a list of options in a menu. Created by @victoryhb.from streamlit_option_menu import option_menu option_menu(""Main Menu"", [""Home"", 'Settings'], icons=['house', 'gear'], menu_icon=""cast"", default_index=1) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.stoggle import stoggle stoggle( ""Click me!"", """"""🥷 Surprise! Here's some additional content"""""",) Next Media elements ImageDisplay an image or list of images.st.image(numpy_array) st.image(image_bytes) st.image(file) st.image(""https://example.com/myimage.jpg"") AudioDisplay an audio player.st.audio(numpy_array) st.audio(audio_bytes) st.audio(file) st.audio(""https://example.com/myaudio.mp3"", format=""audio/mp3"") VideoDisplay a video player.st.video(numpy_array) st.video(video_bytes) st.video(file) st.video(""https://example.com/myvideo.mp4"", format=""video/mp4"") Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration! PreviousStreamlit CropperA simple image cropper for Streamlit. Created by @turner-anderson.from streamlit_cropper import st_cropper st_cropper(img, realtime_update=realtime_update, box_color=box_color, aspect_ratio=aspect_ratio) Image CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates streamlit_image_coordinates(""https://placekitten.com/200/300"") Streamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl(""https://assets5.lottiefiles.com/packages/lf20_V9t630.json"") st_lottie(lottie_hello, key=""hello"") Streamlit WebrtcHandling and transmitting real-time video/audio streams with Streamlit. Created by @whitphx.from streamlit_webrtc import webrtc_streamer webrtc_streamer(key=""sample"") Drawable CanvasProvides a sketching canvas using Fabric.js. Created by @andfanilo.from streamlit_drawable_canvas import st_canvas st_canvas(fill_color=""rgba(255, 165, 0, 0.3)"", stroke_width=stroke_width, stroke_color=stroke_color, background_color=bg_color, background_image=Image.open(bg_image) if bg_image else None, update_streamlit=realtime_update, height=150, drawing_mode=drawing_mode, point_display_radius=point_display_radius if drawing_mode == 'point' else 0, key=""canvas"",) Image ComparisonCompare images with a slider using JuxtaposeJS. Created by @fcakyon.from streamlit_image_comparison import image_comparison image_comparison(img1=""image1.jpg"", img2=""image2.jpg"",) Streamlit CropperA simple image cropper for Streamlit. Created by @turner-anderson.from streamlit_cropper import st_cropper st_cropper(img, realtime_update=realtime_update, box_color=box_color, aspect_ratio=aspect_ratio) Image CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates streamlit_image_coordinates(""https://placekitten.com/200/300"") Streamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl(""https://assets5.lottiefiles.com/packages/lf20_V9t630.json"") st_lottie(lottie_hello, key=""hello"") Streamlit WebrtcHandling and transmitting real-time video/audio streams with Streamlit. Created by @whitphx.from streamlit_webrtc import webrtc_streamer webrtc_streamer(key=""sample"") Drawable CanvasProvides a sketching canvas using Fabric.js. Created by @andfanilo.from streamlit_drawable_canvas import st_canvas st_canvas(fill_color=""rgba(255, 165, 0, 0.3)"", stroke_width=stroke_width, stroke_color=stroke_color, background_color=bg_color, background_image=Image.open(bg_image) if bg_image else None, update_streamlit=realtime_update, height=150, drawing_mode=drawing_mode, point_display_radius=point_display_radius if drawing_mode == 'point' else 0, key=""canvas"",) Image ComparisonCompare images with a slider using JuxtaposeJS. Created by @fcakyon.from streamlit_image_comparison import image_comparison image_comparison(img1=""image1.jpg"", img2=""image2.jpg"",) Streamlit CropperA simple image cropper for Streamlit. Created by @turner-anderson.from streamlit_cropper import st_cropper st_cropper(img, realtime_update=realtime_update, box_color=box_color, aspect_ratio=aspect_ratio) Image CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates streamlit_image_coordinates(""https://placekitten.com/200/300"") Streamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl(""https://assets5.lottiefiles.com/packages/lf20_V9t630.json"") st_lottie(lottie_hello, key=""hello"") Next Layouts and containers ColumnsInsert containers laid out as side-by-side columns.col1, col2 = st.columns(2) col1.write(""this is column 1"") col2.write(""this is column 2"") ContainerInsert a multi-element container.c = st.container() st.write(""This will show last"") c.write(""This will show first"") c.write(""This will show second"") Modal dialogsInsert a modal dialog that can rerun independently from the rest of the script.@st.experimental_dialog(""Sign up"") def email_form(): name = st.text_input(""Name"") email = st.text_input(""Email"") EmptyInsert a single-element container.c = st.empty() st.write(""This will show last"") c.write(""This will be replaced"") c.write(""This will show first"") ExpanderInsert a multi-element container that can be expanded/collapsed.with st.expander(""Open to see more""): st.write(""This is more content"") PopoverInsert a multi-element popover container that can be opened/closed.with st.popover(""Settings""): st.checkbox(""Show completed"") SidebarDisplay items in a sidebar.st.sidebar.write(""This lives in the sidebar"") st.sidebar.button(""Click me!"") TabsInsert containers separated into tabs.tab1, tab2 = st.tabs([""Tab 1"", ""Tab2""]) tab1.write(""this is tab 1"") tab2.write(""this is tab 2"") Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration!Streamlit ElementsCreate a draggable and resizable dashboard in Streamlit. Created by @okls.from streamlit_elements import elements, mui, html with elements(""new_element""): mui.Typography(""Hello world"") PydanticAuto-generate Streamlit UI from Pydantic Models and Dataclasses. Created by @lukasmasuch.import streamlit_pydantic as sp sp.pydantic_form(key=""my_form"", model=ExampleModel) Streamlit PagesAn experimental version of Streamlit Multi-Page Apps. Created by @blackary.from st_pages import Page, show_pages, add_page_title show_pages([ Page(""streamlit_app.py"", ""Home"", ""🏠""), Page(""other_pages/page2.py"", ""Page 2"", "":books:""), ]) Chat elements Streamlit provides a few commands to help you build conversational apps. These chat elements are designed to be used in conjunction with each other, but you can also use them separately. st.chat_message lets you insert a chat message container into the app so you can display messages from the user or the app. Chat containers can contain other Streamlit elements, including charts, tables, text, and more. st.chat_input lets you display a chat input widget so the user can type in a message. Chat inputDisplay a chat input widget.prompt = st.chat_input(""Say something"") if prompt: st.write(f""The user has sent: {prompt}"") Chat messageInsert a chat message container.import numpy as np with st.chat_message(""user""): st.write(""Hello 👋"") st.line_chart(np.random.randn(30, 3)) Status containerDisplay output of long-running tasks in a container.with st.status('Running'): do_something_slow() st.write_streamWrite generators or streams to the app with a typewriter effect.st.write_stream(my_generator) st.write_stream(my_llm_stream) Status elements Progress barDisplay a progress bar.for i in range(101): st.progress(i) do_something_slow() SpinnerTemporarily displays a message while executing a block of code.with st.spinner(""Please wait...""): do_something_slow() Status containerDisplay output of long-running tasks in a container.with st.status('Running'): do_something_slow() ToastBriefly displays a toast message in the bottom-right corner.st.toast('Butter!', icon='🧈') BalloonsDisplay celebratory balloons!do_something() # Celebrate when all done! st.balloons() SnowflakesDisplay celebratory snowflakes!do_something() # Celebrate when all done! st.snow() Success boxDisplay a success message.st.success(""Match found!"") Info boxDisplay an informational message.st.info(""Dataset is updated every day at midnight."") Warning boxDisplay warning message.st.warning(""Unable to fetch image. Skipping..."") Error boxDisplay error message.st.error(""We encountered an error"") Exception outputDisplay an exception.e = RuntimeError(""This is an exception of type RuntimeError"") st.exception(e) Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration!StqdmThe simplest way to handle a progress bar in streamlit app. Created by @Wirg.from stqdm import stqdm for _ in stqdm(range(50)): sleep(0.5) Custom notification boxA custom notification box with the ability to close it out. Created by @Socvest.from streamlit_custom_notification_box import custom_notification_box styles = {'material-icons':{'color': 'red'}, 'text-icon-link-close-container': {'box-shadow': '#3896de 0px 4px'}, 'notification-text': {'':''}, 'close-button':{'':''}, 'link':{'':''}} custom_notification_box(icon='info', textDisplay='We are almost done with your registration...', externalLink='more info', url='#', styles=styles, key=""foo"") Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.let_it_rain import rain rain(emoji=""🎈"", font_size=54, falling_speed=5, animation_length=""infinite"",) App logic and configuration Navigation and pages Switch pageProgrammatically navigates to a specified page.st.switch_page(""pages/my_page.py"") Page linkDisplay a link to another page in a multipage app.st.page_link(""app.py"", label=""Home"", icon=""🏠"") st.page_link(""pages/profile.py"", label=""My profile"") Execution flow Modal dialogsInsert a modal dialog that can rerun independently from the rest of the script.@st.experimental_dialog(""Sign up"") def email_form(): name = st.text_input(""Name"") email = st.text_input(""Email"") FormsCreate a form that batches elements together with a “Submit"" button.with st.form(key='my_form'): name = st.text_input(""Name"") email = st.text_input(""Email"") st.form_submit_button(""Sign up"") Partial rerunsDefine a fragment to rerun independently from the rest of the script.@st.experimental_fragment(run_every=""10s"") def fragment(): df = get_data() st.line_chart(df) Rerun scriptRerun the script immediately.st.rerun() Stop executionStops execution immediately.st.stop() Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration!AutorefreshForce a refresh without tying up a script. Created by @kmcgrady.from streamlit_autorefresh import st_autorefresh st_autorefresh(interval=2000, limit=100, key=""fizzbuzzcounter"") PydanticAuto-generate Streamlit UI from Pydantic Models and Dataclasses. Created by @lukasmasuch.import streamlit_pydantic as sp sp.pydantic_form(key=""my_form"", model=ExampleModel) Streamlit PagesAn experimental version of Streamlit Multi-Page Apps. Created by @blackary.from st_pages import Page, show_pages, add_page_title show_pages([ Page(""streamlit_app.py"", ""Home"", ""🏠""), Page(""other_pages/page2.py"", ""Page 2"", "":books:""), ]) Caching and state Cache dataFunction decorator to cache functions that return data (e.g. dataframe transforms, database queries, ML inference).@st.cache_data def long_function(param1, param2): # Perform expensive computation here or # fetch data from the web here return data Cache resourceFunction decorator to cache functions that return global resources (e.g. database connections, ML models).@st.cache_resource def init_model(): # Return a global resource here return pipeline( ""sentiment-analysis"", model=""distilbert-base-uncased-finetuned-sst-2-english"" ) Session stateSession state is a way to share variables between reruns, for each user session.st.session_state['key'] = value Query parametersGet, set, or clear the query parameters that are shown in the browser's URL bar.st.query_params[key] = value st.query_params.clear() Connections and databases Setup your connection Create a connectionConnect to a data source or APIconn = st.connection('pets_db', type='sql') pet_owners = conn.query('select * from pet_owners') st.dataframe(pet_owners) Built-in connections SnowflakeConnectionA connection to Snowflake.conn = st.connection('snowflake') SQLConnectionA connection to a SQL database using SQLAlchemy.conn = st.connection('sql') Build your own connections Connection base classBuild your own connection with BaseConnection.class MyConnection(BaseConnection[myconn.MyConnection]): def _connect(self, **kwargs) -> MyConnection: return myconn.connect(**self._secrets, **kwargs) def query(self, query): return self._instance.query(query) Secrets management Secrets singletonAccess secrets from a local TOML file.key = st.secrets[""OpenAI_key""] Secrets fileSave your secrets in a per-project or per-profile TOML file.OpenAI_key = """" Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration!AuthenticatorA secure authentication module to validate user credentials. Created by @mkhorasani.import streamlit_authenticator as stauth authenticator = stauth.Authenticate( config['credentials'], config['cookie']['name'], config['cookie']['key'], config['cookie']['expiry_days'], config['preauthorized']) WS localStorageA simple synchronous way of accessing localStorage from your app. Created by @gagangoku.from streamlit_ws_localstorage import injectWebsocketCode ret = conn.setLocalStorageVal(key='k1', val='v1') st.write('ret: ' + ret) Streamlit Auth0The fastest way to provide comprehensive login inside Streamlit. Created by @conradbez.from auth0_component import login_button user_info = login_button(clientId, domain = domain) st.write(user_info) Custom Components Declare a componentCreate and register a custom component.st.components.v1.declare_component( ""custom_slider"", ""/frontend"", ) HTMLDisplay an HTML string in an iframe.st.components.v1.html( ""

Foo bar.

"" ) iframeLoad a remote URL in an iframe.st.components.v1.iframe( ""docs.streamlit.io"" ) Utilities and user info User infost.experimental_user returns information about the logged-in user of private apps on Streamlit Community Cloud.if st.experimental_user.email == ""foo@corp.com"": st.write(""Welcome back, "", st.experimental_user.email) else: st.write(""You are not authorized to view this page."") Get helpDisplay object’s doc string, nicely formatted.st.help(st.write) st.help(pd.DataFrame) Render HTMLRenders HTML strings to your app.css = """""" """""" st.html(css) Configuration Configuration fileConfigures the default settings for your app.your-project/ ├── .streamlit/ │ └── config.toml └── your_app.py Set page title, favicon, and moreConfigures the default settings of the page.st.set_page_config( page_title=""My app"", page_icon="":shark:"", ) Developer tools App testing st.testing.v1.AppTestst.testing.v1.AppTest simulates a running Streamlit app for testing.from streamlit.testing.v1 import AppTest at = AppTest.from_file(""streamlit_app.py"") at.secrets[""WORD""] = ""Foobar"" at.run() assert not at.exception at.text_input(""word"").input(""Bazbat"").run() assert at.warning[0].value == ""Try again."" AppTest.from_filest.testing.v1.AppTest.from_file initializes a simulated app from a file.from streamlit.testing.v1 import AppTest at = AppTest.from_file(""streamlit_app.py"") at.run() AppTest.from_stringst.testing.v1.AppTest.from_string initializes a simulated app from a string.from streamlit.testing.v1 import AppTest at = AppTest.from_string(app_script_as_string) at.run() AppTest.from_functionst.testing.v1.AppTest.from_function initializes a simulated app from a function.from streamlit.testing.v1 import AppTest at = AppTest.from_function(app_script_as_callable) at.run() BlockA representation of container elements, including: st.chat_message st.columns st.sidebar st.tabs The main body of the app. # at.sidebar returns a Block at.sidebar.button[0].click().run() assert not at.exception ElementThe base class for representation of all elements, including: st.title st.header st.markdown st.dataframe # at.title returns a sequence of Title # Title inherits from Element assert at.title[0].value == ""My awesome app"" ButtonA representation of st.button and st.form_submit_button.at.button[0].click().run() ChatInputA representation of st.chat_input.at.chat_input[0].set_value(""What is Streamlit?"").run() CheckboxA representation of st.checkbox.at.checkbox[0].check().run() ColorPickerA representation of st.color_picker.at.color_picker[0].pick(""#FF4B4B"").run() DateInputA representation of st.date_input.release_date = datetime.date(2023, 10, 26) at.date_input[0].set_value(release_date).run() MultiselectA representation of st.multiselect.at.multiselect[0].select(""New York"").run() NumberInputA representation of st.number_input.at.number_input[0].increment().run() RadioA representation of st.radio.at.radio[0].set_value(""New York"").run() SelectSliderA representation of st.select_slider.at.select_slider[0].set_range(""A"",""C"").run() SelectboxA representation of st.selectbox.at.selectbox[0].select(""New York"").run() SliderA representation of st.slider.at.slider[0].set_range(2,5).run() TextAreaA representation of st.text_area.at.text_area[0].input(""Streamlit is awesome!"").run() TextInputA representation of st.text_input.at.text_input[0].input(""Streamlit"").run() TimeInputA representation of st.time_input.at.time_input[0].increment().run() ToggleA representation of st.toggle.at.toggle[0].set_value(""True"").run() Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration!Pandas ProfilingPandas profiling component for Streamlit. Created by @okld.df = pd.read_csv(""https://storage.googleapis.com/tf-datasets/titanic/train.csv"") pr = df.profile_report() st_profile_report(pr) Streamlit AceAce editor component for Streamlit. Created by @okld.from streamlit_ace import st_ace content = st_ace() content Streamlit AnalyticsTrack & visualize user interactions with your streamlit app. Created by @jrieke.import streamlit_analytics with streamlit_analytics.track(): st.text_input(""Write something"") Previous: ConceptsNext: Write and magicforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy" https://docs.streamlit.io/deploy/streamlit-community-cloud/deploy-your-app/app-dependencies#apt-get-dependencies,"DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudremoveGet startedaddDeploy your appremoveApp dependenciesSecrets managementManage your appaddShare your appaddManage your accountaddTroubleshootingStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Deploy/Streamlit Community Cloud/Deploy your app/App dependenciesApp dependencies The main reason that apps fail to build properly is because Streamlit Community Cloud can't find your dependencies! There are two kinds of dependencies your app might have: Python dependencies and external dependencies. Python dependencies are other Python packages (just like Streamlit!) that you import into you script. External dependencies are less common, but they include any other software your script needs to function properly. Since Streamlit Community Cloud runs on Linux, these will be Linux dependencies installed with apt-get outside the Python environment. For your dependencies to be installed correctly, make sure you: Add a requirements file for Python dependencies. (optional) Add a packages.txt file to manage any external dependencies. push_pinNotePython requirements files should be placed either in the root of your repository or in the same directory as your Streamlit app. Add Python dependencies With each import statement in your script, you are bringing in a Python dependency. You need to tell Streamlit Community Cloud how to install those dependencies through a Python package manager. We recommend using a requirements.txt which is based on pip. You should not include built-in Python libraries like math or random in your requirements.txt file. These are a part of Python and aren't installed separately. Also, Streamlit Community Cloud has streamlit installed by default. You don't strictly need to include streamlit unless you want to pin or restrict the version. If you deploy an app without a requirements.txt file, your app will run in an environment with just streamlit (and its dependencies) installed. If you have a script like the following, no extra dependencies would be needed since pandas and numpy are installed as direct dependencies of streamlit. Similarly, math and random are built into Python. import streamlit as st import pandas as pd import numpy as np import math import random st.write('Hi!') However, a valid requirements.txt file would be: streamlit pandas numpy Alternatively, if you needed to specify certain versions, another valid example would be: streamlit==1.24.1 pandas>2.0 numpy<=1.25.1 In the above example, streamlit is pinned to version 1.24.1, pandas must be strictly greater than version 2.0, and numpy must be at-or-below version 1.25.1. Each line in your requirements.txt file is effectively what you would like to pip install into your cloud environment. push_pinNoteWe recommend that you use the latest version of Streamlit to ensure full Streamlit Community Cloud functionality. Be sure to take note of Streamlit's current requirements for package compatibility when planning your environment, especially protobuf>=3.20,<5. If you pin streamlit below 1.20.0, you may experience unexpected results if you've pinned any dependencies of altair. If streamlit is installed below version 1.20.0, altair<5 will be reinstalled on top of your environment for compatibility reasons. When this happens all of altair's dependencies will be updated. Other Python package managers There are other Python package managers besides pip. If you want to consider alternatives to using a requirements.txt file, Streamlit Community Cloud will look for other Python dependency managers to use in the order below. Streamlit will stop and install the first dependency file found. Recognized FilenamePython Package ManagerPipfilepipenvenvironment.ymlcondarequirements.txtpippyproject.tomlpoetry priority_highWarningYou should only use one requirements file for your app. If you include more than one (e.g. requirements.txt and Pipfile), only the first file encountered will be used as described above. Additionally, Streamlit will first look in the directory of your Streamlit app; however, if no requirements file is found, Streamlit will then look at the root of the repo. apt-get dependencies For many apps, a packages.txt file is not required. However, if your script requires any software to be installed that is not a Python package, then you will need a packages.txt file. Streamlit Community Cloud is built on Debian Linux. Anything you would like to apt-get install needs to go in your packages.txt file. If packages.txt exists in the root directory of your repository we automatically detect it, parse it, and install the listed packages. You can read more about apt-get in Linux documentation. Add apt-get dependencies to packages.txt — one package name per line. For example, mysqlclient is a Python package which requires additional software be installed to function. A valid packages.txt file to enable mysqlclient would be: build-essential pkg-config default-libmysqlclient-dev Previous: Deploy your appNext: Secrets managementforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy" https://docs.streamlit.io/deploy/streamlit-community-cloud/manage-your-app/edit-your-app,"DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudremoveGet startedaddDeploy your appaddManage your appremoveApp analyticsApp settingsDelete your appEdit your appFavorite your appReboot your appShare your appaddManage your accountaddTroubleshootingStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Deploy/Streamlit Community Cloud/Manage your app/Edit your appEdit your app You can edit your app from any development environment of your choice. Community Cloud will monitor your repository and automatically copy any file changes you commit. You will immediately see commits reflected in your deployed app for most changes (such as edits to your app's Python files). Community Cloud also makes it easy to skip the work of setting up a development environment. With a few simple clicks, you can configure a development environment using GitHub Codespaces. Edit your app with GitHub Codespaces Spin up a cloud-based development environment for your deployed app in minutes. You can run your app within your codespace to enjoy experimenting in a safe, sandboxed environment. When you are done editing your code, you can commit your changes to your repo or just leave them in your codespace to return to later. Create a codespace for your deployed app From your workspace at share.streamlit.io, click the overflow icon (more_vert) next to your app. Click ""Edit."" A .devcontainer/devcontainer.json file will be added to your repository. If you already have a file of the same name in your repository, it will not be changed. You may delete or rename your existing devcontainer configuration if you would like your repository to receive the instance created by Streamlit Community Cloud. Click ""Create codespace"" to confirm the creation of a codespace on your account. Read more about GitHub Codespaces to learn about monthly limits for free use and paid plans. Wait for GitHub to set up your codespace. GitHub will automatically execute the commands to launch your Streamlit app within your codespace. Your app will be visible in a ""Simple Browser"" on the right. This may take a minute to complete from when your codespace first appears on screen. When you make changes to your app, the file is automatically saved within your codespace. Your edits do not affect your repository unless you choose to commit those changes. We will describe committing your changes in a later step. In order to see updates automatically reflected on the right, click ""Always rerun"" when prompted after an edit. See your edits appear within the ""Simple Browser"" tab and keep going with more! Commit your changes to your repository (optional) After making edits to your app, you can choose to commit your edits to your repository to update your deployed app instantly. If you just want to keep your edits in your codespace to return to later, skip to Stop or delete your codespace. In the left navigation bar, click the source control icon. Fill out your desired commit message and click ""Commit."" Click ""Yes"" to stage and commit all your changes. To learn more about source control in GitHub Codespaces, check out Source control in GitHub Docs. Stop or delete your codespace When you are done, remember to stop your codespace on GitHub to avoid any undesired use of your capacity. Go to github.com/codespaces. At the bottom of the page, all your codespaces are listed. Click the overflow menu icon (more_horiz) for your codespace. Click ""Stop codespace"" if you'd like to return to your work later. Otherwise, click ""Delete."" Previous: Delete your appNext: Favorite your appforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy" https://docs.streamlit.io/develop/api-reference/app-testing/testing-element-classes#elementvalue,"DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceremovePAGE ELEMENTSWrite and magicaddText elementsaddData elementsaddChart elementsaddInput widgetsaddMedia elementsaddLayouts and containersaddChat elementsaddStatus elementsaddThird-party componentsopen_in_newAPPLICATION LOGICNavigation and pagesaddExecution flowaddCaching and stateaddConnections and secretsaddCustom componentsaddUtilitiesaddConfigurationaddTOOLSApp testingremovest.testing.v1.AppTestTesting element classesCommand lineaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Develop/API reference/App testing/Testing element classesTesting element classes st.testing.v1.element_tree.Block The Block class has the same methods and attributes as AppTest. A Block instance represents a container of elements just as AppTest represents the entire app. For example, Block.button will produce a WidgetList of Button in the same manner as AppTest.button. ChatMessage, Column, and Tab all inherit from Block. For all container classes, parameters of the original element can be obtained as properties. For example, ChatMessage.avatar and Tab.label. st.testing.v1.element_tree.ElementStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeElement base class for testing. This class's methods and attributes are universal for all elements implemented in testing. For example, Caption, Code, Text, and Title inherit from Element. All widget classes also inherit from Element, but have additional methods specific to each widget type. See the AppTest class for the full list of supported elements. For all element classes, parameters of the original element can be obtained as properties. For example, Button.label, Caption.help, and Toast.icon. Class description[source] st.testing.v1.element_tree.Element(proto, root) Methods run(*, timeout=None) Run the AppTest script which contains the element. Attributes value The value or contents of the element. st.testing.v1.element_tree.ButtonStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.button and st.form_submit_button. Class description[source] st.testing.v1.element_tree.Button(proto, root) Methods click() Set the value of the button to True. run(*, timeout=None) Run the AppTest script which contains the element. set_value(v) Set the value of the button. Attributes value The value of the button. (bool) st.testing.v1.element_tree.ChatInputStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.chat_input. Class description[source] st.testing.v1.element_tree.ChatInput(proto, root) Methods run(*, timeout=None) Run the AppTest script which contains the element. set_value(v) Set the value of the widget. Attributes value The value of the widget. (str) st.testing.v1.element_tree.CheckboxStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.checkbox. Class description[source] st.testing.v1.element_tree.Checkbox(proto, root) Methods check() Set the value of the widget to True. run(*, timeout=None) Run the AppTest script which contains the element. set_value(v) Set the value of the widget. uncheck() Set the value of the widget to False. Attributes value The value of the widget. (bool) st.testing.v1.element_tree.ColorPickerStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.color_picker. Class description[source] st.testing.v1.element_tree.ColorPicker(proto, root) Methods pick(v) Set the value of the widget as a hex string. May omit the ""#"" prefix. run(*, timeout=None) Run the AppTest script which contains the element. set_value(v) Set the value of the widget as a hex string. Attributes value The currently selected value as a hex string. (str) st.testing.v1.element_tree.DateInputStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.date_input. Class description[source] st.testing.v1.element_tree.DateInput(proto, root) Methods run(*, timeout=None) Run the AppTest script which contains the element. set_value(v) Set the value of the widget. Attributes value The value of the widget. (date or Tuple of date) st.testing.v1.element_tree.MultiselectStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.multiselect. Class description[source] st.testing.v1.element_tree.Multiselect(proto, root) Methods run(*, timeout=None) Run the AppTest script which contains the element. select(v) Add a selection to the widget. Do nothing if the value is already selected. If testing a multiselect widget with repeated options, use set_value instead. set_value(v) Set the value of the multiselect widget. (list) unselect(v) Remove a selection from the widget. Do nothing if the value is not already selected. If a value is selected multiple times, the first instance is removed. Attributes format_func The widget's formatting function for displaying options. (callable) indices The indices of the currently selected values from the options. (list) value The currently selected values from the options. (list) st.testing.v1.element_tree.NumberInputStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.number_input. Class description[source] st.testing.v1.element_tree.NumberInput(proto, root) Methods decrement() Decrement the st.number_input widget as if the user clicked ""-"". increment() Increment the st.number_input widget as if the user clicked ""+"". run(*, timeout=None) Run the AppTest script which contains the element. set_value(v) Set the value of the st.number_input widget. Attributes value Get the current value of the st.number_input widget. st.testing.v1.element_tree.RadioStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.radio. Class description[source] st.testing.v1.element_tree.Radio(proto, root) Methods run(*, timeout=None) Run the AppTest script which contains the element. set_value(v) Set the selection by value. Attributes format_func The widget's formatting function for displaying options. (callable) index The index of the current selection. (int) value The currently selected value from the options. (Any) st.testing.v1.element_tree.SelectSliderStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.select_slider. Class description[source] st.testing.v1.element_tree.SelectSlider(proto, root) Methods run(*, timeout=None) Run the AppTest script which contains the element. set_range(lower, upper) Set the ranged selection by values. set_value(v) Set the (single) selection by value. Attributes format_func The widget's formatting function for displaying options. (callable) value The currently selected value or range. (Any or Sequence of Any) st.testing.v1.element_tree.SelectboxStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.selectbox. Class description[source] st.testing.v1.element_tree.Selectbox(proto, root) Methods run(*, timeout=None) Run the AppTest script which contains the element. select(v) Set the selection by value. select_index(index) Set the selection by index. set_value(v) Set the selection by value. Attributes format_func The widget's formatting function for displaying options. (callable) index The index of the current selection. (int) value The currently selected value from the options. (Any) st.testing.v1.element_tree.SliderStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.slider. Class description[source] st.testing.v1.element_tree.Slider(proto, root) Methods run(*, timeout=None) Run the AppTest script which contains the element. set_range(lower, upper) Set the ranged value of the slider. set_value(v) Set the (single) value of the slider. Attributes value The currently selected value or range. (Any or Sequence of Any) st.testing.v1.element_tree.TextAreaStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.text_area. Class description[source] st.testing.v1.element_tree.TextArea(proto, root) Methods input(v) Set the value of the widget only if the value does not exceed the maximum allowed characters. run(*, timeout=None) Run the AppTest script which contains the element. set_value(v) Set the value of the widget. Attributes value The current value of the widget. (str) st.testing.v1.element_tree.TextInputStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.text_input. Class description[source] st.testing.v1.element_tree.TextInput(proto, root) Methods input(v) Set the value of the widget only if the value does not exceed the maximum allowed characters. run(*, timeout=None) Run the AppTest script which contains the element. set_value(v) Set the value of the widget. Attributes value The current value of the widget. (str) st.testing.v1.element_tree.TimeInputStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.time_input. Class description[source] st.testing.v1.element_tree.TimeInput(proto, root) Methods decrement() Select the previous available time. increment() Select the next available time. run(*, timeout=None) Run the AppTest script which contains the element. set_value(v) Set the value of the widget. Attributes value The current value of the widget. (time) st.testing.v1.element_tree.ToggleStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.toggle. Class description[source] st.testing.v1.element_tree.Toggle(proto, root) Methods run(*, timeout=None) Run the AppTest script which contains the element. set_value(v) Set the value of the widget. Attributes value The current value of the widget. (bool) Previous: st.testing.v1.AppTestNext: Command lineforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy" https://docs.streamlit.io/en/0.69.0/api.html#media-elements,"DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceremovePAGE ELEMENTSWrite and magicaddText elementsaddData elementsaddChart elementsaddInput widgetsaddMedia elementsaddLayouts and containersaddChat elementsaddStatus elementsaddThird-party componentsopen_in_newAPPLICATION LOGICNavigation and pagesaddExecution flowaddCaching and stateaddConnections and secretsaddCustom componentsaddUtilitiesaddConfigurationaddTOOLSApp testingaddCommand lineaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Develop/API referenceAPI reference Streamlit makes it easy for you to visualize, mutate, and share data. The API reference is organized by activity type, like displaying data or optimizing performance. Each section includes methods associated with the activity type, including examples. Browse our API below and click to learn more about any of our available commands! 🎈 Display almost anything Write and magic st.writeWrite arguments to the app.st.write(""Hello **world**!"") st.write(my_data_frame) st.write(my_mpl_figure) st.write_streamWrite generators or streams to the app with a typewriter effect.st.write_stream(my_generator) st.write_stream(my_llm_stream) MagicAny time Streamlit sees either a variable or literal value on its own line, it automatically writes that to your app using st.write""Hello **world**!"" my_data_frame my_mpl_figure Text elements MarkdownDisplay string formatted as Markdown.st.markdown(""Hello **world**!"") TitleDisplay text in title formatting.st.title(""The app title"") HeaderDisplay text in header formatting.st.header(""This is a header"") SubheaderDisplay text in subheader formatting.st.subheader(""This is a subheader"") CaptionDisplay text in small font.st.caption(""This is written small caption text"") Code blockDisplay a code block with optional syntax highlighting.st.code(""a = 1234"") EchoDisplay some code in the app, then execute it. Useful for tutorials.with st.echo(): st.write('This code will be printed') LaTeXDisplay mathematical expressions formatted as LaTeX.st.latex(""\int a x^2 \,dx"") Preformatted textWrite fixed-width and preformatted text.st.text(""Hello world"") DividerDisplay a horizontal rule.st.divider() Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration! PreviousTagsAdd tags to your Streamlit apps. Created by @gagan3012.st_tags(label='# Enter Keywords:', text='Press enter to add more', value=['Zero', 'One', 'Two'], suggestions=['five', 'six', 'seven', 'eight', 'nine', 'three', 'eleven', 'ten', 'four'], maxtags = 4, key='1') NLUApply text mining on a dataframe. Created by @JohnSnowLabs.nlu.load('sentiment').predict('I love NLU! <3') Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.mention(label=""An awesome Streamlit App"", icon=""streamlit"", url=""https://extras.streamlit.app"",) Annotated textDisplay annotated text in Streamlit apps. Created by @tvst.annotated_text(""This "", (""is"", ""verb""), "" some "", (""annotated"", ""adj""), (""text"", ""noun""), "" for those of "", (""you"", ""pronoun""), "" who "", (""like"", ""verb""), "" this sort of "", (""thing"", ""noun""), ""."") Drawable CanvasProvides a sketching canvas using Fabric.js. Created by @andfanilo.st_canvas(fill_color=""rgba(255, 165, 0, 0.3)"", stroke_width=stroke_width, stroke_color=stroke_color, background_color=bg_color, background_image=Image.open(bg_image) if bg_image else None, update_streamlit=realtime_update, height=150, drawing_mode=drawing_mode, point_display_radius=point_display_radius if drawing_mode == 'point' else 0, key=""canvas"",) TagsAdd tags to your Streamlit apps. Created by @gagan3012.st_tags(label='# Enter Keywords:', text='Press enter to add more', value=['Zero', 'One', 'Two'], suggestions=['five', 'six', 'seven', 'eight', 'nine', 'three', 'eleven', 'ten', 'four'], maxtags = 4, key='1') NLUApply text mining on a dataframe. Created by @JohnSnowLabs.nlu.load('sentiment').predict('I love NLU! <3') Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.mention(label=""An awesome Streamlit App"", icon=""streamlit"", url=""https://extras.streamlit.app"",) Annotated textDisplay annotated text in Streamlit apps. Created by @tvst.annotated_text(""This "", (""is"", ""verb""), "" some "", (""annotated"", ""adj""), (""text"", ""noun""), "" for those of "", (""you"", ""pronoun""), "" who "", (""like"", ""verb""), "" this sort of "", (""thing"", ""noun""), ""."") Drawable CanvasProvides a sketching canvas using Fabric.js. Created by @andfanilo.st_canvas(fill_color=""rgba(255, 165, 0, 0.3)"", stroke_width=stroke_width, stroke_color=stroke_color, background_color=bg_color, background_image=Image.open(bg_image) if bg_image else None, update_streamlit=realtime_update, height=150, drawing_mode=drawing_mode, point_display_radius=point_display_radius if drawing_mode == 'point' else 0, key=""canvas"",) TagsAdd tags to your Streamlit apps. Created by @gagan3012.st_tags(label='# Enter Keywords:', text='Press enter to add more', value=['Zero', 'One', 'Two'], suggestions=['five', 'six', 'seven', 'eight', 'nine', 'three', 'eleven', 'ten', 'four'], maxtags = 4, key='1') NLUApply text mining on a dataframe. Created by @JohnSnowLabs.nlu.load('sentiment').predict('I love NLU! <3') Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.mention(label=""An awesome Streamlit App"", icon=""streamlit"", url=""https://extras.streamlit.app"",) Next Data elements DataframesDisplay a dataframe as an interactive table.st.dataframe(my_data_frame) Data editorDisplay a data editor widget.edited = st.data_editor(df, num_rows=""dynamic"") Column configurationConfigure the display and editing behavior of dataframes and data editors.st.column_config.NumberColumn(""Price (in USD)"", min_value=0, format=""$%d"") Static tablesDisplay a static table.st.table(my_data_frame) MetricsDisplay a metric in big bold font, with an optional indicator of how the metric changed.st.metric(""My metric"", 42, 2) Dicts and JSONDisplay object or string as a pretty-printed JSON string.st.json(my_dict) Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration! PreviousImage CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates value = streamlit_image_coordinates(""https://placekitten.com/200/300"") st.write(value) Plotly EventsMake Plotly charts interactive!. Created by @null-jones.from streamlit_plotly_events import plotly_events fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.metric_cards import style_metric_cards col3.metric(label=""No Change"", value=5000, delta=0) style_metric_cards() Streamlit AggridImplementation of Ag-Grid component for Streamlit. Created by @PablocFonseca.df = pd.DataFrame({'col1': [1, 2, 3], 'col2': [4, 5, 6]}) grid_return = AgGrid(df, editable=True) new_df = grid_return['data'] Streamlit FoliumStreamlit Component for rendering Folium maps. Created by @randyzwitch.m = folium.Map(location=[39.949610, -75.150282], zoom_start=16) folium.Marker([39.949610, -75.150282], popup=""Liberty Bell"", tooltip=""Liberty Bell"").add_to(m) st_data = st_folium(m, width=725) Pandas ProfilingPandas profiling component for Streamlit. Created by @okld.df = pd.read_csv(""https://storage.googleapis.com/tf-datasets/titanic/train.csv"") pr = df.profile_report() st_profile_report(pr) Image CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates value = streamlit_image_coordinates(""https://placekitten.com/200/300"") st.write(value) Plotly EventsMake Plotly charts interactive!. Created by @null-jones.from streamlit_plotly_events import plotly_events fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.metric_cards import style_metric_cards col3.metric(label=""No Change"", value=5000, delta=0) style_metric_cards() Streamlit AggridImplementation of Ag-Grid component for Streamlit. Created by @PablocFonseca.df = pd.DataFrame({'col1': [1, 2, 3], 'col2': [4, 5, 6]}) grid_return = AgGrid(df, editable=True) new_df = grid_return['data'] Streamlit FoliumStreamlit Component for rendering Folium maps. Created by @randyzwitch.m = folium.Map(location=[39.949610, -75.150282], zoom_start=16) folium.Marker([39.949610, -75.150282], popup=""Liberty Bell"", tooltip=""Liberty Bell"").add_to(m) st_data = st_folium(m, width=725) Pandas ProfilingPandas profiling component for Streamlit. Created by @okld.df = pd.read_csv(""https://storage.googleapis.com/tf-datasets/titanic/train.csv"") pr = df.profile_report() st_profile_report(pr) Image CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates value = streamlit_image_coordinates(""https://placekitten.com/200/300"") st.write(value) Plotly EventsMake Plotly charts interactive!. Created by @null-jones.from streamlit_plotly_events import plotly_events fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.metric_cards import style_metric_cards col3.metric(label=""No Change"", value=5000, delta=0) style_metric_cards() Next Chart elements Simple area chartsDisplay an area chart.st.area_chart(my_data_frame) Simple bar chartsDisplay a bar chart.st.bar_chart(my_data_frame) Simple line chartsDisplay a line chart.st.line_chart(my_data_frame) Simple scatter chartsDisplay a line chart.st.scatter_chart(my_data_frame) Scatterplots on mapsDisplay a map with points on it.st.map(my_data_frame) MatplotlibDisplay a matplotlib.pyplot figure.st.pyplot(my_mpl_figure) AltairDisplay a chart using the Altair library.st.altair_chart(my_altair_chart) Vega-LiteDisplay a chart using the Vega-Lite library.st.vega_lite_chart(my_vega_lite_chart) PlotlyDisplay an interactive Plotly chart.st.plotly_chart(my_plotly_chart) BokehDisplay an interactive Bokeh chart.st.bokeh_chart(my_bokeh_chart) PyDeckDisplay a chart using the PyDeck library.st.pydeck_chart(my_pydeck_chart) GraphVizDisplay a graph using the dagre-d3 library.st.graphviz_chart(my_graphviz_spec) Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration! PreviousStreamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl(""https://assets5.lottiefiles.com/packages/lf20_V9t630.json"") st_lottie(lottie_hello, key=""hello"") Plotly EventsMake Plotly charts interactive!. Created by @null-jones.fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.chart += get_annotations_chart(annotations=[(""Mar 01, 2008"", ""Pretty good day for GOOG""), (""Dec 01, 2007"", ""Something's going wrong for GOOG & AAPL""), (""Nov 01, 2008"", ""Market starts again thanks to...""), (""Dec 01, 2009"", ""Small crash for GOOG after...""),],) st.altair_chart(chart, use_container_width=True) PlostA deceptively simple plotting library for Streamlit. Created by @tvst.import plost plost.line_chart(my_dataframe, x='time', y='stock_value', color='stock_name',) HiPlotHigh dimensional Interactive Plotting. Created by @facebookresearch.data = [{'dropout':0.1, 'lr': 0.001, 'loss': 10.0, 'optimizer': 'SGD'}, {'dropout':0.15, 'lr': 0.01, 'loss': 3.5, 'optimizer': 'Adam'}, {'dropout':0.3, 'lr': 0.1, 'loss': 4.5, 'optimizer': 'Adam'}] hip.Experiment.from_iterable(data).display() EChartsHigh dimensional Interactive Plotting. Created by @andfanilo.from streamlit_echarts import st_echarts st_echarts(options=options) Streamlit FoliumStreamlit Component for rendering Folium maps. Created by @randyzwitch.m = folium.Map(location=[39.949610, -75.150282], zoom_start=16) st_data = st_folium(m, width=725) Spacy-StreamlitspaCy building blocks and visualizers for Streamlit apps. Created by @explosion.models = [""en_core_web_sm"", ""en_core_web_md""] spacy_streamlit.visualize(models, ""Sundar Pichai is the CEO of Google."") Streamlit AgraphA Streamlit Graph Vis, based on react-grah-vis. Created by @ChrisDelClea.from streamlit_agraph import agraph, Node, Edge, Config agraph(nodes=nodes, edges=edges, config=config) Streamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl(""https://assets5.lottiefiles.com/packages/lf20_V9t630.json"") st_lottie(lottie_hello, key=""hello"") Plotly EventsMake Plotly charts interactive!. Created by @null-jones.fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.chart += get_annotations_chart(annotations=[(""Mar 01, 2008"", ""Pretty good day for GOOG""), (""Dec 01, 2007"", ""Something's going wrong for GOOG & AAPL""), (""Nov 01, 2008"", ""Market starts again thanks to...""), (""Dec 01, 2009"", ""Small crash for GOOG after...""),],) st.altair_chart(chart, use_container_width=True) PlostA deceptively simple plotting library for Streamlit. Created by @tvst.import plost plost.line_chart(my_dataframe, x='time', y='stock_value', color='stock_name',) HiPlotHigh dimensional Interactive Plotting. Created by @facebookresearch.data = [{'dropout':0.1, 'lr': 0.001, 'loss': 10.0, 'optimizer': 'SGD'}, {'dropout':0.15, 'lr': 0.01, 'loss': 3.5, 'optimizer': 'Adam'}, {'dropout':0.3, 'lr': 0.1, 'loss': 4.5, 'optimizer': 'Adam'}] hip.Experiment.from_iterable(data).display() EChartsHigh dimensional Interactive Plotting. Created by @andfanilo.from streamlit_echarts import st_echarts st_echarts(options=options) Streamlit FoliumStreamlit Component for rendering Folium maps. Created by @randyzwitch.m = folium.Map(location=[39.949610, -75.150282], zoom_start=16) st_data = st_folium(m, width=725) Spacy-StreamlitspaCy building blocks and visualizers for Streamlit apps. Created by @explosion.models = [""en_core_web_sm"", ""en_core_web_md""] spacy_streamlit.visualize(models, ""Sundar Pichai is the CEO of Google."") Streamlit AgraphA Streamlit Graph Vis, based on react-grah-vis. Created by @ChrisDelClea.from streamlit_agraph import agraph, Node, Edge, Config agraph(nodes=nodes, edges=edges, config=config) Streamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl(""https://assets5.lottiefiles.com/packages/lf20_V9t630.json"") st_lottie(lottie_hello, key=""hello"") Plotly EventsMake Plotly charts interactive!. Created by @null-jones.fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.chart += get_annotations_chart(annotations=[(""Mar 01, 2008"", ""Pretty good day for GOOG""), (""Dec 01, 2007"", ""Something's going wrong for GOOG & AAPL""), (""Nov 01, 2008"", ""Market starts again thanks to...""), (""Dec 01, 2009"", ""Small crash for GOOG after...""),],) st.altair_chart(chart, use_container_width=True) Next Input widgets ButtonDisplay a button widget.clicked = st.button(""Click me"") Download buttonDisplay a download button widget.st.download_button(""Download file"", file) Form buttonDisplay a form submit button. For use with st.form.st.form_submit_button(""Sign up"") Link buttonDisplay a link button.st.link_button(""Go to gallery"", url) Page linkDisplay a link to another page in a multipage app.st.page_link(""app.py"", label=""Home"", icon=""🏠"") st.page_link(""pages/profile.py"", label=""My profile"") CheckboxDisplay a checkbox widget.selected = st.checkbox(""I agree"") Color pickerDisplay a color picker widget.color = st.color_picker(""Pick a color"") MultiselectDisplay a multiselect widget. The multiselect widget starts as empty.choices = st.multiselect(""Buy"", [""milk"", ""apples"", ""potatoes""]) RadioDisplay a radio button widget.choice = st.radio(""Pick one"", [""cats"", ""dogs""]) SelectboxDisplay a select widget.choice = st.selectbox(""Pick one"", [""cats"", ""dogs""]) Select-sliderDisplay a slider widget to select items from a list.size = st.select_slider(""Pick a size"", [""S"", ""M"", ""L""]) ToggleDisplay a toggle widget.activated = st.toggle(""Activate"") Number inputDisplay a numeric input widget.choice = st.number_input(""Pick a number"", 0, 10) SliderDisplay a slider widget.number = st.slider(""Pick a number"", 0, 100) Date inputDisplay a date input widget.date = st.date_input(""Your birthday"") Time inputDisplay a time input widget.time = st.time_input(""Meeting time"") Chat inputDisplay a chat input widget.prompt = st.chat_input(""Say something"") if prompt: st.write(f""The user has sent: {prompt}"") Text-areaDisplay a multi-line text input widget.text = st.text_area(""Text to translate"") Text inputDisplay a single-line text input widget.name = st.text_input(""First name"") Data editorDisplay a data editor widget.edited = st.experimental_data_editor(df, num_rows=""dynamic"") File UploaderDisplay a file uploader widget.data = st.file_uploader(""Upload a CSV"") Camera inputDisplay a widget that allows users to upload images directly from a camera.image = st.camera_input(""Take a picture"") Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration! PreviousStreamlit ChatStreamlit Component for a Chatbot UI. Created by @AI-Yash.from streamlit_chat import message message(""My message"") message(""Hello bot!"", is_user=True) # align's the message to the right Streamlit Option MenuSelect a single item from a list of options in a menu. Created by @victoryhb.from streamlit_option_menu import option_menu option_menu(""Main Menu"", [""Home"", 'Settings'], icons=['house', 'gear'], menu_icon=""cast"", default_index=1) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.stoggle import stoggle stoggle( ""Click me!"", """"""🥷 Surprise! Here's some additional content"""""",) Streamlit ElementsCreate a draggable and resizable dashboard in Streamlit. Created by @okls.from streamlit_elements import elements, mui, html with elements(""new_element""): mui.Typography(""Hello world"") TagsAdd tags to your Streamlit apps. Created by @gagan3012.from streamlit_tags import st_tags st_tags(label='# Enter Keywords:', text='Press enter to add more', value=['Zero', 'One', 'Two'], suggestions=['five', 'six', 'seven', 'eight', 'nine', 'three', 'eleven', 'ten', 'four'], maxtags = 4, key='1') StqdmThe simplest way to handle a progress bar in streamlit app. Created by @Wirg.from stqdm import stqdm for _ in stqdm(range(50)): sleep(0.5) TimelineDisplay a Timeline in Streamlit apps using TimelineJS. Created by @innerdoc.from streamlit_timeline import timeline with open('example.json', ""r"") as f: timeline(f.read(), height=800) Camera input liveAlternative for st.camera_input which returns the webcam images live. Created by @blackary.from camera_input_live import camera_input_live image = camera_input_live() st.image(value) Streamlit AceAce editor component for Streamlit. Created by @okld.from streamlit_ace import st_ace content = st_ace() content Streamlit ChatStreamlit Component for a Chatbot UI. Created by @AI-Yash.from streamlit_chat import message message(""My message"") message(""Hello bot!"", is_user=True) # align's the message to the right Streamlit Option MenuSelect a single item from a list of options in a menu. Created by @victoryhb.from streamlit_option_menu import option_menu option_menu(""Main Menu"", [""Home"", 'Settings'], icons=['house', 'gear'], menu_icon=""cast"", default_index=1) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.stoggle import stoggle stoggle( ""Click me!"", """"""🥷 Surprise! Here's some additional content"""""",) Streamlit ElementsCreate a draggable and resizable dashboard in Streamlit. Created by @okls.from streamlit_elements import elements, mui, html with elements(""new_element""): mui.Typography(""Hello world"") TagsAdd tags to your Streamlit apps. Created by @gagan3012.from streamlit_tags import st_tags st_tags(label='# Enter Keywords:', text='Press enter to add more', value=['Zero', 'One', 'Two'], suggestions=['five', 'six', 'seven', 'eight', 'nine', 'three', 'eleven', 'ten', 'four'], maxtags = 4, key='1') StqdmThe simplest way to handle a progress bar in streamlit app. Created by @Wirg.from stqdm import stqdm for _ in stqdm(range(50)): sleep(0.5) TimelineDisplay a Timeline in Streamlit apps using TimelineJS. Created by @innerdoc.from streamlit_timeline import timeline with open('example.json', ""r"") as f: timeline(f.read(), height=800) Camera input liveAlternative for st.camera_input which returns the webcam images live. Created by @blackary.from camera_input_live import camera_input_live image = camera_input_live() st.image(value) Streamlit AceAce editor component for Streamlit. Created by @okld.from streamlit_ace import st_ace content = st_ace() content Streamlit ChatStreamlit Component for a Chatbot UI. Created by @AI-Yash.from streamlit_chat import message message(""My message"") message(""Hello bot!"", is_user=True) # align's the message to the right Streamlit Option MenuSelect a single item from a list of options in a menu. Created by @victoryhb.from streamlit_option_menu import option_menu option_menu(""Main Menu"", [""Home"", 'Settings'], icons=['house', 'gear'], menu_icon=""cast"", default_index=1) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.stoggle import stoggle stoggle( ""Click me!"", """"""🥷 Surprise! Here's some additional content"""""",) Next Media elements ImageDisplay an image or list of images.st.image(numpy_array) st.image(image_bytes) st.image(file) st.image(""https://example.com/myimage.jpg"") AudioDisplay an audio player.st.audio(numpy_array) st.audio(audio_bytes) st.audio(file) st.audio(""https://example.com/myaudio.mp3"", format=""audio/mp3"") VideoDisplay a video player.st.video(numpy_array) st.video(video_bytes) st.video(file) st.video(""https://example.com/myvideo.mp4"", format=""video/mp4"") Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration! PreviousStreamlit CropperA simple image cropper for Streamlit. Created by @turner-anderson.from streamlit_cropper import st_cropper st_cropper(img, realtime_update=realtime_update, box_color=box_color, aspect_ratio=aspect_ratio) Image CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates streamlit_image_coordinates(""https://placekitten.com/200/300"") Streamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl(""https://assets5.lottiefiles.com/packages/lf20_V9t630.json"") st_lottie(lottie_hello, key=""hello"") Streamlit WebrtcHandling and transmitting real-time video/audio streams with Streamlit. Created by @whitphx.from streamlit_webrtc import webrtc_streamer webrtc_streamer(key=""sample"") Drawable CanvasProvides a sketching canvas using Fabric.js. Created by @andfanilo.from streamlit_drawable_canvas import st_canvas st_canvas(fill_color=""rgba(255, 165, 0, 0.3)"", stroke_width=stroke_width, stroke_color=stroke_color, background_color=bg_color, background_image=Image.open(bg_image) if bg_image else None, update_streamlit=realtime_update, height=150, drawing_mode=drawing_mode, point_display_radius=point_display_radius if drawing_mode == 'point' else 0, key=""canvas"",) Image ComparisonCompare images with a slider using JuxtaposeJS. Created by @fcakyon.from streamlit_image_comparison import image_comparison image_comparison(img1=""image1.jpg"", img2=""image2.jpg"",) Streamlit CropperA simple image cropper for Streamlit. Created by @turner-anderson.from streamlit_cropper import st_cropper st_cropper(img, realtime_update=realtime_update, box_color=box_color, aspect_ratio=aspect_ratio) Image CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates streamlit_image_coordinates(""https://placekitten.com/200/300"") Streamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl(""https://assets5.lottiefiles.com/packages/lf20_V9t630.json"") st_lottie(lottie_hello, key=""hello"") Streamlit WebrtcHandling and transmitting real-time video/audio streams with Streamlit. Created by @whitphx.from streamlit_webrtc import webrtc_streamer webrtc_streamer(key=""sample"") Drawable CanvasProvides a sketching canvas using Fabric.js. Created by @andfanilo.from streamlit_drawable_canvas import st_canvas st_canvas(fill_color=""rgba(255, 165, 0, 0.3)"", stroke_width=stroke_width, stroke_color=stroke_color, background_color=bg_color, background_image=Image.open(bg_image) if bg_image else None, update_streamlit=realtime_update, height=150, drawing_mode=drawing_mode, point_display_radius=point_display_radius if drawing_mode == 'point' else 0, key=""canvas"",) Image ComparisonCompare images with a slider using JuxtaposeJS. Created by @fcakyon.from streamlit_image_comparison import image_comparison image_comparison(img1=""image1.jpg"", img2=""image2.jpg"",) Streamlit CropperA simple image cropper for Streamlit. Created by @turner-anderson.from streamlit_cropper import st_cropper st_cropper(img, realtime_update=realtime_update, box_color=box_color, aspect_ratio=aspect_ratio) Image CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates streamlit_image_coordinates(""https://placekitten.com/200/300"") Streamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl(""https://assets5.lottiefiles.com/packages/lf20_V9t630.json"") st_lottie(lottie_hello, key=""hello"") Next Layouts and containers ColumnsInsert containers laid out as side-by-side columns.col1, col2 = st.columns(2) col1.write(""this is column 1"") col2.write(""this is column 2"") ContainerInsert a multi-element container.c = st.container() st.write(""This will show last"") c.write(""This will show first"") c.write(""This will show second"") Modal dialogsInsert a modal dialog that can rerun independently from the rest of the script.@st.experimental_dialog(""Sign up"") def email_form(): name = st.text_input(""Name"") email = st.text_input(""Email"") EmptyInsert a single-element container.c = st.empty() st.write(""This will show last"") c.write(""This will be replaced"") c.write(""This will show first"") ExpanderInsert a multi-element container that can be expanded/collapsed.with st.expander(""Open to see more""): st.write(""This is more content"") PopoverInsert a multi-element popover container that can be opened/closed.with st.popover(""Settings""): st.checkbox(""Show completed"") SidebarDisplay items in a sidebar.st.sidebar.write(""This lives in the sidebar"") st.sidebar.button(""Click me!"") TabsInsert containers separated into tabs.tab1, tab2 = st.tabs([""Tab 1"", ""Tab2""]) tab1.write(""this is tab 1"") tab2.write(""this is tab 2"") Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration!Streamlit ElementsCreate a draggable and resizable dashboard in Streamlit. Created by @okls.from streamlit_elements import elements, mui, html with elements(""new_element""): mui.Typography(""Hello world"") PydanticAuto-generate Streamlit UI from Pydantic Models and Dataclasses. Created by @lukasmasuch.import streamlit_pydantic as sp sp.pydantic_form(key=""my_form"", model=ExampleModel) Streamlit PagesAn experimental version of Streamlit Multi-Page Apps. Created by @blackary.from st_pages import Page, show_pages, add_page_title show_pages([ Page(""streamlit_app.py"", ""Home"", ""🏠""), Page(""other_pages/page2.py"", ""Page 2"", "":books:""), ]) Chat elements Streamlit provides a few commands to help you build conversational apps. These chat elements are designed to be used in conjunction with each other, but you can also use them separately. st.chat_message lets you insert a chat message container into the app so you can display messages from the user or the app. Chat containers can contain other Streamlit elements, including charts, tables, text, and more. st.chat_input lets you display a chat input widget so the user can type in a message. Chat inputDisplay a chat input widget.prompt = st.chat_input(""Say something"") if prompt: st.write(f""The user has sent: {prompt}"") Chat messageInsert a chat message container.import numpy as np with st.chat_message(""user""): st.write(""Hello 👋"") st.line_chart(np.random.randn(30, 3)) Status containerDisplay output of long-running tasks in a container.with st.status('Running'): do_something_slow() st.write_streamWrite generators or streams to the app with a typewriter effect.st.write_stream(my_generator) st.write_stream(my_llm_stream) Status elements Progress barDisplay a progress bar.for i in range(101): st.progress(i) do_something_slow() SpinnerTemporarily displays a message while executing a block of code.with st.spinner(""Please wait...""): do_something_slow() Status containerDisplay output of long-running tasks in a container.with st.status('Running'): do_something_slow() ToastBriefly displays a toast message in the bottom-right corner.st.toast('Butter!', icon='🧈') BalloonsDisplay celebratory balloons!do_something() # Celebrate when all done! st.balloons() SnowflakesDisplay celebratory snowflakes!do_something() # Celebrate when all done! st.snow() Success boxDisplay a success message.st.success(""Match found!"") Info boxDisplay an informational message.st.info(""Dataset is updated every day at midnight."") Warning boxDisplay warning message.st.warning(""Unable to fetch image. Skipping..."") Error boxDisplay error message.st.error(""We encountered an error"") Exception outputDisplay an exception.e = RuntimeError(""This is an exception of type RuntimeError"") st.exception(e) Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration!StqdmThe simplest way to handle a progress bar in streamlit app. Created by @Wirg.from stqdm import stqdm for _ in stqdm(range(50)): sleep(0.5) Custom notification boxA custom notification box with the ability to close it out. Created by @Socvest.from streamlit_custom_notification_box import custom_notification_box styles = {'material-icons':{'color': 'red'}, 'text-icon-link-close-container': {'box-shadow': '#3896de 0px 4px'}, 'notification-text': {'':''}, 'close-button':{'':''}, 'link':{'':''}} custom_notification_box(icon='info', textDisplay='We are almost done with your registration...', externalLink='more info', url='#', styles=styles, key=""foo"") Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.let_it_rain import rain rain(emoji=""🎈"", font_size=54, falling_speed=5, animation_length=""infinite"",) App logic and configuration Navigation and pages Switch pageProgrammatically navigates to a specified page.st.switch_page(""pages/my_page.py"") Page linkDisplay a link to another page in a multipage app.st.page_link(""app.py"", label=""Home"", icon=""🏠"") st.page_link(""pages/profile.py"", label=""My profile"") Execution flow Modal dialogsInsert a modal dialog that can rerun independently from the rest of the script.@st.experimental_dialog(""Sign up"") def email_form(): name = st.text_input(""Name"") email = st.text_input(""Email"") FormsCreate a form that batches elements together with a “Submit"" button.with st.form(key='my_form'): name = st.text_input(""Name"") email = st.text_input(""Email"") st.form_submit_button(""Sign up"") Partial rerunsDefine a fragment to rerun independently from the rest of the script.@st.experimental_fragment(run_every=""10s"") def fragment(): df = get_data() st.line_chart(df) Rerun scriptRerun the script immediately.st.rerun() Stop executionStops execution immediately.st.stop() Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration!AutorefreshForce a refresh without tying up a script. Created by @kmcgrady.from streamlit_autorefresh import st_autorefresh st_autorefresh(interval=2000, limit=100, key=""fizzbuzzcounter"") PydanticAuto-generate Streamlit UI from Pydantic Models and Dataclasses. Created by @lukasmasuch.import streamlit_pydantic as sp sp.pydantic_form(key=""my_form"", model=ExampleModel) Streamlit PagesAn experimental version of Streamlit Multi-Page Apps. Created by @blackary.from st_pages import Page, show_pages, add_page_title show_pages([ Page(""streamlit_app.py"", ""Home"", ""🏠""), Page(""other_pages/page2.py"", ""Page 2"", "":books:""), ]) Caching and state Cache dataFunction decorator to cache functions that return data (e.g. dataframe transforms, database queries, ML inference).@st.cache_data def long_function(param1, param2): # Perform expensive computation here or # fetch data from the web here return data Cache resourceFunction decorator to cache functions that return global resources (e.g. database connections, ML models).@st.cache_resource def init_model(): # Return a global resource here return pipeline( ""sentiment-analysis"", model=""distilbert-base-uncased-finetuned-sst-2-english"" ) Session stateSession state is a way to share variables between reruns, for each user session.st.session_state['key'] = value Query parametersGet, set, or clear the query parameters that are shown in the browser's URL bar.st.query_params[key] = value st.query_params.clear() Connections and databases Setup your connection Create a connectionConnect to a data source or APIconn = st.connection('pets_db', type='sql') pet_owners = conn.query('select * from pet_owners') st.dataframe(pet_owners) Built-in connections SnowflakeConnectionA connection to Snowflake.conn = st.connection('snowflake') SQLConnectionA connection to a SQL database using SQLAlchemy.conn = st.connection('sql') Build your own connections Connection base classBuild your own connection with BaseConnection.class MyConnection(BaseConnection[myconn.MyConnection]): def _connect(self, **kwargs) -> MyConnection: return myconn.connect(**self._secrets, **kwargs) def query(self, query): return self._instance.query(query) Secrets management Secrets singletonAccess secrets from a local TOML file.key = st.secrets[""OpenAI_key""] Secrets fileSave your secrets in a per-project or per-profile TOML file.OpenAI_key = """" Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration!AuthenticatorA secure authentication module to validate user credentials. Created by @mkhorasani.import streamlit_authenticator as stauth authenticator = stauth.Authenticate( config['credentials'], config['cookie']['name'], config['cookie']['key'], config['cookie']['expiry_days'], config['preauthorized']) WS localStorageA simple synchronous way of accessing localStorage from your app. Created by @gagangoku.from streamlit_ws_localstorage import injectWebsocketCode ret = conn.setLocalStorageVal(key='k1', val='v1') st.write('ret: ' + ret) Streamlit Auth0The fastest way to provide comprehensive login inside Streamlit. Created by @conradbez.from auth0_component import login_button user_info = login_button(clientId, domain = domain) st.write(user_info) Custom Components Declare a componentCreate and register a custom component.st.components.v1.declare_component( ""custom_slider"", ""/frontend"", ) HTMLDisplay an HTML string in an iframe.st.components.v1.html( ""

Foo bar.

"" ) iframeLoad a remote URL in an iframe.st.components.v1.iframe( ""docs.streamlit.io"" ) Utilities and user info User infost.experimental_user returns information about the logged-in user of private apps on Streamlit Community Cloud.if st.experimental_user.email == ""foo@corp.com"": st.write(""Welcome back, "", st.experimental_user.email) else: st.write(""You are not authorized to view this page."") Get helpDisplay object’s doc string, nicely formatted.st.help(st.write) st.help(pd.DataFrame) Render HTMLRenders HTML strings to your app.css = """""" """""" st.html(css) Configuration Configuration fileConfigures the default settings for your app.your-project/ ├── .streamlit/ │ └── config.toml └── your_app.py Set page title, favicon, and moreConfigures the default settings of the page.st.set_page_config( page_title=""My app"", page_icon="":shark:"", ) Developer tools App testing st.testing.v1.AppTestst.testing.v1.AppTest simulates a running Streamlit app for testing.from streamlit.testing.v1 import AppTest at = AppTest.from_file(""streamlit_app.py"") at.secrets[""WORD""] = ""Foobar"" at.run() assert not at.exception at.text_input(""word"").input(""Bazbat"").run() assert at.warning[0].value == ""Try again."" AppTest.from_filest.testing.v1.AppTest.from_file initializes a simulated app from a file.from streamlit.testing.v1 import AppTest at = AppTest.from_file(""streamlit_app.py"") at.run() AppTest.from_stringst.testing.v1.AppTest.from_string initializes a simulated app from a string.from streamlit.testing.v1 import AppTest at = AppTest.from_string(app_script_as_string) at.run() AppTest.from_functionst.testing.v1.AppTest.from_function initializes a simulated app from a function.from streamlit.testing.v1 import AppTest at = AppTest.from_function(app_script_as_callable) at.run() BlockA representation of container elements, including: st.chat_message st.columns st.sidebar st.tabs The main body of the app. # at.sidebar returns a Block at.sidebar.button[0].click().run() assert not at.exception ElementThe base class for representation of all elements, including: st.title st.header st.markdown st.dataframe # at.title returns a sequence of Title # Title inherits from Element assert at.title[0].value == ""My awesome app"" ButtonA representation of st.button and st.form_submit_button.at.button[0].click().run() ChatInputA representation of st.chat_input.at.chat_input[0].set_value(""What is Streamlit?"").run() CheckboxA representation of st.checkbox.at.checkbox[0].check().run() ColorPickerA representation of st.color_picker.at.color_picker[0].pick(""#FF4B4B"").run() DateInputA representation of st.date_input.release_date = datetime.date(2023, 10, 26) at.date_input[0].set_value(release_date).run() MultiselectA representation of st.multiselect.at.multiselect[0].select(""New York"").run() NumberInputA representation of st.number_input.at.number_input[0].increment().run() RadioA representation of st.radio.at.radio[0].set_value(""New York"").run() SelectSliderA representation of st.select_slider.at.select_slider[0].set_range(""A"",""C"").run() SelectboxA representation of st.selectbox.at.selectbox[0].select(""New York"").run() SliderA representation of st.slider.at.slider[0].set_range(2,5).run() TextAreaA representation of st.text_area.at.text_area[0].input(""Streamlit is awesome!"").run() TextInputA representation of st.text_input.at.text_input[0].input(""Streamlit"").run() TimeInputA representation of st.time_input.at.time_input[0].increment().run() ToggleA representation of st.toggle.at.toggle[0].set_value(""True"").run() Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration!Pandas ProfilingPandas profiling component for Streamlit. Created by @okld.df = pd.read_csv(""https://storage.googleapis.com/tf-datasets/titanic/train.csv"") pr = df.profile_report() st_profile_report(pr) Streamlit AceAce editor component for Streamlit. Created by @okld.from streamlit_ace import st_ace content = st_ace() content Streamlit AnalyticsTrack & visualize user interactions with your streamlit app. Created by @jrieke.import streamlit_analytics with streamlit_analytics.track(): st.text_input(""Write something"") Previous: ConceptsNext: Write and magicforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy" https://docs.streamlit.io/develop/concepts/architecture/app-chrome#clear-cache,"DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsremoveCOREArchitecture & executionremoveRunning your appStreamlit's architectureThe app chromeCachingSession StateFormsFragmentsWidget behaviorMultipage appsaddApp designaddADDITIONALConnections and secretsaddCustom componentsaddConfiguration and themingaddApp testingaddAPI referenceaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Develop/Concepts/Architecture & execution/The app chromeThe app chrome Your Streamlit app has a few widgets in the top right to help you as you develop. These widgets also help your viewers as they use your app. We call this things “the app chrome”. The chrome includes a status area, toolbar, and app menu. Your app menu is configurable. By default, you can access developer options from the app menu when viewing an app locally or on Streamlit Community Cloud while logged into an account with administrative access. While viewing an app, click the icon in the upper-right corner to access the menu. Menu options The menu is split into two sections. The upper section contains options available to all viewers and the lower section contains options for developers. Read more about customizing this menu at the end of this page. Rerun You can manually trigger a rerun of your app by clicking ""Rerun"" from the app menu. This rerun will not reset your session. Your widget states and values stored in st.session_state will be preserved. As a shortcut, without opening the app menu, you can rerun your app by pressing ""R"" on your keyboard (if you aren't currently focused on an input element). Settings With the ""Settings"" option, you can control the appearance of your app while it is running. If viewing the app locally, you can set how your app responds to changes in your source code. See more about development flow in Basic concepts. You can also force your app to appear in wide mode, even if not set within the script using st.set_page_config. Theme settings After clicking ""Settings"" from the app menu, you can choose between ""Light"", ""Dark"", or ""Use system setting"" for the app's base theme. Click on ""Edit active theme"" to modify the theme, color-by-color. Print Click ""Print"" or use keyboard shortcuts (⌘+P or Ctrl+P) to open a print dialog. This option uses your browser's built-in print-to-pdf function. To modify the appearance of your print, you can do the following: Expand or collapse the sidebar before printing to respectively include or exclude it from the print. Resize the sidebar in your app by clicking and dragging its right border to achieve your desired width. You may need to enable ""Background graphics"" in your print dialog if you are printing in dark mode. You may need to disable wide mode in Settings or adjust the print scale to prevent elements from clipping off the page. Record a screencast You can easily make screen recordings right from your app! Screen recording is supported in the latest versions of Chrome, Edge, and Firefox. Ensure your browser is up-to-date for compatibility. Depending on your current settings, you may need to grant permission to your browser to record your screen or to use your microphone if recording a voiceover. While viewing your app, open the app menu from the upper-right corner. Click ""Record a screencast."" If you want to record audio through your microphone, check ""Also record audio."" Click ""Start recording."" (You may be prompted by your OS to permit your browser to record your screen or use your microphone.) Select which tab, window, or monitor you want to record from the listed options. The interface will vary depending on your browser. Click ""Share."" While recording, you will see a red circle on your app's tab and on the app menu icon. If you want to cancel the recording, click ""Stop sharing"" at the bottom of your app. When you are done recording, press ""Esc"" on your keyboard or click ""Stop recording"" from your app's menu. Follow your browser's instructions to save your recording. Your saved recording will be available where your browser saves downloads. The whole process looks like this: About You can conveniently check what version of Streamlit is running from the ""About"" option. Developers also have the option to customize the message shown here using st.set_page_config. Developer options By default, developer options only show when viewing an app locally or when viewing a Community Cloud app while logged in with administrative permission. You can customize the menu if you want to make these options available for all users. Clear cache Reset your app's cache by clicking ""Clear cache"" from the app's menu or by pressing ""C"" on your keyboard while not focused on an input element. This will remove all cached entries for @st.cache_data and @st.cache_resource. Deploy this app If you are running an app locally from within a git repo, you can deploy your app to Streamlit Community Cloud in a few easy clicks! Make sure your work has been pushed to your online GitHub repository before beginning. For the greatest convenience, make sure you have already created your Community Cloud account and are signed in. Click ""Deploy"" next to the app menu icon (more_vert). Click ""Deploy now"". You will be taken to Community Cloud's ""Deploy an app"" page. Your app's repository, branch, and file name will be prefilled to match your current app! Learn more about deploying an app on Streamlit Community Cloud. The whole process looks like this: Customize the menu Using client.toolbarMode in your app's configuration, you can make the app menu appear in the following ways: ""developer"" — Show the developer options to all viewers. ""viewer"" — Hide the developer options from all viewers. ""minimal"" — Show only those options set externally. These options can be declared through st.set_page_config or populated through Streamlit Community Cloud. ""auto"" — This is the default and will show the developer options when accessed through localhost or through Streamlit Community Cloud when logged into an administrative account for the app. Otherwise, the developer options will not show. Previous: Streamlit's architectureNext: CachingforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy" https://docs.streamlit.io/develop/api-reference/app-testing/testing-element-classes#testing-element-classes,"DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceremovePAGE ELEMENTSWrite and magicaddText elementsaddData elementsaddChart elementsaddInput widgetsaddMedia elementsaddLayouts and containersaddChat elementsaddStatus elementsaddThird-party componentsopen_in_newAPPLICATION LOGICNavigation and pagesaddExecution flowaddCaching and stateaddConnections and secretsaddCustom componentsaddUtilitiesaddConfigurationaddTOOLSApp testingremovest.testing.v1.AppTestTesting element classesCommand lineaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Develop/API reference/App testing/Testing element classesTesting element classes st.testing.v1.element_tree.Block The Block class has the same methods and attributes as AppTest. A Block instance represents a container of elements just as AppTest represents the entire app. For example, Block.button will produce a WidgetList of Button in the same manner as AppTest.button. ChatMessage, Column, and Tab all inherit from Block. For all container classes, parameters of the original element can be obtained as properties. For example, ChatMessage.avatar and Tab.label. st.testing.v1.element_tree.ElementStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeElement base class for testing. This class's methods and attributes are universal for all elements implemented in testing. For example, Caption, Code, Text, and Title inherit from Element. All widget classes also inherit from Element, but have additional methods specific to each widget type. See the AppTest class for the full list of supported elements. For all element classes, parameters of the original element can be obtained as properties. For example, Button.label, Caption.help, and Toast.icon. Class description[source] st.testing.v1.element_tree.Element(proto, root) Methods run(*, timeout=None) Run the AppTest script which contains the element. Attributes value The value or contents of the element. st.testing.v1.element_tree.ButtonStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.button and st.form_submit_button. Class description[source] st.testing.v1.element_tree.Button(proto, root) Methods click() Set the value of the button to True. run(*, timeout=None) Run the AppTest script which contains the element. set_value(v) Set the value of the button. Attributes value The value of the button. (bool) st.testing.v1.element_tree.ChatInputStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.chat_input. Class description[source] st.testing.v1.element_tree.ChatInput(proto, root) Methods run(*, timeout=None) Run the AppTest script which contains the element. set_value(v) Set the value of the widget. Attributes value The value of the widget. (str) st.testing.v1.element_tree.CheckboxStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.checkbox. Class description[source] st.testing.v1.element_tree.Checkbox(proto, root) Methods check() Set the value of the widget to True. run(*, timeout=None) Run the AppTest script which contains the element. set_value(v) Set the value of the widget. uncheck() Set the value of the widget to False. Attributes value The value of the widget. (bool) st.testing.v1.element_tree.ColorPickerStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.color_picker. Class description[source] st.testing.v1.element_tree.ColorPicker(proto, root) Methods pick(v) Set the value of the widget as a hex string. May omit the ""#"" prefix. run(*, timeout=None) Run the AppTest script which contains the element. set_value(v) Set the value of the widget as a hex string. Attributes value The currently selected value as a hex string. (str) st.testing.v1.element_tree.DateInputStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.date_input. Class description[source] st.testing.v1.element_tree.DateInput(proto, root) Methods run(*, timeout=None) Run the AppTest script which contains the element. set_value(v) Set the value of the widget. Attributes value The value of the widget. (date or Tuple of date) st.testing.v1.element_tree.MultiselectStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.multiselect. Class description[source] st.testing.v1.element_tree.Multiselect(proto, root) Methods run(*, timeout=None) Run the AppTest script which contains the element. select(v) Add a selection to the widget. Do nothing if the value is already selected. If testing a multiselect widget with repeated options, use set_value instead. set_value(v) Set the value of the multiselect widget. (list) unselect(v) Remove a selection from the widget. Do nothing if the value is not already selected. If a value is selected multiple times, the first instance is removed. Attributes format_func The widget's formatting function for displaying options. (callable) indices The indices of the currently selected values from the options. (list) value The currently selected values from the options. (list) st.testing.v1.element_tree.NumberInputStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.number_input. Class description[source] st.testing.v1.element_tree.NumberInput(proto, root) Methods decrement() Decrement the st.number_input widget as if the user clicked ""-"". increment() Increment the st.number_input widget as if the user clicked ""+"". run(*, timeout=None) Run the AppTest script which contains the element. set_value(v) Set the value of the st.number_input widget. Attributes value Get the current value of the st.number_input widget. st.testing.v1.element_tree.RadioStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.radio. Class description[source] st.testing.v1.element_tree.Radio(proto, root) Methods run(*, timeout=None) Run the AppTest script which contains the element. set_value(v) Set the selection by value. Attributes format_func The widget's formatting function for displaying options. (callable) index The index of the current selection. (int) value The currently selected value from the options. (Any) st.testing.v1.element_tree.SelectSliderStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.select_slider. Class description[source] st.testing.v1.element_tree.SelectSlider(proto, root) Methods run(*, timeout=None) Run the AppTest script which contains the element. set_range(lower, upper) Set the ranged selection by values. set_value(v) Set the (single) selection by value. Attributes format_func The widget's formatting function for displaying options. (callable) value The currently selected value or range. (Any or Sequence of Any) st.testing.v1.element_tree.SelectboxStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.selectbox. Class description[source] st.testing.v1.element_tree.Selectbox(proto, root) Methods run(*, timeout=None) Run the AppTest script which contains the element. select(v) Set the selection by value. select_index(index) Set the selection by index. set_value(v) Set the selection by value. Attributes format_func The widget's formatting function for displaying options. (callable) index The index of the current selection. (int) value The currently selected value from the options. (Any) st.testing.v1.element_tree.SliderStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.slider. Class description[source] st.testing.v1.element_tree.Slider(proto, root) Methods run(*, timeout=None) Run the AppTest script which contains the element. set_range(lower, upper) Set the ranged value of the slider. set_value(v) Set the (single) value of the slider. Attributes value The currently selected value or range. (Any or Sequence of Any) st.testing.v1.element_tree.TextAreaStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.text_area. Class description[source] st.testing.v1.element_tree.TextArea(proto, root) Methods input(v) Set the value of the widget only if the value does not exceed the maximum allowed characters. run(*, timeout=None) Run the AppTest script which contains the element. set_value(v) Set the value of the widget. Attributes value The current value of the widget. (str) st.testing.v1.element_tree.TextInputStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.text_input. Class description[source] st.testing.v1.element_tree.TextInput(proto, root) Methods input(v) Set the value of the widget only if the value does not exceed the maximum allowed characters. run(*, timeout=None) Run the AppTest script which contains the element. set_value(v) Set the value of the widget. Attributes value The current value of the widget. (str) st.testing.v1.element_tree.TimeInputStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.time_input. Class description[source] st.testing.v1.element_tree.TimeInput(proto, root) Methods decrement() Select the previous available time. increment() Select the next available time. run(*, timeout=None) Run the AppTest script which contains the element. set_value(v) Set the value of the widget. Attributes value The current value of the widget. (time) st.testing.v1.element_tree.ToggleStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.toggle. Class description[source] st.testing.v1.element_tree.Toggle(proto, root) Methods run(*, timeout=None) Run the AppTest script which contains the element. set_value(v) Set the value of the widget. Attributes value The current value of the widget. (bool) Previous: st.testing.v1.AppTestNext: Command lineforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy" https://docs.streamlit.io/en/0.75.0/api.html#layouts-and-containers,"DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceremovePAGE ELEMENTSWrite and magicaddText elementsaddData elementsaddChart elementsaddInput widgetsaddMedia elementsaddLayouts and containersaddChat elementsaddStatus elementsaddThird-party componentsopen_in_newAPPLICATION LOGICNavigation and pagesaddExecution flowaddCaching and stateaddConnections and secretsaddCustom componentsaddUtilitiesaddConfigurationaddTOOLSApp testingaddCommand lineaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Develop/API referenceAPI reference Streamlit makes it easy for you to visualize, mutate, and share data. The API reference is organized by activity type, like displaying data or optimizing performance. Each section includes methods associated with the activity type, including examples. Browse our API below and click to learn more about any of our available commands! 🎈 Display almost anything Write and magic st.writeWrite arguments to the app.st.write(""Hello **world**!"") st.write(my_data_frame) st.write(my_mpl_figure) st.write_streamWrite generators or streams to the app with a typewriter effect.st.write_stream(my_generator) st.write_stream(my_llm_stream) MagicAny time Streamlit sees either a variable or literal value on its own line, it automatically writes that to your app using st.write""Hello **world**!"" my_data_frame my_mpl_figure Text elements MarkdownDisplay string formatted as Markdown.st.markdown(""Hello **world**!"") TitleDisplay text in title formatting.st.title(""The app title"") HeaderDisplay text in header formatting.st.header(""This is a header"") SubheaderDisplay text in subheader formatting.st.subheader(""This is a subheader"") CaptionDisplay text in small font.st.caption(""This is written small caption text"") Code blockDisplay a code block with optional syntax highlighting.st.code(""a = 1234"") EchoDisplay some code in the app, then execute it. Useful for tutorials.with st.echo(): st.write('This code will be printed') LaTeXDisplay mathematical expressions formatted as LaTeX.st.latex(""\int a x^2 \,dx"") Preformatted textWrite fixed-width and preformatted text.st.text(""Hello world"") DividerDisplay a horizontal rule.st.divider() Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration! PreviousTagsAdd tags to your Streamlit apps. Created by @gagan3012.st_tags(label='# Enter Keywords:', text='Press enter to add more', value=['Zero', 'One', 'Two'], suggestions=['five', 'six', 'seven', 'eight', 'nine', 'three', 'eleven', 'ten', 'four'], maxtags = 4, key='1') NLUApply text mining on a dataframe. Created by @JohnSnowLabs.nlu.load('sentiment').predict('I love NLU! <3') Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.mention(label=""An awesome Streamlit App"", icon=""streamlit"", url=""https://extras.streamlit.app"",) Annotated textDisplay annotated text in Streamlit apps. Created by @tvst.annotated_text(""This "", (""is"", ""verb""), "" some "", (""annotated"", ""adj""), (""text"", ""noun""), "" for those of "", (""you"", ""pronoun""), "" who "", (""like"", ""verb""), "" this sort of "", (""thing"", ""noun""), ""."") Drawable CanvasProvides a sketching canvas using Fabric.js. Created by @andfanilo.st_canvas(fill_color=""rgba(255, 165, 0, 0.3)"", stroke_width=stroke_width, stroke_color=stroke_color, background_color=bg_color, background_image=Image.open(bg_image) if bg_image else None, update_streamlit=realtime_update, height=150, drawing_mode=drawing_mode, point_display_radius=point_display_radius if drawing_mode == 'point' else 0, key=""canvas"",) TagsAdd tags to your Streamlit apps. Created by @gagan3012.st_tags(label='# Enter Keywords:', text='Press enter to add more', value=['Zero', 'One', 'Two'], suggestions=['five', 'six', 'seven', 'eight', 'nine', 'three', 'eleven', 'ten', 'four'], maxtags = 4, key='1') NLUApply text mining on a dataframe. Created by @JohnSnowLabs.nlu.load('sentiment').predict('I love NLU! <3') Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.mention(label=""An awesome Streamlit App"", icon=""streamlit"", url=""https://extras.streamlit.app"",) Annotated textDisplay annotated text in Streamlit apps. Created by @tvst.annotated_text(""This "", (""is"", ""verb""), "" some "", (""annotated"", ""adj""), (""text"", ""noun""), "" for those of "", (""you"", ""pronoun""), "" who "", (""like"", ""verb""), "" this sort of "", (""thing"", ""noun""), ""."") Drawable CanvasProvides a sketching canvas using Fabric.js. Created by @andfanilo.st_canvas(fill_color=""rgba(255, 165, 0, 0.3)"", stroke_width=stroke_width, stroke_color=stroke_color, background_color=bg_color, background_image=Image.open(bg_image) if bg_image else None, update_streamlit=realtime_update, height=150, drawing_mode=drawing_mode, point_display_radius=point_display_radius if drawing_mode == 'point' else 0, key=""canvas"",) TagsAdd tags to your Streamlit apps. Created by @gagan3012.st_tags(label='# Enter Keywords:', text='Press enter to add more', value=['Zero', 'One', 'Two'], suggestions=['five', 'six', 'seven', 'eight', 'nine', 'three', 'eleven', 'ten', 'four'], maxtags = 4, key='1') NLUApply text mining on a dataframe. Created by @JohnSnowLabs.nlu.load('sentiment').predict('I love NLU! <3') Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.mention(label=""An awesome Streamlit App"", icon=""streamlit"", url=""https://extras.streamlit.app"",) Next Data elements DataframesDisplay a dataframe as an interactive table.st.dataframe(my_data_frame) Data editorDisplay a data editor widget.edited = st.data_editor(df, num_rows=""dynamic"") Column configurationConfigure the display and editing behavior of dataframes and data editors.st.column_config.NumberColumn(""Price (in USD)"", min_value=0, format=""$%d"") Static tablesDisplay a static table.st.table(my_data_frame) MetricsDisplay a metric in big bold font, with an optional indicator of how the metric changed.st.metric(""My metric"", 42, 2) Dicts and JSONDisplay object or string as a pretty-printed JSON string.st.json(my_dict) Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration! PreviousImage CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates value = streamlit_image_coordinates(""https://placekitten.com/200/300"") st.write(value) Plotly EventsMake Plotly charts interactive!. Created by @null-jones.from streamlit_plotly_events import plotly_events fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.metric_cards import style_metric_cards col3.metric(label=""No Change"", value=5000, delta=0) style_metric_cards() Streamlit AggridImplementation of Ag-Grid component for Streamlit. Created by @PablocFonseca.df = pd.DataFrame({'col1': [1, 2, 3], 'col2': [4, 5, 6]}) grid_return = AgGrid(df, editable=True) new_df = grid_return['data'] Streamlit FoliumStreamlit Component for rendering Folium maps. Created by @randyzwitch.m = folium.Map(location=[39.949610, -75.150282], zoom_start=16) folium.Marker([39.949610, -75.150282], popup=""Liberty Bell"", tooltip=""Liberty Bell"").add_to(m) st_data = st_folium(m, width=725) Pandas ProfilingPandas profiling component for Streamlit. Created by @okld.df = pd.read_csv(""https://storage.googleapis.com/tf-datasets/titanic/train.csv"") pr = df.profile_report() st_profile_report(pr) Image CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates value = streamlit_image_coordinates(""https://placekitten.com/200/300"") st.write(value) Plotly EventsMake Plotly charts interactive!. Created by @null-jones.from streamlit_plotly_events import plotly_events fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.metric_cards import style_metric_cards col3.metric(label=""No Change"", value=5000, delta=0) style_metric_cards() Streamlit AggridImplementation of Ag-Grid component for Streamlit. Created by @PablocFonseca.df = pd.DataFrame({'col1': [1, 2, 3], 'col2': [4, 5, 6]}) grid_return = AgGrid(df, editable=True) new_df = grid_return['data'] Streamlit FoliumStreamlit Component for rendering Folium maps. Created by @randyzwitch.m = folium.Map(location=[39.949610, -75.150282], zoom_start=16) folium.Marker([39.949610, -75.150282], popup=""Liberty Bell"", tooltip=""Liberty Bell"").add_to(m) st_data = st_folium(m, width=725) Pandas ProfilingPandas profiling component for Streamlit. Created by @okld.df = pd.read_csv(""https://storage.googleapis.com/tf-datasets/titanic/train.csv"") pr = df.profile_report() st_profile_report(pr) Image CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates value = streamlit_image_coordinates(""https://placekitten.com/200/300"") st.write(value) Plotly EventsMake Plotly charts interactive!. Created by @null-jones.from streamlit_plotly_events import plotly_events fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.metric_cards import style_metric_cards col3.metric(label=""No Change"", value=5000, delta=0) style_metric_cards() Next Chart elements Simple area chartsDisplay an area chart.st.area_chart(my_data_frame) Simple bar chartsDisplay a bar chart.st.bar_chart(my_data_frame) Simple line chartsDisplay a line chart.st.line_chart(my_data_frame) Simple scatter chartsDisplay a line chart.st.scatter_chart(my_data_frame) Scatterplots on mapsDisplay a map with points on it.st.map(my_data_frame) MatplotlibDisplay a matplotlib.pyplot figure.st.pyplot(my_mpl_figure) AltairDisplay a chart using the Altair library.st.altair_chart(my_altair_chart) Vega-LiteDisplay a chart using the Vega-Lite library.st.vega_lite_chart(my_vega_lite_chart) PlotlyDisplay an interactive Plotly chart.st.plotly_chart(my_plotly_chart) BokehDisplay an interactive Bokeh chart.st.bokeh_chart(my_bokeh_chart) PyDeckDisplay a chart using the PyDeck library.st.pydeck_chart(my_pydeck_chart) GraphVizDisplay a graph using the dagre-d3 library.st.graphviz_chart(my_graphviz_spec) Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration! PreviousStreamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl(""https://assets5.lottiefiles.com/packages/lf20_V9t630.json"") st_lottie(lottie_hello, key=""hello"") Plotly EventsMake Plotly charts interactive!. Created by @null-jones.fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.chart += get_annotations_chart(annotations=[(""Mar 01, 2008"", ""Pretty good day for GOOG""), (""Dec 01, 2007"", ""Something's going wrong for GOOG & AAPL""), (""Nov 01, 2008"", ""Market starts again thanks to...""), (""Dec 01, 2009"", ""Small crash for GOOG after...""),],) st.altair_chart(chart, use_container_width=True) PlostA deceptively simple plotting library for Streamlit. Created by @tvst.import plost plost.line_chart(my_dataframe, x='time', y='stock_value', color='stock_name',) HiPlotHigh dimensional Interactive Plotting. Created by @facebookresearch.data = [{'dropout':0.1, 'lr': 0.001, 'loss': 10.0, 'optimizer': 'SGD'}, {'dropout':0.15, 'lr': 0.01, 'loss': 3.5, 'optimizer': 'Adam'}, {'dropout':0.3, 'lr': 0.1, 'loss': 4.5, 'optimizer': 'Adam'}] hip.Experiment.from_iterable(data).display() EChartsHigh dimensional Interactive Plotting. Created by @andfanilo.from streamlit_echarts import st_echarts st_echarts(options=options) Streamlit FoliumStreamlit Component for rendering Folium maps. Created by @randyzwitch.m = folium.Map(location=[39.949610, -75.150282], zoom_start=16) st_data = st_folium(m, width=725) Spacy-StreamlitspaCy building blocks and visualizers for Streamlit apps. Created by @explosion.models = [""en_core_web_sm"", ""en_core_web_md""] spacy_streamlit.visualize(models, ""Sundar Pichai is the CEO of Google."") Streamlit AgraphA Streamlit Graph Vis, based on react-grah-vis. Created by @ChrisDelClea.from streamlit_agraph import agraph, Node, Edge, Config agraph(nodes=nodes, edges=edges, config=config) Streamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl(""https://assets5.lottiefiles.com/packages/lf20_V9t630.json"") st_lottie(lottie_hello, key=""hello"") Plotly EventsMake Plotly charts interactive!. Created by @null-jones.fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.chart += get_annotations_chart(annotations=[(""Mar 01, 2008"", ""Pretty good day for GOOG""), (""Dec 01, 2007"", ""Something's going wrong for GOOG & AAPL""), (""Nov 01, 2008"", ""Market starts again thanks to...""), (""Dec 01, 2009"", ""Small crash for GOOG after...""),],) st.altair_chart(chart, use_container_width=True) PlostA deceptively simple plotting library for Streamlit. Created by @tvst.import plost plost.line_chart(my_dataframe, x='time', y='stock_value', color='stock_name',) HiPlotHigh dimensional Interactive Plotting. Created by @facebookresearch.data = [{'dropout':0.1, 'lr': 0.001, 'loss': 10.0, 'optimizer': 'SGD'}, {'dropout':0.15, 'lr': 0.01, 'loss': 3.5, 'optimizer': 'Adam'}, {'dropout':0.3, 'lr': 0.1, 'loss': 4.5, 'optimizer': 'Adam'}] hip.Experiment.from_iterable(data).display() EChartsHigh dimensional Interactive Plotting. Created by @andfanilo.from streamlit_echarts import st_echarts st_echarts(options=options) Streamlit FoliumStreamlit Component for rendering Folium maps. Created by @randyzwitch.m = folium.Map(location=[39.949610, -75.150282], zoom_start=16) st_data = st_folium(m, width=725) Spacy-StreamlitspaCy building blocks and visualizers for Streamlit apps. Created by @explosion.models = [""en_core_web_sm"", ""en_core_web_md""] spacy_streamlit.visualize(models, ""Sundar Pichai is the CEO of Google."") Streamlit AgraphA Streamlit Graph Vis, based on react-grah-vis. Created by @ChrisDelClea.from streamlit_agraph import agraph, Node, Edge, Config agraph(nodes=nodes, edges=edges, config=config) Streamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl(""https://assets5.lottiefiles.com/packages/lf20_V9t630.json"") st_lottie(lottie_hello, key=""hello"") Plotly EventsMake Plotly charts interactive!. Created by @null-jones.fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.chart += get_annotations_chart(annotations=[(""Mar 01, 2008"", ""Pretty good day for GOOG""), (""Dec 01, 2007"", ""Something's going wrong for GOOG & AAPL""), (""Nov 01, 2008"", ""Market starts again thanks to...""), (""Dec 01, 2009"", ""Small crash for GOOG after...""),],) st.altair_chart(chart, use_container_width=True) Next Input widgets ButtonDisplay a button widget.clicked = st.button(""Click me"") Download buttonDisplay a download button widget.st.download_button(""Download file"", file) Form buttonDisplay a form submit button. For use with st.form.st.form_submit_button(""Sign up"") Link buttonDisplay a link button.st.link_button(""Go to gallery"", url) Page linkDisplay a link to another page in a multipage app.st.page_link(""app.py"", label=""Home"", icon=""🏠"") st.page_link(""pages/profile.py"", label=""My profile"") CheckboxDisplay a checkbox widget.selected = st.checkbox(""I agree"") Color pickerDisplay a color picker widget.color = st.color_picker(""Pick a color"") MultiselectDisplay a multiselect widget. The multiselect widget starts as empty.choices = st.multiselect(""Buy"", [""milk"", ""apples"", ""potatoes""]) RadioDisplay a radio button widget.choice = st.radio(""Pick one"", [""cats"", ""dogs""]) SelectboxDisplay a select widget.choice = st.selectbox(""Pick one"", [""cats"", ""dogs""]) Select-sliderDisplay a slider widget to select items from a list.size = st.select_slider(""Pick a size"", [""S"", ""M"", ""L""]) ToggleDisplay a toggle widget.activated = st.toggle(""Activate"") Number inputDisplay a numeric input widget.choice = st.number_input(""Pick a number"", 0, 10) SliderDisplay a slider widget.number = st.slider(""Pick a number"", 0, 100) Date inputDisplay a date input widget.date = st.date_input(""Your birthday"") Time inputDisplay a time input widget.time = st.time_input(""Meeting time"") Chat inputDisplay a chat input widget.prompt = st.chat_input(""Say something"") if prompt: st.write(f""The user has sent: {prompt}"") Text-areaDisplay a multi-line text input widget.text = st.text_area(""Text to translate"") Text inputDisplay a single-line text input widget.name = st.text_input(""First name"") Data editorDisplay a data editor widget.edited = st.experimental_data_editor(df, num_rows=""dynamic"") File UploaderDisplay a file uploader widget.data = st.file_uploader(""Upload a CSV"") Camera inputDisplay a widget that allows users to upload images directly from a camera.image = st.camera_input(""Take a picture"") Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration! PreviousStreamlit ChatStreamlit Component for a Chatbot UI. Created by @AI-Yash.from streamlit_chat import message message(""My message"") message(""Hello bot!"", is_user=True) # align's the message to the right Streamlit Option MenuSelect a single item from a list of options in a menu. Created by @victoryhb.from streamlit_option_menu import option_menu option_menu(""Main Menu"", [""Home"", 'Settings'], icons=['house', 'gear'], menu_icon=""cast"", default_index=1) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.stoggle import stoggle stoggle( ""Click me!"", """"""🥷 Surprise! Here's some additional content"""""",) Streamlit ElementsCreate a draggable and resizable dashboard in Streamlit. Created by @okls.from streamlit_elements import elements, mui, html with elements(""new_element""): mui.Typography(""Hello world"") TagsAdd tags to your Streamlit apps. Created by @gagan3012.from streamlit_tags import st_tags st_tags(label='# Enter Keywords:', text='Press enter to add more', value=['Zero', 'One', 'Two'], suggestions=['five', 'six', 'seven', 'eight', 'nine', 'three', 'eleven', 'ten', 'four'], maxtags = 4, key='1') StqdmThe simplest way to handle a progress bar in streamlit app. Created by @Wirg.from stqdm import stqdm for _ in stqdm(range(50)): sleep(0.5) TimelineDisplay a Timeline in Streamlit apps using TimelineJS. Created by @innerdoc.from streamlit_timeline import timeline with open('example.json', ""r"") as f: timeline(f.read(), height=800) Camera input liveAlternative for st.camera_input which returns the webcam images live. Created by @blackary.from camera_input_live import camera_input_live image = camera_input_live() st.image(value) Streamlit AceAce editor component for Streamlit. Created by @okld.from streamlit_ace import st_ace content = st_ace() content Streamlit ChatStreamlit Component for a Chatbot UI. Created by @AI-Yash.from streamlit_chat import message message(""My message"") message(""Hello bot!"", is_user=True) # align's the message to the right Streamlit Option MenuSelect a single item from a list of options in a menu. Created by @victoryhb.from streamlit_option_menu import option_menu option_menu(""Main Menu"", [""Home"", 'Settings'], icons=['house', 'gear'], menu_icon=""cast"", default_index=1) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.stoggle import stoggle stoggle( ""Click me!"", """"""🥷 Surprise! Here's some additional content"""""",) Streamlit ElementsCreate a draggable and resizable dashboard in Streamlit. Created by @okls.from streamlit_elements import elements, mui, html with elements(""new_element""): mui.Typography(""Hello world"") TagsAdd tags to your Streamlit apps. Created by @gagan3012.from streamlit_tags import st_tags st_tags(label='# Enter Keywords:', text='Press enter to add more', value=['Zero', 'One', 'Two'], suggestions=['five', 'six', 'seven', 'eight', 'nine', 'three', 'eleven', 'ten', 'four'], maxtags = 4, key='1') StqdmThe simplest way to handle a progress bar in streamlit app. Created by @Wirg.from stqdm import stqdm for _ in stqdm(range(50)): sleep(0.5) TimelineDisplay a Timeline in Streamlit apps using TimelineJS. Created by @innerdoc.from streamlit_timeline import timeline with open('example.json', ""r"") as f: timeline(f.read(), height=800) Camera input liveAlternative for st.camera_input which returns the webcam images live. Created by @blackary.from camera_input_live import camera_input_live image = camera_input_live() st.image(value) Streamlit AceAce editor component for Streamlit. Created by @okld.from streamlit_ace import st_ace content = st_ace() content Streamlit ChatStreamlit Component for a Chatbot UI. Created by @AI-Yash.from streamlit_chat import message message(""My message"") message(""Hello bot!"", is_user=True) # align's the message to the right Streamlit Option MenuSelect a single item from a list of options in a menu. Created by @victoryhb.from streamlit_option_menu import option_menu option_menu(""Main Menu"", [""Home"", 'Settings'], icons=['house', 'gear'], menu_icon=""cast"", default_index=1) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.stoggle import stoggle stoggle( ""Click me!"", """"""🥷 Surprise! Here's some additional content"""""",) Next Media elements ImageDisplay an image or list of images.st.image(numpy_array) st.image(image_bytes) st.image(file) st.image(""https://example.com/myimage.jpg"") AudioDisplay an audio player.st.audio(numpy_array) st.audio(audio_bytes) st.audio(file) st.audio(""https://example.com/myaudio.mp3"", format=""audio/mp3"") VideoDisplay a video player.st.video(numpy_array) st.video(video_bytes) st.video(file) st.video(""https://example.com/myvideo.mp4"", format=""video/mp4"") Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration! PreviousStreamlit CropperA simple image cropper for Streamlit. Created by @turner-anderson.from streamlit_cropper import st_cropper st_cropper(img, realtime_update=realtime_update, box_color=box_color, aspect_ratio=aspect_ratio) Image CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates streamlit_image_coordinates(""https://placekitten.com/200/300"") Streamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl(""https://assets5.lottiefiles.com/packages/lf20_V9t630.json"") st_lottie(lottie_hello, key=""hello"") Streamlit WebrtcHandling and transmitting real-time video/audio streams with Streamlit. Created by @whitphx.from streamlit_webrtc import webrtc_streamer webrtc_streamer(key=""sample"") Drawable CanvasProvides a sketching canvas using Fabric.js. Created by @andfanilo.from streamlit_drawable_canvas import st_canvas st_canvas(fill_color=""rgba(255, 165, 0, 0.3)"", stroke_width=stroke_width, stroke_color=stroke_color, background_color=bg_color, background_image=Image.open(bg_image) if bg_image else None, update_streamlit=realtime_update, height=150, drawing_mode=drawing_mode, point_display_radius=point_display_radius if drawing_mode == 'point' else 0, key=""canvas"",) Image ComparisonCompare images with a slider using JuxtaposeJS. Created by @fcakyon.from streamlit_image_comparison import image_comparison image_comparison(img1=""image1.jpg"", img2=""image2.jpg"",) Streamlit CropperA simple image cropper for Streamlit. Created by @turner-anderson.from streamlit_cropper import st_cropper st_cropper(img, realtime_update=realtime_update, box_color=box_color, aspect_ratio=aspect_ratio) Image CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates streamlit_image_coordinates(""https://placekitten.com/200/300"") Streamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl(""https://assets5.lottiefiles.com/packages/lf20_V9t630.json"") st_lottie(lottie_hello, key=""hello"") Streamlit WebrtcHandling and transmitting real-time video/audio streams with Streamlit. Created by @whitphx.from streamlit_webrtc import webrtc_streamer webrtc_streamer(key=""sample"") Drawable CanvasProvides a sketching canvas using Fabric.js. Created by @andfanilo.from streamlit_drawable_canvas import st_canvas st_canvas(fill_color=""rgba(255, 165, 0, 0.3)"", stroke_width=stroke_width, stroke_color=stroke_color, background_color=bg_color, background_image=Image.open(bg_image) if bg_image else None, update_streamlit=realtime_update, height=150, drawing_mode=drawing_mode, point_display_radius=point_display_radius if drawing_mode == 'point' else 0, key=""canvas"",) Image ComparisonCompare images with a slider using JuxtaposeJS. Created by @fcakyon.from streamlit_image_comparison import image_comparison image_comparison(img1=""image1.jpg"", img2=""image2.jpg"",) Streamlit CropperA simple image cropper for Streamlit. Created by @turner-anderson.from streamlit_cropper import st_cropper st_cropper(img, realtime_update=realtime_update, box_color=box_color, aspect_ratio=aspect_ratio) Image CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates streamlit_image_coordinates(""https://placekitten.com/200/300"") Streamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl(""https://assets5.lottiefiles.com/packages/lf20_V9t630.json"") st_lottie(lottie_hello, key=""hello"") Next Layouts and containers ColumnsInsert containers laid out as side-by-side columns.col1, col2 = st.columns(2) col1.write(""this is column 1"") col2.write(""this is column 2"") ContainerInsert a multi-element container.c = st.container() st.write(""This will show last"") c.write(""This will show first"") c.write(""This will show second"") Modal dialogsInsert a modal dialog that can rerun independently from the rest of the script.@st.experimental_dialog(""Sign up"") def email_form(): name = st.text_input(""Name"") email = st.text_input(""Email"") EmptyInsert a single-element container.c = st.empty() st.write(""This will show last"") c.write(""This will be replaced"") c.write(""This will show first"") ExpanderInsert a multi-element container that can be expanded/collapsed.with st.expander(""Open to see more""): st.write(""This is more content"") PopoverInsert a multi-element popover container that can be opened/closed.with st.popover(""Settings""): st.checkbox(""Show completed"") SidebarDisplay items in a sidebar.st.sidebar.write(""This lives in the sidebar"") st.sidebar.button(""Click me!"") TabsInsert containers separated into tabs.tab1, tab2 = st.tabs([""Tab 1"", ""Tab2""]) tab1.write(""this is tab 1"") tab2.write(""this is tab 2"") Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration!Streamlit ElementsCreate a draggable and resizable dashboard in Streamlit. Created by @okls.from streamlit_elements import elements, mui, html with elements(""new_element""): mui.Typography(""Hello world"") PydanticAuto-generate Streamlit UI from Pydantic Models and Dataclasses. Created by @lukasmasuch.import streamlit_pydantic as sp sp.pydantic_form(key=""my_form"", model=ExampleModel) Streamlit PagesAn experimental version of Streamlit Multi-Page Apps. Created by @blackary.from st_pages import Page, show_pages, add_page_title show_pages([ Page(""streamlit_app.py"", ""Home"", ""🏠""), Page(""other_pages/page2.py"", ""Page 2"", "":books:""), ]) Chat elements Streamlit provides a few commands to help you build conversational apps. These chat elements are designed to be used in conjunction with each other, but you can also use them separately. st.chat_message lets you insert a chat message container into the app so you can display messages from the user or the app. Chat containers can contain other Streamlit elements, including charts, tables, text, and more. st.chat_input lets you display a chat input widget so the user can type in a message. Chat inputDisplay a chat input widget.prompt = st.chat_input(""Say something"") if prompt: st.write(f""The user has sent: {prompt}"") Chat messageInsert a chat message container.import numpy as np with st.chat_message(""user""): st.write(""Hello 👋"") st.line_chart(np.random.randn(30, 3)) Status containerDisplay output of long-running tasks in a container.with st.status('Running'): do_something_slow() st.write_streamWrite generators or streams to the app with a typewriter effect.st.write_stream(my_generator) st.write_stream(my_llm_stream) Status elements Progress barDisplay a progress bar.for i in range(101): st.progress(i) do_something_slow() SpinnerTemporarily displays a message while executing a block of code.with st.spinner(""Please wait...""): do_something_slow() Status containerDisplay output of long-running tasks in a container.with st.status('Running'): do_something_slow() ToastBriefly displays a toast message in the bottom-right corner.st.toast('Butter!', icon='🧈') BalloonsDisplay celebratory balloons!do_something() # Celebrate when all done! st.balloons() SnowflakesDisplay celebratory snowflakes!do_something() # Celebrate when all done! st.snow() Success boxDisplay a success message.st.success(""Match found!"") Info boxDisplay an informational message.st.info(""Dataset is updated every day at midnight."") Warning boxDisplay warning message.st.warning(""Unable to fetch image. Skipping..."") Error boxDisplay error message.st.error(""We encountered an error"") Exception outputDisplay an exception.e = RuntimeError(""This is an exception of type RuntimeError"") st.exception(e) Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration!StqdmThe simplest way to handle a progress bar in streamlit app. Created by @Wirg.from stqdm import stqdm for _ in stqdm(range(50)): sleep(0.5) Custom notification boxA custom notification box with the ability to close it out. Created by @Socvest.from streamlit_custom_notification_box import custom_notification_box styles = {'material-icons':{'color': 'red'}, 'text-icon-link-close-container': {'box-shadow': '#3896de 0px 4px'}, 'notification-text': {'':''}, 'close-button':{'':''}, 'link':{'':''}} custom_notification_box(icon='info', textDisplay='We are almost done with your registration...', externalLink='more info', url='#', styles=styles, key=""foo"") Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.let_it_rain import rain rain(emoji=""🎈"", font_size=54, falling_speed=5, animation_length=""infinite"",) App logic and configuration Navigation and pages Switch pageProgrammatically navigates to a specified page.st.switch_page(""pages/my_page.py"") Page linkDisplay a link to another page in a multipage app.st.page_link(""app.py"", label=""Home"", icon=""🏠"") st.page_link(""pages/profile.py"", label=""My profile"") Execution flow Modal dialogsInsert a modal dialog that can rerun independently from the rest of the script.@st.experimental_dialog(""Sign up"") def email_form(): name = st.text_input(""Name"") email = st.text_input(""Email"") FormsCreate a form that batches elements together with a “Submit"" button.with st.form(key='my_form'): name = st.text_input(""Name"") email = st.text_input(""Email"") st.form_submit_button(""Sign up"") Partial rerunsDefine a fragment to rerun independently from the rest of the script.@st.experimental_fragment(run_every=""10s"") def fragment(): df = get_data() st.line_chart(df) Rerun scriptRerun the script immediately.st.rerun() Stop executionStops execution immediately.st.stop() Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration!AutorefreshForce a refresh without tying up a script. Created by @kmcgrady.from streamlit_autorefresh import st_autorefresh st_autorefresh(interval=2000, limit=100, key=""fizzbuzzcounter"") PydanticAuto-generate Streamlit UI from Pydantic Models and Dataclasses. Created by @lukasmasuch.import streamlit_pydantic as sp sp.pydantic_form(key=""my_form"", model=ExampleModel) Streamlit PagesAn experimental version of Streamlit Multi-Page Apps. Created by @blackary.from st_pages import Page, show_pages, add_page_title show_pages([ Page(""streamlit_app.py"", ""Home"", ""🏠""), Page(""other_pages/page2.py"", ""Page 2"", "":books:""), ]) Caching and state Cache dataFunction decorator to cache functions that return data (e.g. dataframe transforms, database queries, ML inference).@st.cache_data def long_function(param1, param2): # Perform expensive computation here or # fetch data from the web here return data Cache resourceFunction decorator to cache functions that return global resources (e.g. database connections, ML models).@st.cache_resource def init_model(): # Return a global resource here return pipeline( ""sentiment-analysis"", model=""distilbert-base-uncased-finetuned-sst-2-english"" ) Session stateSession state is a way to share variables between reruns, for each user session.st.session_state['key'] = value Query parametersGet, set, or clear the query parameters that are shown in the browser's URL bar.st.query_params[key] = value st.query_params.clear() Connections and databases Setup your connection Create a connectionConnect to a data source or APIconn = st.connection('pets_db', type='sql') pet_owners = conn.query('select * from pet_owners') st.dataframe(pet_owners) Built-in connections SnowflakeConnectionA connection to Snowflake.conn = st.connection('snowflake') SQLConnectionA connection to a SQL database using SQLAlchemy.conn = st.connection('sql') Build your own connections Connection base classBuild your own connection with BaseConnection.class MyConnection(BaseConnection[myconn.MyConnection]): def _connect(self, **kwargs) -> MyConnection: return myconn.connect(**self._secrets, **kwargs) def query(self, query): return self._instance.query(query) Secrets management Secrets singletonAccess secrets from a local TOML file.key = st.secrets[""OpenAI_key""] Secrets fileSave your secrets in a per-project or per-profile TOML file.OpenAI_key = """" Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration!AuthenticatorA secure authentication module to validate user credentials. Created by @mkhorasani.import streamlit_authenticator as stauth authenticator = stauth.Authenticate( config['credentials'], config['cookie']['name'], config['cookie']['key'], config['cookie']['expiry_days'], config['preauthorized']) WS localStorageA simple synchronous way of accessing localStorage from your app. Created by @gagangoku.from streamlit_ws_localstorage import injectWebsocketCode ret = conn.setLocalStorageVal(key='k1', val='v1') st.write('ret: ' + ret) Streamlit Auth0The fastest way to provide comprehensive login inside Streamlit. Created by @conradbez.from auth0_component import login_button user_info = login_button(clientId, domain = domain) st.write(user_info) Custom Components Declare a componentCreate and register a custom component.st.components.v1.declare_component( ""custom_slider"", ""/frontend"", ) HTMLDisplay an HTML string in an iframe.st.components.v1.html( ""

Foo bar.

"" ) iframeLoad a remote URL in an iframe.st.components.v1.iframe( ""docs.streamlit.io"" ) Utilities and user info User infost.experimental_user returns information about the logged-in user of private apps on Streamlit Community Cloud.if st.experimental_user.email == ""foo@corp.com"": st.write(""Welcome back, "", st.experimental_user.email) else: st.write(""You are not authorized to view this page."") Get helpDisplay object’s doc string, nicely formatted.st.help(st.write) st.help(pd.DataFrame) Render HTMLRenders HTML strings to your app.css = """""" """""" st.html(css) Configuration Configuration fileConfigures the default settings for your app.your-project/ ├── .streamlit/ │ └── config.toml └── your_app.py Set page title, favicon, and moreConfigures the default settings of the page.st.set_page_config( page_title=""My app"", page_icon="":shark:"", ) Developer tools App testing st.testing.v1.AppTestst.testing.v1.AppTest simulates a running Streamlit app for testing.from streamlit.testing.v1 import AppTest at = AppTest.from_file(""streamlit_app.py"") at.secrets[""WORD""] = ""Foobar"" at.run() assert not at.exception at.text_input(""word"").input(""Bazbat"").run() assert at.warning[0].value == ""Try again."" AppTest.from_filest.testing.v1.AppTest.from_file initializes a simulated app from a file.from streamlit.testing.v1 import AppTest at = AppTest.from_file(""streamlit_app.py"") at.run() AppTest.from_stringst.testing.v1.AppTest.from_string initializes a simulated app from a string.from streamlit.testing.v1 import AppTest at = AppTest.from_string(app_script_as_string) at.run() AppTest.from_functionst.testing.v1.AppTest.from_function initializes a simulated app from a function.from streamlit.testing.v1 import AppTest at = AppTest.from_function(app_script_as_callable) at.run() BlockA representation of container elements, including: st.chat_message st.columns st.sidebar st.tabs The main body of the app. # at.sidebar returns a Block at.sidebar.button[0].click().run() assert not at.exception ElementThe base class for representation of all elements, including: st.title st.header st.markdown st.dataframe # at.title returns a sequence of Title # Title inherits from Element assert at.title[0].value == ""My awesome app"" ButtonA representation of st.button and st.form_submit_button.at.button[0].click().run() ChatInputA representation of st.chat_input.at.chat_input[0].set_value(""What is Streamlit?"").run() CheckboxA representation of st.checkbox.at.checkbox[0].check().run() ColorPickerA representation of st.color_picker.at.color_picker[0].pick(""#FF4B4B"").run() DateInputA representation of st.date_input.release_date = datetime.date(2023, 10, 26) at.date_input[0].set_value(release_date).run() MultiselectA representation of st.multiselect.at.multiselect[0].select(""New York"").run() NumberInputA representation of st.number_input.at.number_input[0].increment().run() RadioA representation of st.radio.at.radio[0].set_value(""New York"").run() SelectSliderA representation of st.select_slider.at.select_slider[0].set_range(""A"",""C"").run() SelectboxA representation of st.selectbox.at.selectbox[0].select(""New York"").run() SliderA representation of st.slider.at.slider[0].set_range(2,5).run() TextAreaA representation of st.text_area.at.text_area[0].input(""Streamlit is awesome!"").run() TextInputA representation of st.text_input.at.text_input[0].input(""Streamlit"").run() TimeInputA representation of st.time_input.at.time_input[0].increment().run() ToggleA representation of st.toggle.at.toggle[0].set_value(""True"").run() Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration!Pandas ProfilingPandas profiling component for Streamlit. Created by @okld.df = pd.read_csv(""https://storage.googleapis.com/tf-datasets/titanic/train.csv"") pr = df.profile_report() st_profile_report(pr) Streamlit AceAce editor component for Streamlit. Created by @okld.from streamlit_ace import st_ace content = st_ace() content Streamlit AnalyticsTrack & visualize user interactions with your streamlit app. Created by @jrieke.import streamlit_analytics with streamlit_analytics.track(): st.text_input(""Write something"") Previous: ConceptsNext: Write and magicforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy" https://docs.streamlit.io/get-started/installation/anaconda-distribution#whats-next,"DocumentationsearchSearchrocket_launchGet startedInstallationremoveUse command lineUse Anaconda DistributionUse GitHub CodespacesUse SnowflakeFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Get started/Installation/Use Anaconda DistributionInstall Streamlit using Anaconda Distribution This page walks you through installing Streamlit locally using Anaconda Distribution. At the end, you'll build a simple ""Hello world"" app and run it. You can read more about Getting started with Anaconda Distribution in Anaconda's docs. If you prefer to manage your Python environments via command line, check out how to Install Streamlit using command line. Prerequisites A code editor Anaconda Distribution includes Python and basically everything you need to get started. The only thing left for you to choose is a code editor. Our favorite editor is VS Code, which is also what we use in all our tutorials. Knowledge about environment managers Environment managers create virtual environments to isolate Python package installations between projects. For a detailed introduction to Python environments, check out Python Virtual Environments: A Primer. But don't worry! In this guide we'll teach you how to install and use an environment manager (Anaconda). Install Anaconda Distribution Go to anaconda.com/download. Install Anaconda Distribution for your OS. Create an environment using Anaconda Navigator Open Anaconda Navigator (the graphical interface included with Anaconda Distribution). You can decline signing in to Anaconda if prompted. In the left menu, click ""Environments"". At the bottom of your environments list, click ""Create"". Enter ""streamlitenv"" for the name of your environment. Click ""Create."" Activate your environment Click the green play icon (play_circle) next to your environment. Click ""Open Terminal."" A terminal will open with your environment activated. Your environment's name will appear in parentheses at the beginning of your terminal's prompt to show that it's activated. Install Streamlit in your environment In your terminal, type: pip install streamlit To validate your installation, enter: streamlit hello If this doesn't work, use the long-form command: python -m streamlit hello The Streamlit Hello example app will automatically open in your browser. If it doesn't, open your browser and go to the localhost address indicated in your terminal, typically http://localhost:8501. Play around with the app! Close your terminal. Create a Hello World app and run it Open VS Code with a new project. Create a Python file named app.py in your project folder. Copy the following code into app.py and save it. import streamlit as st st.write(""Hello World"") Click your Python interpreter in the lower-right corner, then choose your streamlitenv environment from the drop-down. Right-click app.py in your file navigation and click ""Open in integrated terminal"". A terminal will open with your environment activated. Confirm this by looking for ""(streamlitenv)"" at the beginning of your next prompt. If it is not there, manually activate your environment with the command: conda activate streamlitenv In your terminal, type: streamlit run app.py If this doesn't work, use the long-form command: python -m streamlit run app.py Your app will automatically open in your browser. If it doesn't for any reason, open your browser and go to the localhost address indicated in your terminal, typically http://localhost:8501. Change st.write to st.title and save your file: import streamlit as st st.title(""Hello World"") In your browser, click ""Always rerun"" to instantly rerun your app whenever you save a change to your file. Your app will update! Keep making changes and you will see your changes as soon as you save your file. When you're done, you can stop your app with Ctrl+C in your terminal or just by closing your terminal. What's next? Read about our Basic concepts and try out more commands in your app.Previous: Use command lineNext: Use GitHub CodespacesforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy" https://docs.streamlit.io/en/0.75.0/api.html#chat-elements,"DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceremovePAGE ELEMENTSWrite and magicaddText elementsaddData elementsaddChart elementsaddInput widgetsaddMedia elementsaddLayouts and containersaddChat elementsaddStatus elementsaddThird-party componentsopen_in_newAPPLICATION LOGICNavigation and pagesaddExecution flowaddCaching and stateaddConnections and secretsaddCustom componentsaddUtilitiesaddConfigurationaddTOOLSApp testingaddCommand lineaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Develop/API referenceAPI reference Streamlit makes it easy for you to visualize, mutate, and share data. The API reference is organized by activity type, like displaying data or optimizing performance. Each section includes methods associated with the activity type, including examples. Browse our API below and click to learn more about any of our available commands! 🎈 Display almost anything Write and magic st.writeWrite arguments to the app.st.write(""Hello **world**!"") st.write(my_data_frame) st.write(my_mpl_figure) st.write_streamWrite generators or streams to the app with a typewriter effect.st.write_stream(my_generator) st.write_stream(my_llm_stream) MagicAny time Streamlit sees either a variable or literal value on its own line, it automatically writes that to your app using st.write""Hello **world**!"" my_data_frame my_mpl_figure Text elements MarkdownDisplay string formatted as Markdown.st.markdown(""Hello **world**!"") TitleDisplay text in title formatting.st.title(""The app title"") HeaderDisplay text in header formatting.st.header(""This is a header"") SubheaderDisplay text in subheader formatting.st.subheader(""This is a subheader"") CaptionDisplay text in small font.st.caption(""This is written small caption text"") Code blockDisplay a code block with optional syntax highlighting.st.code(""a = 1234"") EchoDisplay some code in the app, then execute it. Useful for tutorials.with st.echo(): st.write('This code will be printed') LaTeXDisplay mathematical expressions formatted as LaTeX.st.latex(""\int a x^2 \,dx"") Preformatted textWrite fixed-width and preformatted text.st.text(""Hello world"") DividerDisplay a horizontal rule.st.divider() Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration! PreviousTagsAdd tags to your Streamlit apps. Created by @gagan3012.st_tags(label='# Enter Keywords:', text='Press enter to add more', value=['Zero', 'One', 'Two'], suggestions=['five', 'six', 'seven', 'eight', 'nine', 'three', 'eleven', 'ten', 'four'], maxtags = 4, key='1') NLUApply text mining on a dataframe. Created by @JohnSnowLabs.nlu.load('sentiment').predict('I love NLU! <3') Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.mention(label=""An awesome Streamlit App"", icon=""streamlit"", url=""https://extras.streamlit.app"",) Annotated textDisplay annotated text in Streamlit apps. Created by @tvst.annotated_text(""This "", (""is"", ""verb""), "" some "", (""annotated"", ""adj""), (""text"", ""noun""), "" for those of "", (""you"", ""pronoun""), "" who "", (""like"", ""verb""), "" this sort of "", (""thing"", ""noun""), ""."") Drawable CanvasProvides a sketching canvas using Fabric.js. Created by @andfanilo.st_canvas(fill_color=""rgba(255, 165, 0, 0.3)"", stroke_width=stroke_width, stroke_color=stroke_color, background_color=bg_color, background_image=Image.open(bg_image) if bg_image else None, update_streamlit=realtime_update, height=150, drawing_mode=drawing_mode, point_display_radius=point_display_radius if drawing_mode == 'point' else 0, key=""canvas"",) TagsAdd tags to your Streamlit apps. Created by @gagan3012.st_tags(label='# Enter Keywords:', text='Press enter to add more', value=['Zero', 'One', 'Two'], suggestions=['five', 'six', 'seven', 'eight', 'nine', 'three', 'eleven', 'ten', 'four'], maxtags = 4, key='1') NLUApply text mining on a dataframe. Created by @JohnSnowLabs.nlu.load('sentiment').predict('I love NLU! <3') Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.mention(label=""An awesome Streamlit App"", icon=""streamlit"", url=""https://extras.streamlit.app"",) Annotated textDisplay annotated text in Streamlit apps. Created by @tvst.annotated_text(""This "", (""is"", ""verb""), "" some "", (""annotated"", ""adj""), (""text"", ""noun""), "" for those of "", (""you"", ""pronoun""), "" who "", (""like"", ""verb""), "" this sort of "", (""thing"", ""noun""), ""."") Drawable CanvasProvides a sketching canvas using Fabric.js. Created by @andfanilo.st_canvas(fill_color=""rgba(255, 165, 0, 0.3)"", stroke_width=stroke_width, stroke_color=stroke_color, background_color=bg_color, background_image=Image.open(bg_image) if bg_image else None, update_streamlit=realtime_update, height=150, drawing_mode=drawing_mode, point_display_radius=point_display_radius if drawing_mode == 'point' else 0, key=""canvas"",) TagsAdd tags to your Streamlit apps. Created by @gagan3012.st_tags(label='# Enter Keywords:', text='Press enter to add more', value=['Zero', 'One', 'Two'], suggestions=['five', 'six', 'seven', 'eight', 'nine', 'three', 'eleven', 'ten', 'four'], maxtags = 4, key='1') NLUApply text mining on a dataframe. Created by @JohnSnowLabs.nlu.load('sentiment').predict('I love NLU! <3') Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.mention(label=""An awesome Streamlit App"", icon=""streamlit"", url=""https://extras.streamlit.app"",) Next Data elements DataframesDisplay a dataframe as an interactive table.st.dataframe(my_data_frame) Data editorDisplay a data editor widget.edited = st.data_editor(df, num_rows=""dynamic"") Column configurationConfigure the display and editing behavior of dataframes and data editors.st.column_config.NumberColumn(""Price (in USD)"", min_value=0, format=""$%d"") Static tablesDisplay a static table.st.table(my_data_frame) MetricsDisplay a metric in big bold font, with an optional indicator of how the metric changed.st.metric(""My metric"", 42, 2) Dicts and JSONDisplay object or string as a pretty-printed JSON string.st.json(my_dict) Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration! PreviousImage CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates value = streamlit_image_coordinates(""https://placekitten.com/200/300"") st.write(value) Plotly EventsMake Plotly charts interactive!. Created by @null-jones.from streamlit_plotly_events import plotly_events fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.metric_cards import style_metric_cards col3.metric(label=""No Change"", value=5000, delta=0) style_metric_cards() Streamlit AggridImplementation of Ag-Grid component for Streamlit. Created by @PablocFonseca.df = pd.DataFrame({'col1': [1, 2, 3], 'col2': [4, 5, 6]}) grid_return = AgGrid(df, editable=True) new_df = grid_return['data'] Streamlit FoliumStreamlit Component for rendering Folium maps. Created by @randyzwitch.m = folium.Map(location=[39.949610, -75.150282], zoom_start=16) folium.Marker([39.949610, -75.150282], popup=""Liberty Bell"", tooltip=""Liberty Bell"").add_to(m) st_data = st_folium(m, width=725) Pandas ProfilingPandas profiling component for Streamlit. Created by @okld.df = pd.read_csv(""https://storage.googleapis.com/tf-datasets/titanic/train.csv"") pr = df.profile_report() st_profile_report(pr) Image CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates value = streamlit_image_coordinates(""https://placekitten.com/200/300"") st.write(value) Plotly EventsMake Plotly charts interactive!. Created by @null-jones.from streamlit_plotly_events import plotly_events fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.metric_cards import style_metric_cards col3.metric(label=""No Change"", value=5000, delta=0) style_metric_cards() Streamlit AggridImplementation of Ag-Grid component for Streamlit. Created by @PablocFonseca.df = pd.DataFrame({'col1': [1, 2, 3], 'col2': [4, 5, 6]}) grid_return = AgGrid(df, editable=True) new_df = grid_return['data'] Streamlit FoliumStreamlit Component for rendering Folium maps. Created by @randyzwitch.m = folium.Map(location=[39.949610, -75.150282], zoom_start=16) folium.Marker([39.949610, -75.150282], popup=""Liberty Bell"", tooltip=""Liberty Bell"").add_to(m) st_data = st_folium(m, width=725) Pandas ProfilingPandas profiling component for Streamlit. Created by @okld.df = pd.read_csv(""https://storage.googleapis.com/tf-datasets/titanic/train.csv"") pr = df.profile_report() st_profile_report(pr) Image CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates value = streamlit_image_coordinates(""https://placekitten.com/200/300"") st.write(value) Plotly EventsMake Plotly charts interactive!. Created by @null-jones.from streamlit_plotly_events import plotly_events fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.metric_cards import style_metric_cards col3.metric(label=""No Change"", value=5000, delta=0) style_metric_cards() Next Chart elements Simple area chartsDisplay an area chart.st.area_chart(my_data_frame) Simple bar chartsDisplay a bar chart.st.bar_chart(my_data_frame) Simple line chartsDisplay a line chart.st.line_chart(my_data_frame) Simple scatter chartsDisplay a line chart.st.scatter_chart(my_data_frame) Scatterplots on mapsDisplay a map with points on it.st.map(my_data_frame) MatplotlibDisplay a matplotlib.pyplot figure.st.pyplot(my_mpl_figure) AltairDisplay a chart using the Altair library.st.altair_chart(my_altair_chart) Vega-LiteDisplay a chart using the Vega-Lite library.st.vega_lite_chart(my_vega_lite_chart) PlotlyDisplay an interactive Plotly chart.st.plotly_chart(my_plotly_chart) BokehDisplay an interactive Bokeh chart.st.bokeh_chart(my_bokeh_chart) PyDeckDisplay a chart using the PyDeck library.st.pydeck_chart(my_pydeck_chart) GraphVizDisplay a graph using the dagre-d3 library.st.graphviz_chart(my_graphviz_spec) Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration! PreviousStreamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl(""https://assets5.lottiefiles.com/packages/lf20_V9t630.json"") st_lottie(lottie_hello, key=""hello"") Plotly EventsMake Plotly charts interactive!. Created by @null-jones.fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.chart += get_annotations_chart(annotations=[(""Mar 01, 2008"", ""Pretty good day for GOOG""), (""Dec 01, 2007"", ""Something's going wrong for GOOG & AAPL""), (""Nov 01, 2008"", ""Market starts again thanks to...""), (""Dec 01, 2009"", ""Small crash for GOOG after...""),],) st.altair_chart(chart, use_container_width=True) PlostA deceptively simple plotting library for Streamlit. Created by @tvst.import plost plost.line_chart(my_dataframe, x='time', y='stock_value', color='stock_name',) HiPlotHigh dimensional Interactive Plotting. Created by @facebookresearch.data = [{'dropout':0.1, 'lr': 0.001, 'loss': 10.0, 'optimizer': 'SGD'}, {'dropout':0.15, 'lr': 0.01, 'loss': 3.5, 'optimizer': 'Adam'}, {'dropout':0.3, 'lr': 0.1, 'loss': 4.5, 'optimizer': 'Adam'}] hip.Experiment.from_iterable(data).display() EChartsHigh dimensional Interactive Plotting. Created by @andfanilo.from streamlit_echarts import st_echarts st_echarts(options=options) Streamlit FoliumStreamlit Component for rendering Folium maps. Created by @randyzwitch.m = folium.Map(location=[39.949610, -75.150282], zoom_start=16) st_data = st_folium(m, width=725) Spacy-StreamlitspaCy building blocks and visualizers for Streamlit apps. Created by @explosion.models = [""en_core_web_sm"", ""en_core_web_md""] spacy_streamlit.visualize(models, ""Sundar Pichai is the CEO of Google."") Streamlit AgraphA Streamlit Graph Vis, based on react-grah-vis. Created by @ChrisDelClea.from streamlit_agraph import agraph, Node, Edge, Config agraph(nodes=nodes, edges=edges, config=config) Streamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl(""https://assets5.lottiefiles.com/packages/lf20_V9t630.json"") st_lottie(lottie_hello, key=""hello"") Plotly EventsMake Plotly charts interactive!. Created by @null-jones.fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.chart += get_annotations_chart(annotations=[(""Mar 01, 2008"", ""Pretty good day for GOOG""), (""Dec 01, 2007"", ""Something's going wrong for GOOG & AAPL""), (""Nov 01, 2008"", ""Market starts again thanks to...""), (""Dec 01, 2009"", ""Small crash for GOOG after...""),],) st.altair_chart(chart, use_container_width=True) PlostA deceptively simple plotting library for Streamlit. Created by @tvst.import plost plost.line_chart(my_dataframe, x='time', y='stock_value', color='stock_name',) HiPlotHigh dimensional Interactive Plotting. Created by @facebookresearch.data = [{'dropout':0.1, 'lr': 0.001, 'loss': 10.0, 'optimizer': 'SGD'}, {'dropout':0.15, 'lr': 0.01, 'loss': 3.5, 'optimizer': 'Adam'}, {'dropout':0.3, 'lr': 0.1, 'loss': 4.5, 'optimizer': 'Adam'}] hip.Experiment.from_iterable(data).display() EChartsHigh dimensional Interactive Plotting. Created by @andfanilo.from streamlit_echarts import st_echarts st_echarts(options=options) Streamlit FoliumStreamlit Component for rendering Folium maps. Created by @randyzwitch.m = folium.Map(location=[39.949610, -75.150282], zoom_start=16) st_data = st_folium(m, width=725) Spacy-StreamlitspaCy building blocks and visualizers for Streamlit apps. Created by @explosion.models = [""en_core_web_sm"", ""en_core_web_md""] spacy_streamlit.visualize(models, ""Sundar Pichai is the CEO of Google."") Streamlit AgraphA Streamlit Graph Vis, based on react-grah-vis. Created by @ChrisDelClea.from streamlit_agraph import agraph, Node, Edge, Config agraph(nodes=nodes, edges=edges, config=config) Streamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl(""https://assets5.lottiefiles.com/packages/lf20_V9t630.json"") st_lottie(lottie_hello, key=""hello"") Plotly EventsMake Plotly charts interactive!. Created by @null-jones.fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.chart += get_annotations_chart(annotations=[(""Mar 01, 2008"", ""Pretty good day for GOOG""), (""Dec 01, 2007"", ""Something's going wrong for GOOG & AAPL""), (""Nov 01, 2008"", ""Market starts again thanks to...""), (""Dec 01, 2009"", ""Small crash for GOOG after...""),],) st.altair_chart(chart, use_container_width=True) Next Input widgets ButtonDisplay a button widget.clicked = st.button(""Click me"") Download buttonDisplay a download button widget.st.download_button(""Download file"", file) Form buttonDisplay a form submit button. For use with st.form.st.form_submit_button(""Sign up"") Link buttonDisplay a link button.st.link_button(""Go to gallery"", url) Page linkDisplay a link to another page in a multipage app.st.page_link(""app.py"", label=""Home"", icon=""🏠"") st.page_link(""pages/profile.py"", label=""My profile"") CheckboxDisplay a checkbox widget.selected = st.checkbox(""I agree"") Color pickerDisplay a color picker widget.color = st.color_picker(""Pick a color"") MultiselectDisplay a multiselect widget. The multiselect widget starts as empty.choices = st.multiselect(""Buy"", [""milk"", ""apples"", ""potatoes""]) RadioDisplay a radio button widget.choice = st.radio(""Pick one"", [""cats"", ""dogs""]) SelectboxDisplay a select widget.choice = st.selectbox(""Pick one"", [""cats"", ""dogs""]) Select-sliderDisplay a slider widget to select items from a list.size = st.select_slider(""Pick a size"", [""S"", ""M"", ""L""]) ToggleDisplay a toggle widget.activated = st.toggle(""Activate"") Number inputDisplay a numeric input widget.choice = st.number_input(""Pick a number"", 0, 10) SliderDisplay a slider widget.number = st.slider(""Pick a number"", 0, 100) Date inputDisplay a date input widget.date = st.date_input(""Your birthday"") Time inputDisplay a time input widget.time = st.time_input(""Meeting time"") Chat inputDisplay a chat input widget.prompt = st.chat_input(""Say something"") if prompt: st.write(f""The user has sent: {prompt}"") Text-areaDisplay a multi-line text input widget.text = st.text_area(""Text to translate"") Text inputDisplay a single-line text input widget.name = st.text_input(""First name"") Data editorDisplay a data editor widget.edited = st.experimental_data_editor(df, num_rows=""dynamic"") File UploaderDisplay a file uploader widget.data = st.file_uploader(""Upload a CSV"") Camera inputDisplay a widget that allows users to upload images directly from a camera.image = st.camera_input(""Take a picture"") Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration! PreviousStreamlit ChatStreamlit Component for a Chatbot UI. Created by @AI-Yash.from streamlit_chat import message message(""My message"") message(""Hello bot!"", is_user=True) # align's the message to the right Streamlit Option MenuSelect a single item from a list of options in a menu. Created by @victoryhb.from streamlit_option_menu import option_menu option_menu(""Main Menu"", [""Home"", 'Settings'], icons=['house', 'gear'], menu_icon=""cast"", default_index=1) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.stoggle import stoggle stoggle( ""Click me!"", """"""🥷 Surprise! Here's some additional content"""""",) Streamlit ElementsCreate a draggable and resizable dashboard in Streamlit. Created by @okls.from streamlit_elements import elements, mui, html with elements(""new_element""): mui.Typography(""Hello world"") TagsAdd tags to your Streamlit apps. Created by @gagan3012.from streamlit_tags import st_tags st_tags(label='# Enter Keywords:', text='Press enter to add more', value=['Zero', 'One', 'Two'], suggestions=['five', 'six', 'seven', 'eight', 'nine', 'three', 'eleven', 'ten', 'four'], maxtags = 4, key='1') StqdmThe simplest way to handle a progress bar in streamlit app. Created by @Wirg.from stqdm import stqdm for _ in stqdm(range(50)): sleep(0.5) TimelineDisplay a Timeline in Streamlit apps using TimelineJS. Created by @innerdoc.from streamlit_timeline import timeline with open('example.json', ""r"") as f: timeline(f.read(), height=800) Camera input liveAlternative for st.camera_input which returns the webcam images live. Created by @blackary.from camera_input_live import camera_input_live image = camera_input_live() st.image(value) Streamlit AceAce editor component for Streamlit. Created by @okld.from streamlit_ace import st_ace content = st_ace() content Streamlit ChatStreamlit Component for a Chatbot UI. Created by @AI-Yash.from streamlit_chat import message message(""My message"") message(""Hello bot!"", is_user=True) # align's the message to the right Streamlit Option MenuSelect a single item from a list of options in a menu. Created by @victoryhb.from streamlit_option_menu import option_menu option_menu(""Main Menu"", [""Home"", 'Settings'], icons=['house', 'gear'], menu_icon=""cast"", default_index=1) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.stoggle import stoggle stoggle( ""Click me!"", """"""🥷 Surprise! Here's some additional content"""""",) Streamlit ElementsCreate a draggable and resizable dashboard in Streamlit. Created by @okls.from streamlit_elements import elements, mui, html with elements(""new_element""): mui.Typography(""Hello world"") TagsAdd tags to your Streamlit apps. Created by @gagan3012.from streamlit_tags import st_tags st_tags(label='# Enter Keywords:', text='Press enter to add more', value=['Zero', 'One', 'Two'], suggestions=['five', 'six', 'seven', 'eight', 'nine', 'three', 'eleven', 'ten', 'four'], maxtags = 4, key='1') StqdmThe simplest way to handle a progress bar in streamlit app. Created by @Wirg.from stqdm import stqdm for _ in stqdm(range(50)): sleep(0.5) TimelineDisplay a Timeline in Streamlit apps using TimelineJS. Created by @innerdoc.from streamlit_timeline import timeline with open('example.json', ""r"") as f: timeline(f.read(), height=800) Camera input liveAlternative for st.camera_input which returns the webcam images live. Created by @blackary.from camera_input_live import camera_input_live image = camera_input_live() st.image(value) Streamlit AceAce editor component for Streamlit. Created by @okld.from streamlit_ace import st_ace content = st_ace() content Streamlit ChatStreamlit Component for a Chatbot UI. Created by @AI-Yash.from streamlit_chat import message message(""My message"") message(""Hello bot!"", is_user=True) # align's the message to the right Streamlit Option MenuSelect a single item from a list of options in a menu. Created by @victoryhb.from streamlit_option_menu import option_menu option_menu(""Main Menu"", [""Home"", 'Settings'], icons=['house', 'gear'], menu_icon=""cast"", default_index=1) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.stoggle import stoggle stoggle( ""Click me!"", """"""🥷 Surprise! Here's some additional content"""""",) Next Media elements ImageDisplay an image or list of images.st.image(numpy_array) st.image(image_bytes) st.image(file) st.image(""https://example.com/myimage.jpg"") AudioDisplay an audio player.st.audio(numpy_array) st.audio(audio_bytes) st.audio(file) st.audio(""https://example.com/myaudio.mp3"", format=""audio/mp3"") VideoDisplay a video player.st.video(numpy_array) st.video(video_bytes) st.video(file) st.video(""https://example.com/myvideo.mp4"", format=""video/mp4"") Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration! PreviousStreamlit CropperA simple image cropper for Streamlit. Created by @turner-anderson.from streamlit_cropper import st_cropper st_cropper(img, realtime_update=realtime_update, box_color=box_color, aspect_ratio=aspect_ratio) Image CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates streamlit_image_coordinates(""https://placekitten.com/200/300"") Streamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl(""https://assets5.lottiefiles.com/packages/lf20_V9t630.json"") st_lottie(lottie_hello, key=""hello"") Streamlit WebrtcHandling and transmitting real-time video/audio streams with Streamlit. Created by @whitphx.from streamlit_webrtc import webrtc_streamer webrtc_streamer(key=""sample"") Drawable CanvasProvides a sketching canvas using Fabric.js. Created by @andfanilo.from streamlit_drawable_canvas import st_canvas st_canvas(fill_color=""rgba(255, 165, 0, 0.3)"", stroke_width=stroke_width, stroke_color=stroke_color, background_color=bg_color, background_image=Image.open(bg_image) if bg_image else None, update_streamlit=realtime_update, height=150, drawing_mode=drawing_mode, point_display_radius=point_display_radius if drawing_mode == 'point' else 0, key=""canvas"",) Image ComparisonCompare images with a slider using JuxtaposeJS. Created by @fcakyon.from streamlit_image_comparison import image_comparison image_comparison(img1=""image1.jpg"", img2=""image2.jpg"",) Streamlit CropperA simple image cropper for Streamlit. Created by @turner-anderson.from streamlit_cropper import st_cropper st_cropper(img, realtime_update=realtime_update, box_color=box_color, aspect_ratio=aspect_ratio) Image CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates streamlit_image_coordinates(""https://placekitten.com/200/300"") Streamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl(""https://assets5.lottiefiles.com/packages/lf20_V9t630.json"") st_lottie(lottie_hello, key=""hello"") Streamlit WebrtcHandling and transmitting real-time video/audio streams with Streamlit. Created by @whitphx.from streamlit_webrtc import webrtc_streamer webrtc_streamer(key=""sample"") Drawable CanvasProvides a sketching canvas using Fabric.js. Created by @andfanilo.from streamlit_drawable_canvas import st_canvas st_canvas(fill_color=""rgba(255, 165, 0, 0.3)"", stroke_width=stroke_width, stroke_color=stroke_color, background_color=bg_color, background_image=Image.open(bg_image) if bg_image else None, update_streamlit=realtime_update, height=150, drawing_mode=drawing_mode, point_display_radius=point_display_radius if drawing_mode == 'point' else 0, key=""canvas"",) Image ComparisonCompare images with a slider using JuxtaposeJS. Created by @fcakyon.from streamlit_image_comparison import image_comparison image_comparison(img1=""image1.jpg"", img2=""image2.jpg"",) Streamlit CropperA simple image cropper for Streamlit. Created by @turner-anderson.from streamlit_cropper import st_cropper st_cropper(img, realtime_update=realtime_update, box_color=box_color, aspect_ratio=aspect_ratio) Image CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates streamlit_image_coordinates(""https://placekitten.com/200/300"") Streamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl(""https://assets5.lottiefiles.com/packages/lf20_V9t630.json"") st_lottie(lottie_hello, key=""hello"") Next Layouts and containers ColumnsInsert containers laid out as side-by-side columns.col1, col2 = st.columns(2) col1.write(""this is column 1"") col2.write(""this is column 2"") ContainerInsert a multi-element container.c = st.container() st.write(""This will show last"") c.write(""This will show first"") c.write(""This will show second"") Modal dialogsInsert a modal dialog that can rerun independently from the rest of the script.@st.experimental_dialog(""Sign up"") def email_form(): name = st.text_input(""Name"") email = st.text_input(""Email"") EmptyInsert a single-element container.c = st.empty() st.write(""This will show last"") c.write(""This will be replaced"") c.write(""This will show first"") ExpanderInsert a multi-element container that can be expanded/collapsed.with st.expander(""Open to see more""): st.write(""This is more content"") PopoverInsert a multi-element popover container that can be opened/closed.with st.popover(""Settings""): st.checkbox(""Show completed"") SidebarDisplay items in a sidebar.st.sidebar.write(""This lives in the sidebar"") st.sidebar.button(""Click me!"") TabsInsert containers separated into tabs.tab1, tab2 = st.tabs([""Tab 1"", ""Tab2""]) tab1.write(""this is tab 1"") tab2.write(""this is tab 2"") Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration!Streamlit ElementsCreate a draggable and resizable dashboard in Streamlit. Created by @okls.from streamlit_elements import elements, mui, html with elements(""new_element""): mui.Typography(""Hello world"") PydanticAuto-generate Streamlit UI from Pydantic Models and Dataclasses. Created by @lukasmasuch.import streamlit_pydantic as sp sp.pydantic_form(key=""my_form"", model=ExampleModel) Streamlit PagesAn experimental version of Streamlit Multi-Page Apps. Created by @blackary.from st_pages import Page, show_pages, add_page_title show_pages([ Page(""streamlit_app.py"", ""Home"", ""🏠""), Page(""other_pages/page2.py"", ""Page 2"", "":books:""), ]) Chat elements Streamlit provides a few commands to help you build conversational apps. These chat elements are designed to be used in conjunction with each other, but you can also use them separately. st.chat_message lets you insert a chat message container into the app so you can display messages from the user or the app. Chat containers can contain other Streamlit elements, including charts, tables, text, and more. st.chat_input lets you display a chat input widget so the user can type in a message. Chat inputDisplay a chat input widget.prompt = st.chat_input(""Say something"") if prompt: st.write(f""The user has sent: {prompt}"") Chat messageInsert a chat message container.import numpy as np with st.chat_message(""user""): st.write(""Hello 👋"") st.line_chart(np.random.randn(30, 3)) Status containerDisplay output of long-running tasks in a container.with st.status('Running'): do_something_slow() st.write_streamWrite generators or streams to the app with a typewriter effect.st.write_stream(my_generator) st.write_stream(my_llm_stream) Status elements Progress barDisplay a progress bar.for i in range(101): st.progress(i) do_something_slow() SpinnerTemporarily displays a message while executing a block of code.with st.spinner(""Please wait...""): do_something_slow() Status containerDisplay output of long-running tasks in a container.with st.status('Running'): do_something_slow() ToastBriefly displays a toast message in the bottom-right corner.st.toast('Butter!', icon='🧈') BalloonsDisplay celebratory balloons!do_something() # Celebrate when all done! st.balloons() SnowflakesDisplay celebratory snowflakes!do_something() # Celebrate when all done! st.snow() Success boxDisplay a success message.st.success(""Match found!"") Info boxDisplay an informational message.st.info(""Dataset is updated every day at midnight."") Warning boxDisplay warning message.st.warning(""Unable to fetch image. Skipping..."") Error boxDisplay error message.st.error(""We encountered an error"") Exception outputDisplay an exception.e = RuntimeError(""This is an exception of type RuntimeError"") st.exception(e) Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration!StqdmThe simplest way to handle a progress bar in streamlit app. Created by @Wirg.from stqdm import stqdm for _ in stqdm(range(50)): sleep(0.5) Custom notification boxA custom notification box with the ability to close it out. Created by @Socvest.from streamlit_custom_notification_box import custom_notification_box styles = {'material-icons':{'color': 'red'}, 'text-icon-link-close-container': {'box-shadow': '#3896de 0px 4px'}, 'notification-text': {'':''}, 'close-button':{'':''}, 'link':{'':''}} custom_notification_box(icon='info', textDisplay='We are almost done with your registration...', externalLink='more info', url='#', styles=styles, key=""foo"") Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.let_it_rain import rain rain(emoji=""🎈"", font_size=54, falling_speed=5, animation_length=""infinite"",) App logic and configuration Navigation and pages Switch pageProgrammatically navigates to a specified page.st.switch_page(""pages/my_page.py"") Page linkDisplay a link to another page in a multipage app.st.page_link(""app.py"", label=""Home"", icon=""🏠"") st.page_link(""pages/profile.py"", label=""My profile"") Execution flow Modal dialogsInsert a modal dialog that can rerun independently from the rest of the script.@st.experimental_dialog(""Sign up"") def email_form(): name = st.text_input(""Name"") email = st.text_input(""Email"") FormsCreate a form that batches elements together with a “Submit"" button.with st.form(key='my_form'): name = st.text_input(""Name"") email = st.text_input(""Email"") st.form_submit_button(""Sign up"") Partial rerunsDefine a fragment to rerun independently from the rest of the script.@st.experimental_fragment(run_every=""10s"") def fragment(): df = get_data() st.line_chart(df) Rerun scriptRerun the script immediately.st.rerun() Stop executionStops execution immediately.st.stop() Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration!AutorefreshForce a refresh without tying up a script. Created by @kmcgrady.from streamlit_autorefresh import st_autorefresh st_autorefresh(interval=2000, limit=100, key=""fizzbuzzcounter"") PydanticAuto-generate Streamlit UI from Pydantic Models and Dataclasses. Created by @lukasmasuch.import streamlit_pydantic as sp sp.pydantic_form(key=""my_form"", model=ExampleModel) Streamlit PagesAn experimental version of Streamlit Multi-Page Apps. Created by @blackary.from st_pages import Page, show_pages, add_page_title show_pages([ Page(""streamlit_app.py"", ""Home"", ""🏠""), Page(""other_pages/page2.py"", ""Page 2"", "":books:""), ]) Caching and state Cache dataFunction decorator to cache functions that return data (e.g. dataframe transforms, database queries, ML inference).@st.cache_data def long_function(param1, param2): # Perform expensive computation here or # fetch data from the web here return data Cache resourceFunction decorator to cache functions that return global resources (e.g. database connections, ML models).@st.cache_resource def init_model(): # Return a global resource here return pipeline( ""sentiment-analysis"", model=""distilbert-base-uncased-finetuned-sst-2-english"" ) Session stateSession state is a way to share variables between reruns, for each user session.st.session_state['key'] = value Query parametersGet, set, or clear the query parameters that are shown in the browser's URL bar.st.query_params[key] = value st.query_params.clear() Connections and databases Setup your connection Create a connectionConnect to a data source or APIconn = st.connection('pets_db', type='sql') pet_owners = conn.query('select * from pet_owners') st.dataframe(pet_owners) Built-in connections SnowflakeConnectionA connection to Snowflake.conn = st.connection('snowflake') SQLConnectionA connection to a SQL database using SQLAlchemy.conn = st.connection('sql') Build your own connections Connection base classBuild your own connection with BaseConnection.class MyConnection(BaseConnection[myconn.MyConnection]): def _connect(self, **kwargs) -> MyConnection: return myconn.connect(**self._secrets, **kwargs) def query(self, query): return self._instance.query(query) Secrets management Secrets singletonAccess secrets from a local TOML file.key = st.secrets[""OpenAI_key""] Secrets fileSave your secrets in a per-project or per-profile TOML file.OpenAI_key = """" Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration!AuthenticatorA secure authentication module to validate user credentials. Created by @mkhorasani.import streamlit_authenticator as stauth authenticator = stauth.Authenticate( config['credentials'], config['cookie']['name'], config['cookie']['key'], config['cookie']['expiry_days'], config['preauthorized']) WS localStorageA simple synchronous way of accessing localStorage from your app. Created by @gagangoku.from streamlit_ws_localstorage import injectWebsocketCode ret = conn.setLocalStorageVal(key='k1', val='v1') st.write('ret: ' + ret) Streamlit Auth0The fastest way to provide comprehensive login inside Streamlit. Created by @conradbez.from auth0_component import login_button user_info = login_button(clientId, domain = domain) st.write(user_info) Custom Components Declare a componentCreate and register a custom component.st.components.v1.declare_component( ""custom_slider"", ""/frontend"", ) HTMLDisplay an HTML string in an iframe.st.components.v1.html( ""

Foo bar.

"" ) iframeLoad a remote URL in an iframe.st.components.v1.iframe( ""docs.streamlit.io"" ) Utilities and user info User infost.experimental_user returns information about the logged-in user of private apps on Streamlit Community Cloud.if st.experimental_user.email == ""foo@corp.com"": st.write(""Welcome back, "", st.experimental_user.email) else: st.write(""You are not authorized to view this page."") Get helpDisplay object’s doc string, nicely formatted.st.help(st.write) st.help(pd.DataFrame) Render HTMLRenders HTML strings to your app.css = """""" """""" st.html(css) Configuration Configuration fileConfigures the default settings for your app.your-project/ ├── .streamlit/ │ └── config.toml └── your_app.py Set page title, favicon, and moreConfigures the default settings of the page.st.set_page_config( page_title=""My app"", page_icon="":shark:"", ) Developer tools App testing st.testing.v1.AppTestst.testing.v1.AppTest simulates a running Streamlit app for testing.from streamlit.testing.v1 import AppTest at = AppTest.from_file(""streamlit_app.py"") at.secrets[""WORD""] = ""Foobar"" at.run() assert not at.exception at.text_input(""word"").input(""Bazbat"").run() assert at.warning[0].value == ""Try again."" AppTest.from_filest.testing.v1.AppTest.from_file initializes a simulated app from a file.from streamlit.testing.v1 import AppTest at = AppTest.from_file(""streamlit_app.py"") at.run() AppTest.from_stringst.testing.v1.AppTest.from_string initializes a simulated app from a string.from streamlit.testing.v1 import AppTest at = AppTest.from_string(app_script_as_string) at.run() AppTest.from_functionst.testing.v1.AppTest.from_function initializes a simulated app from a function.from streamlit.testing.v1 import AppTest at = AppTest.from_function(app_script_as_callable) at.run() BlockA representation of container elements, including: st.chat_message st.columns st.sidebar st.tabs The main body of the app. # at.sidebar returns a Block at.sidebar.button[0].click().run() assert not at.exception ElementThe base class for representation of all elements, including: st.title st.header st.markdown st.dataframe # at.title returns a sequence of Title # Title inherits from Element assert at.title[0].value == ""My awesome app"" ButtonA representation of st.button and st.form_submit_button.at.button[0].click().run() ChatInputA representation of st.chat_input.at.chat_input[0].set_value(""What is Streamlit?"").run() CheckboxA representation of st.checkbox.at.checkbox[0].check().run() ColorPickerA representation of st.color_picker.at.color_picker[0].pick(""#FF4B4B"").run() DateInputA representation of st.date_input.release_date = datetime.date(2023, 10, 26) at.date_input[0].set_value(release_date).run() MultiselectA representation of st.multiselect.at.multiselect[0].select(""New York"").run() NumberInputA representation of st.number_input.at.number_input[0].increment().run() RadioA representation of st.radio.at.radio[0].set_value(""New York"").run() SelectSliderA representation of st.select_slider.at.select_slider[0].set_range(""A"",""C"").run() SelectboxA representation of st.selectbox.at.selectbox[0].select(""New York"").run() SliderA representation of st.slider.at.slider[0].set_range(2,5).run() TextAreaA representation of st.text_area.at.text_area[0].input(""Streamlit is awesome!"").run() TextInputA representation of st.text_input.at.text_input[0].input(""Streamlit"").run() TimeInputA representation of st.time_input.at.time_input[0].increment().run() ToggleA representation of st.toggle.at.toggle[0].set_value(""True"").run() Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration!Pandas ProfilingPandas profiling component for Streamlit. Created by @okld.df = pd.read_csv(""https://storage.googleapis.com/tf-datasets/titanic/train.csv"") pr = df.profile_report() st_profile_report(pr) Streamlit AceAce editor component for Streamlit. Created by @okld.from streamlit_ace import st_ace content = st_ace() content Streamlit AnalyticsTrack & visualize user interactions with your streamlit app. Created by @jrieke.import streamlit_analytics with streamlit_analytics.track(): st.text_input(""Write something"") Previous: ConceptsNext: Write and magicforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy" https://docs.streamlit.io/develop/api-reference/app-testing/testing-element-classes#numberinputrun,"DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceremovePAGE ELEMENTSWrite and magicaddText elementsaddData elementsaddChart elementsaddInput widgetsaddMedia elementsaddLayouts and containersaddChat elementsaddStatus elementsaddThird-party componentsopen_in_newAPPLICATION LOGICNavigation and pagesaddExecution flowaddCaching and stateaddConnections and secretsaddCustom componentsaddUtilitiesaddConfigurationaddTOOLSApp testingremovest.testing.v1.AppTestTesting element classesCommand lineaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Develop/API reference/App testing/Testing element classesTesting element classes st.testing.v1.element_tree.Block The Block class has the same methods and attributes as AppTest. A Block instance represents a container of elements just as AppTest represents the entire app. For example, Block.button will produce a WidgetList of Button in the same manner as AppTest.button. ChatMessage, Column, and Tab all inherit from Block. For all container classes, parameters of the original element can be obtained as properties. For example, ChatMessage.avatar and Tab.label. st.testing.v1.element_tree.ElementStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeElement base class for testing. This class's methods and attributes are universal for all elements implemented in testing. For example, Caption, Code, Text, and Title inherit from Element. All widget classes also inherit from Element, but have additional methods specific to each widget type. See the AppTest class for the full list of supported elements. For all element classes, parameters of the original element can be obtained as properties. For example, Button.label, Caption.help, and Toast.icon. Class description[source] st.testing.v1.element_tree.Element(proto, root) Methods run(*, timeout=None) Run the AppTest script which contains the element. Attributes value The value or contents of the element. st.testing.v1.element_tree.ButtonStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.button and st.form_submit_button. Class description[source] st.testing.v1.element_tree.Button(proto, root) Methods click() Set the value of the button to True. run(*, timeout=None) Run the AppTest script which contains the element. set_value(v) Set the value of the button. Attributes value The value of the button. (bool) st.testing.v1.element_tree.ChatInputStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.chat_input. Class description[source] st.testing.v1.element_tree.ChatInput(proto, root) Methods run(*, timeout=None) Run the AppTest script which contains the element. set_value(v) Set the value of the widget. Attributes value The value of the widget. (str) st.testing.v1.element_tree.CheckboxStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.checkbox. Class description[source] st.testing.v1.element_tree.Checkbox(proto, root) Methods check() Set the value of the widget to True. run(*, timeout=None) Run the AppTest script which contains the element. set_value(v) Set the value of the widget. uncheck() Set the value of the widget to False. Attributes value The value of the widget. (bool) st.testing.v1.element_tree.ColorPickerStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.color_picker. Class description[source] st.testing.v1.element_tree.ColorPicker(proto, root) Methods pick(v) Set the value of the widget as a hex string. May omit the ""#"" prefix. run(*, timeout=None) Run the AppTest script which contains the element. set_value(v) Set the value of the widget as a hex string. Attributes value The currently selected value as a hex string. (str) st.testing.v1.element_tree.DateInputStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.date_input. Class description[source] st.testing.v1.element_tree.DateInput(proto, root) Methods run(*, timeout=None) Run the AppTest script which contains the element. set_value(v) Set the value of the widget. Attributes value The value of the widget. (date or Tuple of date) st.testing.v1.element_tree.MultiselectStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.multiselect. Class description[source] st.testing.v1.element_tree.Multiselect(proto, root) Methods run(*, timeout=None) Run the AppTest script which contains the element. select(v) Add a selection to the widget. Do nothing if the value is already selected. If testing a multiselect widget with repeated options, use set_value instead. set_value(v) Set the value of the multiselect widget. (list) unselect(v) Remove a selection from the widget. Do nothing if the value is not already selected. If a value is selected multiple times, the first instance is removed. Attributes format_func The widget's formatting function for displaying options. (callable) indices The indices of the currently selected values from the options. (list) value The currently selected values from the options. (list) st.testing.v1.element_tree.NumberInputStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.number_input. Class description[source] st.testing.v1.element_tree.NumberInput(proto, root) Methods decrement() Decrement the st.number_input widget as if the user clicked ""-"". increment() Increment the st.number_input widget as if the user clicked ""+"". run(*, timeout=None) Run the AppTest script which contains the element. set_value(v) Set the value of the st.number_input widget. Attributes value Get the current value of the st.number_input widget. st.testing.v1.element_tree.RadioStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.radio. Class description[source] st.testing.v1.element_tree.Radio(proto, root) Methods run(*, timeout=None) Run the AppTest script which contains the element. set_value(v) Set the selection by value. Attributes format_func The widget's formatting function for displaying options. (callable) index The index of the current selection. (int) value The currently selected value from the options. (Any) st.testing.v1.element_tree.SelectSliderStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.select_slider. Class description[source] st.testing.v1.element_tree.SelectSlider(proto, root) Methods run(*, timeout=None) Run the AppTest script which contains the element. set_range(lower, upper) Set the ranged selection by values. set_value(v) Set the (single) selection by value. Attributes format_func The widget's formatting function for displaying options. (callable) value The currently selected value or range. (Any or Sequence of Any) st.testing.v1.element_tree.SelectboxStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.selectbox. Class description[source] st.testing.v1.element_tree.Selectbox(proto, root) Methods run(*, timeout=None) Run the AppTest script which contains the element. select(v) Set the selection by value. select_index(index) Set the selection by index. set_value(v) Set the selection by value. Attributes format_func The widget's formatting function for displaying options. (callable) index The index of the current selection. (int) value The currently selected value from the options. (Any) st.testing.v1.element_tree.SliderStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.slider. Class description[source] st.testing.v1.element_tree.Slider(proto, root) Methods run(*, timeout=None) Run the AppTest script which contains the element. set_range(lower, upper) Set the ranged value of the slider. set_value(v) Set the (single) value of the slider. Attributes value The currently selected value or range. (Any or Sequence of Any) st.testing.v1.element_tree.TextAreaStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.text_area. Class description[source] st.testing.v1.element_tree.TextArea(proto, root) Methods input(v) Set the value of the widget only if the value does not exceed the maximum allowed characters. run(*, timeout=None) Run the AppTest script which contains the element. set_value(v) Set the value of the widget. Attributes value The current value of the widget. (str) st.testing.v1.element_tree.TextInputStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.text_input. Class description[source] st.testing.v1.element_tree.TextInput(proto, root) Methods input(v) Set the value of the widget only if the value does not exceed the maximum allowed characters. run(*, timeout=None) Run the AppTest script which contains the element. set_value(v) Set the value of the widget. Attributes value The current value of the widget. (str) st.testing.v1.element_tree.TimeInputStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.time_input. Class description[source] st.testing.v1.element_tree.TimeInput(proto, root) Methods decrement() Select the previous available time. increment() Select the next available time. run(*, timeout=None) Run the AppTest script which contains the element. set_value(v) Set the value of the widget. Attributes value The current value of the widget. (time) st.testing.v1.element_tree.ToggleStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.toggle. Class description[source] st.testing.v1.element_tree.Toggle(proto, root) Methods run(*, timeout=None) Run the AppTest script which contains the element. set_value(v) Set the value of the widget. Attributes value The current value of the widget. (bool) Previous: st.testing.v1.AppTestNext: Command lineforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy" https://docs.streamlit.io/en/0.72.0/api.html#streamlit.file_uploader,"DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceremovePAGE ELEMENTSWrite and magicaddText elementsaddData elementsaddChart elementsaddInput widgetsaddMedia elementsaddLayouts and containersaddChat elementsaddStatus elementsaddThird-party componentsopen_in_newAPPLICATION LOGICNavigation and pagesaddExecution flowaddCaching and stateaddConnections and secretsaddCustom componentsaddUtilitiesaddConfigurationaddTOOLSApp testingaddCommand lineaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Develop/API referenceAPI reference Streamlit makes it easy for you to visualize, mutate, and share data. The API reference is organized by activity type, like displaying data or optimizing performance. Each section includes methods associated with the activity type, including examples. Browse our API below and click to learn more about any of our available commands! 🎈 Display almost anything Write and magic st.writeWrite arguments to the app.st.write(""Hello **world**!"") st.write(my_data_frame) st.write(my_mpl_figure) st.write_streamWrite generators or streams to the app with a typewriter effect.st.write_stream(my_generator) st.write_stream(my_llm_stream) MagicAny time Streamlit sees either a variable or literal value on its own line, it automatically writes that to your app using st.write""Hello **world**!"" my_data_frame my_mpl_figure Text elements MarkdownDisplay string formatted as Markdown.st.markdown(""Hello **world**!"") TitleDisplay text in title formatting.st.title(""The app title"") HeaderDisplay text in header formatting.st.header(""This is a header"") SubheaderDisplay text in subheader formatting.st.subheader(""This is a subheader"") CaptionDisplay text in small font.st.caption(""This is written small caption text"") Code blockDisplay a code block with optional syntax highlighting.st.code(""a = 1234"") EchoDisplay some code in the app, then execute it. Useful for tutorials.with st.echo(): st.write('This code will be printed') LaTeXDisplay mathematical expressions formatted as LaTeX.st.latex(""\int a x^2 \,dx"") Preformatted textWrite fixed-width and preformatted text.st.text(""Hello world"") DividerDisplay a horizontal rule.st.divider() Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration! PreviousTagsAdd tags to your Streamlit apps. Created by @gagan3012.st_tags(label='# Enter Keywords:', text='Press enter to add more', value=['Zero', 'One', 'Two'], suggestions=['five', 'six', 'seven', 'eight', 'nine', 'three', 'eleven', 'ten', 'four'], maxtags = 4, key='1') NLUApply text mining on a dataframe. Created by @JohnSnowLabs.nlu.load('sentiment').predict('I love NLU! <3') Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.mention(label=""An awesome Streamlit App"", icon=""streamlit"", url=""https://extras.streamlit.app"",) Annotated textDisplay annotated text in Streamlit apps. Created by @tvst.annotated_text(""This "", (""is"", ""verb""), "" some "", (""annotated"", ""adj""), (""text"", ""noun""), "" for those of "", (""you"", ""pronoun""), "" who "", (""like"", ""verb""), "" this sort of "", (""thing"", ""noun""), ""."") Drawable CanvasProvides a sketching canvas using Fabric.js. Created by @andfanilo.st_canvas(fill_color=""rgba(255, 165, 0, 0.3)"", stroke_width=stroke_width, stroke_color=stroke_color, background_color=bg_color, background_image=Image.open(bg_image) if bg_image else None, update_streamlit=realtime_update, height=150, drawing_mode=drawing_mode, point_display_radius=point_display_radius if drawing_mode == 'point' else 0, key=""canvas"",) TagsAdd tags to your Streamlit apps. Created by @gagan3012.st_tags(label='# Enter Keywords:', text='Press enter to add more', value=['Zero', 'One', 'Two'], suggestions=['five', 'six', 'seven', 'eight', 'nine', 'three', 'eleven', 'ten', 'four'], maxtags = 4, key='1') NLUApply text mining on a dataframe. Created by @JohnSnowLabs.nlu.load('sentiment').predict('I love NLU! <3') Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.mention(label=""An awesome Streamlit App"", icon=""streamlit"", url=""https://extras.streamlit.app"",) Annotated textDisplay annotated text in Streamlit apps. Created by @tvst.annotated_text(""This "", (""is"", ""verb""), "" some "", (""annotated"", ""adj""), (""text"", ""noun""), "" for those of "", (""you"", ""pronoun""), "" who "", (""like"", ""verb""), "" this sort of "", (""thing"", ""noun""), ""."") Drawable CanvasProvides a sketching canvas using Fabric.js. Created by @andfanilo.st_canvas(fill_color=""rgba(255, 165, 0, 0.3)"", stroke_width=stroke_width, stroke_color=stroke_color, background_color=bg_color, background_image=Image.open(bg_image) if bg_image else None, update_streamlit=realtime_update, height=150, drawing_mode=drawing_mode, point_display_radius=point_display_radius if drawing_mode == 'point' else 0, key=""canvas"",) TagsAdd tags to your Streamlit apps. Created by @gagan3012.st_tags(label='# Enter Keywords:', text='Press enter to add more', value=['Zero', 'One', 'Two'], suggestions=['five', 'six', 'seven', 'eight', 'nine', 'three', 'eleven', 'ten', 'four'], maxtags = 4, key='1') NLUApply text mining on a dataframe. Created by @JohnSnowLabs.nlu.load('sentiment').predict('I love NLU! <3') Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.mention(label=""An awesome Streamlit App"", icon=""streamlit"", url=""https://extras.streamlit.app"",) Next Data elements DataframesDisplay a dataframe as an interactive table.st.dataframe(my_data_frame) Data editorDisplay a data editor widget.edited = st.data_editor(df, num_rows=""dynamic"") Column configurationConfigure the display and editing behavior of dataframes and data editors.st.column_config.NumberColumn(""Price (in USD)"", min_value=0, format=""$%d"") Static tablesDisplay a static table.st.table(my_data_frame) MetricsDisplay a metric in big bold font, with an optional indicator of how the metric changed.st.metric(""My metric"", 42, 2) Dicts and JSONDisplay object or string as a pretty-printed JSON string.st.json(my_dict) Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration! PreviousImage CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates value = streamlit_image_coordinates(""https://placekitten.com/200/300"") st.write(value) Plotly EventsMake Plotly charts interactive!. Created by @null-jones.from streamlit_plotly_events import plotly_events fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.metric_cards import style_metric_cards col3.metric(label=""No Change"", value=5000, delta=0) style_metric_cards() Streamlit AggridImplementation of Ag-Grid component for Streamlit. Created by @PablocFonseca.df = pd.DataFrame({'col1': [1, 2, 3], 'col2': [4, 5, 6]}) grid_return = AgGrid(df, editable=True) new_df = grid_return['data'] Streamlit FoliumStreamlit Component for rendering Folium maps. Created by @randyzwitch.m = folium.Map(location=[39.949610, -75.150282], zoom_start=16) folium.Marker([39.949610, -75.150282], popup=""Liberty Bell"", tooltip=""Liberty Bell"").add_to(m) st_data = st_folium(m, width=725) Pandas ProfilingPandas profiling component for Streamlit. Created by @okld.df = pd.read_csv(""https://storage.googleapis.com/tf-datasets/titanic/train.csv"") pr = df.profile_report() st_profile_report(pr) Image CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates value = streamlit_image_coordinates(""https://placekitten.com/200/300"") st.write(value) Plotly EventsMake Plotly charts interactive!. Created by @null-jones.from streamlit_plotly_events import plotly_events fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.metric_cards import style_metric_cards col3.metric(label=""No Change"", value=5000, delta=0) style_metric_cards() Streamlit AggridImplementation of Ag-Grid component for Streamlit. Created by @PablocFonseca.df = pd.DataFrame({'col1': [1, 2, 3], 'col2': [4, 5, 6]}) grid_return = AgGrid(df, editable=True) new_df = grid_return['data'] Streamlit FoliumStreamlit Component for rendering Folium maps. Created by @randyzwitch.m = folium.Map(location=[39.949610, -75.150282], zoom_start=16) folium.Marker([39.949610, -75.150282], popup=""Liberty Bell"", tooltip=""Liberty Bell"").add_to(m) st_data = st_folium(m, width=725) Pandas ProfilingPandas profiling component for Streamlit. Created by @okld.df = pd.read_csv(""https://storage.googleapis.com/tf-datasets/titanic/train.csv"") pr = df.profile_report() st_profile_report(pr) Image CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates value = streamlit_image_coordinates(""https://placekitten.com/200/300"") st.write(value) Plotly EventsMake Plotly charts interactive!. Created by @null-jones.from streamlit_plotly_events import plotly_events fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.metric_cards import style_metric_cards col3.metric(label=""No Change"", value=5000, delta=0) style_metric_cards() Next Chart elements Simple area chartsDisplay an area chart.st.area_chart(my_data_frame) Simple bar chartsDisplay a bar chart.st.bar_chart(my_data_frame) Simple line chartsDisplay a line chart.st.line_chart(my_data_frame) Simple scatter chartsDisplay a line chart.st.scatter_chart(my_data_frame) Scatterplots on mapsDisplay a map with points on it.st.map(my_data_frame) MatplotlibDisplay a matplotlib.pyplot figure.st.pyplot(my_mpl_figure) AltairDisplay a chart using the Altair library.st.altair_chart(my_altair_chart) Vega-LiteDisplay a chart using the Vega-Lite library.st.vega_lite_chart(my_vega_lite_chart) PlotlyDisplay an interactive Plotly chart.st.plotly_chart(my_plotly_chart) BokehDisplay an interactive Bokeh chart.st.bokeh_chart(my_bokeh_chart) PyDeckDisplay a chart using the PyDeck library.st.pydeck_chart(my_pydeck_chart) GraphVizDisplay a graph using the dagre-d3 library.st.graphviz_chart(my_graphviz_spec) Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration! PreviousStreamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl(""https://assets5.lottiefiles.com/packages/lf20_V9t630.json"") st_lottie(lottie_hello, key=""hello"") Plotly EventsMake Plotly charts interactive!. Created by @null-jones.fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.chart += get_annotations_chart(annotations=[(""Mar 01, 2008"", ""Pretty good day for GOOG""), (""Dec 01, 2007"", ""Something's going wrong for GOOG & AAPL""), (""Nov 01, 2008"", ""Market starts again thanks to...""), (""Dec 01, 2009"", ""Small crash for GOOG after...""),],) st.altair_chart(chart, use_container_width=True) PlostA deceptively simple plotting library for Streamlit. Created by @tvst.import plost plost.line_chart(my_dataframe, x='time', y='stock_value', color='stock_name',) HiPlotHigh dimensional Interactive Plotting. Created by @facebookresearch.data = [{'dropout':0.1, 'lr': 0.001, 'loss': 10.0, 'optimizer': 'SGD'}, {'dropout':0.15, 'lr': 0.01, 'loss': 3.5, 'optimizer': 'Adam'}, {'dropout':0.3, 'lr': 0.1, 'loss': 4.5, 'optimizer': 'Adam'}] hip.Experiment.from_iterable(data).display() EChartsHigh dimensional Interactive Plotting. Created by @andfanilo.from streamlit_echarts import st_echarts st_echarts(options=options) Streamlit FoliumStreamlit Component for rendering Folium maps. Created by @randyzwitch.m = folium.Map(location=[39.949610, -75.150282], zoom_start=16) st_data = st_folium(m, width=725) Spacy-StreamlitspaCy building blocks and visualizers for Streamlit apps. Created by @explosion.models = [""en_core_web_sm"", ""en_core_web_md""] spacy_streamlit.visualize(models, ""Sundar Pichai is the CEO of Google."") Streamlit AgraphA Streamlit Graph Vis, based on react-grah-vis. Created by @ChrisDelClea.from streamlit_agraph import agraph, Node, Edge, Config agraph(nodes=nodes, edges=edges, config=config) Streamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl(""https://assets5.lottiefiles.com/packages/lf20_V9t630.json"") st_lottie(lottie_hello, key=""hello"") Plotly EventsMake Plotly charts interactive!. Created by @null-jones.fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.chart += get_annotations_chart(annotations=[(""Mar 01, 2008"", ""Pretty good day for GOOG""), (""Dec 01, 2007"", ""Something's going wrong for GOOG & AAPL""), (""Nov 01, 2008"", ""Market starts again thanks to...""), (""Dec 01, 2009"", ""Small crash for GOOG after...""),],) st.altair_chart(chart, use_container_width=True) PlostA deceptively simple plotting library for Streamlit. Created by @tvst.import plost plost.line_chart(my_dataframe, x='time', y='stock_value', color='stock_name',) HiPlotHigh dimensional Interactive Plotting. Created by @facebookresearch.data = [{'dropout':0.1, 'lr': 0.001, 'loss': 10.0, 'optimizer': 'SGD'}, {'dropout':0.15, 'lr': 0.01, 'loss': 3.5, 'optimizer': 'Adam'}, {'dropout':0.3, 'lr': 0.1, 'loss': 4.5, 'optimizer': 'Adam'}] hip.Experiment.from_iterable(data).display() EChartsHigh dimensional Interactive Plotting. Created by @andfanilo.from streamlit_echarts import st_echarts st_echarts(options=options) Streamlit FoliumStreamlit Component for rendering Folium maps. Created by @randyzwitch.m = folium.Map(location=[39.949610, -75.150282], zoom_start=16) st_data = st_folium(m, width=725) Spacy-StreamlitspaCy building blocks and visualizers for Streamlit apps. Created by @explosion.models = [""en_core_web_sm"", ""en_core_web_md""] spacy_streamlit.visualize(models, ""Sundar Pichai is the CEO of Google."") Streamlit AgraphA Streamlit Graph Vis, based on react-grah-vis. Created by @ChrisDelClea.from streamlit_agraph import agraph, Node, Edge, Config agraph(nodes=nodes, edges=edges, config=config) Streamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl(""https://assets5.lottiefiles.com/packages/lf20_V9t630.json"") st_lottie(lottie_hello, key=""hello"") Plotly EventsMake Plotly charts interactive!. Created by @null-jones.fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.chart += get_annotations_chart(annotations=[(""Mar 01, 2008"", ""Pretty good day for GOOG""), (""Dec 01, 2007"", ""Something's going wrong for GOOG & AAPL""), (""Nov 01, 2008"", ""Market starts again thanks to...""), (""Dec 01, 2009"", ""Small crash for GOOG after...""),],) st.altair_chart(chart, use_container_width=True) Next Input widgets ButtonDisplay a button widget.clicked = st.button(""Click me"") Download buttonDisplay a download button widget.st.download_button(""Download file"", file) Form buttonDisplay a form submit button. For use with st.form.st.form_submit_button(""Sign up"") Link buttonDisplay a link button.st.link_button(""Go to gallery"", url) Page linkDisplay a link to another page in a multipage app.st.page_link(""app.py"", label=""Home"", icon=""🏠"") st.page_link(""pages/profile.py"", label=""My profile"") CheckboxDisplay a checkbox widget.selected = st.checkbox(""I agree"") Color pickerDisplay a color picker widget.color = st.color_picker(""Pick a color"") MultiselectDisplay a multiselect widget. The multiselect widget starts as empty.choices = st.multiselect(""Buy"", [""milk"", ""apples"", ""potatoes""]) RadioDisplay a radio button widget.choice = st.radio(""Pick one"", [""cats"", ""dogs""]) SelectboxDisplay a select widget.choice = st.selectbox(""Pick one"", [""cats"", ""dogs""]) Select-sliderDisplay a slider widget to select items from a list.size = st.select_slider(""Pick a size"", [""S"", ""M"", ""L""]) ToggleDisplay a toggle widget.activated = st.toggle(""Activate"") Number inputDisplay a numeric input widget.choice = st.number_input(""Pick a number"", 0, 10) SliderDisplay a slider widget.number = st.slider(""Pick a number"", 0, 100) Date inputDisplay a date input widget.date = st.date_input(""Your birthday"") Time inputDisplay a time input widget.time = st.time_input(""Meeting time"") Chat inputDisplay a chat input widget.prompt = st.chat_input(""Say something"") if prompt: st.write(f""The user has sent: {prompt}"") Text-areaDisplay a multi-line text input widget.text = st.text_area(""Text to translate"") Text inputDisplay a single-line text input widget.name = st.text_input(""First name"") Data editorDisplay a data editor widget.edited = st.experimental_data_editor(df, num_rows=""dynamic"") File UploaderDisplay a file uploader widget.data = st.file_uploader(""Upload a CSV"") Camera inputDisplay a widget that allows users to upload images directly from a camera.image = st.camera_input(""Take a picture"") Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration! PreviousStreamlit ChatStreamlit Component for a Chatbot UI. Created by @AI-Yash.from streamlit_chat import message message(""My message"") message(""Hello bot!"", is_user=True) # align's the message to the right Streamlit Option MenuSelect a single item from a list of options in a menu. Created by @victoryhb.from streamlit_option_menu import option_menu option_menu(""Main Menu"", [""Home"", 'Settings'], icons=['house', 'gear'], menu_icon=""cast"", default_index=1) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.stoggle import stoggle stoggle( ""Click me!"", """"""🥷 Surprise! Here's some additional content"""""",) Streamlit ElementsCreate a draggable and resizable dashboard in Streamlit. Created by @okls.from streamlit_elements import elements, mui, html with elements(""new_element""): mui.Typography(""Hello world"") TagsAdd tags to your Streamlit apps. Created by @gagan3012.from streamlit_tags import st_tags st_tags(label='# Enter Keywords:', text='Press enter to add more', value=['Zero', 'One', 'Two'], suggestions=['five', 'six', 'seven', 'eight', 'nine', 'three', 'eleven', 'ten', 'four'], maxtags = 4, key='1') StqdmThe simplest way to handle a progress bar in streamlit app. Created by @Wirg.from stqdm import stqdm for _ in stqdm(range(50)): sleep(0.5) TimelineDisplay a Timeline in Streamlit apps using TimelineJS. Created by @innerdoc.from streamlit_timeline import timeline with open('example.json', ""r"") as f: timeline(f.read(), height=800) Camera input liveAlternative for st.camera_input which returns the webcam images live. Created by @blackary.from camera_input_live import camera_input_live image = camera_input_live() st.image(value) Streamlit AceAce editor component for Streamlit. Created by @okld.from streamlit_ace import st_ace content = st_ace() content Streamlit ChatStreamlit Component for a Chatbot UI. Created by @AI-Yash.from streamlit_chat import message message(""My message"") message(""Hello bot!"", is_user=True) # align's the message to the right Streamlit Option MenuSelect a single item from a list of options in a menu. Created by @victoryhb.from streamlit_option_menu import option_menu option_menu(""Main Menu"", [""Home"", 'Settings'], icons=['house', 'gear'], menu_icon=""cast"", default_index=1) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.stoggle import stoggle stoggle( ""Click me!"", """"""🥷 Surprise! Here's some additional content"""""",) Streamlit ElementsCreate a draggable and resizable dashboard in Streamlit. Created by @okls.from streamlit_elements import elements, mui, html with elements(""new_element""): mui.Typography(""Hello world"") TagsAdd tags to your Streamlit apps. Created by @gagan3012.from streamlit_tags import st_tags st_tags(label='# Enter Keywords:', text='Press enter to add more', value=['Zero', 'One', 'Two'], suggestions=['five', 'six', 'seven', 'eight', 'nine', 'three', 'eleven', 'ten', 'four'], maxtags = 4, key='1') StqdmThe simplest way to handle a progress bar in streamlit app. Created by @Wirg.from stqdm import stqdm for _ in stqdm(range(50)): sleep(0.5) TimelineDisplay a Timeline in Streamlit apps using TimelineJS. Created by @innerdoc.from streamlit_timeline import timeline with open('example.json', ""r"") as f: timeline(f.read(), height=800) Camera input liveAlternative for st.camera_input which returns the webcam images live. Created by @blackary.from camera_input_live import camera_input_live image = camera_input_live() st.image(value) Streamlit AceAce editor component for Streamlit. Created by @okld.from streamlit_ace import st_ace content = st_ace() content Streamlit ChatStreamlit Component for a Chatbot UI. Created by @AI-Yash.from streamlit_chat import message message(""My message"") message(""Hello bot!"", is_user=True) # align's the message to the right Streamlit Option MenuSelect a single item from a list of options in a menu. Created by @victoryhb.from streamlit_option_menu import option_menu option_menu(""Main Menu"", [""Home"", 'Settings'], icons=['house', 'gear'], menu_icon=""cast"", default_index=1) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.stoggle import stoggle stoggle( ""Click me!"", """"""🥷 Surprise! Here's some additional content"""""",) Next Media elements ImageDisplay an image or list of images.st.image(numpy_array) st.image(image_bytes) st.image(file) st.image(""https://example.com/myimage.jpg"") AudioDisplay an audio player.st.audio(numpy_array) st.audio(audio_bytes) st.audio(file) st.audio(""https://example.com/myaudio.mp3"", format=""audio/mp3"") VideoDisplay a video player.st.video(numpy_array) st.video(video_bytes) st.video(file) st.video(""https://example.com/myvideo.mp4"", format=""video/mp4"") Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration! PreviousStreamlit CropperA simple image cropper for Streamlit. Created by @turner-anderson.from streamlit_cropper import st_cropper st_cropper(img, realtime_update=realtime_update, box_color=box_color, aspect_ratio=aspect_ratio) Image CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates streamlit_image_coordinates(""https://placekitten.com/200/300"") Streamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl(""https://assets5.lottiefiles.com/packages/lf20_V9t630.json"") st_lottie(lottie_hello, key=""hello"") Streamlit WebrtcHandling and transmitting real-time video/audio streams with Streamlit. Created by @whitphx.from streamlit_webrtc import webrtc_streamer webrtc_streamer(key=""sample"") Drawable CanvasProvides a sketching canvas using Fabric.js. Created by @andfanilo.from streamlit_drawable_canvas import st_canvas st_canvas(fill_color=""rgba(255, 165, 0, 0.3)"", stroke_width=stroke_width, stroke_color=stroke_color, background_color=bg_color, background_image=Image.open(bg_image) if bg_image else None, update_streamlit=realtime_update, height=150, drawing_mode=drawing_mode, point_display_radius=point_display_radius if drawing_mode == 'point' else 0, key=""canvas"",) Image ComparisonCompare images with a slider using JuxtaposeJS. Created by @fcakyon.from streamlit_image_comparison import image_comparison image_comparison(img1=""image1.jpg"", img2=""image2.jpg"",) Streamlit CropperA simple image cropper for Streamlit. Created by @turner-anderson.from streamlit_cropper import st_cropper st_cropper(img, realtime_update=realtime_update, box_color=box_color, aspect_ratio=aspect_ratio) Image CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates streamlit_image_coordinates(""https://placekitten.com/200/300"") Streamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl(""https://assets5.lottiefiles.com/packages/lf20_V9t630.json"") st_lottie(lottie_hello, key=""hello"") Streamlit WebrtcHandling and transmitting real-time video/audio streams with Streamlit. Created by @whitphx.from streamlit_webrtc import webrtc_streamer webrtc_streamer(key=""sample"") Drawable CanvasProvides a sketching canvas using Fabric.js. Created by @andfanilo.from streamlit_drawable_canvas import st_canvas st_canvas(fill_color=""rgba(255, 165, 0, 0.3)"", stroke_width=stroke_width, stroke_color=stroke_color, background_color=bg_color, background_image=Image.open(bg_image) if bg_image else None, update_streamlit=realtime_update, height=150, drawing_mode=drawing_mode, point_display_radius=point_display_radius if drawing_mode == 'point' else 0, key=""canvas"",) Image ComparisonCompare images with a slider using JuxtaposeJS. Created by @fcakyon.from streamlit_image_comparison import image_comparison image_comparison(img1=""image1.jpg"", img2=""image2.jpg"",) Streamlit CropperA simple image cropper for Streamlit. Created by @turner-anderson.from streamlit_cropper import st_cropper st_cropper(img, realtime_update=realtime_update, box_color=box_color, aspect_ratio=aspect_ratio) Image CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates streamlit_image_coordinates(""https://placekitten.com/200/300"") Streamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl(""https://assets5.lottiefiles.com/packages/lf20_V9t630.json"") st_lottie(lottie_hello, key=""hello"") Next Layouts and containers ColumnsInsert containers laid out as side-by-side columns.col1, col2 = st.columns(2) col1.write(""this is column 1"") col2.write(""this is column 2"") ContainerInsert a multi-element container.c = st.container() st.write(""This will show last"") c.write(""This will show first"") c.write(""This will show second"") Modal dialogsInsert a modal dialog that can rerun independently from the rest of the script.@st.experimental_dialog(""Sign up"") def email_form(): name = st.text_input(""Name"") email = st.text_input(""Email"") EmptyInsert a single-element container.c = st.empty() st.write(""This will show last"") c.write(""This will be replaced"") c.write(""This will show first"") ExpanderInsert a multi-element container that can be expanded/collapsed.with st.expander(""Open to see more""): st.write(""This is more content"") PopoverInsert a multi-element popover container that can be opened/closed.with st.popover(""Settings""): st.checkbox(""Show completed"") SidebarDisplay items in a sidebar.st.sidebar.write(""This lives in the sidebar"") st.sidebar.button(""Click me!"") TabsInsert containers separated into tabs.tab1, tab2 = st.tabs([""Tab 1"", ""Tab2""]) tab1.write(""this is tab 1"") tab2.write(""this is tab 2"") Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration!Streamlit ElementsCreate a draggable and resizable dashboard in Streamlit. Created by @okls.from streamlit_elements import elements, mui, html with elements(""new_element""): mui.Typography(""Hello world"") PydanticAuto-generate Streamlit UI from Pydantic Models and Dataclasses. Created by @lukasmasuch.import streamlit_pydantic as sp sp.pydantic_form(key=""my_form"", model=ExampleModel) Streamlit PagesAn experimental version of Streamlit Multi-Page Apps. Created by @blackary.from st_pages import Page, show_pages, add_page_title show_pages([ Page(""streamlit_app.py"", ""Home"", ""🏠""), Page(""other_pages/page2.py"", ""Page 2"", "":books:""), ]) Chat elements Streamlit provides a few commands to help you build conversational apps. These chat elements are designed to be used in conjunction with each other, but you can also use them separately. st.chat_message lets you insert a chat message container into the app so you can display messages from the user or the app. Chat containers can contain other Streamlit elements, including charts, tables, text, and more. st.chat_input lets you display a chat input widget so the user can type in a message. Chat inputDisplay a chat input widget.prompt = st.chat_input(""Say something"") if prompt: st.write(f""The user has sent: {prompt}"") Chat messageInsert a chat message container.import numpy as np with st.chat_message(""user""): st.write(""Hello 👋"") st.line_chart(np.random.randn(30, 3)) Status containerDisplay output of long-running tasks in a container.with st.status('Running'): do_something_slow() st.write_streamWrite generators or streams to the app with a typewriter effect.st.write_stream(my_generator) st.write_stream(my_llm_stream) Status elements Progress barDisplay a progress bar.for i in range(101): st.progress(i) do_something_slow() SpinnerTemporarily displays a message while executing a block of code.with st.spinner(""Please wait...""): do_something_slow() Status containerDisplay output of long-running tasks in a container.with st.status('Running'): do_something_slow() ToastBriefly displays a toast message in the bottom-right corner.st.toast('Butter!', icon='🧈') BalloonsDisplay celebratory balloons!do_something() # Celebrate when all done! st.balloons() SnowflakesDisplay celebratory snowflakes!do_something() # Celebrate when all done! st.snow() Success boxDisplay a success message.st.success(""Match found!"") Info boxDisplay an informational message.st.info(""Dataset is updated every day at midnight."") Warning boxDisplay warning message.st.warning(""Unable to fetch image. Skipping..."") Error boxDisplay error message.st.error(""We encountered an error"") Exception outputDisplay an exception.e = RuntimeError(""This is an exception of type RuntimeError"") st.exception(e) Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration!StqdmThe simplest way to handle a progress bar in streamlit app. Created by @Wirg.from stqdm import stqdm for _ in stqdm(range(50)): sleep(0.5) Custom notification boxA custom notification box with the ability to close it out. Created by @Socvest.from streamlit_custom_notification_box import custom_notification_box styles = {'material-icons':{'color': 'red'}, 'text-icon-link-close-container': {'box-shadow': '#3896de 0px 4px'}, 'notification-text': {'':''}, 'close-button':{'':''}, 'link':{'':''}} custom_notification_box(icon='info', textDisplay='We are almost done with your registration...', externalLink='more info', url='#', styles=styles, key=""foo"") Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.let_it_rain import rain rain(emoji=""🎈"", font_size=54, falling_speed=5, animation_length=""infinite"",) App logic and configuration Navigation and pages Switch pageProgrammatically navigates to a specified page.st.switch_page(""pages/my_page.py"") Page linkDisplay a link to another page in a multipage app.st.page_link(""app.py"", label=""Home"", icon=""🏠"") st.page_link(""pages/profile.py"", label=""My profile"") Execution flow Modal dialogsInsert a modal dialog that can rerun independently from the rest of the script.@st.experimental_dialog(""Sign up"") def email_form(): name = st.text_input(""Name"") email = st.text_input(""Email"") FormsCreate a form that batches elements together with a “Submit"" button.with st.form(key='my_form'): name = st.text_input(""Name"") email = st.text_input(""Email"") st.form_submit_button(""Sign up"") Partial rerunsDefine a fragment to rerun independently from the rest of the script.@st.experimental_fragment(run_every=""10s"") def fragment(): df = get_data() st.line_chart(df) Rerun scriptRerun the script immediately.st.rerun() Stop executionStops execution immediately.st.stop() Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration!AutorefreshForce a refresh without tying up a script. Created by @kmcgrady.from streamlit_autorefresh import st_autorefresh st_autorefresh(interval=2000, limit=100, key=""fizzbuzzcounter"") PydanticAuto-generate Streamlit UI from Pydantic Models and Dataclasses. Created by @lukasmasuch.import streamlit_pydantic as sp sp.pydantic_form(key=""my_form"", model=ExampleModel) Streamlit PagesAn experimental version of Streamlit Multi-Page Apps. Created by @blackary.from st_pages import Page, show_pages, add_page_title show_pages([ Page(""streamlit_app.py"", ""Home"", ""🏠""), Page(""other_pages/page2.py"", ""Page 2"", "":books:""), ]) Caching and state Cache dataFunction decorator to cache functions that return data (e.g. dataframe transforms, database queries, ML inference).@st.cache_data def long_function(param1, param2): # Perform expensive computation here or # fetch data from the web here return data Cache resourceFunction decorator to cache functions that return global resources (e.g. database connections, ML models).@st.cache_resource def init_model(): # Return a global resource here return pipeline( ""sentiment-analysis"", model=""distilbert-base-uncased-finetuned-sst-2-english"" ) Session stateSession state is a way to share variables between reruns, for each user session.st.session_state['key'] = value Query parametersGet, set, or clear the query parameters that are shown in the browser's URL bar.st.query_params[key] = value st.query_params.clear() Connections and databases Setup your connection Create a connectionConnect to a data source or APIconn = st.connection('pets_db', type='sql') pet_owners = conn.query('select * from pet_owners') st.dataframe(pet_owners) Built-in connections SnowflakeConnectionA connection to Snowflake.conn = st.connection('snowflake') SQLConnectionA connection to a SQL database using SQLAlchemy.conn = st.connection('sql') Build your own connections Connection base classBuild your own connection with BaseConnection.class MyConnection(BaseConnection[myconn.MyConnection]): def _connect(self, **kwargs) -> MyConnection: return myconn.connect(**self._secrets, **kwargs) def query(self, query): return self._instance.query(query) Secrets management Secrets singletonAccess secrets from a local TOML file.key = st.secrets[""OpenAI_key""] Secrets fileSave your secrets in a per-project or per-profile TOML file.OpenAI_key = """" Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration!AuthenticatorA secure authentication module to validate user credentials. Created by @mkhorasani.import streamlit_authenticator as stauth authenticator = stauth.Authenticate( config['credentials'], config['cookie']['name'], config['cookie']['key'], config['cookie']['expiry_days'], config['preauthorized']) WS localStorageA simple synchronous way of accessing localStorage from your app. Created by @gagangoku.from streamlit_ws_localstorage import injectWebsocketCode ret = conn.setLocalStorageVal(key='k1', val='v1') st.write('ret: ' + ret) Streamlit Auth0The fastest way to provide comprehensive login inside Streamlit. Created by @conradbez.from auth0_component import login_button user_info = login_button(clientId, domain = domain) st.write(user_info) Custom Components Declare a componentCreate and register a custom component.st.components.v1.declare_component( ""custom_slider"", ""/frontend"", ) HTMLDisplay an HTML string in an iframe.st.components.v1.html( ""

Foo bar.

"" ) iframeLoad a remote URL in an iframe.st.components.v1.iframe( ""docs.streamlit.io"" ) Utilities and user info User infost.experimental_user returns information about the logged-in user of private apps on Streamlit Community Cloud.if st.experimental_user.email == ""foo@corp.com"": st.write(""Welcome back, "", st.experimental_user.email) else: st.write(""You are not authorized to view this page."") Get helpDisplay object’s doc string, nicely formatted.st.help(st.write) st.help(pd.DataFrame) Render HTMLRenders HTML strings to your app.css = """""" """""" st.html(css) Configuration Configuration fileConfigures the default settings for your app.your-project/ ├── .streamlit/ │ └── config.toml └── your_app.py Set page title, favicon, and moreConfigures the default settings of the page.st.set_page_config( page_title=""My app"", page_icon="":shark:"", ) Developer tools App testing st.testing.v1.AppTestst.testing.v1.AppTest simulates a running Streamlit app for testing.from streamlit.testing.v1 import AppTest at = AppTest.from_file(""streamlit_app.py"") at.secrets[""WORD""] = ""Foobar"" at.run() assert not at.exception at.text_input(""word"").input(""Bazbat"").run() assert at.warning[0].value == ""Try again."" AppTest.from_filest.testing.v1.AppTest.from_file initializes a simulated app from a file.from streamlit.testing.v1 import AppTest at = AppTest.from_file(""streamlit_app.py"") at.run() AppTest.from_stringst.testing.v1.AppTest.from_string initializes a simulated app from a string.from streamlit.testing.v1 import AppTest at = AppTest.from_string(app_script_as_string) at.run() AppTest.from_functionst.testing.v1.AppTest.from_function initializes a simulated app from a function.from streamlit.testing.v1 import AppTest at = AppTest.from_function(app_script_as_callable) at.run() BlockA representation of container elements, including: st.chat_message st.columns st.sidebar st.tabs The main body of the app. # at.sidebar returns a Block at.sidebar.button[0].click().run() assert not at.exception ElementThe base class for representation of all elements, including: st.title st.header st.markdown st.dataframe # at.title returns a sequence of Title # Title inherits from Element assert at.title[0].value == ""My awesome app"" ButtonA representation of st.button and st.form_submit_button.at.button[0].click().run() ChatInputA representation of st.chat_input.at.chat_input[0].set_value(""What is Streamlit?"").run() CheckboxA representation of st.checkbox.at.checkbox[0].check().run() ColorPickerA representation of st.color_picker.at.color_picker[0].pick(""#FF4B4B"").run() DateInputA representation of st.date_input.release_date = datetime.date(2023, 10, 26) at.date_input[0].set_value(release_date).run() MultiselectA representation of st.multiselect.at.multiselect[0].select(""New York"").run() NumberInputA representation of st.number_input.at.number_input[0].increment().run() RadioA representation of st.radio.at.radio[0].set_value(""New York"").run() SelectSliderA representation of st.select_slider.at.select_slider[0].set_range(""A"",""C"").run() SelectboxA representation of st.selectbox.at.selectbox[0].select(""New York"").run() SliderA representation of st.slider.at.slider[0].set_range(2,5).run() TextAreaA representation of st.text_area.at.text_area[0].input(""Streamlit is awesome!"").run() TextInputA representation of st.text_input.at.text_input[0].input(""Streamlit"").run() TimeInputA representation of st.time_input.at.time_input[0].increment().run() ToggleA representation of st.toggle.at.toggle[0].set_value(""True"").run() Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration!Pandas ProfilingPandas profiling component for Streamlit. Created by @okld.df = pd.read_csv(""https://storage.googleapis.com/tf-datasets/titanic/train.csv"") pr = df.profile_report() st_profile_report(pr) Streamlit AceAce editor component for Streamlit. Created by @okld.from streamlit_ace import st_ace content = st_ace() content Streamlit AnalyticsTrack & visualize user interactions with your streamlit app. Created by @jrieke.import streamlit_analytics with streamlit_analytics.track(): st.text_input(""Write something"") Previous: ConceptsNext: Write and magicforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy" https://docs.streamlit.io/en/0.76.0/api.html#developer-tools,"DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceremovePAGE ELEMENTSWrite and magicaddText elementsaddData elementsaddChart elementsaddInput widgetsaddMedia elementsaddLayouts and containersaddChat elementsaddStatus elementsaddThird-party componentsopen_in_newAPPLICATION LOGICNavigation and pagesaddExecution flowaddCaching and stateaddConnections and secretsaddCustom componentsaddUtilitiesaddConfigurationaddTOOLSApp testingaddCommand lineaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Develop/API referenceAPI reference Streamlit makes it easy for you to visualize, mutate, and share data. The API reference is organized by activity type, like displaying data or optimizing performance. Each section includes methods associated with the activity type, including examples. Browse our API below and click to learn more about any of our available commands! 🎈 Display almost anything Write and magic st.writeWrite arguments to the app.st.write(""Hello **world**!"") st.write(my_data_frame) st.write(my_mpl_figure) st.write_streamWrite generators or streams to the app with a typewriter effect.st.write_stream(my_generator) st.write_stream(my_llm_stream) MagicAny time Streamlit sees either a variable or literal value on its own line, it automatically writes that to your app using st.write""Hello **world**!"" my_data_frame my_mpl_figure Text elements MarkdownDisplay string formatted as Markdown.st.markdown(""Hello **world**!"") TitleDisplay text in title formatting.st.title(""The app title"") HeaderDisplay text in header formatting.st.header(""This is a header"") SubheaderDisplay text in subheader formatting.st.subheader(""This is a subheader"") CaptionDisplay text in small font.st.caption(""This is written small caption text"") Code blockDisplay a code block with optional syntax highlighting.st.code(""a = 1234"") EchoDisplay some code in the app, then execute it. Useful for tutorials.with st.echo(): st.write('This code will be printed') LaTeXDisplay mathematical expressions formatted as LaTeX.st.latex(""\int a x^2 \,dx"") Preformatted textWrite fixed-width and preformatted text.st.text(""Hello world"") DividerDisplay a horizontal rule.st.divider() Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration! PreviousTagsAdd tags to your Streamlit apps. Created by @gagan3012.st_tags(label='# Enter Keywords:', text='Press enter to add more', value=['Zero', 'One', 'Two'], suggestions=['five', 'six', 'seven', 'eight', 'nine', 'three', 'eleven', 'ten', 'four'], maxtags = 4, key='1') NLUApply text mining on a dataframe. Created by @JohnSnowLabs.nlu.load('sentiment').predict('I love NLU! <3') Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.mention(label=""An awesome Streamlit App"", icon=""streamlit"", url=""https://extras.streamlit.app"",) Annotated textDisplay annotated text in Streamlit apps. Created by @tvst.annotated_text(""This "", (""is"", ""verb""), "" some "", (""annotated"", ""adj""), (""text"", ""noun""), "" for those of "", (""you"", ""pronoun""), "" who "", (""like"", ""verb""), "" this sort of "", (""thing"", ""noun""), ""."") Drawable CanvasProvides a sketching canvas using Fabric.js. Created by @andfanilo.st_canvas(fill_color=""rgba(255, 165, 0, 0.3)"", stroke_width=stroke_width, stroke_color=stroke_color, background_color=bg_color, background_image=Image.open(bg_image) if bg_image else None, update_streamlit=realtime_update, height=150, drawing_mode=drawing_mode, point_display_radius=point_display_radius if drawing_mode == 'point' else 0, key=""canvas"",) TagsAdd tags to your Streamlit apps. Created by @gagan3012.st_tags(label='# Enter Keywords:', text='Press enter to add more', value=['Zero', 'One', 'Two'], suggestions=['five', 'six', 'seven', 'eight', 'nine', 'three', 'eleven', 'ten', 'four'], maxtags = 4, key='1') NLUApply text mining on a dataframe. Created by @JohnSnowLabs.nlu.load('sentiment').predict('I love NLU! <3') Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.mention(label=""An awesome Streamlit App"", icon=""streamlit"", url=""https://extras.streamlit.app"",) Annotated textDisplay annotated text in Streamlit apps. Created by @tvst.annotated_text(""This "", (""is"", ""verb""), "" some "", (""annotated"", ""adj""), (""text"", ""noun""), "" for those of "", (""you"", ""pronoun""), "" who "", (""like"", ""verb""), "" this sort of "", (""thing"", ""noun""), ""."") Drawable CanvasProvides a sketching canvas using Fabric.js. Created by @andfanilo.st_canvas(fill_color=""rgba(255, 165, 0, 0.3)"", stroke_width=stroke_width, stroke_color=stroke_color, background_color=bg_color, background_image=Image.open(bg_image) if bg_image else None, update_streamlit=realtime_update, height=150, drawing_mode=drawing_mode, point_display_radius=point_display_radius if drawing_mode == 'point' else 0, key=""canvas"",) TagsAdd tags to your Streamlit apps. Created by @gagan3012.st_tags(label='# Enter Keywords:', text='Press enter to add more', value=['Zero', 'One', 'Two'], suggestions=['five', 'six', 'seven', 'eight', 'nine', 'three', 'eleven', 'ten', 'four'], maxtags = 4, key='1') NLUApply text mining on a dataframe. Created by @JohnSnowLabs.nlu.load('sentiment').predict('I love NLU! <3') Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.mention(label=""An awesome Streamlit App"", icon=""streamlit"", url=""https://extras.streamlit.app"",) Next Data elements DataframesDisplay a dataframe as an interactive table.st.dataframe(my_data_frame) Data editorDisplay a data editor widget.edited = st.data_editor(df, num_rows=""dynamic"") Column configurationConfigure the display and editing behavior of dataframes and data editors.st.column_config.NumberColumn(""Price (in USD)"", min_value=0, format=""$%d"") Static tablesDisplay a static table.st.table(my_data_frame) MetricsDisplay a metric in big bold font, with an optional indicator of how the metric changed.st.metric(""My metric"", 42, 2) Dicts and JSONDisplay object or string as a pretty-printed JSON string.st.json(my_dict) Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration! PreviousImage CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates value = streamlit_image_coordinates(""https://placekitten.com/200/300"") st.write(value) Plotly EventsMake Plotly charts interactive!. Created by @null-jones.from streamlit_plotly_events import plotly_events fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.metric_cards import style_metric_cards col3.metric(label=""No Change"", value=5000, delta=0) style_metric_cards() Streamlit AggridImplementation of Ag-Grid component for Streamlit. Created by @PablocFonseca.df = pd.DataFrame({'col1': [1, 2, 3], 'col2': [4, 5, 6]}) grid_return = AgGrid(df, editable=True) new_df = grid_return['data'] Streamlit FoliumStreamlit Component for rendering Folium maps. Created by @randyzwitch.m = folium.Map(location=[39.949610, -75.150282], zoom_start=16) folium.Marker([39.949610, -75.150282], popup=""Liberty Bell"", tooltip=""Liberty Bell"").add_to(m) st_data = st_folium(m, width=725) Pandas ProfilingPandas profiling component for Streamlit. Created by @okld.df = pd.read_csv(""https://storage.googleapis.com/tf-datasets/titanic/train.csv"") pr = df.profile_report() st_profile_report(pr) Image CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates value = streamlit_image_coordinates(""https://placekitten.com/200/300"") st.write(value) Plotly EventsMake Plotly charts interactive!. Created by @null-jones.from streamlit_plotly_events import plotly_events fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.metric_cards import style_metric_cards col3.metric(label=""No Change"", value=5000, delta=0) style_metric_cards() Streamlit AggridImplementation of Ag-Grid component for Streamlit. Created by @PablocFonseca.df = pd.DataFrame({'col1': [1, 2, 3], 'col2': [4, 5, 6]}) grid_return = AgGrid(df, editable=True) new_df = grid_return['data'] Streamlit FoliumStreamlit Component for rendering Folium maps. Created by @randyzwitch.m = folium.Map(location=[39.949610, -75.150282], zoom_start=16) folium.Marker([39.949610, -75.150282], popup=""Liberty Bell"", tooltip=""Liberty Bell"").add_to(m) st_data = st_folium(m, width=725) Pandas ProfilingPandas profiling component for Streamlit. Created by @okld.df = pd.read_csv(""https://storage.googleapis.com/tf-datasets/titanic/train.csv"") pr = df.profile_report() st_profile_report(pr) Image CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates value = streamlit_image_coordinates(""https://placekitten.com/200/300"") st.write(value) Plotly EventsMake Plotly charts interactive!. Created by @null-jones.from streamlit_plotly_events import plotly_events fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.metric_cards import style_metric_cards col3.metric(label=""No Change"", value=5000, delta=0) style_metric_cards() Next Chart elements Simple area chartsDisplay an area chart.st.area_chart(my_data_frame) Simple bar chartsDisplay a bar chart.st.bar_chart(my_data_frame) Simple line chartsDisplay a line chart.st.line_chart(my_data_frame) Simple scatter chartsDisplay a line chart.st.scatter_chart(my_data_frame) Scatterplots on mapsDisplay a map with points on it.st.map(my_data_frame) MatplotlibDisplay a matplotlib.pyplot figure.st.pyplot(my_mpl_figure) AltairDisplay a chart using the Altair library.st.altair_chart(my_altair_chart) Vega-LiteDisplay a chart using the Vega-Lite library.st.vega_lite_chart(my_vega_lite_chart) PlotlyDisplay an interactive Plotly chart.st.plotly_chart(my_plotly_chart) BokehDisplay an interactive Bokeh chart.st.bokeh_chart(my_bokeh_chart) PyDeckDisplay a chart using the PyDeck library.st.pydeck_chart(my_pydeck_chart) GraphVizDisplay a graph using the dagre-d3 library.st.graphviz_chart(my_graphviz_spec) Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration! PreviousStreamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl(""https://assets5.lottiefiles.com/packages/lf20_V9t630.json"") st_lottie(lottie_hello, key=""hello"") Plotly EventsMake Plotly charts interactive!. Created by @null-jones.fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.chart += get_annotations_chart(annotations=[(""Mar 01, 2008"", ""Pretty good day for GOOG""), (""Dec 01, 2007"", ""Something's going wrong for GOOG & AAPL""), (""Nov 01, 2008"", ""Market starts again thanks to...""), (""Dec 01, 2009"", ""Small crash for GOOG after...""),],) st.altair_chart(chart, use_container_width=True) PlostA deceptively simple plotting library for Streamlit. Created by @tvst.import plost plost.line_chart(my_dataframe, x='time', y='stock_value', color='stock_name',) HiPlotHigh dimensional Interactive Plotting. Created by @facebookresearch.data = [{'dropout':0.1, 'lr': 0.001, 'loss': 10.0, 'optimizer': 'SGD'}, {'dropout':0.15, 'lr': 0.01, 'loss': 3.5, 'optimizer': 'Adam'}, {'dropout':0.3, 'lr': 0.1, 'loss': 4.5, 'optimizer': 'Adam'}] hip.Experiment.from_iterable(data).display() EChartsHigh dimensional Interactive Plotting. Created by @andfanilo.from streamlit_echarts import st_echarts st_echarts(options=options) Streamlit FoliumStreamlit Component for rendering Folium maps. Created by @randyzwitch.m = folium.Map(location=[39.949610, -75.150282], zoom_start=16) st_data = st_folium(m, width=725) Spacy-StreamlitspaCy building blocks and visualizers for Streamlit apps. Created by @explosion.models = [""en_core_web_sm"", ""en_core_web_md""] spacy_streamlit.visualize(models, ""Sundar Pichai is the CEO of Google."") Streamlit AgraphA Streamlit Graph Vis, based on react-grah-vis. Created by @ChrisDelClea.from streamlit_agraph import agraph, Node, Edge, Config agraph(nodes=nodes, edges=edges, config=config) Streamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl(""https://assets5.lottiefiles.com/packages/lf20_V9t630.json"") st_lottie(lottie_hello, key=""hello"") Plotly EventsMake Plotly charts interactive!. Created by @null-jones.fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.chart += get_annotations_chart(annotations=[(""Mar 01, 2008"", ""Pretty good day for GOOG""), (""Dec 01, 2007"", ""Something's going wrong for GOOG & AAPL""), (""Nov 01, 2008"", ""Market starts again thanks to...""), (""Dec 01, 2009"", ""Small crash for GOOG after...""),],) st.altair_chart(chart, use_container_width=True) PlostA deceptively simple plotting library for Streamlit. Created by @tvst.import plost plost.line_chart(my_dataframe, x='time', y='stock_value', color='stock_name',) HiPlotHigh dimensional Interactive Plotting. Created by @facebookresearch.data = [{'dropout':0.1, 'lr': 0.001, 'loss': 10.0, 'optimizer': 'SGD'}, {'dropout':0.15, 'lr': 0.01, 'loss': 3.5, 'optimizer': 'Adam'}, {'dropout':0.3, 'lr': 0.1, 'loss': 4.5, 'optimizer': 'Adam'}] hip.Experiment.from_iterable(data).display() EChartsHigh dimensional Interactive Plotting. Created by @andfanilo.from streamlit_echarts import st_echarts st_echarts(options=options) Streamlit FoliumStreamlit Component for rendering Folium maps. Created by @randyzwitch.m = folium.Map(location=[39.949610, -75.150282], zoom_start=16) st_data = st_folium(m, width=725) Spacy-StreamlitspaCy building blocks and visualizers for Streamlit apps. Created by @explosion.models = [""en_core_web_sm"", ""en_core_web_md""] spacy_streamlit.visualize(models, ""Sundar Pichai is the CEO of Google."") Streamlit AgraphA Streamlit Graph Vis, based on react-grah-vis. Created by @ChrisDelClea.from streamlit_agraph import agraph, Node, Edge, Config agraph(nodes=nodes, edges=edges, config=config) Streamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl(""https://assets5.lottiefiles.com/packages/lf20_V9t630.json"") st_lottie(lottie_hello, key=""hello"") Plotly EventsMake Plotly charts interactive!. Created by @null-jones.fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.chart += get_annotations_chart(annotations=[(""Mar 01, 2008"", ""Pretty good day for GOOG""), (""Dec 01, 2007"", ""Something's going wrong for GOOG & AAPL""), (""Nov 01, 2008"", ""Market starts again thanks to...""), (""Dec 01, 2009"", ""Small crash for GOOG after...""),],) st.altair_chart(chart, use_container_width=True) Next Input widgets ButtonDisplay a button widget.clicked = st.button(""Click me"") Download buttonDisplay a download button widget.st.download_button(""Download file"", file) Form buttonDisplay a form submit button. For use with st.form.st.form_submit_button(""Sign up"") Link buttonDisplay a link button.st.link_button(""Go to gallery"", url) Page linkDisplay a link to another page in a multipage app.st.page_link(""app.py"", label=""Home"", icon=""🏠"") st.page_link(""pages/profile.py"", label=""My profile"") CheckboxDisplay a checkbox widget.selected = st.checkbox(""I agree"") Color pickerDisplay a color picker widget.color = st.color_picker(""Pick a color"") MultiselectDisplay a multiselect widget. The multiselect widget starts as empty.choices = st.multiselect(""Buy"", [""milk"", ""apples"", ""potatoes""]) RadioDisplay a radio button widget.choice = st.radio(""Pick one"", [""cats"", ""dogs""]) SelectboxDisplay a select widget.choice = st.selectbox(""Pick one"", [""cats"", ""dogs""]) Select-sliderDisplay a slider widget to select items from a list.size = st.select_slider(""Pick a size"", [""S"", ""M"", ""L""]) ToggleDisplay a toggle widget.activated = st.toggle(""Activate"") Number inputDisplay a numeric input widget.choice = st.number_input(""Pick a number"", 0, 10) SliderDisplay a slider widget.number = st.slider(""Pick a number"", 0, 100) Date inputDisplay a date input widget.date = st.date_input(""Your birthday"") Time inputDisplay a time input widget.time = st.time_input(""Meeting time"") Chat inputDisplay a chat input widget.prompt = st.chat_input(""Say something"") if prompt: st.write(f""The user has sent: {prompt}"") Text-areaDisplay a multi-line text input widget.text = st.text_area(""Text to translate"") Text inputDisplay a single-line text input widget.name = st.text_input(""First name"") Data editorDisplay a data editor widget.edited = st.experimental_data_editor(df, num_rows=""dynamic"") File UploaderDisplay a file uploader widget.data = st.file_uploader(""Upload a CSV"") Camera inputDisplay a widget that allows users to upload images directly from a camera.image = st.camera_input(""Take a picture"") Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration! PreviousStreamlit ChatStreamlit Component for a Chatbot UI. Created by @AI-Yash.from streamlit_chat import message message(""My message"") message(""Hello bot!"", is_user=True) # align's the message to the right Streamlit Option MenuSelect a single item from a list of options in a menu. Created by @victoryhb.from streamlit_option_menu import option_menu option_menu(""Main Menu"", [""Home"", 'Settings'], icons=['house', 'gear'], menu_icon=""cast"", default_index=1) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.stoggle import stoggle stoggle( ""Click me!"", """"""🥷 Surprise! Here's some additional content"""""",) Streamlit ElementsCreate a draggable and resizable dashboard in Streamlit. Created by @okls.from streamlit_elements import elements, mui, html with elements(""new_element""): mui.Typography(""Hello world"") TagsAdd tags to your Streamlit apps. Created by @gagan3012.from streamlit_tags import st_tags st_tags(label='# Enter Keywords:', text='Press enter to add more', value=['Zero', 'One', 'Two'], suggestions=['five', 'six', 'seven', 'eight', 'nine', 'three', 'eleven', 'ten', 'four'], maxtags = 4, key='1') StqdmThe simplest way to handle a progress bar in streamlit app. Created by @Wirg.from stqdm import stqdm for _ in stqdm(range(50)): sleep(0.5) TimelineDisplay a Timeline in Streamlit apps using TimelineJS. Created by @innerdoc.from streamlit_timeline import timeline with open('example.json', ""r"") as f: timeline(f.read(), height=800) Camera input liveAlternative for st.camera_input which returns the webcam images live. Created by @blackary.from camera_input_live import camera_input_live image = camera_input_live() st.image(value) Streamlit AceAce editor component for Streamlit. Created by @okld.from streamlit_ace import st_ace content = st_ace() content Streamlit ChatStreamlit Component for a Chatbot UI. Created by @AI-Yash.from streamlit_chat import message message(""My message"") message(""Hello bot!"", is_user=True) # align's the message to the right Streamlit Option MenuSelect a single item from a list of options in a menu. Created by @victoryhb.from streamlit_option_menu import option_menu option_menu(""Main Menu"", [""Home"", 'Settings'], icons=['house', 'gear'], menu_icon=""cast"", default_index=1) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.stoggle import stoggle stoggle( ""Click me!"", """"""🥷 Surprise! Here's some additional content"""""",) Streamlit ElementsCreate a draggable and resizable dashboard in Streamlit. Created by @okls.from streamlit_elements import elements, mui, html with elements(""new_element""): mui.Typography(""Hello world"") TagsAdd tags to your Streamlit apps. Created by @gagan3012.from streamlit_tags import st_tags st_tags(label='# Enter Keywords:', text='Press enter to add more', value=['Zero', 'One', 'Two'], suggestions=['five', 'six', 'seven', 'eight', 'nine', 'three', 'eleven', 'ten', 'four'], maxtags = 4, key='1') StqdmThe simplest way to handle a progress bar in streamlit app. Created by @Wirg.from stqdm import stqdm for _ in stqdm(range(50)): sleep(0.5) TimelineDisplay a Timeline in Streamlit apps using TimelineJS. Created by @innerdoc.from streamlit_timeline import timeline with open('example.json', ""r"") as f: timeline(f.read(), height=800) Camera input liveAlternative for st.camera_input which returns the webcam images live. Created by @blackary.from camera_input_live import camera_input_live image = camera_input_live() st.image(value) Streamlit AceAce editor component for Streamlit. Created by @okld.from streamlit_ace import st_ace content = st_ace() content Streamlit ChatStreamlit Component for a Chatbot UI. Created by @AI-Yash.from streamlit_chat import message message(""My message"") message(""Hello bot!"", is_user=True) # align's the message to the right Streamlit Option MenuSelect a single item from a list of options in a menu. Created by @victoryhb.from streamlit_option_menu import option_menu option_menu(""Main Menu"", [""Home"", 'Settings'], icons=['house', 'gear'], menu_icon=""cast"", default_index=1) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.stoggle import stoggle stoggle( ""Click me!"", """"""🥷 Surprise! Here's some additional content"""""",) Next Media elements ImageDisplay an image or list of images.st.image(numpy_array) st.image(image_bytes) st.image(file) st.image(""https://example.com/myimage.jpg"") AudioDisplay an audio player.st.audio(numpy_array) st.audio(audio_bytes) st.audio(file) st.audio(""https://example.com/myaudio.mp3"", format=""audio/mp3"") VideoDisplay a video player.st.video(numpy_array) st.video(video_bytes) st.video(file) st.video(""https://example.com/myvideo.mp4"", format=""video/mp4"") Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration! PreviousStreamlit CropperA simple image cropper for Streamlit. Created by @turner-anderson.from streamlit_cropper import st_cropper st_cropper(img, realtime_update=realtime_update, box_color=box_color, aspect_ratio=aspect_ratio) Image CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates streamlit_image_coordinates(""https://placekitten.com/200/300"") Streamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl(""https://assets5.lottiefiles.com/packages/lf20_V9t630.json"") st_lottie(lottie_hello, key=""hello"") Streamlit WebrtcHandling and transmitting real-time video/audio streams with Streamlit. Created by @whitphx.from streamlit_webrtc import webrtc_streamer webrtc_streamer(key=""sample"") Drawable CanvasProvides a sketching canvas using Fabric.js. Created by @andfanilo.from streamlit_drawable_canvas import st_canvas st_canvas(fill_color=""rgba(255, 165, 0, 0.3)"", stroke_width=stroke_width, stroke_color=stroke_color, background_color=bg_color, background_image=Image.open(bg_image) if bg_image else None, update_streamlit=realtime_update, height=150, drawing_mode=drawing_mode, point_display_radius=point_display_radius if drawing_mode == 'point' else 0, key=""canvas"",) Image ComparisonCompare images with a slider using JuxtaposeJS. Created by @fcakyon.from streamlit_image_comparison import image_comparison image_comparison(img1=""image1.jpg"", img2=""image2.jpg"",) Streamlit CropperA simple image cropper for Streamlit. Created by @turner-anderson.from streamlit_cropper import st_cropper st_cropper(img, realtime_update=realtime_update, box_color=box_color, aspect_ratio=aspect_ratio) Image CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates streamlit_image_coordinates(""https://placekitten.com/200/300"") Streamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl(""https://assets5.lottiefiles.com/packages/lf20_V9t630.json"") st_lottie(lottie_hello, key=""hello"") Streamlit WebrtcHandling and transmitting real-time video/audio streams with Streamlit. Created by @whitphx.from streamlit_webrtc import webrtc_streamer webrtc_streamer(key=""sample"") Drawable CanvasProvides a sketching canvas using Fabric.js. Created by @andfanilo.from streamlit_drawable_canvas import st_canvas st_canvas(fill_color=""rgba(255, 165, 0, 0.3)"", stroke_width=stroke_width, stroke_color=stroke_color, background_color=bg_color, background_image=Image.open(bg_image) if bg_image else None, update_streamlit=realtime_update, height=150, drawing_mode=drawing_mode, point_display_radius=point_display_radius if drawing_mode == 'point' else 0, key=""canvas"",) Image ComparisonCompare images with a slider using JuxtaposeJS. Created by @fcakyon.from streamlit_image_comparison import image_comparison image_comparison(img1=""image1.jpg"", img2=""image2.jpg"",) Streamlit CropperA simple image cropper for Streamlit. Created by @turner-anderson.from streamlit_cropper import st_cropper st_cropper(img, realtime_update=realtime_update, box_color=box_color, aspect_ratio=aspect_ratio) Image CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates streamlit_image_coordinates(""https://placekitten.com/200/300"") Streamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl(""https://assets5.lottiefiles.com/packages/lf20_V9t630.json"") st_lottie(lottie_hello, key=""hello"") Next Layouts and containers ColumnsInsert containers laid out as side-by-side columns.col1, col2 = st.columns(2) col1.write(""this is column 1"") col2.write(""this is column 2"") ContainerInsert a multi-element container.c = st.container() st.write(""This will show last"") c.write(""This will show first"") c.write(""This will show second"") Modal dialogsInsert a modal dialog that can rerun independently from the rest of the script.@st.experimental_dialog(""Sign up"") def email_form(): name = st.text_input(""Name"") email = st.text_input(""Email"") EmptyInsert a single-element container.c = st.empty() st.write(""This will show last"") c.write(""This will be replaced"") c.write(""This will show first"") ExpanderInsert a multi-element container that can be expanded/collapsed.with st.expander(""Open to see more""): st.write(""This is more content"") PopoverInsert a multi-element popover container that can be opened/closed.with st.popover(""Settings""): st.checkbox(""Show completed"") SidebarDisplay items in a sidebar.st.sidebar.write(""This lives in the sidebar"") st.sidebar.button(""Click me!"") TabsInsert containers separated into tabs.tab1, tab2 = st.tabs([""Tab 1"", ""Tab2""]) tab1.write(""this is tab 1"") tab2.write(""this is tab 2"") Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration!Streamlit ElementsCreate a draggable and resizable dashboard in Streamlit. Created by @okls.from streamlit_elements import elements, mui, html with elements(""new_element""): mui.Typography(""Hello world"") PydanticAuto-generate Streamlit UI from Pydantic Models and Dataclasses. Created by @lukasmasuch.import streamlit_pydantic as sp sp.pydantic_form(key=""my_form"", model=ExampleModel) Streamlit PagesAn experimental version of Streamlit Multi-Page Apps. Created by @blackary.from st_pages import Page, show_pages, add_page_title show_pages([ Page(""streamlit_app.py"", ""Home"", ""🏠""), Page(""other_pages/page2.py"", ""Page 2"", "":books:""), ]) Chat elements Streamlit provides a few commands to help you build conversational apps. These chat elements are designed to be used in conjunction with each other, but you can also use them separately. st.chat_message lets you insert a chat message container into the app so you can display messages from the user or the app. Chat containers can contain other Streamlit elements, including charts, tables, text, and more. st.chat_input lets you display a chat input widget so the user can type in a message. Chat inputDisplay a chat input widget.prompt = st.chat_input(""Say something"") if prompt: st.write(f""The user has sent: {prompt}"") Chat messageInsert a chat message container.import numpy as np with st.chat_message(""user""): st.write(""Hello 👋"") st.line_chart(np.random.randn(30, 3)) Status containerDisplay output of long-running tasks in a container.with st.status('Running'): do_something_slow() st.write_streamWrite generators or streams to the app with a typewriter effect.st.write_stream(my_generator) st.write_stream(my_llm_stream) Status elements Progress barDisplay a progress bar.for i in range(101): st.progress(i) do_something_slow() SpinnerTemporarily displays a message while executing a block of code.with st.spinner(""Please wait...""): do_something_slow() Status containerDisplay output of long-running tasks in a container.with st.status('Running'): do_something_slow() ToastBriefly displays a toast message in the bottom-right corner.st.toast('Butter!', icon='🧈') BalloonsDisplay celebratory balloons!do_something() # Celebrate when all done! st.balloons() SnowflakesDisplay celebratory snowflakes!do_something() # Celebrate when all done! st.snow() Success boxDisplay a success message.st.success(""Match found!"") Info boxDisplay an informational message.st.info(""Dataset is updated every day at midnight."") Warning boxDisplay warning message.st.warning(""Unable to fetch image. Skipping..."") Error boxDisplay error message.st.error(""We encountered an error"") Exception outputDisplay an exception.e = RuntimeError(""This is an exception of type RuntimeError"") st.exception(e) Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration!StqdmThe simplest way to handle a progress bar in streamlit app. Created by @Wirg.from stqdm import stqdm for _ in stqdm(range(50)): sleep(0.5) Custom notification boxA custom notification box with the ability to close it out. Created by @Socvest.from streamlit_custom_notification_box import custom_notification_box styles = {'material-icons':{'color': 'red'}, 'text-icon-link-close-container': {'box-shadow': '#3896de 0px 4px'}, 'notification-text': {'':''}, 'close-button':{'':''}, 'link':{'':''}} custom_notification_box(icon='info', textDisplay='We are almost done with your registration...', externalLink='more info', url='#', styles=styles, key=""foo"") Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.let_it_rain import rain rain(emoji=""🎈"", font_size=54, falling_speed=5, animation_length=""infinite"",) App logic and configuration Navigation and pages Switch pageProgrammatically navigates to a specified page.st.switch_page(""pages/my_page.py"") Page linkDisplay a link to another page in a multipage app.st.page_link(""app.py"", label=""Home"", icon=""🏠"") st.page_link(""pages/profile.py"", label=""My profile"") Execution flow Modal dialogsInsert a modal dialog that can rerun independently from the rest of the script.@st.experimental_dialog(""Sign up"") def email_form(): name = st.text_input(""Name"") email = st.text_input(""Email"") FormsCreate a form that batches elements together with a “Submit"" button.with st.form(key='my_form'): name = st.text_input(""Name"") email = st.text_input(""Email"") st.form_submit_button(""Sign up"") Partial rerunsDefine a fragment to rerun independently from the rest of the script.@st.experimental_fragment(run_every=""10s"") def fragment(): df = get_data() st.line_chart(df) Rerun scriptRerun the script immediately.st.rerun() Stop executionStops execution immediately.st.stop() Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration!AutorefreshForce a refresh without tying up a script. Created by @kmcgrady.from streamlit_autorefresh import st_autorefresh st_autorefresh(interval=2000, limit=100, key=""fizzbuzzcounter"") PydanticAuto-generate Streamlit UI from Pydantic Models and Dataclasses. Created by @lukasmasuch.import streamlit_pydantic as sp sp.pydantic_form(key=""my_form"", model=ExampleModel) Streamlit PagesAn experimental version of Streamlit Multi-Page Apps. Created by @blackary.from st_pages import Page, show_pages, add_page_title show_pages([ Page(""streamlit_app.py"", ""Home"", ""🏠""), Page(""other_pages/page2.py"", ""Page 2"", "":books:""), ]) Caching and state Cache dataFunction decorator to cache functions that return data (e.g. dataframe transforms, database queries, ML inference).@st.cache_data def long_function(param1, param2): # Perform expensive computation here or # fetch data from the web here return data Cache resourceFunction decorator to cache functions that return global resources (e.g. database connections, ML models).@st.cache_resource def init_model(): # Return a global resource here return pipeline( ""sentiment-analysis"", model=""distilbert-base-uncased-finetuned-sst-2-english"" ) Session stateSession state is a way to share variables between reruns, for each user session.st.session_state['key'] = value Query parametersGet, set, or clear the query parameters that are shown in the browser's URL bar.st.query_params[key] = value st.query_params.clear() Connections and databases Setup your connection Create a connectionConnect to a data source or APIconn = st.connection('pets_db', type='sql') pet_owners = conn.query('select * from pet_owners') st.dataframe(pet_owners) Built-in connections SnowflakeConnectionA connection to Snowflake.conn = st.connection('snowflake') SQLConnectionA connection to a SQL database using SQLAlchemy.conn = st.connection('sql') Build your own connections Connection base classBuild your own connection with BaseConnection.class MyConnection(BaseConnection[myconn.MyConnection]): def _connect(self, **kwargs) -> MyConnection: return myconn.connect(**self._secrets, **kwargs) def query(self, query): return self._instance.query(query) Secrets management Secrets singletonAccess secrets from a local TOML file.key = st.secrets[""OpenAI_key""] Secrets fileSave your secrets in a per-project or per-profile TOML file.OpenAI_key = """" Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration!AuthenticatorA secure authentication module to validate user credentials. Created by @mkhorasani.import streamlit_authenticator as stauth authenticator = stauth.Authenticate( config['credentials'], config['cookie']['name'], config['cookie']['key'], config['cookie']['expiry_days'], config['preauthorized']) WS localStorageA simple synchronous way of accessing localStorage from your app. Created by @gagangoku.from streamlit_ws_localstorage import injectWebsocketCode ret = conn.setLocalStorageVal(key='k1', val='v1') st.write('ret: ' + ret) Streamlit Auth0The fastest way to provide comprehensive login inside Streamlit. Created by @conradbez.from auth0_component import login_button user_info = login_button(clientId, domain = domain) st.write(user_info) Custom Components Declare a componentCreate and register a custom component.st.components.v1.declare_component( ""custom_slider"", ""/frontend"", ) HTMLDisplay an HTML string in an iframe.st.components.v1.html( ""

Foo bar.

"" ) iframeLoad a remote URL in an iframe.st.components.v1.iframe( ""docs.streamlit.io"" ) Utilities and user info User infost.experimental_user returns information about the logged-in user of private apps on Streamlit Community Cloud.if st.experimental_user.email == ""foo@corp.com"": st.write(""Welcome back, "", st.experimental_user.email) else: st.write(""You are not authorized to view this page."") Get helpDisplay object’s doc string, nicely formatted.st.help(st.write) st.help(pd.DataFrame) Render HTMLRenders HTML strings to your app.css = """""" """""" st.html(css) Configuration Configuration fileConfigures the default settings for your app.your-project/ ├── .streamlit/ │ └── config.toml └── your_app.py Set page title, favicon, and moreConfigures the default settings of the page.st.set_page_config( page_title=""My app"", page_icon="":shark:"", ) Developer tools App testing st.testing.v1.AppTestst.testing.v1.AppTest simulates a running Streamlit app for testing.from streamlit.testing.v1 import AppTest at = AppTest.from_file(""streamlit_app.py"") at.secrets[""WORD""] = ""Foobar"" at.run() assert not at.exception at.text_input(""word"").input(""Bazbat"").run() assert at.warning[0].value == ""Try again."" AppTest.from_filest.testing.v1.AppTest.from_file initializes a simulated app from a file.from streamlit.testing.v1 import AppTest at = AppTest.from_file(""streamlit_app.py"") at.run() AppTest.from_stringst.testing.v1.AppTest.from_string initializes a simulated app from a string.from streamlit.testing.v1 import AppTest at = AppTest.from_string(app_script_as_string) at.run() AppTest.from_functionst.testing.v1.AppTest.from_function initializes a simulated app from a function.from streamlit.testing.v1 import AppTest at = AppTest.from_function(app_script_as_callable) at.run() BlockA representation of container elements, including: st.chat_message st.columns st.sidebar st.tabs The main body of the app. # at.sidebar returns a Block at.sidebar.button[0].click().run() assert not at.exception ElementThe base class for representation of all elements, including: st.title st.header st.markdown st.dataframe # at.title returns a sequence of Title # Title inherits from Element assert at.title[0].value == ""My awesome app"" ButtonA representation of st.button and st.form_submit_button.at.button[0].click().run() ChatInputA representation of st.chat_input.at.chat_input[0].set_value(""What is Streamlit?"").run() CheckboxA representation of st.checkbox.at.checkbox[0].check().run() ColorPickerA representation of st.color_picker.at.color_picker[0].pick(""#FF4B4B"").run() DateInputA representation of st.date_input.release_date = datetime.date(2023, 10, 26) at.date_input[0].set_value(release_date).run() MultiselectA representation of st.multiselect.at.multiselect[0].select(""New York"").run() NumberInputA representation of st.number_input.at.number_input[0].increment().run() RadioA representation of st.radio.at.radio[0].set_value(""New York"").run() SelectSliderA representation of st.select_slider.at.select_slider[0].set_range(""A"",""C"").run() SelectboxA representation of st.selectbox.at.selectbox[0].select(""New York"").run() SliderA representation of st.slider.at.slider[0].set_range(2,5).run() TextAreaA representation of st.text_area.at.text_area[0].input(""Streamlit is awesome!"").run() TextInputA representation of st.text_input.at.text_input[0].input(""Streamlit"").run() TimeInputA representation of st.time_input.at.time_input[0].increment().run() ToggleA representation of st.toggle.at.toggle[0].set_value(""True"").run() Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration!Pandas ProfilingPandas profiling component for Streamlit. Created by @okld.df = pd.read_csv(""https://storage.googleapis.com/tf-datasets/titanic/train.csv"") pr = df.profile_report() st_profile_report(pr) Streamlit AceAce editor component for Streamlit. Created by @okld.from streamlit_ace import st_ace content = st_ace() content Streamlit AnalyticsTrack & visualize user interactions with your streamlit app. Created by @jrieke.import streamlit_analytics with streamlit_analytics.track(): st.text_input(""Write something"") Previous: ConceptsNext: Write and magicforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy" https://docs.streamlit.io/develop/concepts/architecture/app-chrome#settings,"DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsremoveCOREArchitecture & executionremoveRunning your appStreamlit's architectureThe app chromeCachingSession StateFormsFragmentsWidget behaviorMultipage appsaddApp designaddADDITIONALConnections and secretsaddCustom componentsaddConfiguration and themingaddApp testingaddAPI referenceaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Develop/Concepts/Architecture & execution/The app chromeThe app chrome Your Streamlit app has a few widgets in the top right to help you as you develop. These widgets also help your viewers as they use your app. We call this things “the app chrome”. The chrome includes a status area, toolbar, and app menu. Your app menu is configurable. By default, you can access developer options from the app menu when viewing an app locally or on Streamlit Community Cloud while logged into an account with administrative access. While viewing an app, click the icon in the upper-right corner to access the menu. Menu options The menu is split into two sections. The upper section contains options available to all viewers and the lower section contains options for developers. Read more about customizing this menu at the end of this page. Rerun You can manually trigger a rerun of your app by clicking ""Rerun"" from the app menu. This rerun will not reset your session. Your widget states and values stored in st.session_state will be preserved. As a shortcut, without opening the app menu, you can rerun your app by pressing ""R"" on your keyboard (if you aren't currently focused on an input element). Settings With the ""Settings"" option, you can control the appearance of your app while it is running. If viewing the app locally, you can set how your app responds to changes in your source code. See more about development flow in Basic concepts. You can also force your app to appear in wide mode, even if not set within the script using st.set_page_config. Theme settings After clicking ""Settings"" from the app menu, you can choose between ""Light"", ""Dark"", or ""Use system setting"" for the app's base theme. Click on ""Edit active theme"" to modify the theme, color-by-color. Print Click ""Print"" or use keyboard shortcuts (⌘+P or Ctrl+P) to open a print dialog. This option uses your browser's built-in print-to-pdf function. To modify the appearance of your print, you can do the following: Expand or collapse the sidebar before printing to respectively include or exclude it from the print. Resize the sidebar in your app by clicking and dragging its right border to achieve your desired width. You may need to enable ""Background graphics"" in your print dialog if you are printing in dark mode. You may need to disable wide mode in Settings or adjust the print scale to prevent elements from clipping off the page. Record a screencast You can easily make screen recordings right from your app! Screen recording is supported in the latest versions of Chrome, Edge, and Firefox. Ensure your browser is up-to-date for compatibility. Depending on your current settings, you may need to grant permission to your browser to record your screen or to use your microphone if recording a voiceover. While viewing your app, open the app menu from the upper-right corner. Click ""Record a screencast."" If you want to record audio through your microphone, check ""Also record audio."" Click ""Start recording."" (You may be prompted by your OS to permit your browser to record your screen or use your microphone.) Select which tab, window, or monitor you want to record from the listed options. The interface will vary depending on your browser. Click ""Share."" While recording, you will see a red circle on your app's tab and on the app menu icon. If you want to cancel the recording, click ""Stop sharing"" at the bottom of your app. When you are done recording, press ""Esc"" on your keyboard or click ""Stop recording"" from your app's menu. Follow your browser's instructions to save your recording. Your saved recording will be available where your browser saves downloads. The whole process looks like this: About You can conveniently check what version of Streamlit is running from the ""About"" option. Developers also have the option to customize the message shown here using st.set_page_config. Developer options By default, developer options only show when viewing an app locally or when viewing a Community Cloud app while logged in with administrative permission. You can customize the menu if you want to make these options available for all users. Clear cache Reset your app's cache by clicking ""Clear cache"" from the app's menu or by pressing ""C"" on your keyboard while not focused on an input element. This will remove all cached entries for @st.cache_data and @st.cache_resource. Deploy this app If you are running an app locally from within a git repo, you can deploy your app to Streamlit Community Cloud in a few easy clicks! Make sure your work has been pushed to your online GitHub repository before beginning. For the greatest convenience, make sure you have already created your Community Cloud account and are signed in. Click ""Deploy"" next to the app menu icon (more_vert). Click ""Deploy now"". You will be taken to Community Cloud's ""Deploy an app"" page. Your app's repository, branch, and file name will be prefilled to match your current app! Learn more about deploying an app on Streamlit Community Cloud. The whole process looks like this: Customize the menu Using client.toolbarMode in your app's configuration, you can make the app menu appear in the following ways: ""developer"" — Show the developer options to all viewers. ""viewer"" — Hide the developer options from all viewers. ""minimal"" — Show only those options set externally. These options can be declared through st.set_page_config or populated through Streamlit Community Cloud. ""auto"" — This is the default and will show the developer options when accessed through localhost or through Streamlit Community Cloud when logged into an administrative account for the app. Otherwise, the developer options will not show. Previous: Streamlit's architectureNext: CachingforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy" https://docs.streamlit.io/deploy/tutorials,"DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsremoveDockerKubernetesschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Deploy/Other platformsDeployment tutorials This sections contains step-by-step guides on how to deploy Streamlit apps to various cloud platforms and services. We have deployment guides for: Streamlit Community CloudDockerKubernetes While we work on official Streamlit deployment guides for other hosting providers, here are some user-submitted tutorials for different cloud services: How to Deploy Streamlit to a Free Amazon EC2 instance, by Rahul Agarwal. Host Streamlit on Azure, by Richard Peterson. How to deploy Streamlit apps to Google App Engine, by Yuichiro Tachibana (Tsuchiya). Host Streamlit on Heroku, by Maarten Grootendorst. Deploy Streamlit on Ploomber Cloud, by Ido Michael. Host Streamlit on 21YunBox, by Toby Lei. Community-supported deployment wiki. Previous: Streamlit in SnowflakeNext: DockerforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy" https://docs.streamlit.io/knowledge-base/deploy/organizing-apps-workspaces-streamlit-cloud#organization-workspace,"DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Knowledge base/Deployment issues/Organizing your apps with workspaces on Streamlit Community CloudOrganizing your apps with workspaces on Streamlit Community Cloud Streamlit Community Cloud is organized into workspaces, which automatically group your apps according to the corresponding GitHub repository's owner. If you are part of multiple repositories, then you will have multiple workspaces. Personal workspace If an app's GitHub repository is owned by you, the app will appear in your personal workspace, named """". Organization workspace If an app's GitHub repository is owned by an organization (such as your company), the app will appear in a separate workspace, named """". Workspaces with view access You will also have access to any workspaces containing app(s) for which you only have view access. These apps will have a ""view-only"" tooltip when you click on their respective overflow menu icons (⋮). Switching between workspaces To switch between workspaces, click on the workspace listed in the top right corner, then select the desired workspace name. push_pinNoteIf you have further questions about workspaces on Streamlit Community Cloud, please emails us at success@streamlit.io.Previous: Invoking a Python subprocess in a deployed Streamlit appNext: App is not loading when running remotelyforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy" https://docs.streamlit.io/develop/concepts/multipage-apps/pages-directory#naming-and-ordering-your-pages,"DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsremoveCOREArchitecture & executionaddMultipage appsremovePages directory (v1)App designaddADDITIONALConnections and secretsaddCustom componentsaddConfiguration and themingaddApp testingaddAPI referenceaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Develop/Concepts/Multipage apps/Pages directory (v1)Creating multipage apps using the pages/ directory As your app grows large, it becomes useful to organize your script into multiple pages. This makes your app easier to manage as a developer and easier to navigate as a user. Streamlit provides a frictionless way to create multipage apps. Pages are automatically shown in a navigation widget inside your app's sidebar. If a user clicks on a page in the sidebar, Streamlit navigates to that page without reloading the frontend — making app browsing incredibly fast! In this guide, let’s learn how to create multipage apps. Structuring your multipage app Streamlit identifies pages in a multipage app by directory structure and filenames. The file you pass to streamlit run is called your entrypoint file. This is your app's homepage. When you have a pages/ directory next to your entrypoint file, Streamlit will identify each Python file within it as a page. The following example has three pages. your_homepage.py is the entrypoint file and homepage. your_working_directory/ ├── pages/ │ ├── a_page.py │ └── another_page.py └── your_homepage.py Run your multipage app just like you would for a single-page app. Pass your entrypoint file to streamlit run. streamlit run your_homepage.py Only .py files in the pages/ directory will be identified as pages. Streamlit ignores all other files in the pages/ directory and its subdirectories. Streamlit also ignores Python files in subdirectories of pages/. Keep reading to learn how filenames are displayed and ordered in your app's navigation. Naming and ordering your pages The entrypoint file is your app's homepage and the first page users will see when visiting your app. Once you've added pages to your app, the entrypoint file appears as the topmost page in the sidebar. Streamlit determines the page label and ordering of each page from your filenames. Labels may differ from the page title set in st.set_page_config. Filenames for pages Filenames are composed of four different parts as follows: number. A non-negative integer. separator. Any combination of underscore (""_""), dash (""-""), and space ("" ""). label. Everything up to, but not including, "".py"". "".py"" How Streamlit converts filenames into page labels Streamlit displays page labels as follows: If your filename contains a label, Streamlit displays the label in the left navigation. Any underscores within the page's label are treated as spaces. If your filename contains a number but does not contain a label, Streamlit displays the number instead. If your filename contains only a separator with no number and no label, Streamlit will not display the page in the sidebar navigation. The following filenames would all display as ""Awesome homepage"" in the sidebar navigation. ""Awesome homepage.py"" ""Awesome_homepage.py"" ""02Awesome_homepage.py"" ""--Awesome_homepage.py"" ""1_Awesome_homepage.py"" ""33 - Awesome homepage.py"" How pages are sorted in the sidebar The entrypoint file is always displayed first. The remaining pages are sorted as follows: Files that have a number appear before files without a number. Files are sorted based on the number (if any), followed by the label (if any). When files are sorted, Streamlit treats the number as an actual number rather than a string. So 03 is the same as 3. This table shows examples of filenames and their corresponding labels, sorted by the order in which they appear in the sidebar. Examples: FilenameRendered label1 - first page.pyfirst page12 monkeys.pymonkeys123.py123123_hello_dear_world.pyhello dear world_12 monkeys.py12 monkeys starTipEmojis can be used to make your page names more fun! For example, a file named 🏠_Home.py will create a page titled ""🏠 Home"" in the sidebar. When adding emojis to filenames, it’s best practice to include a numbered prefix to make autocompletion in your terminal easier. Terminal-autocomplete can get confused by unicode (which is how emojis are represented). Navigating between pages Pages are automatically shown in a sidebar navigation UI. When a user clicks on a page in the sidebar UI, Streamlit navigates to that page without reloading the entire frontend — making app browsing incredibly fast! Optionally, you can hide the default navigation UI and build your own with st.page_link. For more information, see Build a custom navigation menu with st.page_link. If you need to programmatically switch pages, use st.switch_page. Users can also navigate between pages using URLs. Pages have their own URLs, defined by the file's label. When multiple files have the same label, Streamlit picks the first one (based on the ordering described above). Users can view a specific page by visiting the page's URL. priority_highImportantNavigating between pages by URL creates a new browser session and clears st.session_state. In particular, clicking markdown links to other pages resets st.session_state. In order to retain values in st.session_state, a user must use the sidebar navigation or other Streamlit widgets to switch pages. If a user tries to access a URL for a page that does not exist, they will see a modal like the one below, saying the user has requested a page that was not found in the app’s pages/ directory. Notes and limitations Pages support run-on-save. When you update a page while your app is running, this causes a rerun for users currently viewing that exact page. When you update a page while your app is running, the app will not automatically rerun for users currently viewing a different page. While your app is running, adding or deleting a page updates the sidebar navigation immediately. st.set_page_config works at the page level. When you set title or favicon using st.set_page_config, this applies to the current page only. When you set layout using st.set_page_config, the setting will remain for the session until changed by another call to st.set_page_config. If you use st.set_page_config to set layout, it's recommended to call it on all pages. Pages share the same Python modules globally: # page1.py import foo foo.hello = 123 # page2.py import foo st.write(foo.hello) # If page1 already executed, this writes 123 Pages share the same st.session_state: # page1.py import streamlit as st if ""shared"" not in st.session_state: st.session_state[""shared""] = True # page2.py import streamlit as st st.write(st.session_state[""shared""]) # If page1 already executed, this writes True You now have a solid understanding of multipage apps. You've learned how to structure apps, define pages, and navigate between pages in the user interface. It's time to create your first multipage app! 🥳Previous: Multipage appsNext: App designforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy" https://docs.streamlit.io/en/0.72.0/api.html#build-your-own-connections,"DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceremovePAGE ELEMENTSWrite and magicaddText elementsaddData elementsaddChart elementsaddInput widgetsaddMedia elementsaddLayouts and containersaddChat elementsaddStatus elementsaddThird-party componentsopen_in_newAPPLICATION LOGICNavigation and pagesaddExecution flowaddCaching and stateaddConnections and secretsaddCustom componentsaddUtilitiesaddConfigurationaddTOOLSApp testingaddCommand lineaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Develop/API referenceAPI reference Streamlit makes it easy for you to visualize, mutate, and share data. The API reference is organized by activity type, like displaying data or optimizing performance. Each section includes methods associated with the activity type, including examples. Browse our API below and click to learn more about any of our available commands! 🎈 Display almost anything Write and magic st.writeWrite arguments to the app.st.write(""Hello **world**!"") st.write(my_data_frame) st.write(my_mpl_figure) st.write_streamWrite generators or streams to the app with a typewriter effect.st.write_stream(my_generator) st.write_stream(my_llm_stream) MagicAny time Streamlit sees either a variable or literal value on its own line, it automatically writes that to your app using st.write""Hello **world**!"" my_data_frame my_mpl_figure Text elements MarkdownDisplay string formatted as Markdown.st.markdown(""Hello **world**!"") TitleDisplay text in title formatting.st.title(""The app title"") HeaderDisplay text in header formatting.st.header(""This is a header"") SubheaderDisplay text in subheader formatting.st.subheader(""This is a subheader"") CaptionDisplay text in small font.st.caption(""This is written small caption text"") Code blockDisplay a code block with optional syntax highlighting.st.code(""a = 1234"") EchoDisplay some code in the app, then execute it. Useful for tutorials.with st.echo(): st.write('This code will be printed') LaTeXDisplay mathematical expressions formatted as LaTeX.st.latex(""\int a x^2 \,dx"") Preformatted textWrite fixed-width and preformatted text.st.text(""Hello world"") DividerDisplay a horizontal rule.st.divider() Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration! PreviousTagsAdd tags to your Streamlit apps. Created by @gagan3012.st_tags(label='# Enter Keywords:', text='Press enter to add more', value=['Zero', 'One', 'Two'], suggestions=['five', 'six', 'seven', 'eight', 'nine', 'three', 'eleven', 'ten', 'four'], maxtags = 4, key='1') NLUApply text mining on a dataframe. Created by @JohnSnowLabs.nlu.load('sentiment').predict('I love NLU! <3') Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.mention(label=""An awesome Streamlit App"", icon=""streamlit"", url=""https://extras.streamlit.app"",) Annotated textDisplay annotated text in Streamlit apps. Created by @tvst.annotated_text(""This "", (""is"", ""verb""), "" some "", (""annotated"", ""adj""), (""text"", ""noun""), "" for those of "", (""you"", ""pronoun""), "" who "", (""like"", ""verb""), "" this sort of "", (""thing"", ""noun""), ""."") Drawable CanvasProvides a sketching canvas using Fabric.js. Created by @andfanilo.st_canvas(fill_color=""rgba(255, 165, 0, 0.3)"", stroke_width=stroke_width, stroke_color=stroke_color, background_color=bg_color, background_image=Image.open(bg_image) if bg_image else None, update_streamlit=realtime_update, height=150, drawing_mode=drawing_mode, point_display_radius=point_display_radius if drawing_mode == 'point' else 0, key=""canvas"",) TagsAdd tags to your Streamlit apps. Created by @gagan3012.st_tags(label='# Enter Keywords:', text='Press enter to add more', value=['Zero', 'One', 'Two'], suggestions=['five', 'six', 'seven', 'eight', 'nine', 'three', 'eleven', 'ten', 'four'], maxtags = 4, key='1') NLUApply text mining on a dataframe. Created by @JohnSnowLabs.nlu.load('sentiment').predict('I love NLU! <3') Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.mention(label=""An awesome Streamlit App"", icon=""streamlit"", url=""https://extras.streamlit.app"",) Annotated textDisplay annotated text in Streamlit apps. Created by @tvst.annotated_text(""This "", (""is"", ""verb""), "" some "", (""annotated"", ""adj""), (""text"", ""noun""), "" for those of "", (""you"", ""pronoun""), "" who "", (""like"", ""verb""), "" this sort of "", (""thing"", ""noun""), ""."") Drawable CanvasProvides a sketching canvas using Fabric.js. Created by @andfanilo.st_canvas(fill_color=""rgba(255, 165, 0, 0.3)"", stroke_width=stroke_width, stroke_color=stroke_color, background_color=bg_color, background_image=Image.open(bg_image) if bg_image else None, update_streamlit=realtime_update, height=150, drawing_mode=drawing_mode, point_display_radius=point_display_radius if drawing_mode == 'point' else 0, key=""canvas"",) TagsAdd tags to your Streamlit apps. Created by @gagan3012.st_tags(label='# Enter Keywords:', text='Press enter to add more', value=['Zero', 'One', 'Two'], suggestions=['five', 'six', 'seven', 'eight', 'nine', 'three', 'eleven', 'ten', 'four'], maxtags = 4, key='1') NLUApply text mining on a dataframe. Created by @JohnSnowLabs.nlu.load('sentiment').predict('I love NLU! <3') Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.mention(label=""An awesome Streamlit App"", icon=""streamlit"", url=""https://extras.streamlit.app"",) Next Data elements DataframesDisplay a dataframe as an interactive table.st.dataframe(my_data_frame) Data editorDisplay a data editor widget.edited = st.data_editor(df, num_rows=""dynamic"") Column configurationConfigure the display and editing behavior of dataframes and data editors.st.column_config.NumberColumn(""Price (in USD)"", min_value=0, format=""$%d"") Static tablesDisplay a static table.st.table(my_data_frame) MetricsDisplay a metric in big bold font, with an optional indicator of how the metric changed.st.metric(""My metric"", 42, 2) Dicts and JSONDisplay object or string as a pretty-printed JSON string.st.json(my_dict) Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration! PreviousImage CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates value = streamlit_image_coordinates(""https://placekitten.com/200/300"") st.write(value) Plotly EventsMake Plotly charts interactive!. Created by @null-jones.from streamlit_plotly_events import plotly_events fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.metric_cards import style_metric_cards col3.metric(label=""No Change"", value=5000, delta=0) style_metric_cards() Streamlit AggridImplementation of Ag-Grid component for Streamlit. Created by @PablocFonseca.df = pd.DataFrame({'col1': [1, 2, 3], 'col2': [4, 5, 6]}) grid_return = AgGrid(df, editable=True) new_df = grid_return['data'] Streamlit FoliumStreamlit Component for rendering Folium maps. Created by @randyzwitch.m = folium.Map(location=[39.949610, -75.150282], zoom_start=16) folium.Marker([39.949610, -75.150282], popup=""Liberty Bell"", tooltip=""Liberty Bell"").add_to(m) st_data = st_folium(m, width=725) Pandas ProfilingPandas profiling component for Streamlit. Created by @okld.df = pd.read_csv(""https://storage.googleapis.com/tf-datasets/titanic/train.csv"") pr = df.profile_report() st_profile_report(pr) Image CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates value = streamlit_image_coordinates(""https://placekitten.com/200/300"") st.write(value) Plotly EventsMake Plotly charts interactive!. Created by @null-jones.from streamlit_plotly_events import plotly_events fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.metric_cards import style_metric_cards col3.metric(label=""No Change"", value=5000, delta=0) style_metric_cards() Streamlit AggridImplementation of Ag-Grid component for Streamlit. Created by @PablocFonseca.df = pd.DataFrame({'col1': [1, 2, 3], 'col2': [4, 5, 6]}) grid_return = AgGrid(df, editable=True) new_df = grid_return['data'] Streamlit FoliumStreamlit Component for rendering Folium maps. Created by @randyzwitch.m = folium.Map(location=[39.949610, -75.150282], zoom_start=16) folium.Marker([39.949610, -75.150282], popup=""Liberty Bell"", tooltip=""Liberty Bell"").add_to(m) st_data = st_folium(m, width=725) Pandas ProfilingPandas profiling component for Streamlit. Created by @okld.df = pd.read_csv(""https://storage.googleapis.com/tf-datasets/titanic/train.csv"") pr = df.profile_report() st_profile_report(pr) Image CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates value = streamlit_image_coordinates(""https://placekitten.com/200/300"") st.write(value) Plotly EventsMake Plotly charts interactive!. Created by @null-jones.from streamlit_plotly_events import plotly_events fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.metric_cards import style_metric_cards col3.metric(label=""No Change"", value=5000, delta=0) style_metric_cards() Next Chart elements Simple area chartsDisplay an area chart.st.area_chart(my_data_frame) Simple bar chartsDisplay a bar chart.st.bar_chart(my_data_frame) Simple line chartsDisplay a line chart.st.line_chart(my_data_frame) Simple scatter chartsDisplay a line chart.st.scatter_chart(my_data_frame) Scatterplots on mapsDisplay a map with points on it.st.map(my_data_frame) MatplotlibDisplay a matplotlib.pyplot figure.st.pyplot(my_mpl_figure) AltairDisplay a chart using the Altair library.st.altair_chart(my_altair_chart) Vega-LiteDisplay a chart using the Vega-Lite library.st.vega_lite_chart(my_vega_lite_chart) PlotlyDisplay an interactive Plotly chart.st.plotly_chart(my_plotly_chart) BokehDisplay an interactive Bokeh chart.st.bokeh_chart(my_bokeh_chart) PyDeckDisplay a chart using the PyDeck library.st.pydeck_chart(my_pydeck_chart) GraphVizDisplay a graph using the dagre-d3 library.st.graphviz_chart(my_graphviz_spec) Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration! PreviousStreamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl(""https://assets5.lottiefiles.com/packages/lf20_V9t630.json"") st_lottie(lottie_hello, key=""hello"") Plotly EventsMake Plotly charts interactive!. Created by @null-jones.fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.chart += get_annotations_chart(annotations=[(""Mar 01, 2008"", ""Pretty good day for GOOG""), (""Dec 01, 2007"", ""Something's going wrong for GOOG & AAPL""), (""Nov 01, 2008"", ""Market starts again thanks to...""), (""Dec 01, 2009"", ""Small crash for GOOG after...""),],) st.altair_chart(chart, use_container_width=True) PlostA deceptively simple plotting library for Streamlit. Created by @tvst.import plost plost.line_chart(my_dataframe, x='time', y='stock_value', color='stock_name',) HiPlotHigh dimensional Interactive Plotting. Created by @facebookresearch.data = [{'dropout':0.1, 'lr': 0.001, 'loss': 10.0, 'optimizer': 'SGD'}, {'dropout':0.15, 'lr': 0.01, 'loss': 3.5, 'optimizer': 'Adam'}, {'dropout':0.3, 'lr': 0.1, 'loss': 4.5, 'optimizer': 'Adam'}] hip.Experiment.from_iterable(data).display() EChartsHigh dimensional Interactive Plotting. Created by @andfanilo.from streamlit_echarts import st_echarts st_echarts(options=options) Streamlit FoliumStreamlit Component for rendering Folium maps. Created by @randyzwitch.m = folium.Map(location=[39.949610, -75.150282], zoom_start=16) st_data = st_folium(m, width=725) Spacy-StreamlitspaCy building blocks and visualizers for Streamlit apps. Created by @explosion.models = [""en_core_web_sm"", ""en_core_web_md""] spacy_streamlit.visualize(models, ""Sundar Pichai is the CEO of Google."") Streamlit AgraphA Streamlit Graph Vis, based on react-grah-vis. Created by @ChrisDelClea.from streamlit_agraph import agraph, Node, Edge, Config agraph(nodes=nodes, edges=edges, config=config) Streamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl(""https://assets5.lottiefiles.com/packages/lf20_V9t630.json"") st_lottie(lottie_hello, key=""hello"") Plotly EventsMake Plotly charts interactive!. Created by @null-jones.fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.chart += get_annotations_chart(annotations=[(""Mar 01, 2008"", ""Pretty good day for GOOG""), (""Dec 01, 2007"", ""Something's going wrong for GOOG & AAPL""), (""Nov 01, 2008"", ""Market starts again thanks to...""), (""Dec 01, 2009"", ""Small crash for GOOG after...""),],) st.altair_chart(chart, use_container_width=True) PlostA deceptively simple plotting library for Streamlit. Created by @tvst.import plost plost.line_chart(my_dataframe, x='time', y='stock_value', color='stock_name',) HiPlotHigh dimensional Interactive Plotting. Created by @facebookresearch.data = [{'dropout':0.1, 'lr': 0.001, 'loss': 10.0, 'optimizer': 'SGD'}, {'dropout':0.15, 'lr': 0.01, 'loss': 3.5, 'optimizer': 'Adam'}, {'dropout':0.3, 'lr': 0.1, 'loss': 4.5, 'optimizer': 'Adam'}] hip.Experiment.from_iterable(data).display() EChartsHigh dimensional Interactive Plotting. Created by @andfanilo.from streamlit_echarts import st_echarts st_echarts(options=options) Streamlit FoliumStreamlit Component for rendering Folium maps. Created by @randyzwitch.m = folium.Map(location=[39.949610, -75.150282], zoom_start=16) st_data = st_folium(m, width=725) Spacy-StreamlitspaCy building blocks and visualizers for Streamlit apps. Created by @explosion.models = [""en_core_web_sm"", ""en_core_web_md""] spacy_streamlit.visualize(models, ""Sundar Pichai is the CEO of Google."") Streamlit AgraphA Streamlit Graph Vis, based on react-grah-vis. Created by @ChrisDelClea.from streamlit_agraph import agraph, Node, Edge, Config agraph(nodes=nodes, edges=edges, config=config) Streamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl(""https://assets5.lottiefiles.com/packages/lf20_V9t630.json"") st_lottie(lottie_hello, key=""hello"") Plotly EventsMake Plotly charts interactive!. Created by @null-jones.fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.chart += get_annotations_chart(annotations=[(""Mar 01, 2008"", ""Pretty good day for GOOG""), (""Dec 01, 2007"", ""Something's going wrong for GOOG & AAPL""), (""Nov 01, 2008"", ""Market starts again thanks to...""), (""Dec 01, 2009"", ""Small crash for GOOG after...""),],) st.altair_chart(chart, use_container_width=True) Next Input widgets ButtonDisplay a button widget.clicked = st.button(""Click me"") Download buttonDisplay a download button widget.st.download_button(""Download file"", file) Form buttonDisplay a form submit button. For use with st.form.st.form_submit_button(""Sign up"") Link buttonDisplay a link button.st.link_button(""Go to gallery"", url) Page linkDisplay a link to another page in a multipage app.st.page_link(""app.py"", label=""Home"", icon=""🏠"") st.page_link(""pages/profile.py"", label=""My profile"") CheckboxDisplay a checkbox widget.selected = st.checkbox(""I agree"") Color pickerDisplay a color picker widget.color = st.color_picker(""Pick a color"") MultiselectDisplay a multiselect widget. The multiselect widget starts as empty.choices = st.multiselect(""Buy"", [""milk"", ""apples"", ""potatoes""]) RadioDisplay a radio button widget.choice = st.radio(""Pick one"", [""cats"", ""dogs""]) SelectboxDisplay a select widget.choice = st.selectbox(""Pick one"", [""cats"", ""dogs""]) Select-sliderDisplay a slider widget to select items from a list.size = st.select_slider(""Pick a size"", [""S"", ""M"", ""L""]) ToggleDisplay a toggle widget.activated = st.toggle(""Activate"") Number inputDisplay a numeric input widget.choice = st.number_input(""Pick a number"", 0, 10) SliderDisplay a slider widget.number = st.slider(""Pick a number"", 0, 100) Date inputDisplay a date input widget.date = st.date_input(""Your birthday"") Time inputDisplay a time input widget.time = st.time_input(""Meeting time"") Chat inputDisplay a chat input widget.prompt = st.chat_input(""Say something"") if prompt: st.write(f""The user has sent: {prompt}"") Text-areaDisplay a multi-line text input widget.text = st.text_area(""Text to translate"") Text inputDisplay a single-line text input widget.name = st.text_input(""First name"") Data editorDisplay a data editor widget.edited = st.experimental_data_editor(df, num_rows=""dynamic"") File UploaderDisplay a file uploader widget.data = st.file_uploader(""Upload a CSV"") Camera inputDisplay a widget that allows users to upload images directly from a camera.image = st.camera_input(""Take a picture"") Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration! PreviousStreamlit ChatStreamlit Component for a Chatbot UI. Created by @AI-Yash.from streamlit_chat import message message(""My message"") message(""Hello bot!"", is_user=True) # align's the message to the right Streamlit Option MenuSelect a single item from a list of options in a menu. Created by @victoryhb.from streamlit_option_menu import option_menu option_menu(""Main Menu"", [""Home"", 'Settings'], icons=['house', 'gear'], menu_icon=""cast"", default_index=1) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.stoggle import stoggle stoggle( ""Click me!"", """"""🥷 Surprise! Here's some additional content"""""",) Streamlit ElementsCreate a draggable and resizable dashboard in Streamlit. Created by @okls.from streamlit_elements import elements, mui, html with elements(""new_element""): mui.Typography(""Hello world"") TagsAdd tags to your Streamlit apps. Created by @gagan3012.from streamlit_tags import st_tags st_tags(label='# Enter Keywords:', text='Press enter to add more', value=['Zero', 'One', 'Two'], suggestions=['five', 'six', 'seven', 'eight', 'nine', 'three', 'eleven', 'ten', 'four'], maxtags = 4, key='1') StqdmThe simplest way to handle a progress bar in streamlit app. Created by @Wirg.from stqdm import stqdm for _ in stqdm(range(50)): sleep(0.5) TimelineDisplay a Timeline in Streamlit apps using TimelineJS. Created by @innerdoc.from streamlit_timeline import timeline with open('example.json', ""r"") as f: timeline(f.read(), height=800) Camera input liveAlternative for st.camera_input which returns the webcam images live. Created by @blackary.from camera_input_live import camera_input_live image = camera_input_live() st.image(value) Streamlit AceAce editor component for Streamlit. Created by @okld.from streamlit_ace import st_ace content = st_ace() content Streamlit ChatStreamlit Component for a Chatbot UI. Created by @AI-Yash.from streamlit_chat import message message(""My message"") message(""Hello bot!"", is_user=True) # align's the message to the right Streamlit Option MenuSelect a single item from a list of options in a menu. Created by @victoryhb.from streamlit_option_menu import option_menu option_menu(""Main Menu"", [""Home"", 'Settings'], icons=['house', 'gear'], menu_icon=""cast"", default_index=1) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.stoggle import stoggle stoggle( ""Click me!"", """"""🥷 Surprise! Here's some additional content"""""",) Streamlit ElementsCreate a draggable and resizable dashboard in Streamlit. Created by @okls.from streamlit_elements import elements, mui, html with elements(""new_element""): mui.Typography(""Hello world"") TagsAdd tags to your Streamlit apps. Created by @gagan3012.from streamlit_tags import st_tags st_tags(label='# Enter Keywords:', text='Press enter to add more', value=['Zero', 'One', 'Two'], suggestions=['five', 'six', 'seven', 'eight', 'nine', 'three', 'eleven', 'ten', 'four'], maxtags = 4, key='1') StqdmThe simplest way to handle a progress bar in streamlit app. Created by @Wirg.from stqdm import stqdm for _ in stqdm(range(50)): sleep(0.5) TimelineDisplay a Timeline in Streamlit apps using TimelineJS. Created by @innerdoc.from streamlit_timeline import timeline with open('example.json', ""r"") as f: timeline(f.read(), height=800) Camera input liveAlternative for st.camera_input which returns the webcam images live. Created by @blackary.from camera_input_live import camera_input_live image = camera_input_live() st.image(value) Streamlit AceAce editor component for Streamlit. Created by @okld.from streamlit_ace import st_ace content = st_ace() content Streamlit ChatStreamlit Component for a Chatbot UI. Created by @AI-Yash.from streamlit_chat import message message(""My message"") message(""Hello bot!"", is_user=True) # align's the message to the right Streamlit Option MenuSelect a single item from a list of options in a menu. Created by @victoryhb.from streamlit_option_menu import option_menu option_menu(""Main Menu"", [""Home"", 'Settings'], icons=['house', 'gear'], menu_icon=""cast"", default_index=1) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.stoggle import stoggle stoggle( ""Click me!"", """"""🥷 Surprise! Here's some additional content"""""",) Next Media elements ImageDisplay an image or list of images.st.image(numpy_array) st.image(image_bytes) st.image(file) st.image(""https://example.com/myimage.jpg"") AudioDisplay an audio player.st.audio(numpy_array) st.audio(audio_bytes) st.audio(file) st.audio(""https://example.com/myaudio.mp3"", format=""audio/mp3"") VideoDisplay a video player.st.video(numpy_array) st.video(video_bytes) st.video(file) st.video(""https://example.com/myvideo.mp4"", format=""video/mp4"") Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration! PreviousStreamlit CropperA simple image cropper for Streamlit. Created by @turner-anderson.from streamlit_cropper import st_cropper st_cropper(img, realtime_update=realtime_update, box_color=box_color, aspect_ratio=aspect_ratio) Image CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates streamlit_image_coordinates(""https://placekitten.com/200/300"") Streamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl(""https://assets5.lottiefiles.com/packages/lf20_V9t630.json"") st_lottie(lottie_hello, key=""hello"") Streamlit WebrtcHandling and transmitting real-time video/audio streams with Streamlit. Created by @whitphx.from streamlit_webrtc import webrtc_streamer webrtc_streamer(key=""sample"") Drawable CanvasProvides a sketching canvas using Fabric.js. Created by @andfanilo.from streamlit_drawable_canvas import st_canvas st_canvas(fill_color=""rgba(255, 165, 0, 0.3)"", stroke_width=stroke_width, stroke_color=stroke_color, background_color=bg_color, background_image=Image.open(bg_image) if bg_image else None, update_streamlit=realtime_update, height=150, drawing_mode=drawing_mode, point_display_radius=point_display_radius if drawing_mode == 'point' else 0, key=""canvas"",) Image ComparisonCompare images with a slider using JuxtaposeJS. Created by @fcakyon.from streamlit_image_comparison import image_comparison image_comparison(img1=""image1.jpg"", img2=""image2.jpg"",) Streamlit CropperA simple image cropper for Streamlit. Created by @turner-anderson.from streamlit_cropper import st_cropper st_cropper(img, realtime_update=realtime_update, box_color=box_color, aspect_ratio=aspect_ratio) Image CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates streamlit_image_coordinates(""https://placekitten.com/200/300"") Streamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl(""https://assets5.lottiefiles.com/packages/lf20_V9t630.json"") st_lottie(lottie_hello, key=""hello"") Streamlit WebrtcHandling and transmitting real-time video/audio streams with Streamlit. Created by @whitphx.from streamlit_webrtc import webrtc_streamer webrtc_streamer(key=""sample"") Drawable CanvasProvides a sketching canvas using Fabric.js. Created by @andfanilo.from streamlit_drawable_canvas import st_canvas st_canvas(fill_color=""rgba(255, 165, 0, 0.3)"", stroke_width=stroke_width, stroke_color=stroke_color, background_color=bg_color, background_image=Image.open(bg_image) if bg_image else None, update_streamlit=realtime_update, height=150, drawing_mode=drawing_mode, point_display_radius=point_display_radius if drawing_mode == 'point' else 0, key=""canvas"",) Image ComparisonCompare images with a slider using JuxtaposeJS. Created by @fcakyon.from streamlit_image_comparison import image_comparison image_comparison(img1=""image1.jpg"", img2=""image2.jpg"",) Streamlit CropperA simple image cropper for Streamlit. Created by @turner-anderson.from streamlit_cropper import st_cropper st_cropper(img, realtime_update=realtime_update, box_color=box_color, aspect_ratio=aspect_ratio) Image CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates streamlit_image_coordinates(""https://placekitten.com/200/300"") Streamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl(""https://assets5.lottiefiles.com/packages/lf20_V9t630.json"") st_lottie(lottie_hello, key=""hello"") Next Layouts and containers ColumnsInsert containers laid out as side-by-side columns.col1, col2 = st.columns(2) col1.write(""this is column 1"") col2.write(""this is column 2"") ContainerInsert a multi-element container.c = st.container() st.write(""This will show last"") c.write(""This will show first"") c.write(""This will show second"") Modal dialogsInsert a modal dialog that can rerun independently from the rest of the script.@st.experimental_dialog(""Sign up"") def email_form(): name = st.text_input(""Name"") email = st.text_input(""Email"") EmptyInsert a single-element container.c = st.empty() st.write(""This will show last"") c.write(""This will be replaced"") c.write(""This will show first"") ExpanderInsert a multi-element container that can be expanded/collapsed.with st.expander(""Open to see more""): st.write(""This is more content"") PopoverInsert a multi-element popover container that can be opened/closed.with st.popover(""Settings""): st.checkbox(""Show completed"") SidebarDisplay items in a sidebar.st.sidebar.write(""This lives in the sidebar"") st.sidebar.button(""Click me!"") TabsInsert containers separated into tabs.tab1, tab2 = st.tabs([""Tab 1"", ""Tab2""]) tab1.write(""this is tab 1"") tab2.write(""this is tab 2"") Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration!Streamlit ElementsCreate a draggable and resizable dashboard in Streamlit. Created by @okls.from streamlit_elements import elements, mui, html with elements(""new_element""): mui.Typography(""Hello world"") PydanticAuto-generate Streamlit UI from Pydantic Models and Dataclasses. Created by @lukasmasuch.import streamlit_pydantic as sp sp.pydantic_form(key=""my_form"", model=ExampleModel) Streamlit PagesAn experimental version of Streamlit Multi-Page Apps. Created by @blackary.from st_pages import Page, show_pages, add_page_title show_pages([ Page(""streamlit_app.py"", ""Home"", ""🏠""), Page(""other_pages/page2.py"", ""Page 2"", "":books:""), ]) Chat elements Streamlit provides a few commands to help you build conversational apps. These chat elements are designed to be used in conjunction with each other, but you can also use them separately. st.chat_message lets you insert a chat message container into the app so you can display messages from the user or the app. Chat containers can contain other Streamlit elements, including charts, tables, text, and more. st.chat_input lets you display a chat input widget so the user can type in a message. Chat inputDisplay a chat input widget.prompt = st.chat_input(""Say something"") if prompt: st.write(f""The user has sent: {prompt}"") Chat messageInsert a chat message container.import numpy as np with st.chat_message(""user""): st.write(""Hello 👋"") st.line_chart(np.random.randn(30, 3)) Status containerDisplay output of long-running tasks in a container.with st.status('Running'): do_something_slow() st.write_streamWrite generators or streams to the app with a typewriter effect.st.write_stream(my_generator) st.write_stream(my_llm_stream) Status elements Progress barDisplay a progress bar.for i in range(101): st.progress(i) do_something_slow() SpinnerTemporarily displays a message while executing a block of code.with st.spinner(""Please wait...""): do_something_slow() Status containerDisplay output of long-running tasks in a container.with st.status('Running'): do_something_slow() ToastBriefly displays a toast message in the bottom-right corner.st.toast('Butter!', icon='🧈') BalloonsDisplay celebratory balloons!do_something() # Celebrate when all done! st.balloons() SnowflakesDisplay celebratory snowflakes!do_something() # Celebrate when all done! st.snow() Success boxDisplay a success message.st.success(""Match found!"") Info boxDisplay an informational message.st.info(""Dataset is updated every day at midnight."") Warning boxDisplay warning message.st.warning(""Unable to fetch image. Skipping..."") Error boxDisplay error message.st.error(""We encountered an error"") Exception outputDisplay an exception.e = RuntimeError(""This is an exception of type RuntimeError"") st.exception(e) Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration!StqdmThe simplest way to handle a progress bar in streamlit app. Created by @Wirg.from stqdm import stqdm for _ in stqdm(range(50)): sleep(0.5) Custom notification boxA custom notification box with the ability to close it out. Created by @Socvest.from streamlit_custom_notification_box import custom_notification_box styles = {'material-icons':{'color': 'red'}, 'text-icon-link-close-container': {'box-shadow': '#3896de 0px 4px'}, 'notification-text': {'':''}, 'close-button':{'':''}, 'link':{'':''}} custom_notification_box(icon='info', textDisplay='We are almost done with your registration...', externalLink='more info', url='#', styles=styles, key=""foo"") Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.let_it_rain import rain rain(emoji=""🎈"", font_size=54, falling_speed=5, animation_length=""infinite"",) App logic and configuration Navigation and pages Switch pageProgrammatically navigates to a specified page.st.switch_page(""pages/my_page.py"") Page linkDisplay a link to another page in a multipage app.st.page_link(""app.py"", label=""Home"", icon=""🏠"") st.page_link(""pages/profile.py"", label=""My profile"") Execution flow Modal dialogsInsert a modal dialog that can rerun independently from the rest of the script.@st.experimental_dialog(""Sign up"") def email_form(): name = st.text_input(""Name"") email = st.text_input(""Email"") FormsCreate a form that batches elements together with a “Submit"" button.with st.form(key='my_form'): name = st.text_input(""Name"") email = st.text_input(""Email"") st.form_submit_button(""Sign up"") Partial rerunsDefine a fragment to rerun independently from the rest of the script.@st.experimental_fragment(run_every=""10s"") def fragment(): df = get_data() st.line_chart(df) Rerun scriptRerun the script immediately.st.rerun() Stop executionStops execution immediately.st.stop() Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration!AutorefreshForce a refresh without tying up a script. Created by @kmcgrady.from streamlit_autorefresh import st_autorefresh st_autorefresh(interval=2000, limit=100, key=""fizzbuzzcounter"") PydanticAuto-generate Streamlit UI from Pydantic Models and Dataclasses. Created by @lukasmasuch.import streamlit_pydantic as sp sp.pydantic_form(key=""my_form"", model=ExampleModel) Streamlit PagesAn experimental version of Streamlit Multi-Page Apps. Created by @blackary.from st_pages import Page, show_pages, add_page_title show_pages([ Page(""streamlit_app.py"", ""Home"", ""🏠""), Page(""other_pages/page2.py"", ""Page 2"", "":books:""), ]) Caching and state Cache dataFunction decorator to cache functions that return data (e.g. dataframe transforms, database queries, ML inference).@st.cache_data def long_function(param1, param2): # Perform expensive computation here or # fetch data from the web here return data Cache resourceFunction decorator to cache functions that return global resources (e.g. database connections, ML models).@st.cache_resource def init_model(): # Return a global resource here return pipeline( ""sentiment-analysis"", model=""distilbert-base-uncased-finetuned-sst-2-english"" ) Session stateSession state is a way to share variables between reruns, for each user session.st.session_state['key'] = value Query parametersGet, set, or clear the query parameters that are shown in the browser's URL bar.st.query_params[key] = value st.query_params.clear() Connections and databases Setup your connection Create a connectionConnect to a data source or APIconn = st.connection('pets_db', type='sql') pet_owners = conn.query('select * from pet_owners') st.dataframe(pet_owners) Built-in connections SnowflakeConnectionA connection to Snowflake.conn = st.connection('snowflake') SQLConnectionA connection to a SQL database using SQLAlchemy.conn = st.connection('sql') Build your own connections Connection base classBuild your own connection with BaseConnection.class MyConnection(BaseConnection[myconn.MyConnection]): def _connect(self, **kwargs) -> MyConnection: return myconn.connect(**self._secrets, **kwargs) def query(self, query): return self._instance.query(query) Secrets management Secrets singletonAccess secrets from a local TOML file.key = st.secrets[""OpenAI_key""] Secrets fileSave your secrets in a per-project or per-profile TOML file.OpenAI_key = """" Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration!AuthenticatorA secure authentication module to validate user credentials. Created by @mkhorasani.import streamlit_authenticator as stauth authenticator = stauth.Authenticate( config['credentials'], config['cookie']['name'], config['cookie']['key'], config['cookie']['expiry_days'], config['preauthorized']) WS localStorageA simple synchronous way of accessing localStorage from your app. Created by @gagangoku.from streamlit_ws_localstorage import injectWebsocketCode ret = conn.setLocalStorageVal(key='k1', val='v1') st.write('ret: ' + ret) Streamlit Auth0The fastest way to provide comprehensive login inside Streamlit. Created by @conradbez.from auth0_component import login_button user_info = login_button(clientId, domain = domain) st.write(user_info) Custom Components Declare a componentCreate and register a custom component.st.components.v1.declare_component( ""custom_slider"", ""/frontend"", ) HTMLDisplay an HTML string in an iframe.st.components.v1.html( ""

Foo bar.

"" ) iframeLoad a remote URL in an iframe.st.components.v1.iframe( ""docs.streamlit.io"" ) Utilities and user info User infost.experimental_user returns information about the logged-in user of private apps on Streamlit Community Cloud.if st.experimental_user.email == ""foo@corp.com"": st.write(""Welcome back, "", st.experimental_user.email) else: st.write(""You are not authorized to view this page."") Get helpDisplay object’s doc string, nicely formatted.st.help(st.write) st.help(pd.DataFrame) Render HTMLRenders HTML strings to your app.css = """""" """""" st.html(css) Configuration Configuration fileConfigures the default settings for your app.your-project/ ├── .streamlit/ │ └── config.toml └── your_app.py Set page title, favicon, and moreConfigures the default settings of the page.st.set_page_config( page_title=""My app"", page_icon="":shark:"", ) Developer tools App testing st.testing.v1.AppTestst.testing.v1.AppTest simulates a running Streamlit app for testing.from streamlit.testing.v1 import AppTest at = AppTest.from_file(""streamlit_app.py"") at.secrets[""WORD""] = ""Foobar"" at.run() assert not at.exception at.text_input(""word"").input(""Bazbat"").run() assert at.warning[0].value == ""Try again."" AppTest.from_filest.testing.v1.AppTest.from_file initializes a simulated app from a file.from streamlit.testing.v1 import AppTest at = AppTest.from_file(""streamlit_app.py"") at.run() AppTest.from_stringst.testing.v1.AppTest.from_string initializes a simulated app from a string.from streamlit.testing.v1 import AppTest at = AppTest.from_string(app_script_as_string) at.run() AppTest.from_functionst.testing.v1.AppTest.from_function initializes a simulated app from a function.from streamlit.testing.v1 import AppTest at = AppTest.from_function(app_script_as_callable) at.run() BlockA representation of container elements, including: st.chat_message st.columns st.sidebar st.tabs The main body of the app. # at.sidebar returns a Block at.sidebar.button[0].click().run() assert not at.exception ElementThe base class for representation of all elements, including: st.title st.header st.markdown st.dataframe # at.title returns a sequence of Title # Title inherits from Element assert at.title[0].value == ""My awesome app"" ButtonA representation of st.button and st.form_submit_button.at.button[0].click().run() ChatInputA representation of st.chat_input.at.chat_input[0].set_value(""What is Streamlit?"").run() CheckboxA representation of st.checkbox.at.checkbox[0].check().run() ColorPickerA representation of st.color_picker.at.color_picker[0].pick(""#FF4B4B"").run() DateInputA representation of st.date_input.release_date = datetime.date(2023, 10, 26) at.date_input[0].set_value(release_date).run() MultiselectA representation of st.multiselect.at.multiselect[0].select(""New York"").run() NumberInputA representation of st.number_input.at.number_input[0].increment().run() RadioA representation of st.radio.at.radio[0].set_value(""New York"").run() SelectSliderA representation of st.select_slider.at.select_slider[0].set_range(""A"",""C"").run() SelectboxA representation of st.selectbox.at.selectbox[0].select(""New York"").run() SliderA representation of st.slider.at.slider[0].set_range(2,5).run() TextAreaA representation of st.text_area.at.text_area[0].input(""Streamlit is awesome!"").run() TextInputA representation of st.text_input.at.text_input[0].input(""Streamlit"").run() TimeInputA representation of st.time_input.at.time_input[0].increment().run() ToggleA representation of st.toggle.at.toggle[0].set_value(""True"").run() Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration!Pandas ProfilingPandas profiling component for Streamlit. Created by @okld.df = pd.read_csv(""https://storage.googleapis.com/tf-datasets/titanic/train.csv"") pr = df.profile_report() st_profile_report(pr) Streamlit AceAce editor component for Streamlit. Created by @okld.from streamlit_ace import st_ace content = st_ace() content Streamlit AnalyticsTrack & visualize user interactions with your streamlit app. Created by @jrieke.import streamlit_analytics with streamlit_analytics.track(): st.text_input(""Write something"") Previous: ConceptsNext: Write and magicforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy" https://docs.streamlit.io/en/0.71.0/api.html#utilities-and-user-info,"DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceremovePAGE ELEMENTSWrite and magicaddText elementsaddData elementsaddChart elementsaddInput widgetsaddMedia elementsaddLayouts and containersaddChat elementsaddStatus elementsaddThird-party componentsopen_in_newAPPLICATION LOGICNavigation and pagesaddExecution flowaddCaching and stateaddConnections and secretsaddCustom componentsaddUtilitiesaddConfigurationaddTOOLSApp testingaddCommand lineaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Develop/API referenceAPI reference Streamlit makes it easy for you to visualize, mutate, and share data. The API reference is organized by activity type, like displaying data or optimizing performance. Each section includes methods associated with the activity type, including examples. Browse our API below and click to learn more about any of our available commands! 🎈 Display almost anything Write and magic st.writeWrite arguments to the app.st.write(""Hello **world**!"") st.write(my_data_frame) st.write(my_mpl_figure) st.write_streamWrite generators or streams to the app with a typewriter effect.st.write_stream(my_generator) st.write_stream(my_llm_stream) MagicAny time Streamlit sees either a variable or literal value on its own line, it automatically writes that to your app using st.write""Hello **world**!"" my_data_frame my_mpl_figure Text elements MarkdownDisplay string formatted as Markdown.st.markdown(""Hello **world**!"") TitleDisplay text in title formatting.st.title(""The app title"") HeaderDisplay text in header formatting.st.header(""This is a header"") SubheaderDisplay text in subheader formatting.st.subheader(""This is a subheader"") CaptionDisplay text in small font.st.caption(""This is written small caption text"") Code blockDisplay a code block with optional syntax highlighting.st.code(""a = 1234"") EchoDisplay some code in the app, then execute it. Useful for tutorials.with st.echo(): st.write('This code will be printed') LaTeXDisplay mathematical expressions formatted as LaTeX.st.latex(""\int a x^2 \,dx"") Preformatted textWrite fixed-width and preformatted text.st.text(""Hello world"") DividerDisplay a horizontal rule.st.divider() Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration! PreviousTagsAdd tags to your Streamlit apps. Created by @gagan3012.st_tags(label='# Enter Keywords:', text='Press enter to add more', value=['Zero', 'One', 'Two'], suggestions=['five', 'six', 'seven', 'eight', 'nine', 'three', 'eleven', 'ten', 'four'], maxtags = 4, key='1') NLUApply text mining on a dataframe. Created by @JohnSnowLabs.nlu.load('sentiment').predict('I love NLU! <3') Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.mention(label=""An awesome Streamlit App"", icon=""streamlit"", url=""https://extras.streamlit.app"",) Annotated textDisplay annotated text in Streamlit apps. Created by @tvst.annotated_text(""This "", (""is"", ""verb""), "" some "", (""annotated"", ""adj""), (""text"", ""noun""), "" for those of "", (""you"", ""pronoun""), "" who "", (""like"", ""verb""), "" this sort of "", (""thing"", ""noun""), ""."") Drawable CanvasProvides a sketching canvas using Fabric.js. Created by @andfanilo.st_canvas(fill_color=""rgba(255, 165, 0, 0.3)"", stroke_width=stroke_width, stroke_color=stroke_color, background_color=bg_color, background_image=Image.open(bg_image) if bg_image else None, update_streamlit=realtime_update, height=150, drawing_mode=drawing_mode, point_display_radius=point_display_radius if drawing_mode == 'point' else 0, key=""canvas"",) TagsAdd tags to your Streamlit apps. Created by @gagan3012.st_tags(label='# Enter Keywords:', text='Press enter to add more', value=['Zero', 'One', 'Two'], suggestions=['five', 'six', 'seven', 'eight', 'nine', 'three', 'eleven', 'ten', 'four'], maxtags = 4, key='1') NLUApply text mining on a dataframe. Created by @JohnSnowLabs.nlu.load('sentiment').predict('I love NLU! <3') Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.mention(label=""An awesome Streamlit App"", icon=""streamlit"", url=""https://extras.streamlit.app"",) Annotated textDisplay annotated text in Streamlit apps. Created by @tvst.annotated_text(""This "", (""is"", ""verb""), "" some "", (""annotated"", ""adj""), (""text"", ""noun""), "" for those of "", (""you"", ""pronoun""), "" who "", (""like"", ""verb""), "" this sort of "", (""thing"", ""noun""), ""."") Drawable CanvasProvides a sketching canvas using Fabric.js. Created by @andfanilo.st_canvas(fill_color=""rgba(255, 165, 0, 0.3)"", stroke_width=stroke_width, stroke_color=stroke_color, background_color=bg_color, background_image=Image.open(bg_image) if bg_image else None, update_streamlit=realtime_update, height=150, drawing_mode=drawing_mode, point_display_radius=point_display_radius if drawing_mode == 'point' else 0, key=""canvas"",) TagsAdd tags to your Streamlit apps. Created by @gagan3012.st_tags(label='# Enter Keywords:', text='Press enter to add more', value=['Zero', 'One', 'Two'], suggestions=['five', 'six', 'seven', 'eight', 'nine', 'three', 'eleven', 'ten', 'four'], maxtags = 4, key='1') NLUApply text mining on a dataframe. Created by @JohnSnowLabs.nlu.load('sentiment').predict('I love NLU! <3') Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.mention(label=""An awesome Streamlit App"", icon=""streamlit"", url=""https://extras.streamlit.app"",) Next Data elements DataframesDisplay a dataframe as an interactive table.st.dataframe(my_data_frame) Data editorDisplay a data editor widget.edited = st.data_editor(df, num_rows=""dynamic"") Column configurationConfigure the display and editing behavior of dataframes and data editors.st.column_config.NumberColumn(""Price (in USD)"", min_value=0, format=""$%d"") Static tablesDisplay a static table.st.table(my_data_frame) MetricsDisplay a metric in big bold font, with an optional indicator of how the metric changed.st.metric(""My metric"", 42, 2) Dicts and JSONDisplay object or string as a pretty-printed JSON string.st.json(my_dict) Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration! PreviousImage CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates value = streamlit_image_coordinates(""https://placekitten.com/200/300"") st.write(value) Plotly EventsMake Plotly charts interactive!. Created by @null-jones.from streamlit_plotly_events import plotly_events fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.metric_cards import style_metric_cards col3.metric(label=""No Change"", value=5000, delta=0) style_metric_cards() Streamlit AggridImplementation of Ag-Grid component for Streamlit. Created by @PablocFonseca.df = pd.DataFrame({'col1': [1, 2, 3], 'col2': [4, 5, 6]}) grid_return = AgGrid(df, editable=True) new_df = grid_return['data'] Streamlit FoliumStreamlit Component for rendering Folium maps. Created by @randyzwitch.m = folium.Map(location=[39.949610, -75.150282], zoom_start=16) folium.Marker([39.949610, -75.150282], popup=""Liberty Bell"", tooltip=""Liberty Bell"").add_to(m) st_data = st_folium(m, width=725) Pandas ProfilingPandas profiling component for Streamlit. Created by @okld.df = pd.read_csv(""https://storage.googleapis.com/tf-datasets/titanic/train.csv"") pr = df.profile_report() st_profile_report(pr) Image CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates value = streamlit_image_coordinates(""https://placekitten.com/200/300"") st.write(value) Plotly EventsMake Plotly charts interactive!. Created by @null-jones.from streamlit_plotly_events import plotly_events fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.metric_cards import style_metric_cards col3.metric(label=""No Change"", value=5000, delta=0) style_metric_cards() Streamlit AggridImplementation of Ag-Grid component for Streamlit. Created by @PablocFonseca.df = pd.DataFrame({'col1': [1, 2, 3], 'col2': [4, 5, 6]}) grid_return = AgGrid(df, editable=True) new_df = grid_return['data'] Streamlit FoliumStreamlit Component for rendering Folium maps. Created by @randyzwitch.m = folium.Map(location=[39.949610, -75.150282], zoom_start=16) folium.Marker([39.949610, -75.150282], popup=""Liberty Bell"", tooltip=""Liberty Bell"").add_to(m) st_data = st_folium(m, width=725) Pandas ProfilingPandas profiling component for Streamlit. Created by @okld.df = pd.read_csv(""https://storage.googleapis.com/tf-datasets/titanic/train.csv"") pr = df.profile_report() st_profile_report(pr) Image CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates value = streamlit_image_coordinates(""https://placekitten.com/200/300"") st.write(value) Plotly EventsMake Plotly charts interactive!. Created by @null-jones.from streamlit_plotly_events import plotly_events fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.metric_cards import style_metric_cards col3.metric(label=""No Change"", value=5000, delta=0) style_metric_cards() Next Chart elements Simple area chartsDisplay an area chart.st.area_chart(my_data_frame) Simple bar chartsDisplay a bar chart.st.bar_chart(my_data_frame) Simple line chartsDisplay a line chart.st.line_chart(my_data_frame) Simple scatter chartsDisplay a line chart.st.scatter_chart(my_data_frame) Scatterplots on mapsDisplay a map with points on it.st.map(my_data_frame) MatplotlibDisplay a matplotlib.pyplot figure.st.pyplot(my_mpl_figure) AltairDisplay a chart using the Altair library.st.altair_chart(my_altair_chart) Vega-LiteDisplay a chart using the Vega-Lite library.st.vega_lite_chart(my_vega_lite_chart) PlotlyDisplay an interactive Plotly chart.st.plotly_chart(my_plotly_chart) BokehDisplay an interactive Bokeh chart.st.bokeh_chart(my_bokeh_chart) PyDeckDisplay a chart using the PyDeck library.st.pydeck_chart(my_pydeck_chart) GraphVizDisplay a graph using the dagre-d3 library.st.graphviz_chart(my_graphviz_spec) Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration! PreviousStreamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl(""https://assets5.lottiefiles.com/packages/lf20_V9t630.json"") st_lottie(lottie_hello, key=""hello"") Plotly EventsMake Plotly charts interactive!. Created by @null-jones.fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.chart += get_annotations_chart(annotations=[(""Mar 01, 2008"", ""Pretty good day for GOOG""), (""Dec 01, 2007"", ""Something's going wrong for GOOG & AAPL""), (""Nov 01, 2008"", ""Market starts again thanks to...""), (""Dec 01, 2009"", ""Small crash for GOOG after...""),],) st.altair_chart(chart, use_container_width=True) PlostA deceptively simple plotting library for Streamlit. Created by @tvst.import plost plost.line_chart(my_dataframe, x='time', y='stock_value', color='stock_name',) HiPlotHigh dimensional Interactive Plotting. Created by @facebookresearch.data = [{'dropout':0.1, 'lr': 0.001, 'loss': 10.0, 'optimizer': 'SGD'}, {'dropout':0.15, 'lr': 0.01, 'loss': 3.5, 'optimizer': 'Adam'}, {'dropout':0.3, 'lr': 0.1, 'loss': 4.5, 'optimizer': 'Adam'}] hip.Experiment.from_iterable(data).display() EChartsHigh dimensional Interactive Plotting. Created by @andfanilo.from streamlit_echarts import st_echarts st_echarts(options=options) Streamlit FoliumStreamlit Component for rendering Folium maps. Created by @randyzwitch.m = folium.Map(location=[39.949610, -75.150282], zoom_start=16) st_data = st_folium(m, width=725) Spacy-StreamlitspaCy building blocks and visualizers for Streamlit apps. Created by @explosion.models = [""en_core_web_sm"", ""en_core_web_md""] spacy_streamlit.visualize(models, ""Sundar Pichai is the CEO of Google."") Streamlit AgraphA Streamlit Graph Vis, based on react-grah-vis. Created by @ChrisDelClea.from streamlit_agraph import agraph, Node, Edge, Config agraph(nodes=nodes, edges=edges, config=config) Streamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl(""https://assets5.lottiefiles.com/packages/lf20_V9t630.json"") st_lottie(lottie_hello, key=""hello"") Plotly EventsMake Plotly charts interactive!. Created by @null-jones.fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.chart += get_annotations_chart(annotations=[(""Mar 01, 2008"", ""Pretty good day for GOOG""), (""Dec 01, 2007"", ""Something's going wrong for GOOG & AAPL""), (""Nov 01, 2008"", ""Market starts again thanks to...""), (""Dec 01, 2009"", ""Small crash for GOOG after...""),],) st.altair_chart(chart, use_container_width=True) PlostA deceptively simple plotting library for Streamlit. Created by @tvst.import plost plost.line_chart(my_dataframe, x='time', y='stock_value', color='stock_name',) HiPlotHigh dimensional Interactive Plotting. Created by @facebookresearch.data = [{'dropout':0.1, 'lr': 0.001, 'loss': 10.0, 'optimizer': 'SGD'}, {'dropout':0.15, 'lr': 0.01, 'loss': 3.5, 'optimizer': 'Adam'}, {'dropout':0.3, 'lr': 0.1, 'loss': 4.5, 'optimizer': 'Adam'}] hip.Experiment.from_iterable(data).display() EChartsHigh dimensional Interactive Plotting. Created by @andfanilo.from streamlit_echarts import st_echarts st_echarts(options=options) Streamlit FoliumStreamlit Component for rendering Folium maps. Created by @randyzwitch.m = folium.Map(location=[39.949610, -75.150282], zoom_start=16) st_data = st_folium(m, width=725) Spacy-StreamlitspaCy building blocks and visualizers for Streamlit apps. Created by @explosion.models = [""en_core_web_sm"", ""en_core_web_md""] spacy_streamlit.visualize(models, ""Sundar Pichai is the CEO of Google."") Streamlit AgraphA Streamlit Graph Vis, based on react-grah-vis. Created by @ChrisDelClea.from streamlit_agraph import agraph, Node, Edge, Config agraph(nodes=nodes, edges=edges, config=config) Streamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl(""https://assets5.lottiefiles.com/packages/lf20_V9t630.json"") st_lottie(lottie_hello, key=""hello"") Plotly EventsMake Plotly charts interactive!. Created by @null-jones.fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.chart += get_annotations_chart(annotations=[(""Mar 01, 2008"", ""Pretty good day for GOOG""), (""Dec 01, 2007"", ""Something's going wrong for GOOG & AAPL""), (""Nov 01, 2008"", ""Market starts again thanks to...""), (""Dec 01, 2009"", ""Small crash for GOOG after...""),],) st.altair_chart(chart, use_container_width=True) Next Input widgets ButtonDisplay a button widget.clicked = st.button(""Click me"") Download buttonDisplay a download button widget.st.download_button(""Download file"", file) Form buttonDisplay a form submit button. For use with st.form.st.form_submit_button(""Sign up"") Link buttonDisplay a link button.st.link_button(""Go to gallery"", url) Page linkDisplay a link to another page in a multipage app.st.page_link(""app.py"", label=""Home"", icon=""🏠"") st.page_link(""pages/profile.py"", label=""My profile"") CheckboxDisplay a checkbox widget.selected = st.checkbox(""I agree"") Color pickerDisplay a color picker widget.color = st.color_picker(""Pick a color"") MultiselectDisplay a multiselect widget. The multiselect widget starts as empty.choices = st.multiselect(""Buy"", [""milk"", ""apples"", ""potatoes""]) RadioDisplay a radio button widget.choice = st.radio(""Pick one"", [""cats"", ""dogs""]) SelectboxDisplay a select widget.choice = st.selectbox(""Pick one"", [""cats"", ""dogs""]) Select-sliderDisplay a slider widget to select items from a list.size = st.select_slider(""Pick a size"", [""S"", ""M"", ""L""]) ToggleDisplay a toggle widget.activated = st.toggle(""Activate"") Number inputDisplay a numeric input widget.choice = st.number_input(""Pick a number"", 0, 10) SliderDisplay a slider widget.number = st.slider(""Pick a number"", 0, 100) Date inputDisplay a date input widget.date = st.date_input(""Your birthday"") Time inputDisplay a time input widget.time = st.time_input(""Meeting time"") Chat inputDisplay a chat input widget.prompt = st.chat_input(""Say something"") if prompt: st.write(f""The user has sent: {prompt}"") Text-areaDisplay a multi-line text input widget.text = st.text_area(""Text to translate"") Text inputDisplay a single-line text input widget.name = st.text_input(""First name"") Data editorDisplay a data editor widget.edited = st.experimental_data_editor(df, num_rows=""dynamic"") File UploaderDisplay a file uploader widget.data = st.file_uploader(""Upload a CSV"") Camera inputDisplay a widget that allows users to upload images directly from a camera.image = st.camera_input(""Take a picture"") Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration! PreviousStreamlit ChatStreamlit Component for a Chatbot UI. Created by @AI-Yash.from streamlit_chat import message message(""My message"") message(""Hello bot!"", is_user=True) # align's the message to the right Streamlit Option MenuSelect a single item from a list of options in a menu. Created by @victoryhb.from streamlit_option_menu import option_menu option_menu(""Main Menu"", [""Home"", 'Settings'], icons=['house', 'gear'], menu_icon=""cast"", default_index=1) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.stoggle import stoggle stoggle( ""Click me!"", """"""🥷 Surprise! Here's some additional content"""""",) Streamlit ElementsCreate a draggable and resizable dashboard in Streamlit. Created by @okls.from streamlit_elements import elements, mui, html with elements(""new_element""): mui.Typography(""Hello world"") TagsAdd tags to your Streamlit apps. Created by @gagan3012.from streamlit_tags import st_tags st_tags(label='# Enter Keywords:', text='Press enter to add more', value=['Zero', 'One', 'Two'], suggestions=['five', 'six', 'seven', 'eight', 'nine', 'three', 'eleven', 'ten', 'four'], maxtags = 4, key='1') StqdmThe simplest way to handle a progress bar in streamlit app. Created by @Wirg.from stqdm import stqdm for _ in stqdm(range(50)): sleep(0.5) TimelineDisplay a Timeline in Streamlit apps using TimelineJS. Created by @innerdoc.from streamlit_timeline import timeline with open('example.json', ""r"") as f: timeline(f.read(), height=800) Camera input liveAlternative for st.camera_input which returns the webcam images live. Created by @blackary.from camera_input_live import camera_input_live image = camera_input_live() st.image(value) Streamlit AceAce editor component for Streamlit. Created by @okld.from streamlit_ace import st_ace content = st_ace() content Streamlit ChatStreamlit Component for a Chatbot UI. Created by @AI-Yash.from streamlit_chat import message message(""My message"") message(""Hello bot!"", is_user=True) # align's the message to the right Streamlit Option MenuSelect a single item from a list of options in a menu. Created by @victoryhb.from streamlit_option_menu import option_menu option_menu(""Main Menu"", [""Home"", 'Settings'], icons=['house', 'gear'], menu_icon=""cast"", default_index=1) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.stoggle import stoggle stoggle( ""Click me!"", """"""🥷 Surprise! Here's some additional content"""""",) Streamlit ElementsCreate a draggable and resizable dashboard in Streamlit. Created by @okls.from streamlit_elements import elements, mui, html with elements(""new_element""): mui.Typography(""Hello world"") TagsAdd tags to your Streamlit apps. Created by @gagan3012.from streamlit_tags import st_tags st_tags(label='# Enter Keywords:', text='Press enter to add more', value=['Zero', 'One', 'Two'], suggestions=['five', 'six', 'seven', 'eight', 'nine', 'three', 'eleven', 'ten', 'four'], maxtags = 4, key='1') StqdmThe simplest way to handle a progress bar in streamlit app. Created by @Wirg.from stqdm import stqdm for _ in stqdm(range(50)): sleep(0.5) TimelineDisplay a Timeline in Streamlit apps using TimelineJS. Created by @innerdoc.from streamlit_timeline import timeline with open('example.json', ""r"") as f: timeline(f.read(), height=800) Camera input liveAlternative for st.camera_input which returns the webcam images live. Created by @blackary.from camera_input_live import camera_input_live image = camera_input_live() st.image(value) Streamlit AceAce editor component for Streamlit. Created by @okld.from streamlit_ace import st_ace content = st_ace() content Streamlit ChatStreamlit Component for a Chatbot UI. Created by @AI-Yash.from streamlit_chat import message message(""My message"") message(""Hello bot!"", is_user=True) # align's the message to the right Streamlit Option MenuSelect a single item from a list of options in a menu. Created by @victoryhb.from streamlit_option_menu import option_menu option_menu(""Main Menu"", [""Home"", 'Settings'], icons=['house', 'gear'], menu_icon=""cast"", default_index=1) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.stoggle import stoggle stoggle( ""Click me!"", """"""🥷 Surprise! Here's some additional content"""""",) Next Media elements ImageDisplay an image or list of images.st.image(numpy_array) st.image(image_bytes) st.image(file) st.image(""https://example.com/myimage.jpg"") AudioDisplay an audio player.st.audio(numpy_array) st.audio(audio_bytes) st.audio(file) st.audio(""https://example.com/myaudio.mp3"", format=""audio/mp3"") VideoDisplay a video player.st.video(numpy_array) st.video(video_bytes) st.video(file) st.video(""https://example.com/myvideo.mp4"", format=""video/mp4"") Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration! PreviousStreamlit CropperA simple image cropper for Streamlit. Created by @turner-anderson.from streamlit_cropper import st_cropper st_cropper(img, realtime_update=realtime_update, box_color=box_color, aspect_ratio=aspect_ratio) Image CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates streamlit_image_coordinates(""https://placekitten.com/200/300"") Streamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl(""https://assets5.lottiefiles.com/packages/lf20_V9t630.json"") st_lottie(lottie_hello, key=""hello"") Streamlit WebrtcHandling and transmitting real-time video/audio streams with Streamlit. Created by @whitphx.from streamlit_webrtc import webrtc_streamer webrtc_streamer(key=""sample"") Drawable CanvasProvides a sketching canvas using Fabric.js. Created by @andfanilo.from streamlit_drawable_canvas import st_canvas st_canvas(fill_color=""rgba(255, 165, 0, 0.3)"", stroke_width=stroke_width, stroke_color=stroke_color, background_color=bg_color, background_image=Image.open(bg_image) if bg_image else None, update_streamlit=realtime_update, height=150, drawing_mode=drawing_mode, point_display_radius=point_display_radius if drawing_mode == 'point' else 0, key=""canvas"",) Image ComparisonCompare images with a slider using JuxtaposeJS. Created by @fcakyon.from streamlit_image_comparison import image_comparison image_comparison(img1=""image1.jpg"", img2=""image2.jpg"",) Streamlit CropperA simple image cropper for Streamlit. Created by @turner-anderson.from streamlit_cropper import st_cropper st_cropper(img, realtime_update=realtime_update, box_color=box_color, aspect_ratio=aspect_ratio) Image CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates streamlit_image_coordinates(""https://placekitten.com/200/300"") Streamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl(""https://assets5.lottiefiles.com/packages/lf20_V9t630.json"") st_lottie(lottie_hello, key=""hello"") Streamlit WebrtcHandling and transmitting real-time video/audio streams with Streamlit. Created by @whitphx.from streamlit_webrtc import webrtc_streamer webrtc_streamer(key=""sample"") Drawable CanvasProvides a sketching canvas using Fabric.js. Created by @andfanilo.from streamlit_drawable_canvas import st_canvas st_canvas(fill_color=""rgba(255, 165, 0, 0.3)"", stroke_width=stroke_width, stroke_color=stroke_color, background_color=bg_color, background_image=Image.open(bg_image) if bg_image else None, update_streamlit=realtime_update, height=150, drawing_mode=drawing_mode, point_display_radius=point_display_radius if drawing_mode == 'point' else 0, key=""canvas"",) Image ComparisonCompare images with a slider using JuxtaposeJS. Created by @fcakyon.from streamlit_image_comparison import image_comparison image_comparison(img1=""image1.jpg"", img2=""image2.jpg"",) Streamlit CropperA simple image cropper for Streamlit. Created by @turner-anderson.from streamlit_cropper import st_cropper st_cropper(img, realtime_update=realtime_update, box_color=box_color, aspect_ratio=aspect_ratio) Image CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates streamlit_image_coordinates(""https://placekitten.com/200/300"") Streamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl(""https://assets5.lottiefiles.com/packages/lf20_V9t630.json"") st_lottie(lottie_hello, key=""hello"") Next Layouts and containers ColumnsInsert containers laid out as side-by-side columns.col1, col2 = st.columns(2) col1.write(""this is column 1"") col2.write(""this is column 2"") ContainerInsert a multi-element container.c = st.container() st.write(""This will show last"") c.write(""This will show first"") c.write(""This will show second"") Modal dialogsInsert a modal dialog that can rerun independently from the rest of the script.@st.experimental_dialog(""Sign up"") def email_form(): name = st.text_input(""Name"") email = st.text_input(""Email"") EmptyInsert a single-element container.c = st.empty() st.write(""This will show last"") c.write(""This will be replaced"") c.write(""This will show first"") ExpanderInsert a multi-element container that can be expanded/collapsed.with st.expander(""Open to see more""): st.write(""This is more content"") PopoverInsert a multi-element popover container that can be opened/closed.with st.popover(""Settings""): st.checkbox(""Show completed"") SidebarDisplay items in a sidebar.st.sidebar.write(""This lives in the sidebar"") st.sidebar.button(""Click me!"") TabsInsert containers separated into tabs.tab1, tab2 = st.tabs([""Tab 1"", ""Tab2""]) tab1.write(""this is tab 1"") tab2.write(""this is tab 2"") Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration!Streamlit ElementsCreate a draggable and resizable dashboard in Streamlit. Created by @okls.from streamlit_elements import elements, mui, html with elements(""new_element""): mui.Typography(""Hello world"") PydanticAuto-generate Streamlit UI from Pydantic Models and Dataclasses. Created by @lukasmasuch.import streamlit_pydantic as sp sp.pydantic_form(key=""my_form"", model=ExampleModel) Streamlit PagesAn experimental version of Streamlit Multi-Page Apps. Created by @blackary.from st_pages import Page, show_pages, add_page_title show_pages([ Page(""streamlit_app.py"", ""Home"", ""🏠""), Page(""other_pages/page2.py"", ""Page 2"", "":books:""), ]) Chat elements Streamlit provides a few commands to help you build conversational apps. These chat elements are designed to be used in conjunction with each other, but you can also use them separately. st.chat_message lets you insert a chat message container into the app so you can display messages from the user or the app. Chat containers can contain other Streamlit elements, including charts, tables, text, and more. st.chat_input lets you display a chat input widget so the user can type in a message. Chat inputDisplay a chat input widget.prompt = st.chat_input(""Say something"") if prompt: st.write(f""The user has sent: {prompt}"") Chat messageInsert a chat message container.import numpy as np with st.chat_message(""user""): st.write(""Hello 👋"") st.line_chart(np.random.randn(30, 3)) Status containerDisplay output of long-running tasks in a container.with st.status('Running'): do_something_slow() st.write_streamWrite generators or streams to the app with a typewriter effect.st.write_stream(my_generator) st.write_stream(my_llm_stream) Status elements Progress barDisplay a progress bar.for i in range(101): st.progress(i) do_something_slow() SpinnerTemporarily displays a message while executing a block of code.with st.spinner(""Please wait...""): do_something_slow() Status containerDisplay output of long-running tasks in a container.with st.status('Running'): do_something_slow() ToastBriefly displays a toast message in the bottom-right corner.st.toast('Butter!', icon='🧈') BalloonsDisplay celebratory balloons!do_something() # Celebrate when all done! st.balloons() SnowflakesDisplay celebratory snowflakes!do_something() # Celebrate when all done! st.snow() Success boxDisplay a success message.st.success(""Match found!"") Info boxDisplay an informational message.st.info(""Dataset is updated every day at midnight."") Warning boxDisplay warning message.st.warning(""Unable to fetch image. Skipping..."") Error boxDisplay error message.st.error(""We encountered an error"") Exception outputDisplay an exception.e = RuntimeError(""This is an exception of type RuntimeError"") st.exception(e) Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration!StqdmThe simplest way to handle a progress bar in streamlit app. Created by @Wirg.from stqdm import stqdm for _ in stqdm(range(50)): sleep(0.5) Custom notification boxA custom notification box with the ability to close it out. Created by @Socvest.from streamlit_custom_notification_box import custom_notification_box styles = {'material-icons':{'color': 'red'}, 'text-icon-link-close-container': {'box-shadow': '#3896de 0px 4px'}, 'notification-text': {'':''}, 'close-button':{'':''}, 'link':{'':''}} custom_notification_box(icon='info', textDisplay='We are almost done with your registration...', externalLink='more info', url='#', styles=styles, key=""foo"") Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.let_it_rain import rain rain(emoji=""🎈"", font_size=54, falling_speed=5, animation_length=""infinite"",) App logic and configuration Navigation and pages Switch pageProgrammatically navigates to a specified page.st.switch_page(""pages/my_page.py"") Page linkDisplay a link to another page in a multipage app.st.page_link(""app.py"", label=""Home"", icon=""🏠"") st.page_link(""pages/profile.py"", label=""My profile"") Execution flow Modal dialogsInsert a modal dialog that can rerun independently from the rest of the script.@st.experimental_dialog(""Sign up"") def email_form(): name = st.text_input(""Name"") email = st.text_input(""Email"") FormsCreate a form that batches elements together with a “Submit"" button.with st.form(key='my_form'): name = st.text_input(""Name"") email = st.text_input(""Email"") st.form_submit_button(""Sign up"") Partial rerunsDefine a fragment to rerun independently from the rest of the script.@st.experimental_fragment(run_every=""10s"") def fragment(): df = get_data() st.line_chart(df) Rerun scriptRerun the script immediately.st.rerun() Stop executionStops execution immediately.st.stop() Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration!AutorefreshForce a refresh without tying up a script. Created by @kmcgrady.from streamlit_autorefresh import st_autorefresh st_autorefresh(interval=2000, limit=100, key=""fizzbuzzcounter"") PydanticAuto-generate Streamlit UI from Pydantic Models and Dataclasses. Created by @lukasmasuch.import streamlit_pydantic as sp sp.pydantic_form(key=""my_form"", model=ExampleModel) Streamlit PagesAn experimental version of Streamlit Multi-Page Apps. Created by @blackary.from st_pages import Page, show_pages, add_page_title show_pages([ Page(""streamlit_app.py"", ""Home"", ""🏠""), Page(""other_pages/page2.py"", ""Page 2"", "":books:""), ]) Caching and state Cache dataFunction decorator to cache functions that return data (e.g. dataframe transforms, database queries, ML inference).@st.cache_data def long_function(param1, param2): # Perform expensive computation here or # fetch data from the web here return data Cache resourceFunction decorator to cache functions that return global resources (e.g. database connections, ML models).@st.cache_resource def init_model(): # Return a global resource here return pipeline( ""sentiment-analysis"", model=""distilbert-base-uncased-finetuned-sst-2-english"" ) Session stateSession state is a way to share variables between reruns, for each user session.st.session_state['key'] = value Query parametersGet, set, or clear the query parameters that are shown in the browser's URL bar.st.query_params[key] = value st.query_params.clear() Connections and databases Setup your connection Create a connectionConnect to a data source or APIconn = st.connection('pets_db', type='sql') pet_owners = conn.query('select * from pet_owners') st.dataframe(pet_owners) Built-in connections SnowflakeConnectionA connection to Snowflake.conn = st.connection('snowflake') SQLConnectionA connection to a SQL database using SQLAlchemy.conn = st.connection('sql') Build your own connections Connection base classBuild your own connection with BaseConnection.class MyConnection(BaseConnection[myconn.MyConnection]): def _connect(self, **kwargs) -> MyConnection: return myconn.connect(**self._secrets, **kwargs) def query(self, query): return self._instance.query(query) Secrets management Secrets singletonAccess secrets from a local TOML file.key = st.secrets[""OpenAI_key""] Secrets fileSave your secrets in a per-project or per-profile TOML file.OpenAI_key = """" Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration!AuthenticatorA secure authentication module to validate user credentials. Created by @mkhorasani.import streamlit_authenticator as stauth authenticator = stauth.Authenticate( config['credentials'], config['cookie']['name'], config['cookie']['key'], config['cookie']['expiry_days'], config['preauthorized']) WS localStorageA simple synchronous way of accessing localStorage from your app. Created by @gagangoku.from streamlit_ws_localstorage import injectWebsocketCode ret = conn.setLocalStorageVal(key='k1', val='v1') st.write('ret: ' + ret) Streamlit Auth0The fastest way to provide comprehensive login inside Streamlit. Created by @conradbez.from auth0_component import login_button user_info = login_button(clientId, domain = domain) st.write(user_info) Custom Components Declare a componentCreate and register a custom component.st.components.v1.declare_component( ""custom_slider"", ""/frontend"", ) HTMLDisplay an HTML string in an iframe.st.components.v1.html( ""

Foo bar.

"" ) iframeLoad a remote URL in an iframe.st.components.v1.iframe( ""docs.streamlit.io"" ) Utilities and user info User infost.experimental_user returns information about the logged-in user of private apps on Streamlit Community Cloud.if st.experimental_user.email == ""foo@corp.com"": st.write(""Welcome back, "", st.experimental_user.email) else: st.write(""You are not authorized to view this page."") Get helpDisplay object’s doc string, nicely formatted.st.help(st.write) st.help(pd.DataFrame) Render HTMLRenders HTML strings to your app.css = """""" """""" st.html(css) Configuration Configuration fileConfigures the default settings for your app.your-project/ ├── .streamlit/ │ └── config.toml └── your_app.py Set page title, favicon, and moreConfigures the default settings of the page.st.set_page_config( page_title=""My app"", page_icon="":shark:"", ) Developer tools App testing st.testing.v1.AppTestst.testing.v1.AppTest simulates a running Streamlit app for testing.from streamlit.testing.v1 import AppTest at = AppTest.from_file(""streamlit_app.py"") at.secrets[""WORD""] = ""Foobar"" at.run() assert not at.exception at.text_input(""word"").input(""Bazbat"").run() assert at.warning[0].value == ""Try again."" AppTest.from_filest.testing.v1.AppTest.from_file initializes a simulated app from a file.from streamlit.testing.v1 import AppTest at = AppTest.from_file(""streamlit_app.py"") at.run() AppTest.from_stringst.testing.v1.AppTest.from_string initializes a simulated app from a string.from streamlit.testing.v1 import AppTest at = AppTest.from_string(app_script_as_string) at.run() AppTest.from_functionst.testing.v1.AppTest.from_function initializes a simulated app from a function.from streamlit.testing.v1 import AppTest at = AppTest.from_function(app_script_as_callable) at.run() BlockA representation of container elements, including: st.chat_message st.columns st.sidebar st.tabs The main body of the app. # at.sidebar returns a Block at.sidebar.button[0].click().run() assert not at.exception ElementThe base class for representation of all elements, including: st.title st.header st.markdown st.dataframe # at.title returns a sequence of Title # Title inherits from Element assert at.title[0].value == ""My awesome app"" ButtonA representation of st.button and st.form_submit_button.at.button[0].click().run() ChatInputA representation of st.chat_input.at.chat_input[0].set_value(""What is Streamlit?"").run() CheckboxA representation of st.checkbox.at.checkbox[0].check().run() ColorPickerA representation of st.color_picker.at.color_picker[0].pick(""#FF4B4B"").run() DateInputA representation of st.date_input.release_date = datetime.date(2023, 10, 26) at.date_input[0].set_value(release_date).run() MultiselectA representation of st.multiselect.at.multiselect[0].select(""New York"").run() NumberInputA representation of st.number_input.at.number_input[0].increment().run() RadioA representation of st.radio.at.radio[0].set_value(""New York"").run() SelectSliderA representation of st.select_slider.at.select_slider[0].set_range(""A"",""C"").run() SelectboxA representation of st.selectbox.at.selectbox[0].select(""New York"").run() SliderA representation of st.slider.at.slider[0].set_range(2,5).run() TextAreaA representation of st.text_area.at.text_area[0].input(""Streamlit is awesome!"").run() TextInputA representation of st.text_input.at.text_input[0].input(""Streamlit"").run() TimeInputA representation of st.time_input.at.time_input[0].increment().run() ToggleA representation of st.toggle.at.toggle[0].set_value(""True"").run() Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration!Pandas ProfilingPandas profiling component for Streamlit. Created by @okld.df = pd.read_csv(""https://storage.googleapis.com/tf-datasets/titanic/train.csv"") pr = df.profile_report() st_profile_report(pr) Streamlit AceAce editor component for Streamlit. Created by @okld.from streamlit_ace import st_ace content = st_ace() content Streamlit AnalyticsTrack & visualize user interactions with your streamlit app. Created by @jrieke.import streamlit_analytics with streamlit_analytics.track(): st.text_input(""Write something"") Previous: ConceptsNext: Write and magicforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy" https://docs.streamlit.io/develop/api-reference/caching-and-state/st.experimental_memo#supported-widgets,"DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceremovePAGE ELEMENTSWrite and magicaddText elementsaddData elementsaddChart elementsaddInput widgetsaddMedia elementsaddLayouts and containersaddChat elementsaddStatus elementsaddThird-party componentsopen_in_newAPPLICATION LOGICNavigation and pagesaddExecution flowaddCaching and stateremovest.cache_datast.cache_resourcest.cachedeletest.session_statest.query_paramsst.experimental_get_query_paramsdeletest.experimental_set_query_paramsdeleteConnections and secretsaddCustom componentsaddUtilitiesaddConfigurationaddTOOLSApp testingaddCommand lineaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Develop/API reference/Caching and state/st.experimental_memopriority_highImportantThis is an experimental feature. Experimental features and their APIs may change or be removed at any time. To learn more, click here. st.experimental_memoStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakedeleteDeprecation noticest.experimental_memo was deprecated in version 1.18.0. Use st.cache_data instead. Learn more in Caching.Decorator to cache functions that return data (e.g. dataframe transforms, database queries, ML inference). Cached objects are stored in ""pickled"" form, which means that the return value of a cached function must be pickleable. Each caller of the cached function gets its own copy of the cached data. You can clear a function's cache with func.clear() or clear the entire cache with st.cache_data.clear(). To cache global resources, use st.cache_resource instead. Learn more about caching at https://docs.streamlit.io/library/advanced-features/caching. Function signature[source] st.experimental_memo(func=None, *, ttl, max_entries, show_spinner, persist, experimental_allow_widgets, hash_funcs=None) Parameters func (callable) The function to cache. Streamlit hashes the function's source code. ttl (float, timedelta, str, or None) The maximum time to keep an entry in the cache. Can be one of: None if cache entries should never expire (default). A number specifying the time in seconds. A string specifying the time in a format supported by Pandas's Timedelta constructor, e.g. ""1d"", ""1.5 days"", or ""1h23s"". A timedelta object from Python's built-in datetime library, e.g. timedelta(days=1). Note that ttl will be ignored if persist=""disk"" or persist=True. max_entries (int or None) The maximum number of entries to keep in the cache, or None for an unbounded cache. When a new entry is added to a full cache, the oldest cached entry will be removed. Defaults to None. show_spinner (bool or str) Enable the spinner. Default is True to show a spinner when there is a ""cache miss"" and the cached data is being created. If string, value of show_spinner param will be used for spinner text. persist (""disk"", bool, or None) Optional location to persist cached data to. Passing ""disk"" (or True) will persist the cached data to the local disk. None (or False) will disable persistence. The default is None. experimental_allow_widgets (bool) Allow widgets to be used in the cached function. Defaults to False. Support for widgets in cached functions is currently experimental. Setting this parameter to True may lead to excessive memory use since the widget value is treated as an additional input parameter to the cache. We may remove support for this option at any time without notice. hash_funcs (dict or None) Mapping of types or fully qualified names to hash functions. This is used to override the behavior of the hasher inside Streamlit's caching mechanism: when the hasher encounters an object, it will first check to see if its type matches a key in this dict and, if so, will use the provided function to generate a hash for it. See below for an example of how this can be used. Example import streamlit as st @st.cache_data def fetch_and_clean_data(url): # Fetch data from URL here, and then clean it up. return data d1 = fetch_and_clean_data(DATA_URL_1) # Actually executes the function, since this is the first time it was # encountered. d2 = fetch_and_clean_data(DATA_URL_1) # Does not execute the function. Instead, returns its previously computed # value. This means that now the data in d1 is the same as in d2. d3 = fetch_and_clean_data(DATA_URL_2) # This is a different URL, so the function executes. To set the persist parameter, use this command as follows: import streamlit as st @st.cache_data(persist=""disk"") def fetch_and_clean_data(url): # Fetch data from URL here, and then clean it up. return data By default, all parameters to a cached function must be hashable. Any parameter whose name begins with _ will not be hashed. You can use this as an ""escape hatch"" for parameters that are not hashable: import streamlit as st @st.cache_data def fetch_and_clean_data(_db_connection, num_rows): # Fetch data from _db_connection here, and then clean it up. return data connection = make_database_connection() d1 = fetch_and_clean_data(connection, num_rows=10) # Actually executes the function, since this is the first time it was # encountered. another_connection = make_database_connection() d2 = fetch_and_clean_data(another_connection, num_rows=10) # Does not execute the function. Instead, returns its previously computed # value - even though the _database_connection parameter was different # in both calls. A cached function's cache can be procedurally cleared: import streamlit as st @st.cache_data def fetch_and_clean_data(_db_connection, num_rows): # Fetch data from _db_connection here, and then clean it up. return data fetch_and_clean_data.clear(_db_connection, 50) # Clear the cached entry for the arguments provided. fetch_and_clean_data.clear() # Clear all cached entries for this function. To override the default hashing behavior, pass a custom hash function. You can do that by mapping a type (e.g. datetime.datetime) to a hash function (lambda dt: dt.isoformat()) like this: import streamlit as st import datetime @st.cache_data(hash_funcs={datetime.datetime: lambda dt: dt.isoformat()}) def convert_to_utc(dt: datetime.datetime): return dt.astimezone(datetime.timezone.utc) Alternatively, you can map the type's fully-qualified name (e.g. ""datetime.datetime"") to the hash function instead: import streamlit as st import datetime @st.cache_data(hash_funcs={""datetime.datetime"": lambda dt: dt.isoformat()}) def convert_to_utc(dt: datetime.datetime): return dt.astimezone(datetime.timezone.utc) Persistent memo caches currently don't support TTL. ttl will be ignored if persist is specified: import streamlit as st @st.experimental_memo(ttl=60, persist=""disk"") def load_data(): return 42 st.write(load_data()) And a warning will be logged to your terminal: streamlit run app.py You can now view your Streamlit app in your browser. Local URL: http://localhost:8501 Network URL: http://192.168.1.1:8501 2022-09-22 13:35:41.587 The memoized function 'load_data' has a TTL that will be ignored. Persistent memo caches currently don't support TTL. st.experimental_memo.clearStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakedeleteDeprecation noticest.experimental_memo.clear was deprecated in version 1.18.0. Use st.cache_data.clear instead. Learn more in Caching.Clear all in-memory and on-disk data caches. Function signature[source] st.experimental_memo.clear() Example In the example below, pressing the ""Clear All"" button will clear memoized values from all functions decorated with @st.experimental_memo. import streamlit as st @st.experimental_memo def square(x): return x**2 @st.experimental_memo def cube(x): return x**3 if st.button(""Clear All""): # Clear values from *all* memoized functions: # i.e. clear values from both square and cube st.experimental_memo.clear() Replay static st elements in cache-decorated functions Functions decorated with @st.experimental_memo can contain static st elements. When a cache-decorated function is executed, we record the element and block messages produced, so the elements will appear in the app even when execution of the function is skipped because the result was cached. In the example below, the @st.experimental_memo decorator is used to cache the execution of the load_data function, that returns a pandas DataFrame. Notice the cached function also contains a st.area_chart command, which will be replayed when the function is skipped because the result was cached. import numpy as np import pandas as pd import streamlit as st @st.experimental_memo def load_data(rows): chart_data = pd.DataFrame( np.random.randn(rows, 10), columns=[""a"", ""b"", ""c"", ""d"", ""e"", ""f"", ""g"", ""h"", ""i"", ""j""], ) # Contains a static element st.area_chart st.area_chart(chart_data) # This will be recorded and displayed even when the function is skipped return chart_data df = load_data(20) st.dataframe(df) Supported static st elements in cache-decorated functions include: st.alert st.altair_chart st.area_chart st.audio st.bar_chart st.ballons st.bokeh_chart st.caption st.code st.components.v1.html st.components.v1.iframe st.container st.dataframe st.echo st.empty st.error st.exception st.expander st.experimental_get_query_params st.experimental_set_query_params st.form st.form_submit_button st.graphviz_chart st.help st.image st.info st.json st.latex st.line_chart st.markdown st.metric st.plotly_chart st.progress st.pydeck_chart st.snow st.spinner st.success st.table st.text st.vega_lite_chart st.video st.warning Replay input widgets in cache-decorated functions In addition to static elements, functions decorated with @st.experimental_memo can also contain input widgets! Replaying input widgets is disabled by default. To enable it, you can set the experimental_allow_widgets parameter for @st.experimental_memo to True. The example below enables widget replaying, and shows the use of a checkbox widget within a cache-decorated function. import streamlit as st # Enable widget replay @st.experimental_memo(experimental_allow_widgets=True) def func(): # Contains an input widget st.checkbox(""Works!"") func() If the cache decorated function contains input widgets, but experimental_allow_widgets is set to False or unset, Streamlit will throw a CachedStFunctionWarning, like the one below: import streamlit as st # Widget replay is disabled by default @st.experimental_memo def func(): # Streamlit will throw a CachedStFunctionWarning st.checkbox(""Doesn't work"") func() How widget replay works Let's demystify how widget replay in cache-decorated functions works and gain a conceptual understanding. Widget values are treated as additional inputs to the function, and are used to determine whether the function should be executed or not. Consider the following example: import streamlit as st @st.experimental_memo(experimental_allow_widgets=True) def plus_one(x): y = x + 1 if st.checkbox(""Nuke the value 💥""): st.write(""Value was nuked, returning 0"") y = 0 return y st.write(plus_one(2)) The plus_one function takes an integer x as input, and returns x + 1. The function also contains a checkbox widget, which is used to ""nuke"" the value of x. i.e. the return value of plus_one depends on the state of the checkbox: if it is checked, the function returns 0, otherwise it returns 3. In order to know which value the cache should return (in case of a cache hit), Streamlit treats the checkbox state (checked / unchecked) as an additional input to the function plus_one (just like x). If the user checks the checkbox (thereby changing its state), we look up the cache for the same value of x (2) and the same checkbox state (checked). If the cache contains a value for this combination of inputs, we return it. Otherwise, we execute the function and store the result in the cache. Let's now understand how enabling and disabling widget replay changes the behavior of the function. Widget replay disabled Widgets in cached functions throw a CachedStFunctionWarning and are ignored. Other static elements in cached functions replay as expected. Widget replay enabled Widgets in cached functions don't lead to a warning, and are replayed as expected. Interacting with a widget in a cached function will cause the function to be executed again, and the cache to be updated. Widgets in cached functions retain their state across reruns. Each unique combination of widget values is treated as a separate input to the function, and is used to determine whether the function should be executed or not. i.e. Each unique combination of widget values has its own cache entry; the cached function runs the first time and the saved value is used afterwards. Calling a cached function multiple times in one script run with the same arguments triggers a DuplicateWidgetID error. If the arguments to a cached function change, widgets from that function that render again retain their state. Changing the source code of a cached function invalidates the cache. Both st.experimental_memo and st.experimental_singleton support widget replay. Fundamentally, the behavior of a function with (supported) widgets in it doesn't change when it is decorated with @st.experimental_memo or @st.experimental_singleton. The only difference is that the function is only executed when we detect a cache ""miss"". Supported widgets All input widgets are supported in cache-decorated functions. The following is an exhaustive list of supported widgets: st.button st.camera_input st.checkbox st.color_picker st.date_input st.download_button st.file_uploader st.multiselect st.number_input st.radio st.selectbox st.select_slider st.slider st.text_area st.text_input st.time_input Previous: st.cacheNext: st.experimental_singletonforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy" https://docs.streamlit.io/deploy/streamlit-community-cloud/get-started/connect-your-github-account#whats-next,"DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudremoveGet startedremoveQuickstartCreate your accountConnect your GitHub accountExplore your workspaceFork and edit a public appTrust and securityDeploy your appaddManage your appaddShare your appaddManage your accountaddTroubleshootingStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Deploy/Streamlit Community Cloud/Get started/Connect your GitHub accountConnect your GitHub account Connecting GitHub to your Streamlit Community Cloud account allows you to deploy apps directly from the files you store in your repos. It also lets the system check for updates to those files and automatically update your app. There are two stages to this authorization: the first happens when you connect your account for the first time and the second happens when you deploy your first app. Everyone is prompted to connect GitHub when they create an account. If you need to connect GitHub to an existing primary identity, see Manage your GitHub connection. This page contains additional information about the authorization needed to connect GitHub. If you have just created your account, you are free to skip ahead and Explore your workspace. GitHub's authorization prompts occur automatically as needed. Authorize your GitHub account There are two different authorization prompts to grant access between Streamlit and your GitHub account. The first authorization—""Authorize Streamlit""—happens when you connect your GitHub account to Streamlit. The second authorization—""Streamlit is requesting additional permissions""—happens when you deploy your first app. You must click ""Authorize streamlit"" on both. If you are a member of any GitHub organizations, read below to understand the extras steps to authorize an organization. Questions about GitHub permissions? Read some frequently asked questions about our GitHub integration. priority_highImportantYou must have admin permissions to your repo in order to deploy apps. If you don't have admin access, talk to the repo's owner or reach out to us on the Community forum. Organization access If you are working in a repository that is owned by an organization, authorization must be granted by that organization. If you are an owner or member of a GitHub organization when you connect your GitHub account, your authorization prompts will include an extra section labeled ""Organization access"". Organizations you own For any organization you own, if authorization has not been previously granted or denied you can click ""Grant"" before you click ""Authorize streamlit"". Organizations owned by others For an organization you don't own, if authorization has not been previously granted or denied you can click ""Request"" before you click ""Authorize streamlit"". Previous or pending authorization If someone has already started the process of authorizing Streamlit for your organization, different options and statuses will display accordingly. Approved access If an organization has already granted Streamlit access, a green check is shown. Pending access If a request has been previously sent but not yet approved, a pending status shows. Denied access If a request has been previously sent and denied, no option to grant or request access is shown. In this case, the organization owner will need to authorize Streamlit from GitHub. See GitHub's documentation on OAuth apps and organizations. What's next? Now that you have your account you can Explore your workspace. Or if you're ready to go, jump right in and Deploy your app.Previous: Create your accountNext: Explore your workspaceforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy" https://docs.streamlit.io/develop/quick-reference/changelog#version-1280,"DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceaddTutorialsaddQuick referenceremoveCheat sheetRelease notesPre-release featuresRoadmapopen_in_newweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Develop/Quick reference/Release notesRelease notes This page lists highlights, bug fixes, and known issues for official Streamlit releases. If you're looking for information about nightly releases, beta features, or experimental features, see Try pre-release features. starTipTo upgrade to the latest version of Streamlit, run:pip install --upgrade streamlit Version 1.34.0 Release date: May 2, 2024 Highlights 🍿 Introducing st.experimental_dialog! Create a modal overlay that can also rerun independently from the rest of your app. Check out the docs to learn how. Notable Changes 🔣 st.toast, st.chat_message, st.set_page_config, st.info, st.success, st.error, and st.warning can use Google Material Symbols for their icons. 🌈 Markdown supports background colors for text. Check out the feature demo app. 🎥 st.audio and st.video can now be set to autoplay. st.video can be muted. 🗃️ You can clear specific cached values for a cached function. Thanks, OscarSaharoy! ❓ You can now set all query parameters with a single call to st.query_params.from_dict. Thanks, Asaurus1! Other Changes 🔲 Streamlit supports Modin and Snowpark pandas DataFrames and Series (#8506). ⏱️ Improved support for period data types in st.dataframe and st.data_editor (#7987). 🗺️ Streamlit supports using pydeck-carto with st.pydeck_chart (#8422). ❄️ Additional snowflake requirements were updated to allow Python versions 3.8 to 3.11 (#8538). 🍞 st.toast received visual improvements and now appears in the top right (#8433). 🦋 Visual tweaks for dialogs and modals. 🦀 Bug fix: st.write_stream returns an empty string when passed a generator with no yield (#8560). 🦎 Bug fix: Widgets that support None values can be correctly set to None through Session State (#8529, #7649). 🐌 Bug fix: If the initial value for st.date_input is not set and today’s date falls outside the declared minimum or maximum, then the minimum or maximum will be used instead, whichever is closer (#8519, #6167). 🕸️ Bug fix: Altair’s resolve_scale method is handled correctly (#8497, #1667). 🦗 Bug fix: st.multiselects correctly handles sets when passed to options or default (#8471, #8466). 🦂 Bug fix: st.status does not show the expander toggle when empty (#8369). 🦟 Bug fix: The width of vconcat charts in Vega and Altair is set correctly (#8498, #2751). 🦠 Bug fix: Apps print beautifully and no longer show excessive whitespace (#8502, #7815). 🪰 Bug fix: Invalid escape sequences were removed to avoid warnings from pytest (#8510, #8501). 🪳 Bug fix: st.file_uploader callback is correctly executed once per file selection after the first selection (#8493, #4877). 🕷️ Bug fix: Streamlit is compatible down to pillow version 7.1.0 instead of 9.1.0 (#8492, #8486). 🐞 Bug fix: Widget values are correctly dropped when a script run is interrupted by switching pages (#8425, #7338). 🐝 Bug fix: Apps in dark mode will return to dark mode after printing (#8469, #7879). 🐜 Bug fix: Component ready state is dynamic to avoid race conditions that caused blank apps in Safari (#8434, #8362). 🪲 Bug fix: st.slider yields a Python error when min_value is less than or equal to max_value (#8413, #8342). 🐛 Bug fix: Time is offset correctly for Vega and Altair (#8278, #4342). Version 1.33.0 Release date: April 4, 2024 Highlights 👟 Introducing st.experimental_fragment to decorate functions and rerun them independently of the whole page. Check out the docs and give your apps a speed boost! 🌐 Introducing st.html to insert custom HTML into your app! Check out the docs for how to use it. Notable Changes 📺 st.audio and st.video allow looping and setting an end time (#8203, #8348). 🔁 AppTest allows switching pages with AppTest.switch_page (#8280). 🧪 format_func is accessible in AppTest for widgets that use it (#8189, #8019, #7679). 📈 Column configuration now includes AreaChartColumn. LineChartColumn no longer shows area (#8237). 🚧 Breaking change: st.write will no longer set unsafe_allow_html=True when passed an object containing a _repr_html_ method. For more information, see PR #8238. Other Changes 🖱️Users can click on the widget label to focus on input for st.number_input, st.text_input, and st.text_area (#8155). Thanks, filiptammergard! ⬆️ Streamlit supports packaging version 24.x (#8338, #8328). 🕸️ Bug fix: Streamlit now watches for changes to imported modules in addition to pages (#8372). Thanks, zyxue! 🦗 Bug fix: Overflowing toast messages are correctly truncated (#8337, #8330). 🦂 Bug fix: st.status correctly updates to complete when using LangChain's StreamlitCallbackHandler (#8331). 🦟 Bug fix: Custom components no longer show white backgrounds in dark themes (#8242, #8156, #7813). 🦠 Bug fix: Content area width is reduced when a fullscreen icon would otherwise cause horizontal overflow (#8279, #6990). 🪰 Bug fix: Custom components with undefined frame heights will render with a height of 0 (#8290, #8285). 🪳 Bug fix: Restored a check for active sessions to prevent apps from needlessly running when no users are connected (#8294). 🕷️ Bug fix: Custom themes have precedence over embedding options (#8021, #7118). 🐞 Bug fix: Reverted the async timer to expire session storage cache to address computational efficiency (#8281). 🐝 Bug fix: When using st.popover with use_container_width=True, the popover container's minimum width will match the popover button (#8266, #8261). 🐜 Bug fix: Using st.rerun with a triggering widget in AppTest no longer creates an infinite loop (#8264, #7768). 🪲 Bug fix: URLs are correctly decoded in LinkColumn if regex is used or if not using fully qualified URLs (#8258, #7064). 🐛 Bug fix: st.query_params only sends one ForwardMsg when updating multiple parameters (#8205, #8199). Thanks, Asaurus1! Version 1.32.0 Release date: March 7, 2024 Highlights 🍿 Introducing st.popover to create popover elements in your Streamlit apps. Check out the docs to see how to use it! Notable Changes 📺 You can now pass subtitles to st.video! Check out our feature demo. ⚗️ AppTest includes support for st.expander and st.status. 🧪 AppTest.from_function accepts a function that takes arguments and/or returns a value. 🧩 The timeout warning for custom components was replaced with an element skeleton to improve the UX for slow-loading components, especially in some cloud-hosted platforms (#8179, #7046). 📄 st.switch_page and st.page_link received significant improvements to path handling, performance, and visual appearance (see below for details). 🦀 Bug fix: Streamlit uses glide-data-grid version 6.0.4 to fix a variety of dataframe issues (#7779, #6900, #7032, #7727, #6810, #7930, #7949, #7831, #8168). 💦 Bug fix: We've plugged a significant memory leak in the coroutine loop. Apps that generate a large number of small messages between client and server will benefit greatly (#8068, #7989, #6510). Other Changes 💪 Multiple modules are now lazy-loaded to speed up Streamlit's import time (#8150, #8143, #8134, #8113, #8125, #8111, #8109, #6066). 🖼️ st.write supports PIL images (#8039). 🔗 st.radio allows markdown links within the items passed to options (#8028, #7992). 💀 The deprecation.showPyplotGlobalUse config option is deprecated and will be removed in the subsequent release (#8133). 🤖 Streamlit supports AzureOpenAI chat stream (#8107, #8084). 🌐 The /healthz endpoint supports the HTTP HEAD method (#8145, #8144). Thanks, rahulmistri1997! 🌀 The cache parameter for st.spinner is now private (_cache) since it's for internal use (#8118). 🏃 Session storage is checked and expired asynchronously to improve performance and efficiency of apps with lower traffic (#8083). 🐜 st.write_stream raises a descriptive Exception when the message cannot be parsed (#8036). 📘 Fixed a typo in the examples for st.switch_page and st.page_link (#8162). Thanks, t1emp0! 👻 Bug fix: st.help correctly displays conditional members (#8228). 🦋 Bug fix: App State fully clears on page change to prevent lingering stale elements (#8208). 🦎 Bug fix: st.info, st.success, st.warning, and st.error don't overflow with long markdown strings (#8194, #6394). 🐌 Bug fix: Streamlit shows a warning that port 3000 is reserved for development when the server port is set to 3000 (#8152, #8149). 🕸️ Bug fix: st.page_link and st.switch_page have improved path calculation for consistency (#8127). 🦗 Bug fix: st.page_link shows the correct path in browser on hover (#8086, #8080). 🦂 Bug fix: st.page_link and st.switch_page normalize paths for correct handling in Windows (#8103, #8070). 🦟 Bug fix: Script runner uses a while loop instead of recursion to avoid stack overflows (#8100). 🦠 Bug fix: st.page_link and st.switch_page correctly handle relative paths prefixed with ""/"" (#8085, #8081). 🪰 Bug fix: st.image parses paths in Windows correctly (#8092, #7271, #6066). 🪳 Bug fix: st.switch_page no longer waits for the current page to finish running before switching pages (#8054, #7954). 🕷️ Bug fix: st.map and other simple charts correctly handle color when data is not indexed starting from 0 (#8158, #8079, #8077). Thanks, awhazell! 🐞 Bug fix: st.selectbox, st.multiselect, st.select_slider, and st.radio use shallow copies of their options to prevent unexpected mutations (#8064, #7534). 🐝 Bug fix: The selected time in st.time_input displays correctly in dark mode (#8056, #7436). 🪲 Bug fix: Dataframe scrollbars display correctly in the latest version of Chrome (#8034). 🐛 Bug fix: Casting st.query_params to str will print the content of the query parameters instead of the class description (#8030). Version 1.31.0 Release date: February 1, 2024 Release videos What's new? Highlights 🔗 Introducing st.page_link! Now, you can build custom navigation menus for your multipage apps. Check out our docs to see how. 💦 Announcing st.write_stream to conveniently handle generators and streamed responses. Check out our docs to see how making chat apps just got easier. Notable Changes 📝 st.chat_input can be used inline and placed anywhere in the app. You can also have multiple st.chat_input widgets on a page (#7896). Other Changes 🧹 Internal refactoring and cleanup (#7980). Thanks, whitphx! ❄️ Bug fix: Snowpark is now an optional dependency for SnowflakeConnection (#7919). 🕷️ Bug fix: The watchdog suggestion is disabled when server.fileWatcherType is set to none or poll (#8024, #7999). 🐞 Bug fix: Required columns can be hidden when not using st.data_editor with dynamic rows (#7996, #7991). 🐝 Bug fix: New period types are supported for pandas 2.2.0 (#7988). 🐜 Bug fix: Custom components receive only the app's origin and path to avoid reloading components when query parameters change (#7951, #7503). Thanks, eric-skydio! 🪲 Bug fix: st.progress won't raise an exception when given a value above 1.0 due to float precision (#7953, #5517). Thanks, notiona! 📚 Streamlit supportsimportlib-metadata version 7 (#7925). Thanks, elgalu! 🐛 Bug fix: AppTest correctly sees widgets inside containers (#7923, #7711). 💿 Custom components no longer accumulate style elements when re-rendered for better performance (#7914). Thanks, Tom-Julux! Version 1.30.0 Release date: January 11, 2024 Release videos What's new? Highlights 🔄 Announcing st.switch_page to programmatically switch pages in multipage apps! Check out our docs to learn about this highly anticipated feature! ❓Introducing st.query_params to handle variables passed through your app's URL. Check out our docs to understand this feature and how it's been upgraded and improved from our experimental version! Notable Changes 📐 st.container can be configured with a height to create grids or scrolling containers (#7697, #2169, #2447). 🔗 For dataframes, LinkColumn has a simplified UI and can be configured with display text, including programmatically defined text through regular expressions (#7784, #7741, #6787). 🧭 Sidebar navigation for multipage apps can be hidden via configuration (#7852). ⏩ Plotly figures can load even faster when used in combination with orjson (#7860). Thanks, eric-skydio! ♻️ Behavior change: Query parameters are removed when changing pages (#7817, #6725, #5505). Other Changes 🛠️ showFooter is no longer an embed option since the footer no longer exists (#7902, #7785). 🕵️ All security concerns should be reported through HackerOne (#7783). 🕷️ Bug fix: Tabs are not disabled when stale to prevent flickering (#7905, #7820). 🛡️ Bug fix: The full file path is used instead of a prefix to prevent custom components from reaching beyond their own folders (#7901). 🪱 Bug fix: Widgets raise an exception if its values aren't Python comparable (#7840, #3714). 🐞 Bug fix: The down-arrow icons on expanders maintain a consistent size (#7596). Thanks, matiboux! 🐝 Bug fix: Tabs no longer flicker when switching between them (#7904). 🐜 Bug fix: Enter-to-submit is automatically disabled when the associated st.form_submit_button is disabled (#7827, #7822). 🪲 Bug fix: Required columns cannot be hidden with column configuration (#7888, #7559). 🐛 Bug fix: Using nan as a value in SelectboxColumn will raise an error instead of silently failing (#7887, #7558). 🌙 Bug fix: Custom component iframes allow dark mode (#7821, #7813). 🪰 Bug fix: The command to start Streamlit is not sent to the frontend (#7787). 💅 Bug fix: The background color of st.toggle is enhanced for better visibility (#7788). 🪳 Bug fix: Built-in charts can handle ordered categorical columns (#7771, #7776). Version 1.29.0 Release date: November 30, 2023 Highlights 🔲 st.container and st.form now have a border parameter to show or hide a border. 🐍 Streamlit supports Python 3.12! Notable Changes ⌛ st.dataframe, st.data_editor, and st.table support datetime.timedelta values (#7689, #4489). 💀 Streamlit apps preload skeleton elements for a smoother appearance when initializing (#7598). 🏃 Reduced the overhead of running AppTest-simulated apps, especially for fast-running apps (#7691). 🛁 String representations of AppTest data are improved for a better testing and debugging experience (#7658). 🔢 Apps can be configured to identify Enum classes as the same if they have matching member names (#7408, #4909). Thanks, Asaurus1! ❌ The ""Made with Streamlit"" footer no longer appears at the bottom of apps (#7583). 🧹 Unused config options have been deprecated (#7584). 🕳️ Query parameters can be empty (#7601, #7416). 💅 Visual tweaks (#7592, #7630). Other Changes 🦗 Bug fix: Convert floats to bytes instead of hashing to avoid hashing instability (#7754). Thanks, BlackHC! 🦎 Bug fix: Corrected broken URLs and typos in error messages (#7746, #7764, #7770). Thanks, ObservedObserver! 🐌 Bug fix: st.connection correctly caches results when using two connections of the same type (#7730, #7709). 🕸️ Bug fix: Using context managers with multithreading now displays content in the expected order (#7715, #7668). Thanks, eric-skydio! 🦂 Bug fix: Added https fallback when obtaining the host machine's address (#7712, #7703). Thanks, LarsHill! 🛡️ Bug fix: Added security patch for pyarrow vulnerability. Custom components using pyarrow table deserialization should require pyarrow>=14.0.1 (#7695, #7700). 🦟 Bug fix: Improved typing for st.connection (#7671). Thanks, thezanke! 🪰 Bug fix: Retries of SnowflakeConnection methods are narrowed to only occur with transient errors to avoid unnecessary repeated errors (#7645, #7637). 🏗️ Removed the v0 testing framework which was undocumented (#7657). 🪳 Bug fix: The navigation expander arrow no longer disappears (#7634, #7547). ❄️ Improved the error message for SnowflakeConnection when a configuration is not found (#7652). 🕷️ Bug fix: st.rerun no longer causes a RecursionError when used with st.chat_input (#7643, #7629). 🐞 Bug fix: st.file_uploader no longer causes an extra rerun and therefore doesn't conflict with st.chat_input (#7641, #7556). 🐝 Bug fix: AppTest no longer raises an error when encountering st.container (#7644, #7636). 🪲 Bug fix: Graphviz charts scale correctly when exiting fullscreen view (#7398, #7527). 🎥 Bug fix: ""Record a screencast"" is hidden when known to be unsupported in a browser (#7604). 🐛 Bug fix: Increased the top padding of embedded apps to better display the dataframe toolbar (#7681, #7609, #7607). 🐜 Bug fix: st.rerun uses NoReturn for improved type checking (#7422) Thanks, kongzii. Version 1.28.0 Release date: October 26, 2023 Release videos Introducing AppTest Highlights 🧪 Introducing a new testing framework for Streamlit apps! Check out our documentation to learn how to build automated tests for your apps. 💻 Announcing the general availability of st.connection, a command to conveniently manage connections in Streamlit apps. Check out the docs to learn more. ❄️ SnowparkConnection has been upgraded to the new and improved SnowflakeConnection — the same, great functionality plus more! Check out our built-in connections. 🛠️ st.dataframe and st.data_editor have a new toolbar! Users can search and download data in addition to enjoying improved UI for row additions and deletions. See our updated guide on Dataframes. Notable Changes 🌀 When using a spinner with cached functions, the spinner will be overlaid instead of pushing content down (#7488). 📅 st.data_editor now supports datetime index editing (#7483). 🔢 Improved support for decimal.Decimal in st.dataframe and st.data_editor (#7475). 🥸 Global kwargs were added for hashlib (#7527, #7526). Thanks, DueViktor! 📋 st.components.v1.iframe now permits writing to clipboard (#7487). Thanks, dilipthakkar! 📝 SafeSessionState disconnect was replaced with script runner yield points for improved efficiency and clarity (#7373). 🤖 The Langchain callback handler will show the full input string inside the body of a st.status when the input string is too long to show as a label (#7478). Thanks, pokidyshev! 📈 st.graphviz_chart now supports using different Graphviz layout engines (#7505, #4089). 🦋 Assorted visual tweaks (#7486, #7592). 📊 plotly.js was upgraded to version 2.26.1 (#7449, #7476, #7045). 💽 Legacy serialization for DataFrames was removed. All DataFrames will be serialized by Apache Arrow (#7429). 🖼️ Compatibility for Pillow 10.x was added (#7442). 📬 Migrated _stcore/allowed-message-origins endpoint to _stcore/host-config (#7342). 💬 Added post_parent_message platform command to send custom messages from a Streamlit app to its parent window (#7522). Other Changes ⌨️ Improved string dtype handling for DataFrames (#7479). ✒️ st.write will avoid using unsafe_allow_html=True if possible (#7432). 🐛 Bug fix: Implementation of st.expander was simplified for improved behavior and consistency (#7247, #2839, #4111, #4651, #5604). 🪲 Bug fix: Multipage links in the sidebar are now aligned with other sidebar elements (#7531). 🐜 Bug fix: st.chat_input won't incorrectly prompt for label parameter in IDEs (#7560). 🐝 Bug fix: Scroll bars correctly overlay st.dataframe and st.data_editor without adding empty space (#7090, #6888). 🐞 Bug fix: st.chat_message behaves correctly with the removal of AutoSizer (#7504, #7473). 🕷️ Bug fix: Anchor links are reliably produced for non-English headers (#7454, #5291). ☃️ Bug fix: st.connections.SnowparkConnection more accurately detects when it's running within Streamlit in Snowflake (#7502). 🪳 Bug fix: A user-friendly warning is shown when exceeding the size limitations of a pandas Styler object (#7497, #5953). 🪰 Bug fix: st.data_editor automatically converts non-string column names to strings (#7485, #6950). 🦠 Bug fix: st.data_editor correctly identifies non-range indices as a required column (#7481, #6995). 🦟 Bug fix: st.file_uploader displays compound file extensions like csv.gz correctly (#7362). Thanks, mo42! 🦂 Bug fix: Column Configuration no longer uses deprecated type checks (#7496, #7477, #7550). Thanks, c-bik! 🦗 Bug fix: Additional toolbar items no longer stack vertically (#7470, #7471). 🕸️ Bug fix: Column Configuration no longer causes a type warning in Mypy (#7457). Thanks, kopp! 🐌 Bug fix: Bokeh Sliders no longer cause JavaScript errors (#7441, #7171). 🦎 Bug fix: Caching now recognizes DataFrames with the same values but different column names as different (#7331, #7086). Version 1.27.0 Release date: September 21, 2023 Highlights ✨ Introducing st.scatter_chart — a new, simple chart element to build scatter charts Streamlit-y fast and easy! See our documentation. 🔗 Introducing st.link_button! Want to open an external link in a new tab with a bit more pizazz than a plain-text link? Check out our documentation to see how. 🏃 Announcing the general availability of st.rerun, a command to interrupt your script and trigger an immediate rerun. Notable Changes 👻 You can initialize widgets with an empty state by setting None as an initial value for st.number_input, st.selectbox, st.date_input, st.time_input, st.radio, st.text_input, and st.text_area! 📤 st.download_button now uses target=""_self"" instead of opening a new tab (#7151, #7132). 🧟 Removed unmaintained pympler dependency (#7193, #7131). Thanks, rudyardrichter! Other Changes 🐛 Bug fix: st.multiselect now shows a correct message when no result matches a user's search (#7205, #7116). 🪲 Bug fix: st.experimental_user now defaults to test@example.com (#7219, #7215). 🐜 Bug fix: st.slider labels don't overlap when small ranges are selected (#7221, #3385). 🐝 Bug fix: Type-checking correctly identifies all string types to avoid hashing errors (#7255, #6455). 🐞 Bug fix: JSON is parsed with JSON5 to avoid errors from null values when using st.pydeck_chart (#7256, #5799). 🕷️ Bug fix: Identical widgets on different pages are correctly interpreted by Streamlit as distinct (#7264, #6146). 🦋 Bug fix: Visual tweaks to widgets for responsive behavior (#7145). 🪳 Bug fix: SVGs are accurately displayed (#7183, #3882). 🪰 Bug fix: st.video correctly updates with changes to start_time (#7257, #7126). 🦠 Bug fix: Additional error handling was added to st.session_state (#7280, #7206). 🦟 Bug fix: st.map correctly refreshes with new data (#7307, #7294). 🦂 Bug fix: The decorative app header line is no longer covered by the sidebar (#7297, #6264). 🦗 Bug fix: st.code no longer triggers a CachedStFunctionWarning (#7306, #7055). 🕸️ Bug fix: st.download_button no longer resets with different data (#7316, #7308). 🐌 Bug fix: Widgets consistently recognize user interaction while a page is still running, with or without fastRerun enabled (#7283, #6643). 🦎 Bug fix: st.tabs was improved to better handle and render conditionally appearing tabs (#7287, #7310, #5454, #7040). Version 1.26.0 Release date: August 24, 2023 Highlights 🤖 Introducing st.status to display output from long-running processes and external API calls (#7140). Works great with st.chat_message! See our documentation for how to use this feature. 🚥 Introducing st.toggle — an alternative to st.checkbox when you need an on/off switch. Notable Changes 🎨 Simple chart elements have a color parameter to set the color of your data points or series (#7022). 🌈 Markdown supports rainbow and gray colors (#7106, #7179). 📏 st.header and st.subheader have optional, colored dividers (#7133). 🚀 Deploying to Community Cloud is even easier—locally running apps have a deploy button in their toolbars (#7085, #6935). 🖌️ st.download_button has a new parameter type for theming (#7056, #7038). 🤖 st.chat_message has ai and human presets for messages (#7094). 💅 st.radio options support markdown and have captions (#7018, #7105, #6085). 🧼 Assorted visual tweaks (#7050, #894). 🛏️ Replaced deprecated imghdr dependency with pillow (#7081, #7027). 🔢 st.number_input's step buttons (+/-) are ignored during tabbing navigation (#7154). Thanks @denck007! Other Changes 🍞 Bug fix: Toast messages are no longer blocked by st.chat_input (#7204, #7115). 🕸️ Bug fix: Widget IDs are now stable to prevent inconsistent statefulness (#7003). 🦟 Bug fix: Browser autofill is correctly recognized within forms now (#7150, #7101, #7084). 🪱 Bug fix: st.file_uploader no longer causes session state to reset when a websocket connection is dropped and reconnected (#7149, #7025). 🏎️ Bug fix: Pydeck JSON data is cached for improved performance (#7113, #5532). 🦋 Bug fix: st.chat_input no longer submits prematurely while typing with an input method editor (#6993). 🐞 Bug fix: Label backgrounds for st.tabs are now transparent (#7070, #5707). 🐝 Bug fix: Page width is no longer ignored when using the help parameter in st.button (#7033, #6161). 🐜 Bug fix: Tweaked Altair color specification for improved visibility in dark mode (#7061, #3343). 🪲 Bug fix: st.chat_message can correctly use local images as avatars (#7130). 🐛 Bug fix: Specified that MD5 is not used for security (#7122, #7120). 🪄 Bug fix: Async function docstrings are ignored by Streamlit magic (#7143, #7137). Version 1.25.0 Release date: July 20, 2023 Highlights 🍞 Introducing st.toast — a command to briefly show toast messages to users in the bottom-right corner of apps. See our documentation on how to use this feature. Notable Changes 🗺️ st.map now has parameters for latitude, longitude, color, and size to customize data points (#6896). 🚩 st.multiselect supports setting placeholders and specifying the maximum number of selections via the placeholder and max_selections keyword-only arguments, respectively (#6901, #4750). Thanks, @fhiroki! 📅 Customize the date format for st.date_input with the format parameter (#6974, #5234). ↩️ Forms can now be submitted with Enter/Return while inside st.text_input, st.number_input, or st.text_area (#6911, #3790). 🍢 The app menu icon in the upper-right corner of apps has been changed from ""☰"" to ""⋮"" (#6947). Other Changes ⛓️ Minimum required versions increased for multiple Python dependencies, including numpy>=1.19.3 and pandas>=1.3.0 (#6802). 🛡️ protobufjs was bumped from 7.2.1 to 7.2.4 (#6959). ✨ Visual design tweaks to Streamlit's input widgets (#6944). 🦋 Bug Fix: st.slider now accepts general number types like numpy.int64 instead of just int and float (#6816, #6815). Thanks, @milliams! 🐜 Bug Fix: Data labels for st.slider and st.select_slider no longer overflow when inside st.expander (#6828, #6297). 🐛 Bug Fix: Elements no longer re-render from scratch with each rerun (#6923, #6920). 🐞 Bug Fix: st.data_editor hashes styler objects correctly for stability across reruns (#6815, #6898). 🐝 Bug Fix: Fixed the padding for embedded apps using st.chat_input to prevent messages being cutoff (#6979). Version 1.24.0 Release date: June 27, 2023 Highlights 💬 Introducing st.chat_message and st.chat_input — two new chat elements that let you build conversational apps. Learn how to use these features in your LLM-powered chat apps in our tutorial. 💾 Streamlit's caching decorators now allow you to customize Streamlit's hashing of input parameters with the keyword-only argument hash_funcs. Notable Changes 🐍 We've deprecated support for Python 3.7 in the core library and Streamlit Community Cloud (#6868). 📅 st.cache_data and st.cache_resource can hash timezone-aware datetime objects (#6812, #6690, #5110). Other Changes ✨ Visual design tweaks to Streamlit's input widgets (#6817). 🐛 Bug fix: st.write pretty-prints dataclasses using st.help (#6750). 🪲 Bug fix: st.button's height is consistent with that of other widgets (#6738). 🐜 Bug fix: Upgraded the react-range frontend dependency to fix the memory usage of sliders (#6764, #5436). Thanks @wolfd! 🐝 Bug fix: Pydantic validators no longer result in exceptions on app reruns (#6664, #3218). 🐞 Bug fix: streamlit config show honors newlines (#6758, #2868). 🪰 Bug fix: Fixed a race condition to ensure Streamlit reruns the latest code when the file changes (#6884). 🦋 Bug fix: Apps no longer rerun when users click anchor links (#6834, #6500). 🕸️ Bug fix: Added robust out-of-bounds checks for min_value and max_value in st.number_input (#6847, #6797). Version 1.23.0 Release date: June 1, 2023 Highlights ✂️ Announcing the general availability of st.data_editor, a widget that allows you to edit DataFrames and many other data structures in a table-like UI. Breaking change: the data editor's representation used in st.session_state was altered. Find out more about the new format in Access edited data. ⚙️ Introducing the Column configuration API with a suite of methods to configure the display and editing behavior of st.dataframe and st.data_editor columns (e.g. their title, visibility, type, or format). Keep an eye out for a detailed blog post and in-depth documentation upcoming in the next two weeks. 🔌 Learn to use st.experimental_connection to create and manage data connections in your apps with the new Connecting to data docs and video tutorial. Notable Changes 📊 Streamlit now supports Protobuf 4 and Altair 5 (#6215, #6618, #5626, #6622). ☎️ st.dataframe and st.data_editor can hide index columns with hide_index, specify the display order of columns with column_order, and disable editing for individual columns with the disabled parameter. ⏱️ The ttl parameter in st.cache_data and st.cache_resource accepts formatted strings, so you can simply say ttl=""30d"", ttl=""1h30m"" and any other combination of w, d, h, m, s supported by Pandas's Timedelta constructor (#6560). 📂 st.file_uploader now interprets the type parameter more accurately. For example, ""jpg"" or "".jpg"" now accept both ""jpg"" and ""jpeg"" extensions. This functionality has also been extended to ""mpeg/mpg"", ""tiff/tif"", ""html/htm"", and ""mpeg4/mp4"". 🤫 The new global.disableWidgetStateDuplicationWarning configuration option allows the silencing of warnings triggered by setting widget default values and keyed session state values concurrently (#3605, #6640). Thanks, @antonAce! Other Changes 🏃‍♀️Improved startup time by lazy loading some dependencies (#6531). 👋 Removed st.beta_* and st.experimental_show due to deprecation and low-use (#6558) 🚀 Further improvements to st.dataframe and st.data_editor: Improved editing on mobile devices for the data editor (#6548). All editable columns have an icon in their column header and support tooltips (#6550, #6561). Enable editing for columns containing datetime, date, or time values (#6025). New input validation options for columns in the data editor, such as max_chars and validate for text columns, and min_value, max_value and step for number columns (#6563). Improved type parsing capabilities in the data editor (#6551). Unified missing values to None in returned data structures (#6544). A warning is shown in cells when integers exceed the maximum safe value of (2^53) -1 (#6311, #6549). Prevented editing the sessions state by showing a warning (#6634). Fixed issues with list columns sometimes breaking the frontend (#6644). Fixed a display issue with index columns using category dtype (#6680, #6598). Fixed an issue that prevented a rerun when adding empty rows (#6598). Unified the behavior between st.data_editor and st.dataframe related to auto-hiding the index column(s) based on the input data (#6659, #6598) 🛡️ Streamlit's Security Policy can be found in its GitHub repository (#6666). 🤏 Documented the integer size limit for st.number_input and st.slider (#6724). 🐍 The majority of Streamlit's Python dependencies have set a maximum allowable version, with the standard upper limit set to the next major version, but not inclusive of it (#6691). 💅 UI design improvements to in-app modals (#6688). 🐞 Bug fix: st.date_input's date selector is equally visible in dark mode (#6072, #6630). 🐜 Bug fix: the sidebar navigation expansion indicator in multipage apps is restored (#6731). 🐛 Bug fix: The docstring and exception message for st.set_page_config have been updated to clarify that this command can be invoked once for each page within a multipage app, rather than once per entire app (#6594). 🐝 Bug fix: st.json no longer collapses multiple spaces in both keys and values with single space when rendered (#6657, #6663). Version 1.22.0 Release date: April 27, 2023 Highlights 🔌 Introducing st.experimental_connection: Easily connect your app to data sources and APIs using our new connection feature. Find more details in the API reference, and stay tuned for an upcoming blog post and in-depth documentation! In the meantime, explore our updated MySQL and Snowflake connection tutorials for examples of this feature. Notable Changes 🐼 Streamlit now supports Pandas 2.0 (#6413, #6378, #6507). Thanks, connortann! 🍔 Customize the visibility of items in the toolbar, options menu, and the settings dialog using the client.toolbarMode config option (#6174). 🪵 Streamlit logs now reside in the ""streamlit"" namespace instead of the root logger, enabling app developers to better manage log handling (#3978, #6377). Other Changes 🔏 CLI parameters can no longer be used to set sensitive configuration values (#6376). 🤖 Improved the debugging experience by reducing log noise (#6391). 🐞 Bug fix: @st.cache_data decorated functions support UUID objects as parameters (#6440, #6459). 🐛 Bug fix: Tabbing through buttons and other elements now displays a red border only when focused, not when clicked (#6373). 🪲 Bug fix: st.multiselect's clear icon is larger and includes a hover effect (#6471). 🐜 Bug fix: Custom theme font settings no longer apply to code blocks (#6484, #6535). ©️ Bug fix: st.code's copy-to-clipboard button appears when you hover on code blocks (#6490, #6498). Version 1.21.0 Release date: April 6, 2023 Highlights 📏 Introducing st.divider — a command that displays a horizontal line in your app. Learn how to use this command in its API reference. 🔏 Streamlit now supports the use of a global secrets.toml file, in addition to a project-level file, to easily store and securely access your secrets. Learn more in Secrets management. 🚀 st.help has been revamped to show more information about object methods, attributes, classes, and more, which is great for debugging (#5857, #6382)! Notable Changes 🪜 st.time_input supports adding a stepping interval with the keyword-only step parameter (#6071). ❓ Most text elements can include tooltips with the help parameter (#6043). ↔️ st.pyplot has a use_container_width parameter to set the chart to the container width (now all chart elements support this parameter) (#6067). 👩‍💻 st.code supports optionally displaying line numbers to the code block's left with the boolean line_numbers parameter (#5756, #6042). ⚓ Anchors in header elements can be turned off by setting anchor=False (#6158). Other Changes 🐼 st.table and st.dataframe support pandas.Period, and number and boolean types in categorical columns (#2547, #5429, #5329, #6248). 🕸️ Added .webp to the list of allowed static file extensions (#6331) 🐞 Bug fix: stop script execution on websocket close to immediately clear session information (#6166, #6204). 🐜 Bug fixes: updated allowed/disallowed label markdown behavior such that unsupported elements are unwrapped and only their children (text contents) render (#5872, #6036, #6054, #6163). 🪲 Bug fixes: don't push browser history states on rerun, use HTTPS to load external resources in streamlit hello, and make the browser back button work for multipage apps (#5292, #6266, #6232). Thanks, whitphx! 🐝 Bug fix: avoid showing emoji on non-UTF-8 terminals. (#2284, #6088). Thanks, kcarnold! 📁 Bug fix: override default use of File System Access API for react-dropzone so that st.file_uploader's File Selection Dialog only shows file types corresponding to those included in the type parameter (#6176, #6315). 💾 Bug fix: make the .clear() method on cache-decorated functions work (#6310, #6321). 🏃 Bug fix: st.experimental_get_query_params doesn't need reruns to work (#6347, #6348). Thanks, PaleNeutron! 🐛 Bug fix: CachedStFunctionWarning mentions experimental_allow_widgets instead of the deprecated suppress_st_warning (#6216, #6217). Version 1.20.0 Release date: March 09, 2023 Notable Changes 🔐 Added support for configuring SSL to serve apps directly over HTTPS (#5969). 🖼️ Granular control over app embedding behavior with the /?embed and /?embed_options query parameters. Learn how to use this feature in our docs (#6011, #6019). ⚡ Enabled the runner.fastReruns configuration option by default to make apps much more responsive to user interaction (#6200). Other Changes 🍔 Cleaned up the hamburger menu by removing the least used options (#6080). 🖨️ Design changes to ensure apps being printed or saved as a PDF look good (#6180). 🐞 Bug fix: improved dtypes checking in st.experimental_data_editor (#6185, #6188). 🐛 Bug fix: properly position st.metric's help tooltip when not inside columns (#6168). 🪲 Bug fix: regression in retrieving messages from the server's ForwardMsgCache (#6210). 🌀 Bug fix: st.cache_data docstring for the show_spinner param now lists str as a supported type (#6207, #6213). ⏱️ Made ping and websocket timeouts far more forgiving (#6212). 🗺️ st.map and st.pydeck_chart docs state that Streamlit's Mapbox token will not work indefinitely (#6143). Version 1.19.0 Release date: February 23, 2023 Highlights ✂️ Introducing st.experimental_data_editor, a widget that allows you to edit DataFrames and many other data structures in a table-like UI. Read more in our documentation and blog post. Other Changes ✨ Streamlit's GitHub README got a new look (#6016). 🌚 Improved readability of styled dataframe cells in dark mode (#6060, #6098). 🐛 Bug fix: make apps work again in the latest versions of Safari, and in Chrome with third-party cookies blocked (#6092, #6094, #6087, #6100). 🐞 Bug fix: refer to new cache primitives in the ""Clear cache"" dialog and error messages (#6082, #6128). 🐝 Bug fix: properly cache class member functions and instance methods (#6109, #6114). 🐜 Bug fix: regression in st.metric tooltip position (#6093, #6129). 🪲 Bug fix: allow fullscreen button to show for dataframes, charts, etc, in expander (#6083, #6148). Version 1.18.0 Release date: February 09, 2023 Highlights 🎊 Introducing @st.cache_data and @st.cache_resource — two new caching commands to replace st.cache! Check out our blog post and documentation for more information. Notable Changes 🪆 st.columns supports up to one level of column nesting (i.e., columns inside columns) in the main area of the app. ⏳ st.progress supports adding a message to display above the progress bar with the text keyword parameter. ↔️ st.button has an optional use_container_width parameter to allow you to stretch buttons across the full container width. 🐍 We formally added support for Python 3.11. 🖨️ Save your app as a PDF via the ""Print"" option in your app's hamburger menu. 🛎️ Apps can serve small, static media files via the enableStaticServing config option. See our documentation on how to use this feature and our demo app for an example. Other Changes 🏁 All Streamlit endpoints (including /healthz) have been renamed to have a consistent pattern and avoid any clashes with reserved endpoints of GCP (notably Cloud Run and App Engine) (#5534). ⚡ Improved caching performance when multiple sessions access an uncomputed cached value simultaneously (#6017). 🚧 Streamlit only displays deprecation warnings in the browser when the client.showErrorDetails config option is set to True. Deprecation warnings always get logged to the console, regardless of whether they're displayed in-browser (#5945). 🏓 Refactored the st.dataframe internals to improve dataframe handling and conversion, such as detecting more types, converting key-value dicts to dataframes, and more (#6026, #6023). 💽 The behavior of widget labels when they are passed unsupported Markdown elements is documented (#5978). 📊 Bug fix: Plotly improvements — upgraded multiple frontend dependencies, including Plotly, to the latest version to properly redraw cached charts, make Plotly mapbox animations work, and allow users to update the figure layout when using the Streamlit theme (#5885, #5967, #6055). 📶 Bug fix: allow browser tabs that transiently disconnect (due to a network blip, load balancer timeout, etc.) to avoid losing all of their state (#5856). 📱 Bug fix: the keyboard is hidden on mobile when st.selectbox and st.multiselect have less than 10 options (#5979). 🐝 Bug fix: design tweaks to st.metric, st.multiselect, st.tabs , and menu items to prevent label overflow and scrolling issues, especially with small viewport sizes (#5933, #6034). 🐞 Bug fix: switched to a functioning Twemoji URL from which page favicons are loaded in st.set_page_config (#5943). ✍️ More type hints (#5986). Thanks, harahu! Version 1.17.0 Release date: January 12, 2023 Notable Changes 🪄 @st.experimental_singleton supports an optional validate parameter that accepts a validation function for cached data and is called each time the cached value is accessed. 💾  @st.experimental_memo's persist parameter can also accept booleans. Other Changes 📟 Multipage apps exclude __init__.py from the page selector (#5890). 📐 The iframes of embedded apps have the ability to dynamically resize their height (#5894). 🐞 Bug fix: thumb values of range sliders respect the container width (#5913). 🪲 Bug fix: all examples in docstrings of Streamlit commands contain relevant imports to make them reproducible (#5877). Version 1.16.0 Release date: December 14, 2022 Highlights 👩‍🎨 Introducing a new Streamlit theme for Altair, Plotly, and Vega-Lite charts! Check out our blog post for more information. 🎨 Streamlit now supports colored text in all commands that accept Markdown, including st.markdown, st.header, and more. Learn more in our documentation. Notable Changes 🔁 Functions cached with st.experimental_memo or st.experimental_singleton can contain Streamlit media elements and forms. ⛄ All Streamlit commands that accept pandas DataFrames as input also support Snowpark and PySpark DataFrames. 🏷 st.checkbox and st.metric can customize how to hide their labels with the label_visibility parameter. Other Changes 🗺️ st.map improvements: support for upper case columns and better exception messages (#5679, #5792). 🐞 Bug fix: st.plotly_chart respects the figure's height attribute and the use_container_width parameter (#5779). 🪲 Bug fix: all commands with the icon parameter such as st.error, st.warning, etc, can contain emojis with variant selectors (#5583). 🐝 Bug fix: prevent st.camera_input from jittering when resizing the browser window (#5661). 🐜 Bug fix: update exception layout to avoid overflow of stack traces (#5700). Version 1.15.0 Release date: November 17, 2022 Notable Changes 💅 Widget labels can contain inline Markdown. See our docs and demo app for more info. 🎵 st.audio now supports playing audio data passed in as NumPy arrays with the keyword-only sample_rate parameter. 🔁 Functions cached with st.experimental_memo or st.experimental_singleton can contain Streamlit widgets using the experimental_allow_widgets parameter. This allows caching checkboxes, sliders, radio buttons, and more! Other Changes 👩‍🎨 Design tweak to prevent jittering in sliders (#5612). 🐛 Bug fix: links in headers are red, not blue (#5609). 🐞 Bug fix: properly resize Plotly charts when exiting fullscreen (#5645). 🐝: Bug fix: don't accidentally trigger st.balloons and st.snow (#5401). Version 1.14.0 Release date: October 27, 2022 Highlights 🎨 st.button and st.form_submit_button support designating buttons as ""primary"" (for additional emphasis) or ""secondary"" (for normal buttons) with the type keyword-only parameter. Notable Changes 🤏 st.multiselect has a keyword-only max_selections parameter to limit the number of options that can be selected at a time. 📄 st.form_submit_button now has the disabled parameter that removes interactivity. Other Changes 🏓 st.dataframe and st.table accept categorical intervals as input (#5395). ⚡ Performance improvements to Plotly charts (#5542). 🪲 Bug fix: st.download_button supports non-latin1 characters in filenames (#5465). 🐞 Bug fix: Allow st.image to render a local GIF as a GIF, not as a static PNG (#5438). 📱 Design tweaks to the sidebar in multipage apps (#5538, #5445, #5559). 📊 Improvements to the axis configuration for built-in charts (#5412). 🔧 Memo and singleton improvements: support text values for show_spinner, use datetime.timedelta objects as ttl parameter value, properly hash PIL images and Enum classes, show better error messages when returning unevaluated dataframes (#5447, #5413, #5504, #5426, #5515). 🔍 Zoom buttons in maps created with st.map and st.pydeck_chart use light or dark style based on the app's theme (#5479). 🗜 Websocket headers from the current session's incoming WebSocket request can be obtained from a new ""internal"" (i.e.: subject to change without deprecation) API (#5457). 📝 Improve the text that gets printed when you first install and use Streamlit (#5473). Version 1.13.0 Release date: September 22, 2022 Notable Changes 🏷 Widgets can customize how to hide their labels with the label_visibility parameter. 🔍 st.map adds zoom buttons to the map by default. ↔️ st.dataframe supports the use_container_width parameter to stretch across the full container width. 🪄 Improvements to st.dataframe sizing: Column width calculation respects column headers, supports double click between column headers to autosize, better fullscreen support, and fixes the issue with the width parameter. Other Changes ⌨️ st.time_input allows for keyboard-only input (#5194). 💿 st.memo will warn the user when using ttl and persist keyword argument together (#5032). 🔢 st.number_input returns consistent type after rerun (#5359). 🚒 st.sidebar UI fixes including a fix for scrollbars in Firefox browsers (#5157, #5324). 👩‍💻 Improvements to usage metrics to guide API development. ✍️ More type hints! (#5191, #5192, #5242, #5243, #5244, #5245, #5246) Thanks harahu! Older versions Are you curious about older versions? To see older release notes, see Release notes (historical).Previous: Cheat sheetNext: Release notes (historical)forumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy" https://docs.streamlit.io/develop/api-reference/connections/st.secrets#stsecrets,"DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceremovePAGE ELEMENTSWrite and magicaddText elementsaddData elementsaddChart elementsaddInput widgetsaddMedia elementsaddLayouts and containersaddChat elementsaddStatus elementsaddThird-party componentsopen_in_newAPPLICATION LOGICNavigation and pagesaddExecution flowaddCaching and stateaddConnections and secretsremoveSECRETSst.secretssecrets.tomlCONNECTIONSst.connectionSnowflakeConnectionSQLConnectionBaseConnectionSnowparkConnectiondeleteCustom componentsaddUtilitiesaddConfigurationaddTOOLSApp testingaddCommand lineaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Develop/API reference/Connections and secrets/st.secretsst.secrets st.secrets provides a dictionary-like interface to access secrets stored in a secrets.toml file. It behaves similarly to st.session_state. st.secrets can be used with both key and attribute notation. For example, st.secrets.your_key and st.secrets[""your_key""] refer to the same value. For more information about using st.secrets, see Secrets management. secrets.toml Secrets can be saved globally or per-project. When both types of secrets are saved, Streamlit will combine the saved values but give precedence to per-project secrets if there are duplicate keys. For information on how to format and locate your secrets.toml file for your development environment, see secrets.toml. Example OpenAI_key = ""your OpenAI key"" whitelist = [""sally"", ""bob"", ""joe""] [database] user = ""your username"" password = ""your password"" In your Streamlit app, the following values would be true: st.secrets[""OpenAI_key""] == ""your OpenAI key"" ""sally"" in st.secrets.whitelist st.secrets[""database""][""user""] == ""your username"" st.secrets.database.password == ""your password"" Previous: Connections and secretsNext: secrets.tomlforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy" https://docs.streamlit.io/develop/api-reference/custom-components,"DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceremovePAGE ELEMENTSWrite and magicaddText elementsaddData elementsaddChart elementsaddInput widgetsaddMedia elementsaddLayouts and containersaddChat elementsaddStatus elementsaddThird-party componentsopen_in_newAPPLICATION LOGICNavigation and pagesaddExecution flowaddCaching and stateaddConnections and secretsaddCustom componentsremovest.components.v1​.declare_componentst.components.v1.htmlst.components.v1.iframeUtilitiesaddConfigurationaddTOOLSApp testingaddCommand lineaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Develop/API reference/Custom componentsCustom components Declare a componentCreate and register a custom component.st.components.v1.declare_component( ""custom_slider"", ""/frontend"", ) HTMLDisplay an HTML string in an iframe.st.components.v1.html( ""

Foo bar.

"" ) iframeLoad a remote URL in an iframe.st.components.v1.iframe( ""docs.streamlit.io"" ) Previous: Connections and secretsNext: st.components.v1​.declare_componentforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy" https://docs.streamlit.io/en/0.68.0/api.html#text-elements,"DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceremovePAGE ELEMENTSWrite and magicaddText elementsaddData elementsaddChart elementsaddInput widgetsaddMedia elementsaddLayouts and containersaddChat elementsaddStatus elementsaddThird-party componentsopen_in_newAPPLICATION LOGICNavigation and pagesaddExecution flowaddCaching and stateaddConnections and secretsaddCustom componentsaddUtilitiesaddConfigurationaddTOOLSApp testingaddCommand lineaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Develop/API referenceAPI reference Streamlit makes it easy for you to visualize, mutate, and share data. The API reference is organized by activity type, like displaying data or optimizing performance. Each section includes methods associated with the activity type, including examples. Browse our API below and click to learn more about any of our available commands! 🎈 Display almost anything Write and magic st.writeWrite arguments to the app.st.write(""Hello **world**!"") st.write(my_data_frame) st.write(my_mpl_figure) st.write_streamWrite generators or streams to the app with a typewriter effect.st.write_stream(my_generator) st.write_stream(my_llm_stream) MagicAny time Streamlit sees either a variable or literal value on its own line, it automatically writes that to your app using st.write""Hello **world**!"" my_data_frame my_mpl_figure Text elements MarkdownDisplay string formatted as Markdown.st.markdown(""Hello **world**!"") TitleDisplay text in title formatting.st.title(""The app title"") HeaderDisplay text in header formatting.st.header(""This is a header"") SubheaderDisplay text in subheader formatting.st.subheader(""This is a subheader"") CaptionDisplay text in small font.st.caption(""This is written small caption text"") Code blockDisplay a code block with optional syntax highlighting.st.code(""a = 1234"") EchoDisplay some code in the app, then execute it. Useful for tutorials.with st.echo(): st.write('This code will be printed') LaTeXDisplay mathematical expressions formatted as LaTeX.st.latex(""\int a x^2 \,dx"") Preformatted textWrite fixed-width and preformatted text.st.text(""Hello world"") DividerDisplay a horizontal rule.st.divider() Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration! PreviousTagsAdd tags to your Streamlit apps. Created by @gagan3012.st_tags(label='# Enter Keywords:', text='Press enter to add more', value=['Zero', 'One', 'Two'], suggestions=['five', 'six', 'seven', 'eight', 'nine', 'three', 'eleven', 'ten', 'four'], maxtags = 4, key='1') NLUApply text mining on a dataframe. Created by @JohnSnowLabs.nlu.load('sentiment').predict('I love NLU! <3') Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.mention(label=""An awesome Streamlit App"", icon=""streamlit"", url=""https://extras.streamlit.app"",) Annotated textDisplay annotated text in Streamlit apps. Created by @tvst.annotated_text(""This "", (""is"", ""verb""), "" some "", (""annotated"", ""adj""), (""text"", ""noun""), "" for those of "", (""you"", ""pronoun""), "" who "", (""like"", ""verb""), "" this sort of "", (""thing"", ""noun""), ""."") Drawable CanvasProvides a sketching canvas using Fabric.js. Created by @andfanilo.st_canvas(fill_color=""rgba(255, 165, 0, 0.3)"", stroke_width=stroke_width, stroke_color=stroke_color, background_color=bg_color, background_image=Image.open(bg_image) if bg_image else None, update_streamlit=realtime_update, height=150, drawing_mode=drawing_mode, point_display_radius=point_display_radius if drawing_mode == 'point' else 0, key=""canvas"",) TagsAdd tags to your Streamlit apps. Created by @gagan3012.st_tags(label='# Enter Keywords:', text='Press enter to add more', value=['Zero', 'One', 'Two'], suggestions=['five', 'six', 'seven', 'eight', 'nine', 'three', 'eleven', 'ten', 'four'], maxtags = 4, key='1') NLUApply text mining on a dataframe. Created by @JohnSnowLabs.nlu.load('sentiment').predict('I love NLU! <3') Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.mention(label=""An awesome Streamlit App"", icon=""streamlit"", url=""https://extras.streamlit.app"",) Annotated textDisplay annotated text in Streamlit apps. Created by @tvst.annotated_text(""This "", (""is"", ""verb""), "" some "", (""annotated"", ""adj""), (""text"", ""noun""), "" for those of "", (""you"", ""pronoun""), "" who "", (""like"", ""verb""), "" this sort of "", (""thing"", ""noun""), ""."") Drawable CanvasProvides a sketching canvas using Fabric.js. Created by @andfanilo.st_canvas(fill_color=""rgba(255, 165, 0, 0.3)"", stroke_width=stroke_width, stroke_color=stroke_color, background_color=bg_color, background_image=Image.open(bg_image) if bg_image else None, update_streamlit=realtime_update, height=150, drawing_mode=drawing_mode, point_display_radius=point_display_radius if drawing_mode == 'point' else 0, key=""canvas"",) TagsAdd tags to your Streamlit apps. Created by @gagan3012.st_tags(label='# Enter Keywords:', text='Press enter to add more', value=['Zero', 'One', 'Two'], suggestions=['five', 'six', 'seven', 'eight', 'nine', 'three', 'eleven', 'ten', 'four'], maxtags = 4, key='1') NLUApply text mining on a dataframe. Created by @JohnSnowLabs.nlu.load('sentiment').predict('I love NLU! <3') Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.mention(label=""An awesome Streamlit App"", icon=""streamlit"", url=""https://extras.streamlit.app"",) Next Data elements DataframesDisplay a dataframe as an interactive table.st.dataframe(my_data_frame) Data editorDisplay a data editor widget.edited = st.data_editor(df, num_rows=""dynamic"") Column configurationConfigure the display and editing behavior of dataframes and data editors.st.column_config.NumberColumn(""Price (in USD)"", min_value=0, format=""$%d"") Static tablesDisplay a static table.st.table(my_data_frame) MetricsDisplay a metric in big bold font, with an optional indicator of how the metric changed.st.metric(""My metric"", 42, 2) Dicts and JSONDisplay object or string as a pretty-printed JSON string.st.json(my_dict) Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration! PreviousImage CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates value = streamlit_image_coordinates(""https://placekitten.com/200/300"") st.write(value) Plotly EventsMake Plotly charts interactive!. Created by @null-jones.from streamlit_plotly_events import plotly_events fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.metric_cards import style_metric_cards col3.metric(label=""No Change"", value=5000, delta=0) style_metric_cards() Streamlit AggridImplementation of Ag-Grid component for Streamlit. Created by @PablocFonseca.df = pd.DataFrame({'col1': [1, 2, 3], 'col2': [4, 5, 6]}) grid_return = AgGrid(df, editable=True) new_df = grid_return['data'] Streamlit FoliumStreamlit Component for rendering Folium maps. Created by @randyzwitch.m = folium.Map(location=[39.949610, -75.150282], zoom_start=16) folium.Marker([39.949610, -75.150282], popup=""Liberty Bell"", tooltip=""Liberty Bell"").add_to(m) st_data = st_folium(m, width=725) Pandas ProfilingPandas profiling component for Streamlit. Created by @okld.df = pd.read_csv(""https://storage.googleapis.com/tf-datasets/titanic/train.csv"") pr = df.profile_report() st_profile_report(pr) Image CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates value = streamlit_image_coordinates(""https://placekitten.com/200/300"") st.write(value) Plotly EventsMake Plotly charts interactive!. Created by @null-jones.from streamlit_plotly_events import plotly_events fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.metric_cards import style_metric_cards col3.metric(label=""No Change"", value=5000, delta=0) style_metric_cards() Streamlit AggridImplementation of Ag-Grid component for Streamlit. Created by @PablocFonseca.df = pd.DataFrame({'col1': [1, 2, 3], 'col2': [4, 5, 6]}) grid_return = AgGrid(df, editable=True) new_df = grid_return['data'] Streamlit FoliumStreamlit Component for rendering Folium maps. Created by @randyzwitch.m = folium.Map(location=[39.949610, -75.150282], zoom_start=16) folium.Marker([39.949610, -75.150282], popup=""Liberty Bell"", tooltip=""Liberty Bell"").add_to(m) st_data = st_folium(m, width=725) Pandas ProfilingPandas profiling component for Streamlit. Created by @okld.df = pd.read_csv(""https://storage.googleapis.com/tf-datasets/titanic/train.csv"") pr = df.profile_report() st_profile_report(pr) Image CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates value = streamlit_image_coordinates(""https://placekitten.com/200/300"") st.write(value) Plotly EventsMake Plotly charts interactive!. Created by @null-jones.from streamlit_plotly_events import plotly_events fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.metric_cards import style_metric_cards col3.metric(label=""No Change"", value=5000, delta=0) style_metric_cards() Next Chart elements Simple area chartsDisplay an area chart.st.area_chart(my_data_frame) Simple bar chartsDisplay a bar chart.st.bar_chart(my_data_frame) Simple line chartsDisplay a line chart.st.line_chart(my_data_frame) Simple scatter chartsDisplay a line chart.st.scatter_chart(my_data_frame) Scatterplots on mapsDisplay a map with points on it.st.map(my_data_frame) MatplotlibDisplay a matplotlib.pyplot figure.st.pyplot(my_mpl_figure) AltairDisplay a chart using the Altair library.st.altair_chart(my_altair_chart) Vega-LiteDisplay a chart using the Vega-Lite library.st.vega_lite_chart(my_vega_lite_chart) PlotlyDisplay an interactive Plotly chart.st.plotly_chart(my_plotly_chart) BokehDisplay an interactive Bokeh chart.st.bokeh_chart(my_bokeh_chart) PyDeckDisplay a chart using the PyDeck library.st.pydeck_chart(my_pydeck_chart) GraphVizDisplay a graph using the dagre-d3 library.st.graphviz_chart(my_graphviz_spec) Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration! PreviousStreamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl(""https://assets5.lottiefiles.com/packages/lf20_V9t630.json"") st_lottie(lottie_hello, key=""hello"") Plotly EventsMake Plotly charts interactive!. Created by @null-jones.fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.chart += get_annotations_chart(annotations=[(""Mar 01, 2008"", ""Pretty good day for GOOG""), (""Dec 01, 2007"", ""Something's going wrong for GOOG & AAPL""), (""Nov 01, 2008"", ""Market starts again thanks to...""), (""Dec 01, 2009"", ""Small crash for GOOG after...""),],) st.altair_chart(chart, use_container_width=True) PlostA deceptively simple plotting library for Streamlit. Created by @tvst.import plost plost.line_chart(my_dataframe, x='time', y='stock_value', color='stock_name',) HiPlotHigh dimensional Interactive Plotting. Created by @facebookresearch.data = [{'dropout':0.1, 'lr': 0.001, 'loss': 10.0, 'optimizer': 'SGD'}, {'dropout':0.15, 'lr': 0.01, 'loss': 3.5, 'optimizer': 'Adam'}, {'dropout':0.3, 'lr': 0.1, 'loss': 4.5, 'optimizer': 'Adam'}] hip.Experiment.from_iterable(data).display() EChartsHigh dimensional Interactive Plotting. Created by @andfanilo.from streamlit_echarts import st_echarts st_echarts(options=options) Streamlit FoliumStreamlit Component for rendering Folium maps. Created by @randyzwitch.m = folium.Map(location=[39.949610, -75.150282], zoom_start=16) st_data = st_folium(m, width=725) Spacy-StreamlitspaCy building blocks and visualizers for Streamlit apps. Created by @explosion.models = [""en_core_web_sm"", ""en_core_web_md""] spacy_streamlit.visualize(models, ""Sundar Pichai is the CEO of Google."") Streamlit AgraphA Streamlit Graph Vis, based on react-grah-vis. Created by @ChrisDelClea.from streamlit_agraph import agraph, Node, Edge, Config agraph(nodes=nodes, edges=edges, config=config) Streamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl(""https://assets5.lottiefiles.com/packages/lf20_V9t630.json"") st_lottie(lottie_hello, key=""hello"") Plotly EventsMake Plotly charts interactive!. Created by @null-jones.fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.chart += get_annotations_chart(annotations=[(""Mar 01, 2008"", ""Pretty good day for GOOG""), (""Dec 01, 2007"", ""Something's going wrong for GOOG & AAPL""), (""Nov 01, 2008"", ""Market starts again thanks to...""), (""Dec 01, 2009"", ""Small crash for GOOG after...""),],) st.altair_chart(chart, use_container_width=True) PlostA deceptively simple plotting library for Streamlit. Created by @tvst.import plost plost.line_chart(my_dataframe, x='time', y='stock_value', color='stock_name',) HiPlotHigh dimensional Interactive Plotting. Created by @facebookresearch.data = [{'dropout':0.1, 'lr': 0.001, 'loss': 10.0, 'optimizer': 'SGD'}, {'dropout':0.15, 'lr': 0.01, 'loss': 3.5, 'optimizer': 'Adam'}, {'dropout':0.3, 'lr': 0.1, 'loss': 4.5, 'optimizer': 'Adam'}] hip.Experiment.from_iterable(data).display() EChartsHigh dimensional Interactive Plotting. Created by @andfanilo.from streamlit_echarts import st_echarts st_echarts(options=options) Streamlit FoliumStreamlit Component for rendering Folium maps. Created by @randyzwitch.m = folium.Map(location=[39.949610, -75.150282], zoom_start=16) st_data = st_folium(m, width=725) Spacy-StreamlitspaCy building blocks and visualizers for Streamlit apps. Created by @explosion.models = [""en_core_web_sm"", ""en_core_web_md""] spacy_streamlit.visualize(models, ""Sundar Pichai is the CEO of Google."") Streamlit AgraphA Streamlit Graph Vis, based on react-grah-vis. Created by @ChrisDelClea.from streamlit_agraph import agraph, Node, Edge, Config agraph(nodes=nodes, edges=edges, config=config) Streamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl(""https://assets5.lottiefiles.com/packages/lf20_V9t630.json"") st_lottie(lottie_hello, key=""hello"") Plotly EventsMake Plotly charts interactive!. Created by @null-jones.fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.chart += get_annotations_chart(annotations=[(""Mar 01, 2008"", ""Pretty good day for GOOG""), (""Dec 01, 2007"", ""Something's going wrong for GOOG & AAPL""), (""Nov 01, 2008"", ""Market starts again thanks to...""), (""Dec 01, 2009"", ""Small crash for GOOG after...""),],) st.altair_chart(chart, use_container_width=True) Next Input widgets ButtonDisplay a button widget.clicked = st.button(""Click me"") Download buttonDisplay a download button widget.st.download_button(""Download file"", file) Form buttonDisplay a form submit button. For use with st.form.st.form_submit_button(""Sign up"") Link buttonDisplay a link button.st.link_button(""Go to gallery"", url) Page linkDisplay a link to another page in a multipage app.st.page_link(""app.py"", label=""Home"", icon=""🏠"") st.page_link(""pages/profile.py"", label=""My profile"") CheckboxDisplay a checkbox widget.selected = st.checkbox(""I agree"") Color pickerDisplay a color picker widget.color = st.color_picker(""Pick a color"") MultiselectDisplay a multiselect widget. The multiselect widget starts as empty.choices = st.multiselect(""Buy"", [""milk"", ""apples"", ""potatoes""]) RadioDisplay a radio button widget.choice = st.radio(""Pick one"", [""cats"", ""dogs""]) SelectboxDisplay a select widget.choice = st.selectbox(""Pick one"", [""cats"", ""dogs""]) Select-sliderDisplay a slider widget to select items from a list.size = st.select_slider(""Pick a size"", [""S"", ""M"", ""L""]) ToggleDisplay a toggle widget.activated = st.toggle(""Activate"") Number inputDisplay a numeric input widget.choice = st.number_input(""Pick a number"", 0, 10) SliderDisplay a slider widget.number = st.slider(""Pick a number"", 0, 100) Date inputDisplay a date input widget.date = st.date_input(""Your birthday"") Time inputDisplay a time input widget.time = st.time_input(""Meeting time"") Chat inputDisplay a chat input widget.prompt = st.chat_input(""Say something"") if prompt: st.write(f""The user has sent: {prompt}"") Text-areaDisplay a multi-line text input widget.text = st.text_area(""Text to translate"") Text inputDisplay a single-line text input widget.name = st.text_input(""First name"") Data editorDisplay a data editor widget.edited = st.experimental_data_editor(df, num_rows=""dynamic"") File UploaderDisplay a file uploader widget.data = st.file_uploader(""Upload a CSV"") Camera inputDisplay a widget that allows users to upload images directly from a camera.image = st.camera_input(""Take a picture"") Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration! PreviousStreamlit ChatStreamlit Component for a Chatbot UI. Created by @AI-Yash.from streamlit_chat import message message(""My message"") message(""Hello bot!"", is_user=True) # align's the message to the right Streamlit Option MenuSelect a single item from a list of options in a menu. Created by @victoryhb.from streamlit_option_menu import option_menu option_menu(""Main Menu"", [""Home"", 'Settings'], icons=['house', 'gear'], menu_icon=""cast"", default_index=1) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.stoggle import stoggle stoggle( ""Click me!"", """"""🥷 Surprise! Here's some additional content"""""",) Streamlit ElementsCreate a draggable and resizable dashboard in Streamlit. Created by @okls.from streamlit_elements import elements, mui, html with elements(""new_element""): mui.Typography(""Hello world"") TagsAdd tags to your Streamlit apps. Created by @gagan3012.from streamlit_tags import st_tags st_tags(label='# Enter Keywords:', text='Press enter to add more', value=['Zero', 'One', 'Two'], suggestions=['five', 'six', 'seven', 'eight', 'nine', 'three', 'eleven', 'ten', 'four'], maxtags = 4, key='1') StqdmThe simplest way to handle a progress bar in streamlit app. Created by @Wirg.from stqdm import stqdm for _ in stqdm(range(50)): sleep(0.5) TimelineDisplay a Timeline in Streamlit apps using TimelineJS. Created by @innerdoc.from streamlit_timeline import timeline with open('example.json', ""r"") as f: timeline(f.read(), height=800) Camera input liveAlternative for st.camera_input which returns the webcam images live. Created by @blackary.from camera_input_live import camera_input_live image = camera_input_live() st.image(value) Streamlit AceAce editor component for Streamlit. Created by @okld.from streamlit_ace import st_ace content = st_ace() content Streamlit ChatStreamlit Component for a Chatbot UI. Created by @AI-Yash.from streamlit_chat import message message(""My message"") message(""Hello bot!"", is_user=True) # align's the message to the right Streamlit Option MenuSelect a single item from a list of options in a menu. Created by @victoryhb.from streamlit_option_menu import option_menu option_menu(""Main Menu"", [""Home"", 'Settings'], icons=['house', 'gear'], menu_icon=""cast"", default_index=1) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.stoggle import stoggle stoggle( ""Click me!"", """"""🥷 Surprise! Here's some additional content"""""",) Streamlit ElementsCreate a draggable and resizable dashboard in Streamlit. Created by @okls.from streamlit_elements import elements, mui, html with elements(""new_element""): mui.Typography(""Hello world"") TagsAdd tags to your Streamlit apps. Created by @gagan3012.from streamlit_tags import st_tags st_tags(label='# Enter Keywords:', text='Press enter to add more', value=['Zero', 'One', 'Two'], suggestions=['five', 'six', 'seven', 'eight', 'nine', 'three', 'eleven', 'ten', 'four'], maxtags = 4, key='1') StqdmThe simplest way to handle a progress bar in streamlit app. Created by @Wirg.from stqdm import stqdm for _ in stqdm(range(50)): sleep(0.5) TimelineDisplay a Timeline in Streamlit apps using TimelineJS. Created by @innerdoc.from streamlit_timeline import timeline with open('example.json', ""r"") as f: timeline(f.read(), height=800) Camera input liveAlternative for st.camera_input which returns the webcam images live. Created by @blackary.from camera_input_live import camera_input_live image = camera_input_live() st.image(value) Streamlit AceAce editor component for Streamlit. Created by @okld.from streamlit_ace import st_ace content = st_ace() content Streamlit ChatStreamlit Component for a Chatbot UI. Created by @AI-Yash.from streamlit_chat import message message(""My message"") message(""Hello bot!"", is_user=True) # align's the message to the right Streamlit Option MenuSelect a single item from a list of options in a menu. Created by @victoryhb.from streamlit_option_menu import option_menu option_menu(""Main Menu"", [""Home"", 'Settings'], icons=['house', 'gear'], menu_icon=""cast"", default_index=1) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.stoggle import stoggle stoggle( ""Click me!"", """"""🥷 Surprise! Here's some additional content"""""",) Next Media elements ImageDisplay an image or list of images.st.image(numpy_array) st.image(image_bytes) st.image(file) st.image(""https://example.com/myimage.jpg"") AudioDisplay an audio player.st.audio(numpy_array) st.audio(audio_bytes) st.audio(file) st.audio(""https://example.com/myaudio.mp3"", format=""audio/mp3"") VideoDisplay a video player.st.video(numpy_array) st.video(video_bytes) st.video(file) st.video(""https://example.com/myvideo.mp4"", format=""video/mp4"") Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration! PreviousStreamlit CropperA simple image cropper for Streamlit. Created by @turner-anderson.from streamlit_cropper import st_cropper st_cropper(img, realtime_update=realtime_update, box_color=box_color, aspect_ratio=aspect_ratio) Image CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates streamlit_image_coordinates(""https://placekitten.com/200/300"") Streamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl(""https://assets5.lottiefiles.com/packages/lf20_V9t630.json"") st_lottie(lottie_hello, key=""hello"") Streamlit WebrtcHandling and transmitting real-time video/audio streams with Streamlit. Created by @whitphx.from streamlit_webrtc import webrtc_streamer webrtc_streamer(key=""sample"") Drawable CanvasProvides a sketching canvas using Fabric.js. Created by @andfanilo.from streamlit_drawable_canvas import st_canvas st_canvas(fill_color=""rgba(255, 165, 0, 0.3)"", stroke_width=stroke_width, stroke_color=stroke_color, background_color=bg_color, background_image=Image.open(bg_image) if bg_image else None, update_streamlit=realtime_update, height=150, drawing_mode=drawing_mode, point_display_radius=point_display_radius if drawing_mode == 'point' else 0, key=""canvas"",) Image ComparisonCompare images with a slider using JuxtaposeJS. Created by @fcakyon.from streamlit_image_comparison import image_comparison image_comparison(img1=""image1.jpg"", img2=""image2.jpg"",) Streamlit CropperA simple image cropper for Streamlit. Created by @turner-anderson.from streamlit_cropper import st_cropper st_cropper(img, realtime_update=realtime_update, box_color=box_color, aspect_ratio=aspect_ratio) Image CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates streamlit_image_coordinates(""https://placekitten.com/200/300"") Streamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl(""https://assets5.lottiefiles.com/packages/lf20_V9t630.json"") st_lottie(lottie_hello, key=""hello"") Streamlit WebrtcHandling and transmitting real-time video/audio streams with Streamlit. Created by @whitphx.from streamlit_webrtc import webrtc_streamer webrtc_streamer(key=""sample"") Drawable CanvasProvides a sketching canvas using Fabric.js. Created by @andfanilo.from streamlit_drawable_canvas import st_canvas st_canvas(fill_color=""rgba(255, 165, 0, 0.3)"", stroke_width=stroke_width, stroke_color=stroke_color, background_color=bg_color, background_image=Image.open(bg_image) if bg_image else None, update_streamlit=realtime_update, height=150, drawing_mode=drawing_mode, point_display_radius=point_display_radius if drawing_mode == 'point' else 0, key=""canvas"",) Image ComparisonCompare images with a slider using JuxtaposeJS. Created by @fcakyon.from streamlit_image_comparison import image_comparison image_comparison(img1=""image1.jpg"", img2=""image2.jpg"",) Streamlit CropperA simple image cropper for Streamlit. Created by @turner-anderson.from streamlit_cropper import st_cropper st_cropper(img, realtime_update=realtime_update, box_color=box_color, aspect_ratio=aspect_ratio) Image CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates streamlit_image_coordinates(""https://placekitten.com/200/300"") Streamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl(""https://assets5.lottiefiles.com/packages/lf20_V9t630.json"") st_lottie(lottie_hello, key=""hello"") Next Layouts and containers ColumnsInsert containers laid out as side-by-side columns.col1, col2 = st.columns(2) col1.write(""this is column 1"") col2.write(""this is column 2"") ContainerInsert a multi-element container.c = st.container() st.write(""This will show last"") c.write(""This will show first"") c.write(""This will show second"") Modal dialogsInsert a modal dialog that can rerun independently from the rest of the script.@st.experimental_dialog(""Sign up"") def email_form(): name = st.text_input(""Name"") email = st.text_input(""Email"") EmptyInsert a single-element container.c = st.empty() st.write(""This will show last"") c.write(""This will be replaced"") c.write(""This will show first"") ExpanderInsert a multi-element container that can be expanded/collapsed.with st.expander(""Open to see more""): st.write(""This is more content"") PopoverInsert a multi-element popover container that can be opened/closed.with st.popover(""Settings""): st.checkbox(""Show completed"") SidebarDisplay items in a sidebar.st.sidebar.write(""This lives in the sidebar"") st.sidebar.button(""Click me!"") TabsInsert containers separated into tabs.tab1, tab2 = st.tabs([""Tab 1"", ""Tab2""]) tab1.write(""this is tab 1"") tab2.write(""this is tab 2"") Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration!Streamlit ElementsCreate a draggable and resizable dashboard in Streamlit. Created by @okls.from streamlit_elements import elements, mui, html with elements(""new_element""): mui.Typography(""Hello world"") PydanticAuto-generate Streamlit UI from Pydantic Models and Dataclasses. Created by @lukasmasuch.import streamlit_pydantic as sp sp.pydantic_form(key=""my_form"", model=ExampleModel) Streamlit PagesAn experimental version of Streamlit Multi-Page Apps. Created by @blackary.from st_pages import Page, show_pages, add_page_title show_pages([ Page(""streamlit_app.py"", ""Home"", ""🏠""), Page(""other_pages/page2.py"", ""Page 2"", "":books:""), ]) Chat elements Streamlit provides a few commands to help you build conversational apps. These chat elements are designed to be used in conjunction with each other, but you can also use them separately. st.chat_message lets you insert a chat message container into the app so you can display messages from the user or the app. Chat containers can contain other Streamlit elements, including charts, tables, text, and more. st.chat_input lets you display a chat input widget so the user can type in a message. Chat inputDisplay a chat input widget.prompt = st.chat_input(""Say something"") if prompt: st.write(f""The user has sent: {prompt}"") Chat messageInsert a chat message container.import numpy as np with st.chat_message(""user""): st.write(""Hello 👋"") st.line_chart(np.random.randn(30, 3)) Status containerDisplay output of long-running tasks in a container.with st.status('Running'): do_something_slow() st.write_streamWrite generators or streams to the app with a typewriter effect.st.write_stream(my_generator) st.write_stream(my_llm_stream) Status elements Progress barDisplay a progress bar.for i in range(101): st.progress(i) do_something_slow() SpinnerTemporarily displays a message while executing a block of code.with st.spinner(""Please wait...""): do_something_slow() Status containerDisplay output of long-running tasks in a container.with st.status('Running'): do_something_slow() ToastBriefly displays a toast message in the bottom-right corner.st.toast('Butter!', icon='🧈') BalloonsDisplay celebratory balloons!do_something() # Celebrate when all done! st.balloons() SnowflakesDisplay celebratory snowflakes!do_something() # Celebrate when all done! st.snow() Success boxDisplay a success message.st.success(""Match found!"") Info boxDisplay an informational message.st.info(""Dataset is updated every day at midnight."") Warning boxDisplay warning message.st.warning(""Unable to fetch image. Skipping..."") Error boxDisplay error message.st.error(""We encountered an error"") Exception outputDisplay an exception.e = RuntimeError(""This is an exception of type RuntimeError"") st.exception(e) Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration!StqdmThe simplest way to handle a progress bar in streamlit app. Created by @Wirg.from stqdm import stqdm for _ in stqdm(range(50)): sleep(0.5) Custom notification boxA custom notification box with the ability to close it out. Created by @Socvest.from streamlit_custom_notification_box import custom_notification_box styles = {'material-icons':{'color': 'red'}, 'text-icon-link-close-container': {'box-shadow': '#3896de 0px 4px'}, 'notification-text': {'':''}, 'close-button':{'':''}, 'link':{'':''}} custom_notification_box(icon='info', textDisplay='We are almost done with your registration...', externalLink='more info', url='#', styles=styles, key=""foo"") Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.let_it_rain import rain rain(emoji=""🎈"", font_size=54, falling_speed=5, animation_length=""infinite"",) App logic and configuration Navigation and pages Switch pageProgrammatically navigates to a specified page.st.switch_page(""pages/my_page.py"") Page linkDisplay a link to another page in a multipage app.st.page_link(""app.py"", label=""Home"", icon=""🏠"") st.page_link(""pages/profile.py"", label=""My profile"") Execution flow Modal dialogsInsert a modal dialog that can rerun independently from the rest of the script.@st.experimental_dialog(""Sign up"") def email_form(): name = st.text_input(""Name"") email = st.text_input(""Email"") FormsCreate a form that batches elements together with a “Submit"" button.with st.form(key='my_form'): name = st.text_input(""Name"") email = st.text_input(""Email"") st.form_submit_button(""Sign up"") Partial rerunsDefine a fragment to rerun independently from the rest of the script.@st.experimental_fragment(run_every=""10s"") def fragment(): df = get_data() st.line_chart(df) Rerun scriptRerun the script immediately.st.rerun() Stop executionStops execution immediately.st.stop() Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration!AutorefreshForce a refresh without tying up a script. Created by @kmcgrady.from streamlit_autorefresh import st_autorefresh st_autorefresh(interval=2000, limit=100, key=""fizzbuzzcounter"") PydanticAuto-generate Streamlit UI from Pydantic Models and Dataclasses. Created by @lukasmasuch.import streamlit_pydantic as sp sp.pydantic_form(key=""my_form"", model=ExampleModel) Streamlit PagesAn experimental version of Streamlit Multi-Page Apps. Created by @blackary.from st_pages import Page, show_pages, add_page_title show_pages([ Page(""streamlit_app.py"", ""Home"", ""🏠""), Page(""other_pages/page2.py"", ""Page 2"", "":books:""), ]) Caching and state Cache dataFunction decorator to cache functions that return data (e.g. dataframe transforms, database queries, ML inference).@st.cache_data def long_function(param1, param2): # Perform expensive computation here or # fetch data from the web here return data Cache resourceFunction decorator to cache functions that return global resources (e.g. database connections, ML models).@st.cache_resource def init_model(): # Return a global resource here return pipeline( ""sentiment-analysis"", model=""distilbert-base-uncased-finetuned-sst-2-english"" ) Session stateSession state is a way to share variables between reruns, for each user session.st.session_state['key'] = value Query parametersGet, set, or clear the query parameters that are shown in the browser's URL bar.st.query_params[key] = value st.query_params.clear() Connections and databases Setup your connection Create a connectionConnect to a data source or APIconn = st.connection('pets_db', type='sql') pet_owners = conn.query('select * from pet_owners') st.dataframe(pet_owners) Built-in connections SnowflakeConnectionA connection to Snowflake.conn = st.connection('snowflake') SQLConnectionA connection to a SQL database using SQLAlchemy.conn = st.connection('sql') Build your own connections Connection base classBuild your own connection with BaseConnection.class MyConnection(BaseConnection[myconn.MyConnection]): def _connect(self, **kwargs) -> MyConnection: return myconn.connect(**self._secrets, **kwargs) def query(self, query): return self._instance.query(query) Secrets management Secrets singletonAccess secrets from a local TOML file.key = st.secrets[""OpenAI_key""] Secrets fileSave your secrets in a per-project or per-profile TOML file.OpenAI_key = """" Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration!AuthenticatorA secure authentication module to validate user credentials. Created by @mkhorasani.import streamlit_authenticator as stauth authenticator = stauth.Authenticate( config['credentials'], config['cookie']['name'], config['cookie']['key'], config['cookie']['expiry_days'], config['preauthorized']) WS localStorageA simple synchronous way of accessing localStorage from your app. Created by @gagangoku.from streamlit_ws_localstorage import injectWebsocketCode ret = conn.setLocalStorageVal(key='k1', val='v1') st.write('ret: ' + ret) Streamlit Auth0The fastest way to provide comprehensive login inside Streamlit. Created by @conradbez.from auth0_component import login_button user_info = login_button(clientId, domain = domain) st.write(user_info) Custom Components Declare a componentCreate and register a custom component.st.components.v1.declare_component( ""custom_slider"", ""/frontend"", ) HTMLDisplay an HTML string in an iframe.st.components.v1.html( ""

Foo bar.

"" ) iframeLoad a remote URL in an iframe.st.components.v1.iframe( ""docs.streamlit.io"" ) Utilities and user info User infost.experimental_user returns information about the logged-in user of private apps on Streamlit Community Cloud.if st.experimental_user.email == ""foo@corp.com"": st.write(""Welcome back, "", st.experimental_user.email) else: st.write(""You are not authorized to view this page."") Get helpDisplay object’s doc string, nicely formatted.st.help(st.write) st.help(pd.DataFrame) Render HTMLRenders HTML strings to your app.css = """""" """""" st.html(css) Configuration Configuration fileConfigures the default settings for your app.your-project/ ├── .streamlit/ │ └── config.toml └── your_app.py Set page title, favicon, and moreConfigures the default settings of the page.st.set_page_config( page_title=""My app"", page_icon="":shark:"", ) Developer tools App testing st.testing.v1.AppTestst.testing.v1.AppTest simulates a running Streamlit app for testing.from streamlit.testing.v1 import AppTest at = AppTest.from_file(""streamlit_app.py"") at.secrets[""WORD""] = ""Foobar"" at.run() assert not at.exception at.text_input(""word"").input(""Bazbat"").run() assert at.warning[0].value == ""Try again."" AppTest.from_filest.testing.v1.AppTest.from_file initializes a simulated app from a file.from streamlit.testing.v1 import AppTest at = AppTest.from_file(""streamlit_app.py"") at.run() AppTest.from_stringst.testing.v1.AppTest.from_string initializes a simulated app from a string.from streamlit.testing.v1 import AppTest at = AppTest.from_string(app_script_as_string) at.run() AppTest.from_functionst.testing.v1.AppTest.from_function initializes a simulated app from a function.from streamlit.testing.v1 import AppTest at = AppTest.from_function(app_script_as_callable) at.run() BlockA representation of container elements, including: st.chat_message st.columns st.sidebar st.tabs The main body of the app. # at.sidebar returns a Block at.sidebar.button[0].click().run() assert not at.exception ElementThe base class for representation of all elements, including: st.title st.header st.markdown st.dataframe # at.title returns a sequence of Title # Title inherits from Element assert at.title[0].value == ""My awesome app"" ButtonA representation of st.button and st.form_submit_button.at.button[0].click().run() ChatInputA representation of st.chat_input.at.chat_input[0].set_value(""What is Streamlit?"").run() CheckboxA representation of st.checkbox.at.checkbox[0].check().run() ColorPickerA representation of st.color_picker.at.color_picker[0].pick(""#FF4B4B"").run() DateInputA representation of st.date_input.release_date = datetime.date(2023, 10, 26) at.date_input[0].set_value(release_date).run() MultiselectA representation of st.multiselect.at.multiselect[0].select(""New York"").run() NumberInputA representation of st.number_input.at.number_input[0].increment().run() RadioA representation of st.radio.at.radio[0].set_value(""New York"").run() SelectSliderA representation of st.select_slider.at.select_slider[0].set_range(""A"",""C"").run() SelectboxA representation of st.selectbox.at.selectbox[0].select(""New York"").run() SliderA representation of st.slider.at.slider[0].set_range(2,5).run() TextAreaA representation of st.text_area.at.text_area[0].input(""Streamlit is awesome!"").run() TextInputA representation of st.text_input.at.text_input[0].input(""Streamlit"").run() TimeInputA representation of st.time_input.at.time_input[0].increment().run() ToggleA representation of st.toggle.at.toggle[0].set_value(""True"").run() Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration!Pandas ProfilingPandas profiling component for Streamlit. Created by @okld.df = pd.read_csv(""https://storage.googleapis.com/tf-datasets/titanic/train.csv"") pr = df.profile_report() st_profile_report(pr) Streamlit AceAce editor component for Streamlit. Created by @okld.from streamlit_ace import st_ace content = st_ace() content Streamlit AnalyticsTrack & visualize user interactions with your streamlit app. Created by @jrieke.import streamlit_analytics with streamlit_analytics.track(): st.text_input(""Write something"") Previous: ConceptsNext: Write and magicforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy" https://docs.streamlit.io/develop/api-reference/custom-components/st.components.v1.html,"DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceremovePAGE ELEMENTSWrite and magicaddText elementsaddData elementsaddChart elementsaddInput widgetsaddMedia elementsaddLayouts and containersaddChat elementsaddStatus elementsaddThird-party componentsopen_in_newAPPLICATION LOGICNavigation and pagesaddExecution flowaddCaching and stateaddConnections and secretsaddCustom componentsremovest.components.v1​.declare_componentst.components.v1.htmlst.components.v1.iframeUtilitiesaddConfigurationaddTOOLSApp testingaddCommand lineaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Develop/API reference/Custom components/st.components.v1.htmlst.components.v1.htmlStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeDisplay an HTML string in an iframe. Function signature[source] st.components.v1.html(html, width=None, height=None, scrolling=False) Parameters html (str) The HTML string to embed in the iframe. width (int) The width of the frame in CSS pixels. Defaults to the app's default element width. height (int) The height of the frame in CSS pixels. Defaults to 150. scrolling (bool) If True, show a scrollbar when the content is larger than the iframe. Otherwise, do not show a scrollbar. Defaults to False. Example import streamlit as st import streamlit.components.v1 as components # bootstrap 4 collapse example components.html( """"""
Collapsible Group Item #1 content
Collapsible Group Item #2 content
"""""", height=600, ) Previous: st.components.v1​.declare_componentNext: st.components.v1.iframeforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy" https://docs.streamlit.io/develop/tutorials/databases/gcs,"DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceaddTutorialsremoveExecution flowaddConnect to data sourcesremoveAWS S3BigQueryDeta BaseFirestoreopen_in_newGoogle Cloud StorageMicrosoft SQL ServerMongoDBMySQLNeonPostgreSQLPrivate Google SheetPublic Google SheetSnowflakeSupabaseTableauTiDBTigerGraphMultipage appsaddWork with LLMsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Develop/Tutorials/Connect to data sources/Google Cloud StorageConnect Streamlit to Google Cloud Storage Introduction This guide explains how to securely access files on Google Cloud Storage from Streamlit Community Cloud. It uses Streamlit FilesConnection, the gcsfs library and Streamlit's Secrets management. Create a Google Cloud Storage bucket and add a file push_pinNoteIf you already have a bucket that you want to use, feel free to skip to the next step. First, sign up for Google Cloud Platform or log in. Go to the Google Cloud Storage console and create a new bucket. Navigate to the upload section of your new bucket: And upload the following CSV file, which contains some example data: myfile.csv Enable the Google Cloud Storage API The Google Cloud Storage API is enabled by default when you create a project through the Google Cloud Console or CLI. Feel free to skip to the next step. If you do need to enable the API for programmatic access in your project, head over to the APIs & Services dashboard (select or create a project if asked). Search for the Cloud Storage API and enable it. The screenshot below has a blue ""Manage"" button and indicates the ""API is enabled"" which means no further action needs to be taken. This is very likely what you have since the API is enabled by default. However, if that is not what you see and you have an ""Enable"" button, you'll need to enable the API: Create a service account and key file To use the Google Cloud Storage API from Streamlit, you need a Google Cloud Platform service account (a special type for programmatic data access). Go to the Service Accounts page and create an account with Viewer permission. push_pinNoteIf the button CREATE SERVICE ACCOUNT is gray, you don't have the correct permissions. Ask the admin of your Google Cloud project for help. After clicking DONE, you should be back on the service accounts overview. Create a JSON key file for the new account and download it: Add the key to your local app secrets Your local Streamlit app will read secrets from a file .streamlit/secrets.toml in your app's root directory. Create this file if it doesn't exist yet and add the access key to it as shown below: # .streamlit/secrets.toml [connections.gcs] type = ""service_account"" project_id = ""xxx"" private_key_id = ""xxx"" private_key = ""xxx"" client_email = ""xxx"" client_id = ""xxx"" auth_uri = ""https://accounts.google.com/o/oauth2/auth"" token_uri = ""https://oauth2.googleapis.com/token"" auth_provider_x509_cert_url = ""https://www.googleapis.com/oauth2/v1/certs"" client_x509_cert_url = ""xxx"" priority_highImportantAdd this file to .gitignore and don't commit it to your GitHub repo! Copy your app secrets to the cloud As the secrets.toml file above is not committed to GitHub, you need to pass its content to your deployed app (on Streamlit Community Cloud) separately. Go to the app dashboard and in the app's dropdown menu, click on Edit Secrets. Copy the content of secrets.toml into the text area. More information is available at Secrets management. Add FilesConnection and gcsfs to your requirements file Add the FilesConnection and gcsfs packages to your requirements.txt file, preferably pinning the versions (replace x.x.x with the version you want installed): # requirements.txt gcsfs==x.x.x st-files-connection Write your Streamlit app Copy the code below to your Streamlit app and run it. Make sure to adapt the name of your bucket and file. Note that Streamlit automatically turns the access keys from your secrets file into environment variables. # streamlit_app.py import streamlit as st from st_files_connection import FilesConnection # Create connection object and retrieve file contents. # Specify input format is a csv and to cache the result for 600 seconds. conn = st.connection('gcs', type=FilesConnection) df = conn.read(""streamlit-bucket/myfile.csv"", input_format=""csv"", ttl=600) # Print results. for row in df.itertuples(): st.write(f""{row.Owner} has a :{row.Pet}:"") See st.connection above? This handles secrets retrieval, setup, result caching and retries. By default, read() results are cached without expiring. In this case, we set ttl=600 to ensure the file contents is cached for no longer than 10 minutes. You can also set ttl=0 to disable caching. Learn more in Caching. If everything worked out (and you used the example file given above), your app should look like this: Previous: FirestoreNext: Microsoft SQL ServerforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy" https://docs.streamlit.io/en/latest/api.html#streamlit.write,"DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceremovePAGE ELEMENTSWrite and magicaddText elementsaddData elementsaddChart elementsaddInput widgetsaddMedia elementsaddLayouts and containersaddChat elementsaddStatus elementsaddThird-party componentsopen_in_newAPPLICATION LOGICNavigation and pagesaddExecution flowaddCaching and stateaddConnections and secretsaddCustom componentsaddUtilitiesaddConfigurationaddTOOLSApp testingaddCommand lineaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Develop/API referenceAPI reference Streamlit makes it easy for you to visualize, mutate, and share data. The API reference is organized by activity type, like displaying data or optimizing performance. Each section includes methods associated with the activity type, including examples. Browse our API below and click to learn more about any of our available commands! 🎈 Display almost anything Write and magic st.writeWrite arguments to the app.st.write(""Hello **world**!"") st.write(my_data_frame) st.write(my_mpl_figure) st.write_streamWrite generators or streams to the app with a typewriter effect.st.write_stream(my_generator) st.write_stream(my_llm_stream) MagicAny time Streamlit sees either a variable or literal value on its own line, it automatically writes that to your app using st.write""Hello **world**!"" my_data_frame my_mpl_figure Text elements MarkdownDisplay string formatted as Markdown.st.markdown(""Hello **world**!"") TitleDisplay text in title formatting.st.title(""The app title"") HeaderDisplay text in header formatting.st.header(""This is a header"") SubheaderDisplay text in subheader formatting.st.subheader(""This is a subheader"") CaptionDisplay text in small font.st.caption(""This is written small caption text"") Code blockDisplay a code block with optional syntax highlighting.st.code(""a = 1234"") EchoDisplay some code in the app, then execute it. Useful for tutorials.with st.echo(): st.write('This code will be printed') LaTeXDisplay mathematical expressions formatted as LaTeX.st.latex(""\int a x^2 \,dx"") Preformatted textWrite fixed-width and preformatted text.st.text(""Hello world"") DividerDisplay a horizontal rule.st.divider() Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration! PreviousTagsAdd tags to your Streamlit apps. Created by @gagan3012.st_tags(label='# Enter Keywords:', text='Press enter to add more', value=['Zero', 'One', 'Two'], suggestions=['five', 'six', 'seven', 'eight', 'nine', 'three', 'eleven', 'ten', 'four'], maxtags = 4, key='1') NLUApply text mining on a dataframe. Created by @JohnSnowLabs.nlu.load('sentiment').predict('I love NLU! <3') Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.mention(label=""An awesome Streamlit App"", icon=""streamlit"", url=""https://extras.streamlit.app"",) Annotated textDisplay annotated text in Streamlit apps. Created by @tvst.annotated_text(""This "", (""is"", ""verb""), "" some "", (""annotated"", ""adj""), (""text"", ""noun""), "" for those of "", (""you"", ""pronoun""), "" who "", (""like"", ""verb""), "" this sort of "", (""thing"", ""noun""), ""."") Drawable CanvasProvides a sketching canvas using Fabric.js. Created by @andfanilo.st_canvas(fill_color=""rgba(255, 165, 0, 0.3)"", stroke_width=stroke_width, stroke_color=stroke_color, background_color=bg_color, background_image=Image.open(bg_image) if bg_image else None, update_streamlit=realtime_update, height=150, drawing_mode=drawing_mode, point_display_radius=point_display_radius if drawing_mode == 'point' else 0, key=""canvas"",) TagsAdd tags to your Streamlit apps. Created by @gagan3012.st_tags(label='# Enter Keywords:', text='Press enter to add more', value=['Zero', 'One', 'Two'], suggestions=['five', 'six', 'seven', 'eight', 'nine', 'three', 'eleven', 'ten', 'four'], maxtags = 4, key='1') NLUApply text mining on a dataframe. Created by @JohnSnowLabs.nlu.load('sentiment').predict('I love NLU! <3') Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.mention(label=""An awesome Streamlit App"", icon=""streamlit"", url=""https://extras.streamlit.app"",) Annotated textDisplay annotated text in Streamlit apps. Created by @tvst.annotated_text(""This "", (""is"", ""verb""), "" some "", (""annotated"", ""adj""), (""text"", ""noun""), "" for those of "", (""you"", ""pronoun""), "" who "", (""like"", ""verb""), "" this sort of "", (""thing"", ""noun""), ""."") Drawable CanvasProvides a sketching canvas using Fabric.js. Created by @andfanilo.st_canvas(fill_color=""rgba(255, 165, 0, 0.3)"", stroke_width=stroke_width, stroke_color=stroke_color, background_color=bg_color, background_image=Image.open(bg_image) if bg_image else None, update_streamlit=realtime_update, height=150, drawing_mode=drawing_mode, point_display_radius=point_display_radius if drawing_mode == 'point' else 0, key=""canvas"",) TagsAdd tags to your Streamlit apps. Created by @gagan3012.st_tags(label='# Enter Keywords:', text='Press enter to add more', value=['Zero', 'One', 'Two'], suggestions=['five', 'six', 'seven', 'eight', 'nine', 'three', 'eleven', 'ten', 'four'], maxtags = 4, key='1') NLUApply text mining on a dataframe. Created by @JohnSnowLabs.nlu.load('sentiment').predict('I love NLU! <3') Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.mention(label=""An awesome Streamlit App"", icon=""streamlit"", url=""https://extras.streamlit.app"",) Next Data elements DataframesDisplay a dataframe as an interactive table.st.dataframe(my_data_frame) Data editorDisplay a data editor widget.edited = st.data_editor(df, num_rows=""dynamic"") Column configurationConfigure the display and editing behavior of dataframes and data editors.st.column_config.NumberColumn(""Price (in USD)"", min_value=0, format=""$%d"") Static tablesDisplay a static table.st.table(my_data_frame) MetricsDisplay a metric in big bold font, with an optional indicator of how the metric changed.st.metric(""My metric"", 42, 2) Dicts and JSONDisplay object or string as a pretty-printed JSON string.st.json(my_dict) Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration! PreviousImage CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates value = streamlit_image_coordinates(""https://placekitten.com/200/300"") st.write(value) Plotly EventsMake Plotly charts interactive!. Created by @null-jones.from streamlit_plotly_events import plotly_events fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.metric_cards import style_metric_cards col3.metric(label=""No Change"", value=5000, delta=0) style_metric_cards() Streamlit AggridImplementation of Ag-Grid component for Streamlit. Created by @PablocFonseca.df = pd.DataFrame({'col1': [1, 2, 3], 'col2': [4, 5, 6]}) grid_return = AgGrid(df, editable=True) new_df = grid_return['data'] Streamlit FoliumStreamlit Component for rendering Folium maps. Created by @randyzwitch.m = folium.Map(location=[39.949610, -75.150282], zoom_start=16) folium.Marker([39.949610, -75.150282], popup=""Liberty Bell"", tooltip=""Liberty Bell"").add_to(m) st_data = st_folium(m, width=725) Pandas ProfilingPandas profiling component for Streamlit. Created by @okld.df = pd.read_csv(""https://storage.googleapis.com/tf-datasets/titanic/train.csv"") pr = df.profile_report() st_profile_report(pr) Image CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates value = streamlit_image_coordinates(""https://placekitten.com/200/300"") st.write(value) Plotly EventsMake Plotly charts interactive!. Created by @null-jones.from streamlit_plotly_events import plotly_events fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.metric_cards import style_metric_cards col3.metric(label=""No Change"", value=5000, delta=0) style_metric_cards() Streamlit AggridImplementation of Ag-Grid component for Streamlit. Created by @PablocFonseca.df = pd.DataFrame({'col1': [1, 2, 3], 'col2': [4, 5, 6]}) grid_return = AgGrid(df, editable=True) new_df = grid_return['data'] Streamlit FoliumStreamlit Component for rendering Folium maps. Created by @randyzwitch.m = folium.Map(location=[39.949610, -75.150282], zoom_start=16) folium.Marker([39.949610, -75.150282], popup=""Liberty Bell"", tooltip=""Liberty Bell"").add_to(m) st_data = st_folium(m, width=725) Pandas ProfilingPandas profiling component for Streamlit. Created by @okld.df = pd.read_csv(""https://storage.googleapis.com/tf-datasets/titanic/train.csv"") pr = df.profile_report() st_profile_report(pr) Image CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates value = streamlit_image_coordinates(""https://placekitten.com/200/300"") st.write(value) Plotly EventsMake Plotly charts interactive!. Created by @null-jones.from streamlit_plotly_events import plotly_events fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.metric_cards import style_metric_cards col3.metric(label=""No Change"", value=5000, delta=0) style_metric_cards() Next Chart elements Simple area chartsDisplay an area chart.st.area_chart(my_data_frame) Simple bar chartsDisplay a bar chart.st.bar_chart(my_data_frame) Simple line chartsDisplay a line chart.st.line_chart(my_data_frame) Simple scatter chartsDisplay a line chart.st.scatter_chart(my_data_frame) Scatterplots on mapsDisplay a map with points on it.st.map(my_data_frame) MatplotlibDisplay a matplotlib.pyplot figure.st.pyplot(my_mpl_figure) AltairDisplay a chart using the Altair library.st.altair_chart(my_altair_chart) Vega-LiteDisplay a chart using the Vega-Lite library.st.vega_lite_chart(my_vega_lite_chart) PlotlyDisplay an interactive Plotly chart.st.plotly_chart(my_plotly_chart) BokehDisplay an interactive Bokeh chart.st.bokeh_chart(my_bokeh_chart) PyDeckDisplay a chart using the PyDeck library.st.pydeck_chart(my_pydeck_chart) GraphVizDisplay a graph using the dagre-d3 library.st.graphviz_chart(my_graphviz_spec) Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration! PreviousStreamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl(""https://assets5.lottiefiles.com/packages/lf20_V9t630.json"") st_lottie(lottie_hello, key=""hello"") Plotly EventsMake Plotly charts interactive!. Created by @null-jones.fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.chart += get_annotations_chart(annotations=[(""Mar 01, 2008"", ""Pretty good day for GOOG""), (""Dec 01, 2007"", ""Something's going wrong for GOOG & AAPL""), (""Nov 01, 2008"", ""Market starts again thanks to...""), (""Dec 01, 2009"", ""Small crash for GOOG after...""),],) st.altair_chart(chart, use_container_width=True) PlostA deceptively simple plotting library for Streamlit. Created by @tvst.import plost plost.line_chart(my_dataframe, x='time', y='stock_value', color='stock_name',) HiPlotHigh dimensional Interactive Plotting. Created by @facebookresearch.data = [{'dropout':0.1, 'lr': 0.001, 'loss': 10.0, 'optimizer': 'SGD'}, {'dropout':0.15, 'lr': 0.01, 'loss': 3.5, 'optimizer': 'Adam'}, {'dropout':0.3, 'lr': 0.1, 'loss': 4.5, 'optimizer': 'Adam'}] hip.Experiment.from_iterable(data).display() EChartsHigh dimensional Interactive Plotting. Created by @andfanilo.from streamlit_echarts import st_echarts st_echarts(options=options) Streamlit FoliumStreamlit Component for rendering Folium maps. Created by @randyzwitch.m = folium.Map(location=[39.949610, -75.150282], zoom_start=16) st_data = st_folium(m, width=725) Spacy-StreamlitspaCy building blocks and visualizers for Streamlit apps. Created by @explosion.models = [""en_core_web_sm"", ""en_core_web_md""] spacy_streamlit.visualize(models, ""Sundar Pichai is the CEO of Google."") Streamlit AgraphA Streamlit Graph Vis, based on react-grah-vis. Created by @ChrisDelClea.from streamlit_agraph import agraph, Node, Edge, Config agraph(nodes=nodes, edges=edges, config=config) Streamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl(""https://assets5.lottiefiles.com/packages/lf20_V9t630.json"") st_lottie(lottie_hello, key=""hello"") Plotly EventsMake Plotly charts interactive!. Created by @null-jones.fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.chart += get_annotations_chart(annotations=[(""Mar 01, 2008"", ""Pretty good day for GOOG""), (""Dec 01, 2007"", ""Something's going wrong for GOOG & AAPL""), (""Nov 01, 2008"", ""Market starts again thanks to...""), (""Dec 01, 2009"", ""Small crash for GOOG after...""),],) st.altair_chart(chart, use_container_width=True) PlostA deceptively simple plotting library for Streamlit. Created by @tvst.import plost plost.line_chart(my_dataframe, x='time', y='stock_value', color='stock_name',) HiPlotHigh dimensional Interactive Plotting. Created by @facebookresearch.data = [{'dropout':0.1, 'lr': 0.001, 'loss': 10.0, 'optimizer': 'SGD'}, {'dropout':0.15, 'lr': 0.01, 'loss': 3.5, 'optimizer': 'Adam'}, {'dropout':0.3, 'lr': 0.1, 'loss': 4.5, 'optimizer': 'Adam'}] hip.Experiment.from_iterable(data).display() EChartsHigh dimensional Interactive Plotting. Created by @andfanilo.from streamlit_echarts import st_echarts st_echarts(options=options) Streamlit FoliumStreamlit Component for rendering Folium maps. Created by @randyzwitch.m = folium.Map(location=[39.949610, -75.150282], zoom_start=16) st_data = st_folium(m, width=725) Spacy-StreamlitspaCy building blocks and visualizers for Streamlit apps. Created by @explosion.models = [""en_core_web_sm"", ""en_core_web_md""] spacy_streamlit.visualize(models, ""Sundar Pichai is the CEO of Google."") Streamlit AgraphA Streamlit Graph Vis, based on react-grah-vis. Created by @ChrisDelClea.from streamlit_agraph import agraph, Node, Edge, Config agraph(nodes=nodes, edges=edges, config=config) Streamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl(""https://assets5.lottiefiles.com/packages/lf20_V9t630.json"") st_lottie(lottie_hello, key=""hello"") Plotly EventsMake Plotly charts interactive!. Created by @null-jones.fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.chart += get_annotations_chart(annotations=[(""Mar 01, 2008"", ""Pretty good day for GOOG""), (""Dec 01, 2007"", ""Something's going wrong for GOOG & AAPL""), (""Nov 01, 2008"", ""Market starts again thanks to...""), (""Dec 01, 2009"", ""Small crash for GOOG after...""),],) st.altair_chart(chart, use_container_width=True) Next Input widgets ButtonDisplay a button widget.clicked = st.button(""Click me"") Download buttonDisplay a download button widget.st.download_button(""Download file"", file) Form buttonDisplay a form submit button. For use with st.form.st.form_submit_button(""Sign up"") Link buttonDisplay a link button.st.link_button(""Go to gallery"", url) Page linkDisplay a link to another page in a multipage app.st.page_link(""app.py"", label=""Home"", icon=""🏠"") st.page_link(""pages/profile.py"", label=""My profile"") CheckboxDisplay a checkbox widget.selected = st.checkbox(""I agree"") Color pickerDisplay a color picker widget.color = st.color_picker(""Pick a color"") MultiselectDisplay a multiselect widget. The multiselect widget starts as empty.choices = st.multiselect(""Buy"", [""milk"", ""apples"", ""potatoes""]) RadioDisplay a radio button widget.choice = st.radio(""Pick one"", [""cats"", ""dogs""]) SelectboxDisplay a select widget.choice = st.selectbox(""Pick one"", [""cats"", ""dogs""]) Select-sliderDisplay a slider widget to select items from a list.size = st.select_slider(""Pick a size"", [""S"", ""M"", ""L""]) ToggleDisplay a toggle widget.activated = st.toggle(""Activate"") Number inputDisplay a numeric input widget.choice = st.number_input(""Pick a number"", 0, 10) SliderDisplay a slider widget.number = st.slider(""Pick a number"", 0, 100) Date inputDisplay a date input widget.date = st.date_input(""Your birthday"") Time inputDisplay a time input widget.time = st.time_input(""Meeting time"") Chat inputDisplay a chat input widget.prompt = st.chat_input(""Say something"") if prompt: st.write(f""The user has sent: {prompt}"") Text-areaDisplay a multi-line text input widget.text = st.text_area(""Text to translate"") Text inputDisplay a single-line text input widget.name = st.text_input(""First name"") Data editorDisplay a data editor widget.edited = st.experimental_data_editor(df, num_rows=""dynamic"") File UploaderDisplay a file uploader widget.data = st.file_uploader(""Upload a CSV"") Camera inputDisplay a widget that allows users to upload images directly from a camera.image = st.camera_input(""Take a picture"") Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration! PreviousStreamlit ChatStreamlit Component for a Chatbot UI. Created by @AI-Yash.from streamlit_chat import message message(""My message"") message(""Hello bot!"", is_user=True) # align's the message to the right Streamlit Option MenuSelect a single item from a list of options in a menu. Created by @victoryhb.from streamlit_option_menu import option_menu option_menu(""Main Menu"", [""Home"", 'Settings'], icons=['house', 'gear'], menu_icon=""cast"", default_index=1) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.stoggle import stoggle stoggle( ""Click me!"", """"""🥷 Surprise! Here's some additional content"""""",) Streamlit ElementsCreate a draggable and resizable dashboard in Streamlit. Created by @okls.from streamlit_elements import elements, mui, html with elements(""new_element""): mui.Typography(""Hello world"") TagsAdd tags to your Streamlit apps. Created by @gagan3012.from streamlit_tags import st_tags st_tags(label='# Enter Keywords:', text='Press enter to add more', value=['Zero', 'One', 'Two'], suggestions=['five', 'six', 'seven', 'eight', 'nine', 'three', 'eleven', 'ten', 'four'], maxtags = 4, key='1') StqdmThe simplest way to handle a progress bar in streamlit app. Created by @Wirg.from stqdm import stqdm for _ in stqdm(range(50)): sleep(0.5) TimelineDisplay a Timeline in Streamlit apps using TimelineJS. Created by @innerdoc.from streamlit_timeline import timeline with open('example.json', ""r"") as f: timeline(f.read(), height=800) Camera input liveAlternative for st.camera_input which returns the webcam images live. Created by @blackary.from camera_input_live import camera_input_live image = camera_input_live() st.image(value) Streamlit AceAce editor component for Streamlit. Created by @okld.from streamlit_ace import st_ace content = st_ace() content Streamlit ChatStreamlit Component for a Chatbot UI. Created by @AI-Yash.from streamlit_chat import message message(""My message"") message(""Hello bot!"", is_user=True) # align's the message to the right Streamlit Option MenuSelect a single item from a list of options in a menu. Created by @victoryhb.from streamlit_option_menu import option_menu option_menu(""Main Menu"", [""Home"", 'Settings'], icons=['house', 'gear'], menu_icon=""cast"", default_index=1) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.stoggle import stoggle stoggle( ""Click me!"", """"""🥷 Surprise! Here's some additional content"""""",) Streamlit ElementsCreate a draggable and resizable dashboard in Streamlit. Created by @okls.from streamlit_elements import elements, mui, html with elements(""new_element""): mui.Typography(""Hello world"") TagsAdd tags to your Streamlit apps. Created by @gagan3012.from streamlit_tags import st_tags st_tags(label='# Enter Keywords:', text='Press enter to add more', value=['Zero', 'One', 'Two'], suggestions=['five', 'six', 'seven', 'eight', 'nine', 'three', 'eleven', 'ten', 'four'], maxtags = 4, key='1') StqdmThe simplest way to handle a progress bar in streamlit app. Created by @Wirg.from stqdm import stqdm for _ in stqdm(range(50)): sleep(0.5) TimelineDisplay a Timeline in Streamlit apps using TimelineJS. Created by @innerdoc.from streamlit_timeline import timeline with open('example.json', ""r"") as f: timeline(f.read(), height=800) Camera input liveAlternative for st.camera_input which returns the webcam images live. Created by @blackary.from camera_input_live import camera_input_live image = camera_input_live() st.image(value) Streamlit AceAce editor component for Streamlit. Created by @okld.from streamlit_ace import st_ace content = st_ace() content Streamlit ChatStreamlit Component for a Chatbot UI. Created by @AI-Yash.from streamlit_chat import message message(""My message"") message(""Hello bot!"", is_user=True) # align's the message to the right Streamlit Option MenuSelect a single item from a list of options in a menu. Created by @victoryhb.from streamlit_option_menu import option_menu option_menu(""Main Menu"", [""Home"", 'Settings'], icons=['house', 'gear'], menu_icon=""cast"", default_index=1) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.stoggle import stoggle stoggle( ""Click me!"", """"""🥷 Surprise! Here's some additional content"""""",) Next Media elements ImageDisplay an image or list of images.st.image(numpy_array) st.image(image_bytes) st.image(file) st.image(""https://example.com/myimage.jpg"") AudioDisplay an audio player.st.audio(numpy_array) st.audio(audio_bytes) st.audio(file) st.audio(""https://example.com/myaudio.mp3"", format=""audio/mp3"") VideoDisplay a video player.st.video(numpy_array) st.video(video_bytes) st.video(file) st.video(""https://example.com/myvideo.mp4"", format=""video/mp4"") Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration! PreviousStreamlit CropperA simple image cropper for Streamlit. Created by @turner-anderson.from streamlit_cropper import st_cropper st_cropper(img, realtime_update=realtime_update, box_color=box_color, aspect_ratio=aspect_ratio) Image CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates streamlit_image_coordinates(""https://placekitten.com/200/300"") Streamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl(""https://assets5.lottiefiles.com/packages/lf20_V9t630.json"") st_lottie(lottie_hello, key=""hello"") Streamlit WebrtcHandling and transmitting real-time video/audio streams with Streamlit. Created by @whitphx.from streamlit_webrtc import webrtc_streamer webrtc_streamer(key=""sample"") Drawable CanvasProvides a sketching canvas using Fabric.js. Created by @andfanilo.from streamlit_drawable_canvas import st_canvas st_canvas(fill_color=""rgba(255, 165, 0, 0.3)"", stroke_width=stroke_width, stroke_color=stroke_color, background_color=bg_color, background_image=Image.open(bg_image) if bg_image else None, update_streamlit=realtime_update, height=150, drawing_mode=drawing_mode, point_display_radius=point_display_radius if drawing_mode == 'point' else 0, key=""canvas"",) Image ComparisonCompare images with a slider using JuxtaposeJS. Created by @fcakyon.from streamlit_image_comparison import image_comparison image_comparison(img1=""image1.jpg"", img2=""image2.jpg"",) Streamlit CropperA simple image cropper for Streamlit. Created by @turner-anderson.from streamlit_cropper import st_cropper st_cropper(img, realtime_update=realtime_update, box_color=box_color, aspect_ratio=aspect_ratio) Image CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates streamlit_image_coordinates(""https://placekitten.com/200/300"") Streamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl(""https://assets5.lottiefiles.com/packages/lf20_V9t630.json"") st_lottie(lottie_hello, key=""hello"") Streamlit WebrtcHandling and transmitting real-time video/audio streams with Streamlit. Created by @whitphx.from streamlit_webrtc import webrtc_streamer webrtc_streamer(key=""sample"") Drawable CanvasProvides a sketching canvas using Fabric.js. Created by @andfanilo.from streamlit_drawable_canvas import st_canvas st_canvas(fill_color=""rgba(255, 165, 0, 0.3)"", stroke_width=stroke_width, stroke_color=stroke_color, background_color=bg_color, background_image=Image.open(bg_image) if bg_image else None, update_streamlit=realtime_update, height=150, drawing_mode=drawing_mode, point_display_radius=point_display_radius if drawing_mode == 'point' else 0, key=""canvas"",) Image ComparisonCompare images with a slider using JuxtaposeJS. Created by @fcakyon.from streamlit_image_comparison import image_comparison image_comparison(img1=""image1.jpg"", img2=""image2.jpg"",) Streamlit CropperA simple image cropper for Streamlit. Created by @turner-anderson.from streamlit_cropper import st_cropper st_cropper(img, realtime_update=realtime_update, box_color=box_color, aspect_ratio=aspect_ratio) Image CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates streamlit_image_coordinates(""https://placekitten.com/200/300"") Streamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl(""https://assets5.lottiefiles.com/packages/lf20_V9t630.json"") st_lottie(lottie_hello, key=""hello"") Next Layouts and containers ColumnsInsert containers laid out as side-by-side columns.col1, col2 = st.columns(2) col1.write(""this is column 1"") col2.write(""this is column 2"") ContainerInsert a multi-element container.c = st.container() st.write(""This will show last"") c.write(""This will show first"") c.write(""This will show second"") Modal dialogsInsert a modal dialog that can rerun independently from the rest of the script.@st.experimental_dialog(""Sign up"") def email_form(): name = st.text_input(""Name"") email = st.text_input(""Email"") EmptyInsert a single-element container.c = st.empty() st.write(""This will show last"") c.write(""This will be replaced"") c.write(""This will show first"") ExpanderInsert a multi-element container that can be expanded/collapsed.with st.expander(""Open to see more""): st.write(""This is more content"") PopoverInsert a multi-element popover container that can be opened/closed.with st.popover(""Settings""): st.checkbox(""Show completed"") SidebarDisplay items in a sidebar.st.sidebar.write(""This lives in the sidebar"") st.sidebar.button(""Click me!"") TabsInsert containers separated into tabs.tab1, tab2 = st.tabs([""Tab 1"", ""Tab2""]) tab1.write(""this is tab 1"") tab2.write(""this is tab 2"") Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration!Streamlit ElementsCreate a draggable and resizable dashboard in Streamlit. Created by @okls.from streamlit_elements import elements, mui, html with elements(""new_element""): mui.Typography(""Hello world"") PydanticAuto-generate Streamlit UI from Pydantic Models and Dataclasses. Created by @lukasmasuch.import streamlit_pydantic as sp sp.pydantic_form(key=""my_form"", model=ExampleModel) Streamlit PagesAn experimental version of Streamlit Multi-Page Apps. Created by @blackary.from st_pages import Page, show_pages, add_page_title show_pages([ Page(""streamlit_app.py"", ""Home"", ""🏠""), Page(""other_pages/page2.py"", ""Page 2"", "":books:""), ]) Chat elements Streamlit provides a few commands to help you build conversational apps. These chat elements are designed to be used in conjunction with each other, but you can also use them separately. st.chat_message lets you insert a chat message container into the app so you can display messages from the user or the app. Chat containers can contain other Streamlit elements, including charts, tables, text, and more. st.chat_input lets you display a chat input widget so the user can type in a message. Chat inputDisplay a chat input widget.prompt = st.chat_input(""Say something"") if prompt: st.write(f""The user has sent: {prompt}"") Chat messageInsert a chat message container.import numpy as np with st.chat_message(""user""): st.write(""Hello 👋"") st.line_chart(np.random.randn(30, 3)) Status containerDisplay output of long-running tasks in a container.with st.status('Running'): do_something_slow() st.write_streamWrite generators or streams to the app with a typewriter effect.st.write_stream(my_generator) st.write_stream(my_llm_stream) Status elements Progress barDisplay a progress bar.for i in range(101): st.progress(i) do_something_slow() SpinnerTemporarily displays a message while executing a block of code.with st.spinner(""Please wait...""): do_something_slow() Status containerDisplay output of long-running tasks in a container.with st.status('Running'): do_something_slow() ToastBriefly displays a toast message in the bottom-right corner.st.toast('Butter!', icon='🧈') BalloonsDisplay celebratory balloons!do_something() # Celebrate when all done! st.balloons() SnowflakesDisplay celebratory snowflakes!do_something() # Celebrate when all done! st.snow() Success boxDisplay a success message.st.success(""Match found!"") Info boxDisplay an informational message.st.info(""Dataset is updated every day at midnight."") Warning boxDisplay warning message.st.warning(""Unable to fetch image. Skipping..."") Error boxDisplay error message.st.error(""We encountered an error"") Exception outputDisplay an exception.e = RuntimeError(""This is an exception of type RuntimeError"") st.exception(e) Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration!StqdmThe simplest way to handle a progress bar in streamlit app. Created by @Wirg.from stqdm import stqdm for _ in stqdm(range(50)): sleep(0.5) Custom notification boxA custom notification box with the ability to close it out. Created by @Socvest.from streamlit_custom_notification_box import custom_notification_box styles = {'material-icons':{'color': 'red'}, 'text-icon-link-close-container': {'box-shadow': '#3896de 0px 4px'}, 'notification-text': {'':''}, 'close-button':{'':''}, 'link':{'':''}} custom_notification_box(icon='info', textDisplay='We are almost done with your registration...', externalLink='more info', url='#', styles=styles, key=""foo"") Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.let_it_rain import rain rain(emoji=""🎈"", font_size=54, falling_speed=5, animation_length=""infinite"",) App logic and configuration Navigation and pages Switch pageProgrammatically navigates to a specified page.st.switch_page(""pages/my_page.py"") Page linkDisplay a link to another page in a multipage app.st.page_link(""app.py"", label=""Home"", icon=""🏠"") st.page_link(""pages/profile.py"", label=""My profile"") Execution flow Modal dialogsInsert a modal dialog that can rerun independently from the rest of the script.@st.experimental_dialog(""Sign up"") def email_form(): name = st.text_input(""Name"") email = st.text_input(""Email"") FormsCreate a form that batches elements together with a “Submit"" button.with st.form(key='my_form'): name = st.text_input(""Name"") email = st.text_input(""Email"") st.form_submit_button(""Sign up"") Partial rerunsDefine a fragment to rerun independently from the rest of the script.@st.experimental_fragment(run_every=""10s"") def fragment(): df = get_data() st.line_chart(df) Rerun scriptRerun the script immediately.st.rerun() Stop executionStops execution immediately.st.stop() Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration!AutorefreshForce a refresh without tying up a script. Created by @kmcgrady.from streamlit_autorefresh import st_autorefresh st_autorefresh(interval=2000, limit=100, key=""fizzbuzzcounter"") PydanticAuto-generate Streamlit UI from Pydantic Models and Dataclasses. Created by @lukasmasuch.import streamlit_pydantic as sp sp.pydantic_form(key=""my_form"", model=ExampleModel) Streamlit PagesAn experimental version of Streamlit Multi-Page Apps. Created by @blackary.from st_pages import Page, show_pages, add_page_title show_pages([ Page(""streamlit_app.py"", ""Home"", ""🏠""), Page(""other_pages/page2.py"", ""Page 2"", "":books:""), ]) Caching and state Cache dataFunction decorator to cache functions that return data (e.g. dataframe transforms, database queries, ML inference).@st.cache_data def long_function(param1, param2): # Perform expensive computation here or # fetch data from the web here return data Cache resourceFunction decorator to cache functions that return global resources (e.g. database connections, ML models).@st.cache_resource def init_model(): # Return a global resource here return pipeline( ""sentiment-analysis"", model=""distilbert-base-uncased-finetuned-sst-2-english"" ) Session stateSession state is a way to share variables between reruns, for each user session.st.session_state['key'] = value Query parametersGet, set, or clear the query parameters that are shown in the browser's URL bar.st.query_params[key] = value st.query_params.clear() Connections and databases Setup your connection Create a connectionConnect to a data source or APIconn = st.connection('pets_db', type='sql') pet_owners = conn.query('select * from pet_owners') st.dataframe(pet_owners) Built-in connections SnowflakeConnectionA connection to Snowflake.conn = st.connection('snowflake') SQLConnectionA connection to a SQL database using SQLAlchemy.conn = st.connection('sql') Build your own connections Connection base classBuild your own connection with BaseConnection.class MyConnection(BaseConnection[myconn.MyConnection]): def _connect(self, **kwargs) -> MyConnection: return myconn.connect(**self._secrets, **kwargs) def query(self, query): return self._instance.query(query) Secrets management Secrets singletonAccess secrets from a local TOML file.key = st.secrets[""OpenAI_key""] Secrets fileSave your secrets in a per-project or per-profile TOML file.OpenAI_key = """" Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration!AuthenticatorA secure authentication module to validate user credentials. Created by @mkhorasani.import streamlit_authenticator as stauth authenticator = stauth.Authenticate( config['credentials'], config['cookie']['name'], config['cookie']['key'], config['cookie']['expiry_days'], config['preauthorized']) WS localStorageA simple synchronous way of accessing localStorage from your app. Created by @gagangoku.from streamlit_ws_localstorage import injectWebsocketCode ret = conn.setLocalStorageVal(key='k1', val='v1') st.write('ret: ' + ret) Streamlit Auth0The fastest way to provide comprehensive login inside Streamlit. Created by @conradbez.from auth0_component import login_button user_info = login_button(clientId, domain = domain) st.write(user_info) Custom Components Declare a componentCreate and register a custom component.st.components.v1.declare_component( ""custom_slider"", ""/frontend"", ) HTMLDisplay an HTML string in an iframe.st.components.v1.html( ""

Foo bar.

"" ) iframeLoad a remote URL in an iframe.st.components.v1.iframe( ""docs.streamlit.io"" ) Utilities and user info User infost.experimental_user returns information about the logged-in user of private apps on Streamlit Community Cloud.if st.experimental_user.email == ""foo@corp.com"": st.write(""Welcome back, "", st.experimental_user.email) else: st.write(""You are not authorized to view this page."") Get helpDisplay object’s doc string, nicely formatted.st.help(st.write) st.help(pd.DataFrame) Render HTMLRenders HTML strings to your app.css = """""" """""" st.html(css) Configuration Configuration fileConfigures the default settings for your app.your-project/ ├── .streamlit/ │ └── config.toml └── your_app.py Set page title, favicon, and moreConfigures the default settings of the page.st.set_page_config( page_title=""My app"", page_icon="":shark:"", ) Developer tools App testing st.testing.v1.AppTestst.testing.v1.AppTest simulates a running Streamlit app for testing.from streamlit.testing.v1 import AppTest at = AppTest.from_file(""streamlit_app.py"") at.secrets[""WORD""] = ""Foobar"" at.run() assert not at.exception at.text_input(""word"").input(""Bazbat"").run() assert at.warning[0].value == ""Try again."" AppTest.from_filest.testing.v1.AppTest.from_file initializes a simulated app from a file.from streamlit.testing.v1 import AppTest at = AppTest.from_file(""streamlit_app.py"") at.run() AppTest.from_stringst.testing.v1.AppTest.from_string initializes a simulated app from a string.from streamlit.testing.v1 import AppTest at = AppTest.from_string(app_script_as_string) at.run() AppTest.from_functionst.testing.v1.AppTest.from_function initializes a simulated app from a function.from streamlit.testing.v1 import AppTest at = AppTest.from_function(app_script_as_callable) at.run() BlockA representation of container elements, including: st.chat_message st.columns st.sidebar st.tabs The main body of the app. # at.sidebar returns a Block at.sidebar.button[0].click().run() assert not at.exception ElementThe base class for representation of all elements, including: st.title st.header st.markdown st.dataframe # at.title returns a sequence of Title # Title inherits from Element assert at.title[0].value == ""My awesome app"" ButtonA representation of st.button and st.form_submit_button.at.button[0].click().run() ChatInputA representation of st.chat_input.at.chat_input[0].set_value(""What is Streamlit?"").run() CheckboxA representation of st.checkbox.at.checkbox[0].check().run() ColorPickerA representation of st.color_picker.at.color_picker[0].pick(""#FF4B4B"").run() DateInputA representation of st.date_input.release_date = datetime.date(2023, 10, 26) at.date_input[0].set_value(release_date).run() MultiselectA representation of st.multiselect.at.multiselect[0].select(""New York"").run() NumberInputA representation of st.number_input.at.number_input[0].increment().run() RadioA representation of st.radio.at.radio[0].set_value(""New York"").run() SelectSliderA representation of st.select_slider.at.select_slider[0].set_range(""A"",""C"").run() SelectboxA representation of st.selectbox.at.selectbox[0].select(""New York"").run() SliderA representation of st.slider.at.slider[0].set_range(2,5).run() TextAreaA representation of st.text_area.at.text_area[0].input(""Streamlit is awesome!"").run() TextInputA representation of st.text_input.at.text_input[0].input(""Streamlit"").run() TimeInputA representation of st.time_input.at.time_input[0].increment().run() ToggleA representation of st.toggle.at.toggle[0].set_value(""True"").run() Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration!Pandas ProfilingPandas profiling component for Streamlit. Created by @okld.df = pd.read_csv(""https://storage.googleapis.com/tf-datasets/titanic/train.csv"") pr = df.profile_report() st_profile_report(pr) Streamlit AceAce editor component for Streamlit. Created by @okld.from streamlit_ace import st_ace content = st_ace() content Streamlit AnalyticsTrack & visualize user interactions with your streamlit app. Created by @jrieke.import streamlit_analytics with streamlit_analytics.track(): st.text_input(""Write something"") Previous: ConceptsNext: Write and magicforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy" https://docs.streamlit.io/knowledge-base/deploy/share-apps-with-viewers-outside-organization#invite-viewers-from-your-app-settings,"DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudremoveGet startedaddDeploy your appaddManage your appaddShare your appremoveEmbed your appSearch indexabilityShare previewsManage your accountaddTroubleshootingStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Deploy/Streamlit Community Cloud/Share your appShare your app Now that your app is deployed you can easily share it and collaborate on it. But first, let's take a moment and do a little joy dance for getting that app deployed! 🕺💃 Your app is now live at a fixed URL, so go wild and share it with whomever you want. Your app will inherit permissions from your GitHub repo, meaning that if your repo is private your app will be private and if your repo is public your app will be public. If you want to change that you can simply do so from the app settings menu. You are only allowed one private app at a time. If you've deployed from a private repository, you will have to make that app public or delete it before you can deploy another app from a private repository. Only developers can change your app between public and private. Make your app public or private Share your public app Share your private app Make your app public or private If you deployed your app from a public repository, your app will be public by default. If you deployed your app from a private repository, you will need to make the app public if you want to freely share it with the community at large. Set privacy from your app settings Access your App settings and go to the ""Sharing"" section. Set your app's privacy under ""Who can view this app."" Select ""This app is public and searchable"" to make your app public. Select ""Only specific people can view this app"" to make your app private. Set privacy from the share button From your app at .streamlit.app, click ""Share"" in the upper-right corner. Toggle your app between public and private by clicking ""Make this app public"". Share your public app Once your app is public, just give anyone your app's URL and they view it! Streamlit Community Cloud has several convenient shortcuts for sharing your app. Share your app on social media From your app at .streamlit.app, click ""Share"" in the upper-right corner. Click ""Social"" to access convenient social media share buttons. starTipUse the social media sharing buttons to post your app on our forum! We'd love to see what you make and perhaps feature your app as our app of the month. 💖 Invite viewers by email Whether your app is public or private, you can send an email invite to your app directly from Streamlit Community Cloud. This grants the viewer access to analytics for all your public apps and the ability to invite other viewers to your workspace. Developers and invited viewers are identified by their email in analytics instead of appearing anonymously (if they view any of your apps while logged in). Read more about viewers in App analytics. From your app at .streamlit.app, click ""Share"" in the upper-right corner. Enter an email address and click ""Invite"". Invited users will get a direct link to your app in their inbox. Copy your app's URL You can convenitiently copy your app's URL from the share menu or from your workspace. From your app click ""Share"" in the upper-right corner then click ""Copy link"". From your workspace click the overflow menu icon (more_vert) then click ""Copy URL"". Add a badge to your GitHub repository To help others find and play with your Streamlit app, you can add Streamlit's GitHub badge to your repo. Below is an enlarged example of what the badge looks like. Clicking on the badge takes you to—in this case—Streamlit's Roadmap. Once you deploy your app, you can embed this badge right into your GitHub README.md by adding the following Markdown: [![Streamlit App](https://static.streamlit.io/badges/streamlit_badge_black_white.svg)](https://.streamlit.app) push_pinNoteBe sure to replace https://.streamlit.app with the URL of your deployed app! Share your private app By default an app deployed from a private repository will be private to the developers in the workspace. A private app will not be visible to anyone else unless you grant them explicit permission. You can grant permission by adding them as a developer on GitHub or by adding them as a viewer on Streamlit Community Cloud. Once you have added someone's email address to your app's viewer list, that person will be able to sign in and view your private app. If their email is associated to a Google account, they will be able to sign in with Google OAuth. Otherwise, they will be able to sign in with single-use, emailed links. Streamlit sends an email invitation with a link to your app every time you invite someone. priority_highImportantWhen you add a viewer to any app in your workspace, they are granted access to analytics for that app as well as analytics for all your public apps. They can also pass these permissions to others by inviting more viewers. All viewers and developers in your workspace are identified by their email in analytics. Furthermore, their emails show in analytics for every app in your workspace and not just apps they are explicitly invited to. Read more about viewers in App analytics Invite viewers from the share button From your app at .streamlit.app, click ""Share"" in the upper-right corner. Enter the email to send an invitation to and click ""Invite"". Invited users appear in the list below. Invited users will get a direct link to your app in their inbox. To remove a viewer, simply access the share menu as above and click the close next to their name. Invite viewers from your app settings Access your App settings and go to the ""Sharing"" section. Add or remove users from the list of viewers. Click ""Save"". Previous: Manage your appNext: Embed your appforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy" https://docs.streamlit.io/develop/tutorials/databases/private-gsheet,"DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceaddTutorialsremoveExecution flowaddConnect to data sourcesremoveAWS S3BigQueryDeta BaseFirestoreopen_in_newGoogle Cloud StorageMicrosoft SQL ServerMongoDBMySQLNeonPostgreSQLPrivate Google SheetPublic Google SheetSnowflakeSupabaseTableauTiDBTigerGraphMultipage appsaddWork with LLMsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Develop/Tutorials/Connect to data sources/Private Google SheetConnect Streamlit to a private Google Sheet Introduction This guide explains how to securely access a private Google Sheet from Streamlit Community Cloud. It uses st.connection, Streamlit GSheetsConnection, and Streamlit's Secrets management. If you are fine with enabling link sharing for your Google Sheet (i.e. everyone with the link can view it), the guide Connect Streamlit to a public Google Sheet shows a simpler method of doing this. If your Sheet contains sensitive information and you cannot enable link sharing, keep on reading. Prerequisites This tutorial requires streamlit>=1.28 and st-gsheets-connection in your Python environment. Create a Google Sheet If you already have a Sheet that you want to use, feel free to skip to the next step. Create a spreadsheet with this example data. namepetMarydogJohncatRobertbird Enable the Sheets API Programmatic access to Google Sheets is controlled through Google Cloud Platform. Create an account or sign in and head over to the APIs & Services dashboard (select or create a project if asked). As shown below, search for the Sheets API and enable it: Create a service account & key file To use the Sheets API from Streamlit Community Cloud, you need a Google Cloud Platform service account (a special account type for programmatic data access). Go to the Service Accounts page and create an account with the Viewer permission (this will let the account access data but not change it): push_pinNoteThe button ""CREATE SERVICE ACCOUNT"" is gray, you don't have the correct permissions. Ask the admin of your Google Cloud project for help. After clicking ""DONE"", you should be back on the service accounts overview. First, note down the email address of the account you just created (important for next step!). Then, create a JSON key file for the new account and download it: Share the Google Sheet with the service account By default, the service account you just created cannot access your Google Sheet. To give it access, click on the ""Share"" button in the Google Sheet, add the email of the service account (noted down in step 2), and choose the correct permission (if you just want to read the data, ""Viewer"" is enough): Add the key file to your local app secrets Your local Streamlit app will read secrets from a file .streamlit/secrets.toml in your app's root directory. Create this file if it doesn't exist yet and add the URL of your Google Sheet plus the content of the key file you downloaded to it as shown below: # .streamlit/secrets.toml [connections.gsheets] spreadsheet = ""https://docs.google.com/spreadsheets/d/xxxxxxx/edit#gid=0"" # From your JSON key file type = ""service_account"" project_id = ""xxx"" private_key_id = ""xxx"" private_key = ""xxx"" client_email = ""xxx"" client_id = ""xxx"" auth_uri = ""https://accounts.google.com/o/oauth2/auth"" token_uri = ""https://oauth2.googleapis.com/token"" auth_provider_x509_cert_url = ""https://www.googleapis.com/oauth2/v1/certs"" client_x509_cert_url = ""xxx"" priority_highImportantAdd this file to .gitignore and don't commit it to your GitHub repo! Write your Streamlit app Copy the code below to your Streamlit app and run it. # streamlit_app.py import streamlit as st from streamlit_gsheets import GSheetsConnection # Create a connection object. conn = st.connection(""gsheets"", type=GSheetsConnection) df = conn.read() # Print results. for row in df.itertuples(): st.write(f""{row.name} has a :{row.pet}:"") See st.connection above? This handles secrets retrieval, setup, query caching and retries. By default, .read() results are cached without expiring. You can pass optional parameters to .read() to customize your connection. For example, you can specify the name of a worksheet, cache expiration time, or pass-through parameters for pandas.read_csv like this: df = conn.read( worksheet=""Sheet1"", ttl=""10m"", usecols=[0, 1], nrows=3, ) In this case, we set ttl=""10m"" to ensure the query result is cached for no longer than 10 minutes. You can also set ttl=0 to disable caching. Learn more in Caching. We've declared optional parameters usecols=[0,1] and nrows=3 for pandas to use under the hood. If everything worked out (and you used the example table we created above), your app should look like this: Connecting to a Google Sheet from Community Cloud This tutorial assumes a local Streamlit app, however you can also connect to Google Sheets from apps hosted in Community Cloud. The main additional steps are: Include information about dependencies using a requirements.txt file with st-gsheets-connection and any other dependencies. Add your secrets to your Community Cloud app. Previous: PostgreSQLNext: Public Google SheetforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy" https://docs.streamlit.io/develop/concepts/architecture/fragments#limitations-and-unsupported-behavior,"DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsremoveCOREArchitecture & executionremoveRunning your appStreamlit's architectureThe app chromeCachingSession StateFormsFragmentsWidget behaviorMultipage appsaddApp designaddADDITIONALConnections and secretsaddCustom componentsaddConfiguration and themingaddApp testingaddAPI referenceaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Develop/Concepts/Architecture & execution/FragmentsWorking with fragments and partial reruns Reruns are a central part of every Streamlit app. When users interact with widgets, your script reruns from top to bottom, and your app's frontend is updated. Streamlit provides several features to help you develop your app within this execution model. Streamlit version 1.33.0 introduced fragments to allow rerunning a portion of your code instead of your full script. As your app grows larger and more complex, these partial reruns help your app be efficient and performant. Fragments give you finer, easy-to-understand control over your app's execution flow. Before you read about fragments, we recommend having a basic understanding of caching, Session State, and forms. Use cases for fragments Fragments are versatile and applicable to a wide variety of circumstances. Here are just a few, common scenarios where fragments are useful: Your app has multiple visualizations and each one takes time to load, but you have a filter input that only updates one of them. You have a dynamic form that doesn't need to update the rest of your app (until the form is complete). You want to automatically update a single component or group of components to stream data. Defining and calling a fragment Streamlit provides a decorator (st.experimental_fragment) to turn any function into a fragment function. When you call a fragment function that contains a widget function, a user triggers a partial rerun instead of a full rerun when they interact with that fragment's widget. During a partial rerun, your fragment function is re-executed. Anything within the main body of your fragment is updated on the frontend, while the rest of your app remains the same. We'll describe fragments written across multiple containers later on. Here is a basic example of defining and calling a fragment function. Just like with caching, remember to call your function after defining it. import streamlit as st @st.experimental_fragment def fragment_function(): if st.button(""Hi!""): st.write(""Hi back!"") fragment_function() If you want the main body of your fragment to appear in the sidebar or another container, call your fragment function inside a context manager. with st.sidebar: fragment_function() Partial rerun execution flow Consider the following code with the explanation and diagram below. import streamlit as st st.title(""My Awesome App"") @st.experimental_fragment() def toggle_and_text(): cols = st.columns(2) cols[0].toggle(""Toggle"") cols[1].text_area(""Enter text"") @st.experimental_fragment() def filter_and_file(): cols = st.columns(2) cols[0].checkbox(""Filter"") cols[1].file_uploader(""Upload image"") toggle_and_text() cols = st.columns(2) cols[0].selectbox(""Select"", [1,2,3], None) cols[1].button(""Update"") filter_and_file() When a user interacts with an input widget inside a fragment, only the fragment reruns instead of the full script. When a user interacts with an input widget outside a fragment, the full script reruns as usual. If you run the code above, the full script will run top to bottom on your app's initial load. If you flip the toggle button in your running app, the first fragment (toggle_and_text()) will rerun, redrawing the toggle and text area while leaving everything else unchanged. If you click the checkbox, the second fragment (filter_and_file()) will rerun and consequently redraw the checkbox and file uploader. Everything else remains unchanged. Finally, if you click the update button, the full script will rerun, and Streamlit will redraw everything. Fragment return values and interacting with the rest of your app Streamlit ignores fragment return values during fragment reruns, so defining return values for your fragment functions is not recommended. Instead, if your fragment needs to share data with the rest of your app, use Session State. Fragments are just functions in your script, so they can access Session State, imported modules, and other Streamlit elements like containers. If your fragment writes to any container created outside of itself, note the following difference in behavior: Elements drawn in the main body of your fragment are cleared and redrawn in place during a fragment rerun. Repeated fragment reruns will not cause additional elements to appear. Elements drawn to containers outside the main body of fragment will not be cleared with each fragment rerun. Instead, Streamlit will draw them additively and these elements will accumulate until the next full-script rerun. To prevent elements from accumulating in outside containers, use st.empty containers. For a related tutorial, see Create a fragment across multiple containers. If you need to trigger a full-script rerun from inside a fragment, call st.rerun. For a related tutorial, see Trigger a full-script rerun from inside a fragment. Automate fragment reruns st.experimental_fragment includes a convenient run_every parameter that causes the fragment to rerun automatically at the specified time interval. These reruns are in addition to any reruns (fragment or full-script) triggered by your user. The automatic fragment reruns will continue even if your user is not interacting with your app. This is a great way to show a live data stream or status on a running background job, efficiently updating your rendered data and only your rendered data. @st.experimental_fragment(run_every=""10s"") def auto_function(): # This will update every 10 seconds! df = get_latest_updates() st.line_chart(df) auto_function() For a related tutorial, see Start and stop a streaming fragment. Compare fragments to other Streamlit features Fragments vs forms Here is a comparison between fragments and forms: Forms allow users to interact with widgets without rerunning your app. Streamlit does not send user actions within a form to your app's Python backend until the form is submitted. Widgets within a form can not dynamically update other widgets (in or out of the form) in real-time. Fragments run independently from the rest of your code. As your users interact with fragment widgets, their actions are immediately processed by your app's Python backend and your fragment code is rerun. Widgets within a fragment can dynamically update other widgets within the same fragment in real-time. A form batches user input without interaction between any widgets. A fragment immediately processes user input but limits the scope of the rerun. Fragments vs callbacks Here is a comparison between fragments and callbacks: Callbacks allow you to execute a function at the beginning of a script rerun. A callback is a single prefix to your script rerun. Fragments allow you to rerun a portion of your script. A fragment is a repeatable postfix to your script, running each time a user interacts with a fragment widget, or automatically in sequence when run_every is set. When callbacks render elements to your page, they are rendered before the rest of your page elements. When fragments render elements to your page, they are updated with each fragment rerun (unless they are written to containers outside of the fragment, in which case they accumulate there). Fragments vs custom components Here is a comparison between fragments and custom components: Components are custom frontend code that can interact with the Python code, native elements, and widgets in your Streamlit app. Custom components extend what’s possible with Streamlit. They follow the normal Streamlit execution flow. Fragments are parts of your app that can rerun independently of the full app. Fragments can be composed of multiple Streamlit elements, widgets, or any Python code. A fragment can include one or more custom components. A custom component could not easily include a fragment! Fragments vs caching Here is a comparison between fragments and caching: Caching: allows you to skip over a function and return a previously computed value. When you use caching, you execute everything except the cached function (if you've already run it before). Fragments: allow you to freeze most of your app and just execute the fragment. When you use fragments, you execute only the fragment (when triggering a fragment rerun). Caching saves you from unnecessarily running a piece of your app while the rest runs. Fragments save you from running your full app when you only want to run one piece. Limitations and unsupported behavior Fragments can't detect a change in input values. It is best to use Session State for dynamic input and output for fragment functions. Calling fragments within fragments is unsupported. Using caching and fragments on the same function is unsupported. Previous: FormsNext: Widget behaviorforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy" https://docs.streamlit.io/develop/concepts/architecture/forms#use-a-callback-with-session-state,"DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsremoveCOREArchitecture & executionremoveRunning your appStreamlit's architectureThe app chromeCachingSession StateFormsFragmentsWidget behaviorMultipage appsaddApp designaddADDITIONALConnections and secretsaddCustom componentsaddConfiguration and themingaddApp testingaddAPI referenceaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Develop/Concepts/Architecture & execution/FormsUsing forms When you don't want to rerun your script with each input made by a user, st.form is here to help! Forms make it easy to batch user input into a single rerun. This guide to using forms provides examples and explains how users interact with forms. Example In the following example, a user can set multiple parameters to update the map. As the user changes the parameters, the script will not rerun and the map will not update. When the user submits the form with the button labeled ""Update map"", the script reruns and the map updates. If at any time the user clicks ""Generate new points"" which is outside of the form, the script will rerun. If the user has any unsubmitted changes within the form, these will not be sent with the rerun. All changes made to a form will only be sent to the Python backend when the form itself is submitted. View source codeexpand_moreimport streamlit as st import pandas as pd import numpy as np def get_data(): df = pd.DataFrame({ ""lat"": np.random.randn(200) / 50 + 37.76, ""lon"": np.random.randn(200) / 50 + -122.4, ""team"": ['A','B']*100 }) return df if st.button('Generate new points'): st.session_state.df = get_data() if 'df' not in st.session_state: st.session_state.df = get_data() df = st.session_state.df with st.form(""my_form""): header = st.columns([1,2,2]) header[0].subheader('Color') header[1].subheader('Opacity') header[2].subheader('Size') row1 = st.columns([1,2,2]) colorA = row1[0].color_picker('Team A', '#0000FF') opacityA = row1[1].slider('A opacity', 20, 100, 50, label_visibility='hidden') sizeA = row1[2].slider('A size', 50, 200, 100, step=10, label_visibility='hidden') row2 = st.columns([1,2,2]) colorB = row2[0].color_picker('Team B', '#FF0000') opacityB = row2[1].slider('B opacity', 20, 100, 50, label_visibility='hidden') sizeB = row2[2].slider('B size', 50, 200, 100, step=10, label_visibility='hidden') st.form_submit_button('Update map') alphaA = int(opacityA*255/100) alphaB = int(opacityB*255/100) df['color'] = np.where(df.team=='A',colorA+f'{alphaA:02x}',colorB+f'{alphaB:02x}') df['size'] = np.where(df.team=='A',sizeA, sizeB) st.map(df, size='size', color='color') Built with Streamlit 🎈Fullscreen open_in_new User interaction If a widget is not in a form, that widget will trigger a script rerun whenever a user changes its value. For widgets with keyed input (st.number_input, st.text_input, st.text_area), a new value triggers a rerun when the user clicks or tabs out of the widget. A user can also submit a change by pressing Enter while thier cursor is active in the widget. On the other hand if a widget is inside of a form, the script will not rerun when a user clicks or tabs out of that widget. For widgets inside a form, the script will rerun when the form is submitted and all widgets within the form will send their updated values to the Python backend. A user can submit a form using Enter on their keyboard if their cursor active in a widget that accepts keyed input. Within st.number_input and st.text_input a user presses Enter to submit the form. Within st.text_area a user presses Ctrl+Enter/⌘+Enter to submit the form. Widget values Before a form is submitted, all widgets within that form will have default values, just like widgets outside of a form have default values. import streamlit as st with st.form(""my_form""): st.write(""Inside the form"") my_number = st.slider('Pick a number', 1, 10) my_color = st.selectbox('Pick a color', ['red','orange','green','blue','violet']) st.form_submit_button('Submit my picks') # This is outside the form st.write(my_number) st.write(my_color) Built with Streamlit 🎈Fullscreen open_in_new Forms are containers When st.form is called, a container is created on the frontend. You can write to that container like you do with other container elements. That is, you can use Python's with statement as shown in the example above, or you can assign the form container to a variable and call methods on it directly. Additionally, you can place st.form_submit_button anywhere in the form container. import streamlit as st animal = st.form('my_animal') # This is writing directly to the main body. Since the form container is # defined above, this will appear below everything written in the form. sound = st.selectbox('Sounds like', ['meow','woof','squeak','tweet']) # These methods called on the form container, so they appear inside the form. submit = animal.form_submit_button(f'Say it with {sound}!') sentence = animal.text_input('Your sentence:', 'Where\'s the tuna?') say_it = sentence.rstrip('.,!?') + f', {sound}!' if submit: animal.subheader(say_it) else: animal.subheader(' ') Built with Streamlit 🎈Fullscreen open_in_new Processing form submissions The purpose of a form is to override the default behavior of Streamlit which reruns a script as soon as the user makes a change. For widgets outside of a form, the logical flow is: The user changes a widget's value on the frontend. The widget's value in st.session_state and in the Python backend (server) is updated. The script rerun begins. If the widget has a callback, it is executed as a prefix to the page rerun. When the updated widget's function is executed during the rerun, it outputs the new value. For widgets inside a form, any changes made by a user (step 1) do not get passed to the Python backend (step 2) until the form is submitted. Furthermore, the only widget inside a form that can have a callback function is the st.form_submit_button. If you need to execute a process using newly submitted values, you have three major patterns for doing so. Execute the process after the form If you need to execute a one-time process as a result of a form submission, you can condition that process on the st.form_submit_button and execute it after the form. If you need results from your process to display above the form, you can use containers to control where the form displays relative to your output. import streamlit as st col1,col2 = st.columns([1,2]) col1.title('Sum:') with st.form('addition'): a = st.number_input('a') b = st.number_input('b') submit = st.form_submit_button('add') if submit: col2.title(f'{a+b:.2f}') Built with Streamlit 🎈Fullscreen open_in_new Use a callback with session state You can use a callback to execute a process as a prefix to the script rerunning. priority_highImportantWhen processing newly updated values within a callback, do not pass those values to the callback directly through the args or kwargs parameters. You need to assign a key to any widget whose value you use within the callback. If you look up the value of that widget from st.session_state within the body of the callback, you will be able to access the newly submitted value. See the example below. import streamlit as st if 'sum' not in st.session_state: st.session_state.sum = '' def sum(): result = st.session_state.a + st.session_state.b st.session_state.sum = result col1,col2 = st.columns(2) col1.title('Sum:') if isinstance(st.session_state.sum, float): col2.title(f'{st.session_state.sum:.2f}') with st.form('addition'): st.number_input('a', key = 'a') st.number_input('b', key = 'b') st.form_submit_button('add', on_click=sum) Built with Streamlit 🎈Fullscreen open_in_new Use st.rerun If your process affects content above your form, another alternative is using an extra rerun. This can be less resource-efficient though, and may be less desirable that the above options. import streamlit as st if 'sum' not in st.session_state: st.session_state.sum = '' col1,col2 = st.columns(2) col1.title('Sum:') if isinstance(st.session_state.sum, float): col2.title(f'{st.session_state.sum:.2f}') with st.form('addition'): a = st.number_input('a') b = st.number_input('b') submit = st.form_submit_button('add') # The value of st.session_state.sum is updated at the end of the script rerun, # so the displayed value at the top in col2 does not show the new sum. Trigger # a second rerun when the form is submitted to update the value above. st.session_state.sum = a + b if submit: st.rerun() Built with Streamlit 🎈Fullscreen open_in_new Limitations Every form must contain a st.form_submit_button. st.button and st.download_button cannot be added to a form. st.form cannot be embedded inside another st.form. Callback functions can only be assigned to st.form_submit_button within a form; no other widgets in a form can have a callback. Interdependent widgets within a form are unlikely to be particularly useful. If you pass widget1's value into widget2 when they are both inside a form, then widget2 will only update when the form is submitted. Previous: Session StateNext: FragmentsforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy" https://docs.streamlit.io/en/0.68.0/api.html#configuration,"DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceremovePAGE ELEMENTSWrite and magicaddText elementsaddData elementsaddChart elementsaddInput widgetsaddMedia elementsaddLayouts and containersaddChat elementsaddStatus elementsaddThird-party componentsopen_in_newAPPLICATION LOGICNavigation and pagesaddExecution flowaddCaching and stateaddConnections and secretsaddCustom componentsaddUtilitiesaddConfigurationaddTOOLSApp testingaddCommand lineaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Develop/API referenceAPI reference Streamlit makes it easy for you to visualize, mutate, and share data. The API reference is organized by activity type, like displaying data or optimizing performance. Each section includes methods associated with the activity type, including examples. Browse our API below and click to learn more about any of our available commands! 🎈 Display almost anything Write and magic st.writeWrite arguments to the app.st.write(""Hello **world**!"") st.write(my_data_frame) st.write(my_mpl_figure) st.write_streamWrite generators or streams to the app with a typewriter effect.st.write_stream(my_generator) st.write_stream(my_llm_stream) MagicAny time Streamlit sees either a variable or literal value on its own line, it automatically writes that to your app using st.write""Hello **world**!"" my_data_frame my_mpl_figure Text elements MarkdownDisplay string formatted as Markdown.st.markdown(""Hello **world**!"") TitleDisplay text in title formatting.st.title(""The app title"") HeaderDisplay text in header formatting.st.header(""This is a header"") SubheaderDisplay text in subheader formatting.st.subheader(""This is a subheader"") CaptionDisplay text in small font.st.caption(""This is written small caption text"") Code blockDisplay a code block with optional syntax highlighting.st.code(""a = 1234"") EchoDisplay some code in the app, then execute it. Useful for tutorials.with st.echo(): st.write('This code will be printed') LaTeXDisplay mathematical expressions formatted as LaTeX.st.latex(""\int a x^2 \,dx"") Preformatted textWrite fixed-width and preformatted text.st.text(""Hello world"") DividerDisplay a horizontal rule.st.divider() Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration! PreviousTagsAdd tags to your Streamlit apps. Created by @gagan3012.st_tags(label='# Enter Keywords:', text='Press enter to add more', value=['Zero', 'One', 'Two'], suggestions=['five', 'six', 'seven', 'eight', 'nine', 'three', 'eleven', 'ten', 'four'], maxtags = 4, key='1') NLUApply text mining on a dataframe. Created by @JohnSnowLabs.nlu.load('sentiment').predict('I love NLU! <3') Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.mention(label=""An awesome Streamlit App"", icon=""streamlit"", url=""https://extras.streamlit.app"",) Annotated textDisplay annotated text in Streamlit apps. Created by @tvst.annotated_text(""This "", (""is"", ""verb""), "" some "", (""annotated"", ""adj""), (""text"", ""noun""), "" for those of "", (""you"", ""pronoun""), "" who "", (""like"", ""verb""), "" this sort of "", (""thing"", ""noun""), ""."") Drawable CanvasProvides a sketching canvas using Fabric.js. Created by @andfanilo.st_canvas(fill_color=""rgba(255, 165, 0, 0.3)"", stroke_width=stroke_width, stroke_color=stroke_color, background_color=bg_color, background_image=Image.open(bg_image) if bg_image else None, update_streamlit=realtime_update, height=150, drawing_mode=drawing_mode, point_display_radius=point_display_radius if drawing_mode == 'point' else 0, key=""canvas"",) TagsAdd tags to your Streamlit apps. Created by @gagan3012.st_tags(label='# Enter Keywords:', text='Press enter to add more', value=['Zero', 'One', 'Two'], suggestions=['five', 'six', 'seven', 'eight', 'nine', 'three', 'eleven', 'ten', 'four'], maxtags = 4, key='1') NLUApply text mining on a dataframe. Created by @JohnSnowLabs.nlu.load('sentiment').predict('I love NLU! <3') Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.mention(label=""An awesome Streamlit App"", icon=""streamlit"", url=""https://extras.streamlit.app"",) Annotated textDisplay annotated text in Streamlit apps. Created by @tvst.annotated_text(""This "", (""is"", ""verb""), "" some "", (""annotated"", ""adj""), (""text"", ""noun""), "" for those of "", (""you"", ""pronoun""), "" who "", (""like"", ""verb""), "" this sort of "", (""thing"", ""noun""), ""."") Drawable CanvasProvides a sketching canvas using Fabric.js. Created by @andfanilo.st_canvas(fill_color=""rgba(255, 165, 0, 0.3)"", stroke_width=stroke_width, stroke_color=stroke_color, background_color=bg_color, background_image=Image.open(bg_image) if bg_image else None, update_streamlit=realtime_update, height=150, drawing_mode=drawing_mode, point_display_radius=point_display_radius if drawing_mode == 'point' else 0, key=""canvas"",) TagsAdd tags to your Streamlit apps. Created by @gagan3012.st_tags(label='# Enter Keywords:', text='Press enter to add more', value=['Zero', 'One', 'Two'], suggestions=['five', 'six', 'seven', 'eight', 'nine', 'three', 'eleven', 'ten', 'four'], maxtags = 4, key='1') NLUApply text mining on a dataframe. Created by @JohnSnowLabs.nlu.load('sentiment').predict('I love NLU! <3') Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.mention(label=""An awesome Streamlit App"", icon=""streamlit"", url=""https://extras.streamlit.app"",) Next Data elements DataframesDisplay a dataframe as an interactive table.st.dataframe(my_data_frame) Data editorDisplay a data editor widget.edited = st.data_editor(df, num_rows=""dynamic"") Column configurationConfigure the display and editing behavior of dataframes and data editors.st.column_config.NumberColumn(""Price (in USD)"", min_value=0, format=""$%d"") Static tablesDisplay a static table.st.table(my_data_frame) MetricsDisplay a metric in big bold font, with an optional indicator of how the metric changed.st.metric(""My metric"", 42, 2) Dicts and JSONDisplay object or string as a pretty-printed JSON string.st.json(my_dict) Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration! PreviousImage CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates value = streamlit_image_coordinates(""https://placekitten.com/200/300"") st.write(value) Plotly EventsMake Plotly charts interactive!. Created by @null-jones.from streamlit_plotly_events import plotly_events fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.metric_cards import style_metric_cards col3.metric(label=""No Change"", value=5000, delta=0) style_metric_cards() Streamlit AggridImplementation of Ag-Grid component for Streamlit. Created by @PablocFonseca.df = pd.DataFrame({'col1': [1, 2, 3], 'col2': [4, 5, 6]}) grid_return = AgGrid(df, editable=True) new_df = grid_return['data'] Streamlit FoliumStreamlit Component for rendering Folium maps. Created by @randyzwitch.m = folium.Map(location=[39.949610, -75.150282], zoom_start=16) folium.Marker([39.949610, -75.150282], popup=""Liberty Bell"", tooltip=""Liberty Bell"").add_to(m) st_data = st_folium(m, width=725) Pandas ProfilingPandas profiling component for Streamlit. Created by @okld.df = pd.read_csv(""https://storage.googleapis.com/tf-datasets/titanic/train.csv"") pr = df.profile_report() st_profile_report(pr) Image CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates value = streamlit_image_coordinates(""https://placekitten.com/200/300"") st.write(value) Plotly EventsMake Plotly charts interactive!. Created by @null-jones.from streamlit_plotly_events import plotly_events fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.metric_cards import style_metric_cards col3.metric(label=""No Change"", value=5000, delta=0) style_metric_cards() Streamlit AggridImplementation of Ag-Grid component for Streamlit. Created by @PablocFonseca.df = pd.DataFrame({'col1': [1, 2, 3], 'col2': [4, 5, 6]}) grid_return = AgGrid(df, editable=True) new_df = grid_return['data'] Streamlit FoliumStreamlit Component for rendering Folium maps. Created by @randyzwitch.m = folium.Map(location=[39.949610, -75.150282], zoom_start=16) folium.Marker([39.949610, -75.150282], popup=""Liberty Bell"", tooltip=""Liberty Bell"").add_to(m) st_data = st_folium(m, width=725) Pandas ProfilingPandas profiling component for Streamlit. Created by @okld.df = pd.read_csv(""https://storage.googleapis.com/tf-datasets/titanic/train.csv"") pr = df.profile_report() st_profile_report(pr) Image CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates value = streamlit_image_coordinates(""https://placekitten.com/200/300"") st.write(value) Plotly EventsMake Plotly charts interactive!. Created by @null-jones.from streamlit_plotly_events import plotly_events fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.metric_cards import style_metric_cards col3.metric(label=""No Change"", value=5000, delta=0) style_metric_cards() Next Chart elements Simple area chartsDisplay an area chart.st.area_chart(my_data_frame) Simple bar chartsDisplay a bar chart.st.bar_chart(my_data_frame) Simple line chartsDisplay a line chart.st.line_chart(my_data_frame) Simple scatter chartsDisplay a line chart.st.scatter_chart(my_data_frame) Scatterplots on mapsDisplay a map with points on it.st.map(my_data_frame) MatplotlibDisplay a matplotlib.pyplot figure.st.pyplot(my_mpl_figure) AltairDisplay a chart using the Altair library.st.altair_chart(my_altair_chart) Vega-LiteDisplay a chart using the Vega-Lite library.st.vega_lite_chart(my_vega_lite_chart) PlotlyDisplay an interactive Plotly chart.st.plotly_chart(my_plotly_chart) BokehDisplay an interactive Bokeh chart.st.bokeh_chart(my_bokeh_chart) PyDeckDisplay a chart using the PyDeck library.st.pydeck_chart(my_pydeck_chart) GraphVizDisplay a graph using the dagre-d3 library.st.graphviz_chart(my_graphviz_spec) Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration! PreviousStreamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl(""https://assets5.lottiefiles.com/packages/lf20_V9t630.json"") st_lottie(lottie_hello, key=""hello"") Plotly EventsMake Plotly charts interactive!. Created by @null-jones.fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.chart += get_annotations_chart(annotations=[(""Mar 01, 2008"", ""Pretty good day for GOOG""), (""Dec 01, 2007"", ""Something's going wrong for GOOG & AAPL""), (""Nov 01, 2008"", ""Market starts again thanks to...""), (""Dec 01, 2009"", ""Small crash for GOOG after...""),],) st.altair_chart(chart, use_container_width=True) PlostA deceptively simple plotting library for Streamlit. Created by @tvst.import plost plost.line_chart(my_dataframe, x='time', y='stock_value', color='stock_name',) HiPlotHigh dimensional Interactive Plotting. Created by @facebookresearch.data = [{'dropout':0.1, 'lr': 0.001, 'loss': 10.0, 'optimizer': 'SGD'}, {'dropout':0.15, 'lr': 0.01, 'loss': 3.5, 'optimizer': 'Adam'}, {'dropout':0.3, 'lr': 0.1, 'loss': 4.5, 'optimizer': 'Adam'}] hip.Experiment.from_iterable(data).display() EChartsHigh dimensional Interactive Plotting. Created by @andfanilo.from streamlit_echarts import st_echarts st_echarts(options=options) Streamlit FoliumStreamlit Component for rendering Folium maps. Created by @randyzwitch.m = folium.Map(location=[39.949610, -75.150282], zoom_start=16) st_data = st_folium(m, width=725) Spacy-StreamlitspaCy building blocks and visualizers for Streamlit apps. Created by @explosion.models = [""en_core_web_sm"", ""en_core_web_md""] spacy_streamlit.visualize(models, ""Sundar Pichai is the CEO of Google."") Streamlit AgraphA Streamlit Graph Vis, based on react-grah-vis. Created by @ChrisDelClea.from streamlit_agraph import agraph, Node, Edge, Config agraph(nodes=nodes, edges=edges, config=config) Streamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl(""https://assets5.lottiefiles.com/packages/lf20_V9t630.json"") st_lottie(lottie_hello, key=""hello"") Plotly EventsMake Plotly charts interactive!. Created by @null-jones.fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.chart += get_annotations_chart(annotations=[(""Mar 01, 2008"", ""Pretty good day for GOOG""), (""Dec 01, 2007"", ""Something's going wrong for GOOG & AAPL""), (""Nov 01, 2008"", ""Market starts again thanks to...""), (""Dec 01, 2009"", ""Small crash for GOOG after...""),],) st.altair_chart(chart, use_container_width=True) PlostA deceptively simple plotting library for Streamlit. Created by @tvst.import plost plost.line_chart(my_dataframe, x='time', y='stock_value', color='stock_name',) HiPlotHigh dimensional Interactive Plotting. Created by @facebookresearch.data = [{'dropout':0.1, 'lr': 0.001, 'loss': 10.0, 'optimizer': 'SGD'}, {'dropout':0.15, 'lr': 0.01, 'loss': 3.5, 'optimizer': 'Adam'}, {'dropout':0.3, 'lr': 0.1, 'loss': 4.5, 'optimizer': 'Adam'}] hip.Experiment.from_iterable(data).display() EChartsHigh dimensional Interactive Plotting. Created by @andfanilo.from streamlit_echarts import st_echarts st_echarts(options=options) Streamlit FoliumStreamlit Component for rendering Folium maps. Created by @randyzwitch.m = folium.Map(location=[39.949610, -75.150282], zoom_start=16) st_data = st_folium(m, width=725) Spacy-StreamlitspaCy building blocks and visualizers for Streamlit apps. Created by @explosion.models = [""en_core_web_sm"", ""en_core_web_md""] spacy_streamlit.visualize(models, ""Sundar Pichai is the CEO of Google."") Streamlit AgraphA Streamlit Graph Vis, based on react-grah-vis. Created by @ChrisDelClea.from streamlit_agraph import agraph, Node, Edge, Config agraph(nodes=nodes, edges=edges, config=config) Streamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl(""https://assets5.lottiefiles.com/packages/lf20_V9t630.json"") st_lottie(lottie_hello, key=""hello"") Plotly EventsMake Plotly charts interactive!. Created by @null-jones.fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.chart += get_annotations_chart(annotations=[(""Mar 01, 2008"", ""Pretty good day for GOOG""), (""Dec 01, 2007"", ""Something's going wrong for GOOG & AAPL""), (""Nov 01, 2008"", ""Market starts again thanks to...""), (""Dec 01, 2009"", ""Small crash for GOOG after...""),],) st.altair_chart(chart, use_container_width=True) Next Input widgets ButtonDisplay a button widget.clicked = st.button(""Click me"") Download buttonDisplay a download button widget.st.download_button(""Download file"", file) Form buttonDisplay a form submit button. For use with st.form.st.form_submit_button(""Sign up"") Link buttonDisplay a link button.st.link_button(""Go to gallery"", url) Page linkDisplay a link to another page in a multipage app.st.page_link(""app.py"", label=""Home"", icon=""🏠"") st.page_link(""pages/profile.py"", label=""My profile"") CheckboxDisplay a checkbox widget.selected = st.checkbox(""I agree"") Color pickerDisplay a color picker widget.color = st.color_picker(""Pick a color"") MultiselectDisplay a multiselect widget. The multiselect widget starts as empty.choices = st.multiselect(""Buy"", [""milk"", ""apples"", ""potatoes""]) RadioDisplay a radio button widget.choice = st.radio(""Pick one"", [""cats"", ""dogs""]) SelectboxDisplay a select widget.choice = st.selectbox(""Pick one"", [""cats"", ""dogs""]) Select-sliderDisplay a slider widget to select items from a list.size = st.select_slider(""Pick a size"", [""S"", ""M"", ""L""]) ToggleDisplay a toggle widget.activated = st.toggle(""Activate"") Number inputDisplay a numeric input widget.choice = st.number_input(""Pick a number"", 0, 10) SliderDisplay a slider widget.number = st.slider(""Pick a number"", 0, 100) Date inputDisplay a date input widget.date = st.date_input(""Your birthday"") Time inputDisplay a time input widget.time = st.time_input(""Meeting time"") Chat inputDisplay a chat input widget.prompt = st.chat_input(""Say something"") if prompt: st.write(f""The user has sent: {prompt}"") Text-areaDisplay a multi-line text input widget.text = st.text_area(""Text to translate"") Text inputDisplay a single-line text input widget.name = st.text_input(""First name"") Data editorDisplay a data editor widget.edited = st.experimental_data_editor(df, num_rows=""dynamic"") File UploaderDisplay a file uploader widget.data = st.file_uploader(""Upload a CSV"") Camera inputDisplay a widget that allows users to upload images directly from a camera.image = st.camera_input(""Take a picture"") Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration! PreviousStreamlit ChatStreamlit Component for a Chatbot UI. Created by @AI-Yash.from streamlit_chat import message message(""My message"") message(""Hello bot!"", is_user=True) # align's the message to the right Streamlit Option MenuSelect a single item from a list of options in a menu. Created by @victoryhb.from streamlit_option_menu import option_menu option_menu(""Main Menu"", [""Home"", 'Settings'], icons=['house', 'gear'], menu_icon=""cast"", default_index=1) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.stoggle import stoggle stoggle( ""Click me!"", """"""🥷 Surprise! Here's some additional content"""""",) Streamlit ElementsCreate a draggable and resizable dashboard in Streamlit. Created by @okls.from streamlit_elements import elements, mui, html with elements(""new_element""): mui.Typography(""Hello world"") TagsAdd tags to your Streamlit apps. Created by @gagan3012.from streamlit_tags import st_tags st_tags(label='# Enter Keywords:', text='Press enter to add more', value=['Zero', 'One', 'Two'], suggestions=['five', 'six', 'seven', 'eight', 'nine', 'three', 'eleven', 'ten', 'four'], maxtags = 4, key='1') StqdmThe simplest way to handle a progress bar in streamlit app. Created by @Wirg.from stqdm import stqdm for _ in stqdm(range(50)): sleep(0.5) TimelineDisplay a Timeline in Streamlit apps using TimelineJS. Created by @innerdoc.from streamlit_timeline import timeline with open('example.json', ""r"") as f: timeline(f.read(), height=800) Camera input liveAlternative for st.camera_input which returns the webcam images live. Created by @blackary.from camera_input_live import camera_input_live image = camera_input_live() st.image(value) Streamlit AceAce editor component for Streamlit. Created by @okld.from streamlit_ace import st_ace content = st_ace() content Streamlit ChatStreamlit Component for a Chatbot UI. Created by @AI-Yash.from streamlit_chat import message message(""My message"") message(""Hello bot!"", is_user=True) # align's the message to the right Streamlit Option MenuSelect a single item from a list of options in a menu. Created by @victoryhb.from streamlit_option_menu import option_menu option_menu(""Main Menu"", [""Home"", 'Settings'], icons=['house', 'gear'], menu_icon=""cast"", default_index=1) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.stoggle import stoggle stoggle( ""Click me!"", """"""🥷 Surprise! Here's some additional content"""""",) Streamlit ElementsCreate a draggable and resizable dashboard in Streamlit. Created by @okls.from streamlit_elements import elements, mui, html with elements(""new_element""): mui.Typography(""Hello world"") TagsAdd tags to your Streamlit apps. Created by @gagan3012.from streamlit_tags import st_tags st_tags(label='# Enter Keywords:', text='Press enter to add more', value=['Zero', 'One', 'Two'], suggestions=['five', 'six', 'seven', 'eight', 'nine', 'three', 'eleven', 'ten', 'four'], maxtags = 4, key='1') StqdmThe simplest way to handle a progress bar in streamlit app. Created by @Wirg.from stqdm import stqdm for _ in stqdm(range(50)): sleep(0.5) TimelineDisplay a Timeline in Streamlit apps using TimelineJS. Created by @innerdoc.from streamlit_timeline import timeline with open('example.json', ""r"") as f: timeline(f.read(), height=800) Camera input liveAlternative for st.camera_input which returns the webcam images live. Created by @blackary.from camera_input_live import camera_input_live image = camera_input_live() st.image(value) Streamlit AceAce editor component for Streamlit. Created by @okld.from streamlit_ace import st_ace content = st_ace() content Streamlit ChatStreamlit Component for a Chatbot UI. Created by @AI-Yash.from streamlit_chat import message message(""My message"") message(""Hello bot!"", is_user=True) # align's the message to the right Streamlit Option MenuSelect a single item from a list of options in a menu. Created by @victoryhb.from streamlit_option_menu import option_menu option_menu(""Main Menu"", [""Home"", 'Settings'], icons=['house', 'gear'], menu_icon=""cast"", default_index=1) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.stoggle import stoggle stoggle( ""Click me!"", """"""🥷 Surprise! Here's some additional content"""""",) Next Media elements ImageDisplay an image or list of images.st.image(numpy_array) st.image(image_bytes) st.image(file) st.image(""https://example.com/myimage.jpg"") AudioDisplay an audio player.st.audio(numpy_array) st.audio(audio_bytes) st.audio(file) st.audio(""https://example.com/myaudio.mp3"", format=""audio/mp3"") VideoDisplay a video player.st.video(numpy_array) st.video(video_bytes) st.video(file) st.video(""https://example.com/myvideo.mp4"", format=""video/mp4"") Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration! PreviousStreamlit CropperA simple image cropper for Streamlit. Created by @turner-anderson.from streamlit_cropper import st_cropper st_cropper(img, realtime_update=realtime_update, box_color=box_color, aspect_ratio=aspect_ratio) Image CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates streamlit_image_coordinates(""https://placekitten.com/200/300"") Streamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl(""https://assets5.lottiefiles.com/packages/lf20_V9t630.json"") st_lottie(lottie_hello, key=""hello"") Streamlit WebrtcHandling and transmitting real-time video/audio streams with Streamlit. Created by @whitphx.from streamlit_webrtc import webrtc_streamer webrtc_streamer(key=""sample"") Drawable CanvasProvides a sketching canvas using Fabric.js. Created by @andfanilo.from streamlit_drawable_canvas import st_canvas st_canvas(fill_color=""rgba(255, 165, 0, 0.3)"", stroke_width=stroke_width, stroke_color=stroke_color, background_color=bg_color, background_image=Image.open(bg_image) if bg_image else None, update_streamlit=realtime_update, height=150, drawing_mode=drawing_mode, point_display_radius=point_display_radius if drawing_mode == 'point' else 0, key=""canvas"",) Image ComparisonCompare images with a slider using JuxtaposeJS. Created by @fcakyon.from streamlit_image_comparison import image_comparison image_comparison(img1=""image1.jpg"", img2=""image2.jpg"",) Streamlit CropperA simple image cropper for Streamlit. Created by @turner-anderson.from streamlit_cropper import st_cropper st_cropper(img, realtime_update=realtime_update, box_color=box_color, aspect_ratio=aspect_ratio) Image CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates streamlit_image_coordinates(""https://placekitten.com/200/300"") Streamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl(""https://assets5.lottiefiles.com/packages/lf20_V9t630.json"") st_lottie(lottie_hello, key=""hello"") Streamlit WebrtcHandling and transmitting real-time video/audio streams with Streamlit. Created by @whitphx.from streamlit_webrtc import webrtc_streamer webrtc_streamer(key=""sample"") Drawable CanvasProvides a sketching canvas using Fabric.js. Created by @andfanilo.from streamlit_drawable_canvas import st_canvas st_canvas(fill_color=""rgba(255, 165, 0, 0.3)"", stroke_width=stroke_width, stroke_color=stroke_color, background_color=bg_color, background_image=Image.open(bg_image) if bg_image else None, update_streamlit=realtime_update, height=150, drawing_mode=drawing_mode, point_display_radius=point_display_radius if drawing_mode == 'point' else 0, key=""canvas"",) Image ComparisonCompare images with a slider using JuxtaposeJS. Created by @fcakyon.from streamlit_image_comparison import image_comparison image_comparison(img1=""image1.jpg"", img2=""image2.jpg"",) Streamlit CropperA simple image cropper for Streamlit. Created by @turner-anderson.from streamlit_cropper import st_cropper st_cropper(img, realtime_update=realtime_update, box_color=box_color, aspect_ratio=aspect_ratio) Image CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates streamlit_image_coordinates(""https://placekitten.com/200/300"") Streamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl(""https://assets5.lottiefiles.com/packages/lf20_V9t630.json"") st_lottie(lottie_hello, key=""hello"") Next Layouts and containers ColumnsInsert containers laid out as side-by-side columns.col1, col2 = st.columns(2) col1.write(""this is column 1"") col2.write(""this is column 2"") ContainerInsert a multi-element container.c = st.container() st.write(""This will show last"") c.write(""This will show first"") c.write(""This will show second"") Modal dialogsInsert a modal dialog that can rerun independently from the rest of the script.@st.experimental_dialog(""Sign up"") def email_form(): name = st.text_input(""Name"") email = st.text_input(""Email"") EmptyInsert a single-element container.c = st.empty() st.write(""This will show last"") c.write(""This will be replaced"") c.write(""This will show first"") ExpanderInsert a multi-element container that can be expanded/collapsed.with st.expander(""Open to see more""): st.write(""This is more content"") PopoverInsert a multi-element popover container that can be opened/closed.with st.popover(""Settings""): st.checkbox(""Show completed"") SidebarDisplay items in a sidebar.st.sidebar.write(""This lives in the sidebar"") st.sidebar.button(""Click me!"") TabsInsert containers separated into tabs.tab1, tab2 = st.tabs([""Tab 1"", ""Tab2""]) tab1.write(""this is tab 1"") tab2.write(""this is tab 2"") Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration!Streamlit ElementsCreate a draggable and resizable dashboard in Streamlit. Created by @okls.from streamlit_elements import elements, mui, html with elements(""new_element""): mui.Typography(""Hello world"") PydanticAuto-generate Streamlit UI from Pydantic Models and Dataclasses. Created by @lukasmasuch.import streamlit_pydantic as sp sp.pydantic_form(key=""my_form"", model=ExampleModel) Streamlit PagesAn experimental version of Streamlit Multi-Page Apps. Created by @blackary.from st_pages import Page, show_pages, add_page_title show_pages([ Page(""streamlit_app.py"", ""Home"", ""🏠""), Page(""other_pages/page2.py"", ""Page 2"", "":books:""), ]) Chat elements Streamlit provides a few commands to help you build conversational apps. These chat elements are designed to be used in conjunction with each other, but you can also use them separately. st.chat_message lets you insert a chat message container into the app so you can display messages from the user or the app. Chat containers can contain other Streamlit elements, including charts, tables, text, and more. st.chat_input lets you display a chat input widget so the user can type in a message. Chat inputDisplay a chat input widget.prompt = st.chat_input(""Say something"") if prompt: st.write(f""The user has sent: {prompt}"") Chat messageInsert a chat message container.import numpy as np with st.chat_message(""user""): st.write(""Hello 👋"") st.line_chart(np.random.randn(30, 3)) Status containerDisplay output of long-running tasks in a container.with st.status('Running'): do_something_slow() st.write_streamWrite generators or streams to the app with a typewriter effect.st.write_stream(my_generator) st.write_stream(my_llm_stream) Status elements Progress barDisplay a progress bar.for i in range(101): st.progress(i) do_something_slow() SpinnerTemporarily displays a message while executing a block of code.with st.spinner(""Please wait...""): do_something_slow() Status containerDisplay output of long-running tasks in a container.with st.status('Running'): do_something_slow() ToastBriefly displays a toast message in the bottom-right corner.st.toast('Butter!', icon='🧈') BalloonsDisplay celebratory balloons!do_something() # Celebrate when all done! st.balloons() SnowflakesDisplay celebratory snowflakes!do_something() # Celebrate when all done! st.snow() Success boxDisplay a success message.st.success(""Match found!"") Info boxDisplay an informational message.st.info(""Dataset is updated every day at midnight."") Warning boxDisplay warning message.st.warning(""Unable to fetch image. Skipping..."") Error boxDisplay error message.st.error(""We encountered an error"") Exception outputDisplay an exception.e = RuntimeError(""This is an exception of type RuntimeError"") st.exception(e) Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration!StqdmThe simplest way to handle a progress bar in streamlit app. Created by @Wirg.from stqdm import stqdm for _ in stqdm(range(50)): sleep(0.5) Custom notification boxA custom notification box with the ability to close it out. Created by @Socvest.from streamlit_custom_notification_box import custom_notification_box styles = {'material-icons':{'color': 'red'}, 'text-icon-link-close-container': {'box-shadow': '#3896de 0px 4px'}, 'notification-text': {'':''}, 'close-button':{'':''}, 'link':{'':''}} custom_notification_box(icon='info', textDisplay='We are almost done with your registration...', externalLink='more info', url='#', styles=styles, key=""foo"") Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.let_it_rain import rain rain(emoji=""🎈"", font_size=54, falling_speed=5, animation_length=""infinite"",) App logic and configuration Navigation and pages Switch pageProgrammatically navigates to a specified page.st.switch_page(""pages/my_page.py"") Page linkDisplay a link to another page in a multipage app.st.page_link(""app.py"", label=""Home"", icon=""🏠"") st.page_link(""pages/profile.py"", label=""My profile"") Execution flow Modal dialogsInsert a modal dialog that can rerun independently from the rest of the script.@st.experimental_dialog(""Sign up"") def email_form(): name = st.text_input(""Name"") email = st.text_input(""Email"") FormsCreate a form that batches elements together with a “Submit"" button.with st.form(key='my_form'): name = st.text_input(""Name"") email = st.text_input(""Email"") st.form_submit_button(""Sign up"") Partial rerunsDefine a fragment to rerun independently from the rest of the script.@st.experimental_fragment(run_every=""10s"") def fragment(): df = get_data() st.line_chart(df) Rerun scriptRerun the script immediately.st.rerun() Stop executionStops execution immediately.st.stop() Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration!AutorefreshForce a refresh without tying up a script. Created by @kmcgrady.from streamlit_autorefresh import st_autorefresh st_autorefresh(interval=2000, limit=100, key=""fizzbuzzcounter"") PydanticAuto-generate Streamlit UI from Pydantic Models and Dataclasses. Created by @lukasmasuch.import streamlit_pydantic as sp sp.pydantic_form(key=""my_form"", model=ExampleModel) Streamlit PagesAn experimental version of Streamlit Multi-Page Apps. Created by @blackary.from st_pages import Page, show_pages, add_page_title show_pages([ Page(""streamlit_app.py"", ""Home"", ""🏠""), Page(""other_pages/page2.py"", ""Page 2"", "":books:""), ]) Caching and state Cache dataFunction decorator to cache functions that return data (e.g. dataframe transforms, database queries, ML inference).@st.cache_data def long_function(param1, param2): # Perform expensive computation here or # fetch data from the web here return data Cache resourceFunction decorator to cache functions that return global resources (e.g. database connections, ML models).@st.cache_resource def init_model(): # Return a global resource here return pipeline( ""sentiment-analysis"", model=""distilbert-base-uncased-finetuned-sst-2-english"" ) Session stateSession state is a way to share variables between reruns, for each user session.st.session_state['key'] = value Query parametersGet, set, or clear the query parameters that are shown in the browser's URL bar.st.query_params[key] = value st.query_params.clear() Connections and databases Setup your connection Create a connectionConnect to a data source or APIconn = st.connection('pets_db', type='sql') pet_owners = conn.query('select * from pet_owners') st.dataframe(pet_owners) Built-in connections SnowflakeConnectionA connection to Snowflake.conn = st.connection('snowflake') SQLConnectionA connection to a SQL database using SQLAlchemy.conn = st.connection('sql') Build your own connections Connection base classBuild your own connection with BaseConnection.class MyConnection(BaseConnection[myconn.MyConnection]): def _connect(self, **kwargs) -> MyConnection: return myconn.connect(**self._secrets, **kwargs) def query(self, query): return self._instance.query(query) Secrets management Secrets singletonAccess secrets from a local TOML file.key = st.secrets[""OpenAI_key""] Secrets fileSave your secrets in a per-project or per-profile TOML file.OpenAI_key = """" Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration!AuthenticatorA secure authentication module to validate user credentials. Created by @mkhorasani.import streamlit_authenticator as stauth authenticator = stauth.Authenticate( config['credentials'], config['cookie']['name'], config['cookie']['key'], config['cookie']['expiry_days'], config['preauthorized']) WS localStorageA simple synchronous way of accessing localStorage from your app. Created by @gagangoku.from streamlit_ws_localstorage import injectWebsocketCode ret = conn.setLocalStorageVal(key='k1', val='v1') st.write('ret: ' + ret) Streamlit Auth0The fastest way to provide comprehensive login inside Streamlit. Created by @conradbez.from auth0_component import login_button user_info = login_button(clientId, domain = domain) st.write(user_info) Custom Components Declare a componentCreate and register a custom component.st.components.v1.declare_component( ""custom_slider"", ""/frontend"", ) HTMLDisplay an HTML string in an iframe.st.components.v1.html( ""

Foo bar.

"" ) iframeLoad a remote URL in an iframe.st.components.v1.iframe( ""docs.streamlit.io"" ) Utilities and user info User infost.experimental_user returns information about the logged-in user of private apps on Streamlit Community Cloud.if st.experimental_user.email == ""foo@corp.com"": st.write(""Welcome back, "", st.experimental_user.email) else: st.write(""You are not authorized to view this page."") Get helpDisplay object’s doc string, nicely formatted.st.help(st.write) st.help(pd.DataFrame) Render HTMLRenders HTML strings to your app.css = """""" """""" st.html(css) Configuration Configuration fileConfigures the default settings for your app.your-project/ ├── .streamlit/ │ └── config.toml └── your_app.py Set page title, favicon, and moreConfigures the default settings of the page.st.set_page_config( page_title=""My app"", page_icon="":shark:"", ) Developer tools App testing st.testing.v1.AppTestst.testing.v1.AppTest simulates a running Streamlit app for testing.from streamlit.testing.v1 import AppTest at = AppTest.from_file(""streamlit_app.py"") at.secrets[""WORD""] = ""Foobar"" at.run() assert not at.exception at.text_input(""word"").input(""Bazbat"").run() assert at.warning[0].value == ""Try again."" AppTest.from_filest.testing.v1.AppTest.from_file initializes a simulated app from a file.from streamlit.testing.v1 import AppTest at = AppTest.from_file(""streamlit_app.py"") at.run() AppTest.from_stringst.testing.v1.AppTest.from_string initializes a simulated app from a string.from streamlit.testing.v1 import AppTest at = AppTest.from_string(app_script_as_string) at.run() AppTest.from_functionst.testing.v1.AppTest.from_function initializes a simulated app from a function.from streamlit.testing.v1 import AppTest at = AppTest.from_function(app_script_as_callable) at.run() BlockA representation of container elements, including: st.chat_message st.columns st.sidebar st.tabs The main body of the app. # at.sidebar returns a Block at.sidebar.button[0].click().run() assert not at.exception ElementThe base class for representation of all elements, including: st.title st.header st.markdown st.dataframe # at.title returns a sequence of Title # Title inherits from Element assert at.title[0].value == ""My awesome app"" ButtonA representation of st.button and st.form_submit_button.at.button[0].click().run() ChatInputA representation of st.chat_input.at.chat_input[0].set_value(""What is Streamlit?"").run() CheckboxA representation of st.checkbox.at.checkbox[0].check().run() ColorPickerA representation of st.color_picker.at.color_picker[0].pick(""#FF4B4B"").run() DateInputA representation of st.date_input.release_date = datetime.date(2023, 10, 26) at.date_input[0].set_value(release_date).run() MultiselectA representation of st.multiselect.at.multiselect[0].select(""New York"").run() NumberInputA representation of st.number_input.at.number_input[0].increment().run() RadioA representation of st.radio.at.radio[0].set_value(""New York"").run() SelectSliderA representation of st.select_slider.at.select_slider[0].set_range(""A"",""C"").run() SelectboxA representation of st.selectbox.at.selectbox[0].select(""New York"").run() SliderA representation of st.slider.at.slider[0].set_range(2,5).run() TextAreaA representation of st.text_area.at.text_area[0].input(""Streamlit is awesome!"").run() TextInputA representation of st.text_input.at.text_input[0].input(""Streamlit"").run() TimeInputA representation of st.time_input.at.time_input[0].increment().run() ToggleA representation of st.toggle.at.toggle[0].set_value(""True"").run() Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration!Pandas ProfilingPandas profiling component for Streamlit. Created by @okld.df = pd.read_csv(""https://storage.googleapis.com/tf-datasets/titanic/train.csv"") pr = df.profile_report() st_profile_report(pr) Streamlit AceAce editor component for Streamlit. Created by @okld.from streamlit_ace import st_ace content = st_ace() content Streamlit AnalyticsTrack & visualize user interactions with your streamlit app. Created by @jrieke.import streamlit_analytics with streamlit_analytics.track(): st.text_input(""Write something"") Previous: ConceptsNext: Write and magicforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy" https://docs.streamlit.io/knowledge-base/using-streamlit/how-download-pandas-dataframe-csv#how-to-download-a-pandas-dataframe-as-a-csv,"DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Knowledge base/FAQ/How to download a Pandas DataFrame as a CSV?How to download a Pandas DataFrame as a CSV? Use the st.download_button widget that is natively built into Streamlit. Check out a sample app demonstrating how you can use st.download_button to download common file formats. Example usage import streamlit as st import pandas as pd df = pd.read_csv(""dir/file.csv"") @st.experimental_memo def convert_df(df): return df.to_csv(index=False).encode('utf-8') csv = convert_df(df) st.download_button( ""Press to Download"", csv, ""file.csv"", ""text/csv"", key='download-csv' ) Additional resources: https://blog.streamlit.io/0-88-0-release-notes/ https://streamlit-release-demos-0-88streamlit-app-0-88-v8ram3.streamlit.app/ https://docs.streamlit.io/develop/api-reference/widgets/st.download_button Previous: How to download a file in Streamlit?Next: How do I get dataframe row-selections from a user?forumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy" https://docs.streamlit.io/deploy/streamlit-community-cloud/get-started/connect-your-github-account#approved-access,"DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudremoveGet startedremoveQuickstartCreate your accountConnect your GitHub accountExplore your workspaceFork and edit a public appTrust and securityDeploy your appaddManage your appaddShare your appaddManage your accountaddTroubleshootingStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Deploy/Streamlit Community Cloud/Get started/Connect your GitHub accountConnect your GitHub account Connecting GitHub to your Streamlit Community Cloud account allows you to deploy apps directly from the files you store in your repos. It also lets the system check for updates to those files and automatically update your app. There are two stages to this authorization: the first happens when you connect your account for the first time and the second happens when you deploy your first app. Everyone is prompted to connect GitHub when they create an account. If you need to connect GitHub to an existing primary identity, see Manage your GitHub connection. This page contains additional information about the authorization needed to connect GitHub. If you have just created your account, you are free to skip ahead and Explore your workspace. GitHub's authorization prompts occur automatically as needed. Authorize your GitHub account There are two different authorization prompts to grant access between Streamlit and your GitHub account. The first authorization—""Authorize Streamlit""—happens when you connect your GitHub account to Streamlit. The second authorization—""Streamlit is requesting additional permissions""—happens when you deploy your first app. You must click ""Authorize streamlit"" on both. If you are a member of any GitHub organizations, read below to understand the extras steps to authorize an organization. Questions about GitHub permissions? Read some frequently asked questions about our GitHub integration. priority_highImportantYou must have admin permissions to your repo in order to deploy apps. If you don't have admin access, talk to the repo's owner or reach out to us on the Community forum. Organization access If you are working in a repository that is owned by an organization, authorization must be granted by that organization. If you are an owner or member of a GitHub organization when you connect your GitHub account, your authorization prompts will include an extra section labeled ""Organization access"". Organizations you own For any organization you own, if authorization has not been previously granted or denied you can click ""Grant"" before you click ""Authorize streamlit"". Organizations owned by others For an organization you don't own, if authorization has not been previously granted or denied you can click ""Request"" before you click ""Authorize streamlit"". Previous or pending authorization If someone has already started the process of authorizing Streamlit for your organization, different options and statuses will display accordingly. Approved access If an organization has already granted Streamlit access, a green check is shown. Pending access If a request has been previously sent but not yet approved, a pending status shows. Denied access If a request has been previously sent and denied, no option to grant or request access is shown. In this case, the organization owner will need to authorize Streamlit from GitHub. See GitHub's documentation on OAuth apps and organizations. What's next? Now that you have your account you can Explore your workspace. Or if you're ready to go, jump right in and Deploy your app.Previous: Create your accountNext: Explore your workspaceforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy" https://docs.streamlit.io/develop/tutorials/multipage/st.page_link-nav#build-a-custom-navigation-menu-with-stpage_link,"DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceaddTutorialsremoveExecution flowaddConnect to data sourcesaddMultipage appsremoveBuild navigation with st.page_linkWork with LLMsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Develop/Tutorials/Multipage apps/Build navigation with st.page_linkBuild a custom navigation menu with st.page_link Streamlit lets you build custom navigation menus and elements with st.page_link. Introduced in Streamlit version 1.31.0, st.page_link can link to other pages in your multipage app or to external sites. When linked to another page in your app, st.page_link will show a highlight effect to indicate the current page. When combined with the client.showSidebarNavigation configuration option, you can build sleek, dynamic navigation in your app. Prerequisites Create a new working directory in your development environment. We'll call this directory your-repository. Summary In this example, we'll build a dynamic navigation menu for a multipage app that depends on the current user's role. We've abstracted away the use of username and creditials to simplify the example. Instead, we'll use a selectbox on the main page of the app to switch between roles. Session State will carry this selection between pages. The app will have a main page (app.py) which serves as the abstracted log-in page. There will be three additional pages which will be hidden or accessible, depending on the current role. The file structure will be as follows: your-repository/ ├── .streamlit/ │ └── config.toml ├── pages/ │ ├── admin.py │ ├── super-admin.py │ └── user.py ├── menu.py └── app.py Here's a look at what we'll build: Built with Streamlit 🎈Fullscreen open_in_new Build the example Hide the default sidebar navigation When creating a custom navigation menu, you need to hide the default sidebar navigation using client.showSidebarNavigation. Add the following .streamlit/config.toml file to your working directory: [client] showSidebarNavigation = false Create a menu function You can write different menu logic for different pages or you can create a single menu function to call on multiple pages. In this example, we'll use the same menu logic on all pages, including a redirect to the main page when a user isn't logged in. We'll build a few helper functions to do this. menu_with_redirect() checks if a user is logged in, then either redirects them to the main page or renders the menu. menu() will call the correct helper function to render the menu based on whether the user is logged in or not. authenticated_menu() will display a menu based on an authenticated user's role. unauthenticated_menu() will display a menu for unauthenticated users. We'll call menu() on the main page and call menu_with_redirect() on the other pages. st.session_state.role will store the current selected role. If this value does not exist or is set to None, then the user is not logged in. Otherwise, it will hold the user's role as a string: ""user"", ""admin"", or ""super-admin"". Add the following menu.py file to your working directory. (We'll describe the functions in more detail below.) import streamlit as st def authenticated_menu(): # Show a navigation menu for authenticated users st.sidebar.page_link(""app.py"", label=""Switch accounts"") st.sidebar.page_link(""pages/user.py"", label=""Your profile"") if st.session_state.role in [""admin"", ""super-admin""]: st.sidebar.page_link(""pages/admin.py"", label=""Manage users"") st.sidebar.page_link( ""pages/super-admin.py"", label=""Manage admin access"", disabled=st.session_state.role != ""super-admin"", ) def unauthenticated_menu(): # Show a navigation menu for unauthenticated users st.sidebar.page_link(""app.py"", label=""Log in"") def menu(): # Determine if a user is logged in or not, then show the correct # navigation menu if ""role"" not in st.session_state or st.session_state.role is None: unauthenticated_menu() return authenticated_menu() def menu_with_redirect(): # Redirect users to the main page if not logged in, otherwise continue to # render the navigation menu if ""role"" not in st.session_state or st.session_state.role is None: st.switch_page(""app.py"") menu() Let's take a closer look at authenticated_menu(). When this function is called, st.session_state.role exists and has a value other than None. def authenticated_menu(): # Show a navigation menu for authenticated users The first two pages in the navigation menu are available to all users. Since we know a user is logged in when this function is called, we'll use the label ""Switch accounts"" for the main page. (If you don't use the label parameter, the page name will be derived from the file name like it is with the default sidebar navigation.) st.sidebar.page_link(""app.py"", label=""Switch accounts"") st.sidebar.page_link(""pages/user.py"", label=""Your profile"") We only want to show the next two pages to admins. Furthermore, we've chosen to disable—but not hide—the super-admin page when the admin user is not a super-admin. We do this using the disabled parameter. (disabled=True when the role is not ""super-admin"".) if st.session_state.role in [""admin"", ""super-admin""]: st.sidebar.page_link(""pages/admin.py"", label=""Manage users"") st.sidebar.page_link( ""pages/super-admin.py"", label=""Manage admin access"", disabled=st.session_state.role != ""super-admin"", ) It's that simple! unauthenticated_menu() will only show a link to the main page of the app with the label ""Log in."" menu() does a simple inspection of st.session_state.role to switch between the two menu-rendering functions. Finally, menu_with_redirect() extends menu() to redirect users to app.py if they aren't logged in. starTipIf you want to include emojis in your page labels, you can use the icon parameter. There's no need to include emojis in your file name or the label parameter. Create the main file of your app The main app.py file will serve as a pseudo-login page. The user can choose a role from the st.selectbox widget. A few bits of logic will save that role into Session State to preserve it while navigating between pages—even when returning to app.py. Add the following app.py file to your working directory: import streamlit as st from menu import menu # Initialize st.session_state.role to None if ""role"" not in st.session_state: st.session_state.role = None # Retrieve the role from Session State to initialize the widget st.session_state._role = st.session_state.role def set_role(): # Callback function to save the role selection to Session State st.session_state.role = st.session_state._role # Selectbox to choose role st.selectbox( ""Select your role:"", [None, ""user"", ""admin"", ""super-admin""], key=""_role"", on_change=set_role, ) menu() # Render the dynamic menu! Add other pages to your app Add the following pages/user.py file: import streamlit as st from menu import menu_with_redirect # Redirect to app.py if not logged in, otherwise show the navigation menu menu_with_redirect() st.title(""This page is available to all users"") st.markdown(f""You are currently logged with the role of {st.session_state.role}."") Session State resets if a user manually navigates to a page by URL. Therefore, if a user tries to access an admin page in this example, Session State will be cleared, and they will be redirected to the main page as an unauthenicated user. However, it's still good practice to include a check of the role at the top of each restricted page. You can use st.stop to halt an app if a role is not whitelisted. pages/admin.py: import streamlit as st from menu import menu_with_redirect # Redirect to app.py if not logged in, otherwise show the navigation menu menu_with_redirect() # Verify the user's role if st.session_state.role not in [""admin"", ""super-admin""]: st.warning(""You do not have permission to view this page."") st.stop() st.title(""This page is available to all admins"") st.markdown(f""You are currently logged with the role of {st.session_state.role}."") pages/super-admin.py: import streamlit as st from menu import menu_with_redirect # Redirect to app.py if not logged in, otherwise show the navigation menu menu_with_redirect() # Verify the user's role if st.session_state.role not in [""super-admin""]: st.warning(""You do not have permission to view this page."") st.stop() st.title(""This page is available to super-admins"") st.markdown(f""You are currently logged with the role of {st.session_state.role}."") As noted above, the redirect in menu_with_redirect() will prevent a user from ever seeing the warning messages on the admin pages. If you want to see the warning, just add another st.page_link(""pages/admin.py"") button at the bottom of app.py so you can navigate to the admin page after selecting the ""user"" role. 😉Previous: Multipage appsNext: Work with LLMsforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy" https://docs.streamlit.io/deploy/streamlit-community-cloud/get-started/trust-and-security#product-security,"DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudremoveGet startedremoveQuickstartCreate your accountConnect your GitHub accountExplore your workspaceFork and edit a public appTrust and securityDeploy your appaddManage your appaddShare your appaddManage your accountaddTroubleshootingStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Deploy/Streamlit Community Cloud/Get started/Trust and securityStreamlit trust and security Streamlit is a framework that turns Python scripts into interactive apps, giving data scientists the ability to quickly create data and model-based apps for the entire company. A simple Streamlit app is: import streamlit as st number = st.slider(""Pick a number: "", min_value=1, max_value=10) st.text(""Your number is "" + str(number)) When you streamlit run my_app.py, you start a web server that runs the interactive application on your local computer at http://localhost:8501. This is great for local development. When you want to share with your colleagues, Streamlit Community Cloud enables you to deploy and run these applications in the cloud. Streamlit Community Cloud handles the details of containerization and provides you an interface for easily managing your deployed apps. This document provides an overview of the security safeguards we've implemented to protect you and your data. Security, however, is a shared responsibility and you are ultimately responsible for making appropriate use of Streamlit and the Streamlit Community Cloud, including implementation of appropriate user-configurable security safeguards and best practices. Product security Authentication You must authenticate through GitHub to deploy or administer an app. Authentication through Google or single-use emailed links are required to view a private app when you don't have push or admin permissions on the associated GitHub repository. The single-use emailed links are valid for 15 minutes once requested. Permissions Streamlit Community Cloud inherits the permissions you have assigned in GitHub. Users with write access to a GitHub repository for a given app will be able to make changes in the Streamlit administrative console. However, only users with admin access to a repository are able to deploy and delete apps. Network and application security Data hosting Our physical infrastructure is hosted and managed within secure data centers maintained by infrastructure-as-a-service cloud providers. Streamlit leverages many of these platforms' built-in security, privacy, and redundancy features. Our cloud providers continually monitor their data centers for risk and undergo assessments to ensure compliance with industry standards. Data deletion Community Cloud users have the option to delete any apps they’ve deployed as well as their entire account. When a user deletes their application from the admin console, we delete their source code, including any files copied from their GitHub repository or created within our system from the running app. However, we keep a record representing the application in our database. This record contains the coordinates of the application: the GitHub organization or user, the GitHub repository, the branch, and the path of the main module file. When a user deletes their account, we perform a hard deletion of their data and a hard deletion of all the apps that belong to the GitHub identity associated with their account. In this case, we do not maintain the records of application coordinates described above. When an account is deleted, we also delete any HubSpot contact associated with the Community Cloud account. Virtual private cloud All of our servers are within a virtual private cloud (VPC) with firewalls and network access control lists (ACLs) to allow external access to a select few API endpoints; all other internal services are only accessible within the VPC. Encryption Streamlit apps are served entirely over HTTPS. We use only strong cipher suites and HTTP Strict Transport Security (HSTS) to ensure browsers interact with Streamlit apps over HTTPS. All data sent to or from Streamlit over the public internet is encrypted in transit using 256-bit encryption. Our API and application endpoints use Transport Layer Security (TLS) 1.2 (or better). We also encrypt data at rest on disk using AES-256. Permissions and authentication Access to Community Cloud user account data is limited to authorized personnel. We run a zero-trust corporate network, utilize single sign-on and multi-factor authentication (MFA), and enforce strong password policies to ensure access to cloud-related services is protected. Incident response Our internal protocol for handling security events includes detection, analysis, response, escalation, and mitigation. Security advisories are made available at https://streamlit.io/advisories. Penetration testing Streamlit uses third-party security tools to scan for vulnerabilities on a regular basis. Our security teams conduct periodic, intensive penetration tests on the Streamlit platform. Our product development team responds to any identified issues or potential vulnerabilities to ensure the quality, security, and availability of Streamlit applications. Vulnerability management We keep our systems up-to-date with the latest security patches and continuously monitor for new vulnerabilities. This includes automated scanning of our code repositories for vulnerable dependencies. If you discover a vulnerability in one of our products or websites, please report the issue to HackerOne.Previous: Fork and edit a public appNext: Deploy your appforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy" https://docs.streamlit.io/get-started/installation#install-streamlit,"DocumentationsearchSearchrocket_launchGet startedInstallationremoveUse command lineUse Anaconda DistributionUse GitHub CodespacesUse SnowflakeFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Get started/InstallationInstall Streamlit There are multiple ways to set up your development environment and install Streamlit. Read below to understand these options. Developing locally with Python installed on your own computer is the most common scenario. Summary for experts Set up your Python development environment. Run: pip install streamlit Validate the installation by running our Hello app: streamlit hello Jump to our Basic concepts. Installation steps for the rest of us Option 1: I'm comfortable with the command lineInstall Streamlit on your own machine using tools like venv and pip.Option 2: I prefer a graphical interfaceInstall Streamlit using the Anaconda Distribution graphical user interface. This is also the best approach if you're on Windows or don't have Python set up.Option 3: I'd rather use a cloud-based environmentUse Streamlit Community Cloud with GitHub Codespaces so you don't have to go through the trouble of installing Python and setting up an environment.Option 4: I need something secure, controlled, and in the cloudUse Streamlit in Snowflake to code your apps in the cloud, right alongside your data with role-based access controls.Previous: Get startedNext: Use command lineforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy" https://docs.streamlit.io/develop/api-reference/status/st.warning#stwarning,"DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceremovePAGE ELEMENTSWrite and magicaddText elementsaddData elementsaddChart elementsaddInput widgetsaddMedia elementsaddLayouts and containersaddChat elementsaddStatus elementsremoveCALLOUTSst.successst.infost.warningst.errorst.exceptionOTHERst.progressst.spinnerst.statusst.toastst.balloonsst.snowThird-party componentsopen_in_newAPPLICATION LOGICNavigation and pagesaddExecution flowaddCaching and stateaddConnections and secretsaddCustom componentsaddUtilitiesaddConfigurationaddTOOLSApp testingaddCommand lineaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Develop/API reference/Status elements/st.warningst.warningStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeDisplay warning message. Function signature[source] st.warning(body, *, icon=None) Parameters body (str) The warning text to display. icon (str, None) An optional emoji or icon to display next to the alert. If icon is None (default), no icon is displayed. If icon is a string, the following options are valid: A single-character emoji. For example, you can set icon=""🚨"" or icon=""🔥"". Emoji short codes are not supported. An icon from the Material Symbols library (outlined style) in the format "":material/icon_name:"" where ""icon_name"" is the name of the icon in snake case. For example, icon="":material/thumb_up:"" will display the Thumb Up icon. Find additional icons in the Material Symbols font library. Example import streamlit as st st.warning('This is a warning', icon=""⚠️"") Previous: st.infoNext: st.errorforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy" https://docs.streamlit.io/get-started/installation/command-line#create-an-environment-using-venv,"DocumentationsearchSearchrocket_launchGet startedInstallationremoveUse command lineUse Anaconda DistributionUse GitHub CodespacesUse SnowflakeFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Get started/Installation/Use command lineInstall Streamlit using command line This page will walk you through creating an environment with venv and installing Streamlit with pip. These are our recommended tools, but if you are familiar with others you can use your favorite ones too. At the end, you'll build a simple ""Hello world"" app and run it. If you prefer to have a graphical interface to manage your Python environments, check out how to Install Streamlit using Anaconda Distribution. Prerequisites As with any programming tool, in order to install Streamlit you first need to make sure your computer is properly set up. More specifically, you’ll need: Python We support version 3.8 to 3.12. A Python environment manager (recommended) Environment managers create virtual environments to isolate Python package installations between projects. We recommend using virtual environments because installing or upgrading a Python package may cause unintentional effects on another package. For a detailed introduction to Python environments, check out Python Virtual Environments: A Primer. For this guide, we'll be using venv, which comes with Python. A Python package manager Package managers handle installing each of your Python packages, including Streamlit. For this guide, we'll be using pip, which comes with Python. Only on MacOS: Xcode command line tools Download Xcode command line tools using these instructions in order to let the package manager install some of Streamlit's dependencies. A code editor Our favorite editor is VS Code, which is also what we use in all our tutorials. Create an environment using venv Open a terminal and navigate to your project folder. cd myproject In your terminal, type: python -m venv .venv A folder named "".venv"" will appear in your project. This directory is where your virtual environment and its dependencies are installed. Activate your environment In your terminal, activate your environment with one of the following commands, depending on your operating system. # Windows command prompt .venv\Scripts\activate.bat # Windows PowerShell .venv\Scripts\Activate.ps1 # macOS and Linux source .venv/bin/activate Once activated, you will see your environment name in parentheses before your prompt. ""(.venv)"" Install Streamlit in your environment In the terminal with your environment activated, type: pip install streamlit Test that the installation worked by launching the Streamlit Hello example app: streamlit hello If this doesn't work, use the long-form command: python -m streamlit hello Streamlit's Hello app should appear in a new tab in your web browser! Built with Streamlit 🎈Fullscreen open_in_new Close your terminal when you are done. Create a ""Hello World"" app and run it Create a file named app.py in your project folder. import streamlit as st st.write(""Hello world"") Any time you want to use your new environment, you first need to go to your project folder (where the .venv directory lives) and run the command to activate it: # Windows command prompt .venv\Scripts\activate.bat # Windows PowerShell .venv\Scripts\Activate.ps1 # macOS and Linux source .venv/bin/activate Once activated, you will see your environment's name in parentheses at the beginning of your terminal prompt. ""(.venv)"" Run your Streamlit app. streamlit run app.py If this doesn't work, use the long-form command: python -m streamlit run app.py To stop the Streamlit server, press Ctrl+C in the terminal. When you're done using this environment, return to your normal shell by typing: deactivate What's next? Read about our Basic concepts to understand Streamlit's dataflow model.Previous: InstallationNext: Use Anaconda DistributionforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy" https://docs.streamlit.io/get-started/fundamentals/main-concepts#write-a-data-frame,"DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsremoveBasic conceptsAdvanced conceptsAdditional featuresSummaryFirst stepsaddcodeDevelopConceptsaddAPI referenceaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Get started/Fundamentals/Basic conceptsBasic concepts of Streamlit Working with Streamlit is simple. First you sprinkle a few Streamlit commands into a normal Python script, then you run it with streamlit run: streamlit run your_script.py [-- script args] As soon as you run the script as shown above, a local Streamlit server will spin up and your app will open in a new tab in your default web browser. The app is your canvas, where you'll draw charts, text, widgets, tables, and more. What gets drawn in the app is up to you. For example st.text writes raw text to your app, and st.line_chart draws — you guessed it — a line chart. Refer to our API documentation to see all commands that are available to you. push_pinNoteWhen passing your script some custom arguments, they must be passed after two dashes. Otherwise the arguments get interpreted as arguments to Streamlit itself. Another way of running Streamlit is to run it as a Python module. This can be useful when configuring an IDE like PyCharm to work with Streamlit: # Running python -m streamlit run your_script.py # is equivalent to: streamlit run your_script.py starTipYou can also pass a URL to streamlit run! This is great when combined with GitHub Gists. For example:streamlit run https://raw.githubusercontent.com/streamlit/demo-uber-nyc-pickups/master/streamlit_app.py Development flow Every time you want to update your app, save the source file. When you do that, Streamlit detects if there is a change and asks you whether you want to rerun your app. Choose ""Always rerun"" at the top-right of your screen to automatically update your app every time you change its source code. This allows you to work in a fast interactive loop: you type some code, save it, try it out live, then type some more code, save it, try it out, and so on until you're happy with the results. This tight loop between coding and viewing results live is one of the ways Streamlit makes your life easier. starTipWhile developing a Streamlit app, it's recommended to lay out your editor and browser windows side by side, so the code and the app can be seen at the same time. Give it a try! As of Streamlit version 1.10.0 and higher, Streamlit apps cannot be run from the root directory of Linux distributions. If you try to run a Streamlit app from the root directory, Streamlit will throw a FileNotFoundError: [Errno 2] No such file or directory error. For more information, see GitHub issue #5239. If you are using Streamlit version 1.10.0 or higher, your main script should live in a directory other than the root directory. When using Docker, you can use the WORKDIR command to specify the directory where your main script lives. For an example of how to do this, read Create a Dockerfile. Data flow Streamlit's architecture allows you to write apps the same way you write plain Python scripts. To unlock this, Streamlit apps have a unique data flow: any time something must be updated on the screen, Streamlit reruns your entire Python script from top to bottom. This can happen in two situations: Whenever you modify your app's source code. Whenever a user interacts with widgets in the app. For example, when dragging a slider, entering text in an input box, or clicking a button. Whenever a callback is passed to a widget via the on_change (or on_click) parameter, the callback will always run before the rest of your script. For details on the Callbacks API, please refer to our Session State API Reference Guide. And to make all of this fast and seamless, Streamlit does some heavy lifting for you behind the scenes. A big player in this story is the @st.cache_data decorator, which allows developers to skip certain costly computations when their apps rerun. We'll cover caching later in this page. Display and style data There are a few ways to display data (tables, arrays, data frames) in Streamlit apps. Below, you will be introduced to magic and st.write(), which can be used to write anything from text to tables. After that, let's take a look at methods designed specifically for visualizing data. Use magic You can also write to your app without calling any Streamlit methods. Streamlit supports ""magic commands,"" which means you don't have to use st.write() at all! To see this in action try this snippet: """""" # My first app Here's our first attempt at using data to create a table: """""" import streamlit as st import pandas as pd df = pd.DataFrame({ 'first column': [1, 2, 3, 4], 'second column': [10, 20, 30, 40] }) df Any time that Streamlit sees a variable or a literal value on its own line, it automatically writes that to your app using st.write(). For more information, refer to the documentation on magic commands. Write a data frame Along with magic commands, st.write() is Streamlit's ""Swiss Army knife"". You can pass almost anything to st.write(): text, data, Matplotlib figures, Altair charts, and more. Don't worry, Streamlit will figure it out and render things the right way. import streamlit as st import pandas as pd st.write(""Here's our first attempt at using data to create a table:"") st.write(pd.DataFrame({ 'first column': [1, 2, 3, 4], 'second column': [10, 20, 30, 40] })) There are other data specific functions like st.dataframe() and st.table() that you can also use for displaying data. Let's understand when to use these features and how to add colors and styling to your data frames. You might be asking yourself, ""why wouldn't I always use st.write()?"" There are a few reasons: Magic and st.write() inspect the type of data that you've passed in, and then decide how to best render it in the app. Sometimes you want to draw it another way. For example, instead of drawing a dataframe as an interactive table, you may want to draw it as a static table by using st.table(df). The second reason is that other methods return an object that can be used and modified, either by adding data to it or replacing it. Finally, if you use a more specific Streamlit method you can pass additional arguments to customize its behavior. For example, let's create a data frame and change its formatting with a Pandas Styler object. In this example, you'll use Numpy to generate a random sample, and the st.dataframe() method to draw an interactive table. push_pinNoteThis example uses Numpy to generate a random sample, but you can use Pandas DataFrames, Numpy arrays, or plain Python arrays. import streamlit as st import numpy as np dataframe = np.random.randn(10, 20) st.dataframe(dataframe) Let's expand on the first example using the Pandas Styler object to highlight some elements in the interactive table. import streamlit as st import numpy as np import pandas as pd dataframe = pd.DataFrame( np.random.randn(10, 20), columns=('col %d' % i for i in range(20))) st.dataframe(dataframe.style.highlight_max(axis=0)) Streamlit also has a method for static table generation: st.table(). import streamlit as st import numpy as np import pandas as pd dataframe = pd.DataFrame( np.random.randn(10, 20), columns=('col %d' % i for i in range(20))) st.table(dataframe) Draw charts and maps Streamlit supports several popular data charting libraries like Matplotlib, Altair, deck.gl, and more. In this section, you'll add a bar chart, line chart, and a map to your app. Draw a line chart You can easily add a line chart to your app with st.line_chart(). We'll generate a random sample using Numpy and then chart it. import streamlit as st import numpy as np import pandas as pd chart_data = pd.DataFrame( np.random.randn(20, 3), columns=['a', 'b', 'c']) st.line_chart(chart_data) Plot a map With st.map() you can display data points on a map. Let's use Numpy to generate some sample data and plot it on a map of San Francisco. import streamlit as st import numpy as np import pandas as pd map_data = pd.DataFrame( np.random.randn(1000, 2) / [50, 50] + [37.76, -122.4], columns=['lat', 'lon']) st.map(map_data) Widgets When you've got the data or model into the state that you want to explore, you can add in widgets like st.slider(), st.button() or st.selectbox(). It's really straightforward — treat widgets as variables: import streamlit as st x = st.slider('x') # 👈 this is a widget st.write(x, 'squared is', x * x) On first run, the app above should output the text ""0 squared is 0"". Then every time a user interacts with a widget, Streamlit simply reruns your script from top to bottom, assigning the current state of the widget to your variable in the process. For example, if the user moves the slider to position 10, Streamlit will rerun the code above and set x to 10 accordingly. So now you should see the text ""10 squared is 100"". Widgets can also be accessed by key, if you choose to specify a string to use as the unique key for the widget: import streamlit as st st.text_input(""Your name"", key=""name"") # You can access the value at any point with: st.session_state.name Every widget with a key is automatically added to Session State. For more information about Session State, its association with widget state, and its limitations, see Session State API Reference Guide. Use checkboxes to show/hide data One use case for checkboxes is to hide or show a specific chart or section in an app. st.checkbox() takes a single argument, which is the widget label. In this sample, the checkbox is used to toggle a conditional statement. import streamlit as st import numpy as np import pandas as pd if st.checkbox('Show dataframe'): chart_data = pd.DataFrame( np.random.randn(20, 3), columns=['a', 'b', 'c']) chart_data Use a selectbox for options Use st.selectbox to choose from a series. You can write in the options you want, or pass through an array or data frame column. Let's use the df data frame we created earlier. import streamlit as st import pandas as pd df = pd.DataFrame({ 'first column': [1, 2, 3, 4], 'second column': [10, 20, 30, 40] }) option = st.selectbox( 'Which number do you like best?', df['first column']) 'You selected: ', option Layout Streamlit makes it easy to organize your widgets in a left panel sidebar with st.sidebar. Each element that's passed to st.sidebar is pinned to the left, allowing users to focus on the content in your app while still having access to UI controls. For example, if you want to add a selectbox and a slider to a sidebar, use st.sidebar.slider and st.sidebar.selectbox instead of st.slider and st.selectbox: import streamlit as st # Add a selectbox to the sidebar: add_selectbox = st.sidebar.selectbox( 'How would you like to be contacted?', ('Email', 'Home phone', 'Mobile phone') ) # Add a slider to the sidebar: add_slider = st.sidebar.slider( 'Select a range of values', 0.0, 100.0, (25.0, 75.0) ) Beyond the sidebar, Streamlit offers several other ways to control the layout of your app. st.columns lets you place widgets side-by-side, and st.expander lets you conserve space by hiding away large content. import streamlit as st left_column, right_column = st.columns(2) # You can use a column just like st.sidebar: left_column.button('Press me!') # Or even better, call Streamlit functions inside a ""with"" block: with right_column: chosen = st.radio( 'Sorting hat', (""Gryffindor"", ""Ravenclaw"", ""Hufflepuff"", ""Slytherin"")) st.write(f""You are in {chosen} house!"") push_pinNotest.echo and st.spinner are not currently supported inside the sidebar or layout options. Rest assured, though, we're currently working on adding support for those too! Show progress When adding long running computations to an app, you can use st.progress() to display status in real time. First, let's import time. We're going to use the time.sleep() method to simulate a long running computation: import time Now, let's create a progress bar: import streamlit as st import time 'Starting a long computation...' # Add a placeholder latest_iteration = st.empty() bar = st.progress(0) for i in range(100): # Update the progress bar with each iteration. latest_iteration.text(f'Iteration {i+1}') bar.progress(i + 1) time.sleep(0.1) '...and now we\'re done!' Previous: FundamentalsNext: Advanced conceptsforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy" https://docs.streamlit.io/develop/tutorials/databases/supabase#sign-in-to-supabase-and-create-a-project,"DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceaddTutorialsremoveExecution flowaddConnect to data sourcesremoveAWS S3BigQueryDeta BaseFirestoreopen_in_newGoogle Cloud StorageMicrosoft SQL ServerMongoDBMySQLNeonPostgreSQLPrivate Google SheetPublic Google SheetSnowflakeSupabaseTableauTiDBTigerGraphMultipage appsaddWork with LLMsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Develop/Tutorials/Connect to data sources/SupabaseConnect Streamlit to Supabase Introduction This guide explains how to securely access a Supabase instance from Streamlit Community Cloud. It uses st.connection, Streamlit Supabase Connector (a community-built connection developed by @SiddhantSadangi) and Streamlit's Secrets management. Supabase is the open source Firebase alternative and is based on PostgreSQL. push_pinNoteCommunity-built connections, such as the Streamlit Supabase Connector, extend and build on the st.connection interface and make it easier than ever to build Streamlit apps with a wide variety of data sources. These type of connections work exactly the same as the ones built into Streamlit and have access to all the same capabilities. Sign in to Supabase and create a project First, head over to Supabase and sign up for a free account using your GitHub. Sign in with GitHubAuthorize Supabase Once you're signed in, you can create a project. Your Supabase accountCreate a new project Your screen should look like this once your project has been created: priority_highImportantMake sure to note down your Project API Key and Project URL highlighted in the above screenshot. ☝️You will need these to connect to your Supabase instance from Streamlit. Create a Supabase database Now that you have a project, you can create a database and populate it with some sample data. To do so, click on the SQL editor button on the same project page, followed by the New query button in the SQL editor. Open the SQL editorCreate a new query In the SQL editor, enter the following queries to create a database and a table with some example values: CREATE TABLE mytable ( name varchar(80), pet varchar(80) ); INSERT INTO mytable VALUES ('Mary', 'dog'), ('John', 'cat'), ('Robert', 'bird'); Click Run to execute the queries. To verify that the queries were executed successfully, click on the Table Editor button on the left menu, followed by your newly created table mytable. Write and run your queriesView your table in the Table Editor With your Supabase database created, you can now connect to it from Streamlit! Add Supabase Project URL and API key to your local app secrets Your local Streamlit app will read secrets from a file .streamlit/secrets.toml in your app's root directory. Create this file if it doesn't exist yet and add the SUPABASE_URL and SUPABASE_KEY here: # .streamlit/secrets.toml [connections.supabase] SUPABASE_URL = ""xxxx"" SUPABASE_KEY = ""xxxx"" Replace xxxx above with your Project URL and API key from Step 1. priority_highImportantAdd this file to .gitignore and don't commit it to your GitHub repo! Copy your app secrets to the cloud As the secrets.toml file above is not committed to GitHub, you need to pass its content to your deployed app (on Streamlit Community Cloud) separately. Go to the app dashboard and in the app's dropdown menu, click on Edit Secrets. Copy the content of secrets.toml into the text area. More information is available at Secrets management. Add st-supabase-connection to your requirements file Add the st-supabase-connection community-built connection library to your requirements.txt file, preferably pinning its version (replace x.x.x with the version you want installed): # requirements.txt st-supabase-connection==x.x.x starTipWe've used the st-supabase-connection library here in combination with st.connection to benefit from the ease of setting up the data connection, managing your credentials, and Streamlit's caching capabilities that native and community-built connections provide.You can however still directly use the Supabase Python Client Library library if you prefer, but you'll need to write more code to set up the connection and cache the results. See Using the Supabase Python Client Library below for an example. Write your Streamlit app Copy the code below to your Streamlit app and run it. # streamlit_app.py import streamlit as st from st_supabase_connection import SupabaseConnection # Initialize connection. conn = st.connection(""supabase"",type=SupabaseConnection) # Perform query. rows = conn.query(""*"", table=""mytable"", ttl=""10m"").execute() # Print results. for row in rows.data: st.write(f""{row['name']} has a :{row['pet']}:"") See st.connection above? This handles secrets retrieval, setup, query caching and retries. By default, query() results are cached without expiring. In this case, we set ttl=""10m"" to ensure the query result is cached for no longer than 10 minutes. You can also set ttl=0 to disable caching. Learn more in Caching. If everything worked out (and you used the example table we created above), your app should look like this: As Supabase uses PostgresSQL under the hood, you can also connect to Supabase by using the connection string Supabase provides under Settings > Databases. From there, you can refer to the PostgresSQL tutorial to connect to your database. Using the Supabase Python Client Library If you prefer to use the Supabase Python Client Library directly, you can do so by following the steps below. Add your Supabase Project URL and API key to your local app secrets: Your local Streamlit app will read secrets from a file .streamlit/secrets.toml in your app's root directory. Create this file if it doesn't exist yet and add the SUPABASE_URL and SUPABASE_KEY here: # .streamlit/secrets.toml SUPABASE_URL = ""xxxx"" SUPABASE_KEY = ""xxxx"" Add supabase to your requirements file: Add the supabase Python Client Library to your requirements.txt file, preferably pinning its version (replace x.x.x with the version you want installed): # requirements.txt supabase==x.x.x Write your Streamlit app: Copy the code below to your Streamlit app and run it. # streamlit_app.py import streamlit as st from supabase import create_client, Client # Initialize connection. # Uses st.cache_resource to only run once. @st.cache_resource def init_connection(): url = st.secrets[""SUPABASE_URL""] key = st.secrets[""SUPABASE_KEY""] return create_client(url, key) supabase = init_connection() # Perform query. # Uses st.cache_data to only rerun when the query changes or after 10 min. @st.cache_data(ttl=600) def run_query(): return supabase.table(""mytable"").select(""*"").execute() rows = run_query() # Print results. for row in rows.data: st.write(f""{row['name']} has a :{row['pet']}:"") See st.cache_data above? Without it, Streamlit would run the query every time the app reruns (e.g. on a widget interaction). With st.cache_data, it only runs when the query changes or after 10 minutes (that's what ttl is for). Watch out: If your database updates more frequently, you should adapt ttl or remove caching so viewers always see the latest data. Learn more in Caching. Previous: SnowflakeNext: TableauforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy" https://docs.streamlit.io/en/0.65.0/api.html#built-in-connections,"DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceremovePAGE ELEMENTSWrite and magicaddText elementsaddData elementsaddChart elementsaddInput widgetsaddMedia elementsaddLayouts and containersaddChat elementsaddStatus elementsaddThird-party componentsopen_in_newAPPLICATION LOGICNavigation and pagesaddExecution flowaddCaching and stateaddConnections and secretsaddCustom componentsaddUtilitiesaddConfigurationaddTOOLSApp testingaddCommand lineaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Develop/API referenceAPI reference Streamlit makes it easy for you to visualize, mutate, and share data. The API reference is organized by activity type, like displaying data or optimizing performance. Each section includes methods associated with the activity type, including examples. Browse our API below and click to learn more about any of our available commands! 🎈 Display almost anything Write and magic st.writeWrite arguments to the app.st.write(""Hello **world**!"") st.write(my_data_frame) st.write(my_mpl_figure) st.write_streamWrite generators or streams to the app with a typewriter effect.st.write_stream(my_generator) st.write_stream(my_llm_stream) MagicAny time Streamlit sees either a variable or literal value on its own line, it automatically writes that to your app using st.write""Hello **world**!"" my_data_frame my_mpl_figure Text elements MarkdownDisplay string formatted as Markdown.st.markdown(""Hello **world**!"") TitleDisplay text in title formatting.st.title(""The app title"") HeaderDisplay text in header formatting.st.header(""This is a header"") SubheaderDisplay text in subheader formatting.st.subheader(""This is a subheader"") CaptionDisplay text in small font.st.caption(""This is written small caption text"") Code blockDisplay a code block with optional syntax highlighting.st.code(""a = 1234"") EchoDisplay some code in the app, then execute it. Useful for tutorials.with st.echo(): st.write('This code will be printed') LaTeXDisplay mathematical expressions formatted as LaTeX.st.latex(""\int a x^2 \,dx"") Preformatted textWrite fixed-width and preformatted text.st.text(""Hello world"") DividerDisplay a horizontal rule.st.divider() Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration! PreviousTagsAdd tags to your Streamlit apps. Created by @gagan3012.st_tags(label='# Enter Keywords:', text='Press enter to add more', value=['Zero', 'One', 'Two'], suggestions=['five', 'six', 'seven', 'eight', 'nine', 'three', 'eleven', 'ten', 'four'], maxtags = 4, key='1') NLUApply text mining on a dataframe. Created by @JohnSnowLabs.nlu.load('sentiment').predict('I love NLU! <3') Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.mention(label=""An awesome Streamlit App"", icon=""streamlit"", url=""https://extras.streamlit.app"",) Annotated textDisplay annotated text in Streamlit apps. Created by @tvst.annotated_text(""This "", (""is"", ""verb""), "" some "", (""annotated"", ""adj""), (""text"", ""noun""), "" for those of "", (""you"", ""pronoun""), "" who "", (""like"", ""verb""), "" this sort of "", (""thing"", ""noun""), ""."") Drawable CanvasProvides a sketching canvas using Fabric.js. Created by @andfanilo.st_canvas(fill_color=""rgba(255, 165, 0, 0.3)"", stroke_width=stroke_width, stroke_color=stroke_color, background_color=bg_color, background_image=Image.open(bg_image) if bg_image else None, update_streamlit=realtime_update, height=150, drawing_mode=drawing_mode, point_display_radius=point_display_radius if drawing_mode == 'point' else 0, key=""canvas"",) TagsAdd tags to your Streamlit apps. Created by @gagan3012.st_tags(label='# Enter Keywords:', text='Press enter to add more', value=['Zero', 'One', 'Two'], suggestions=['five', 'six', 'seven', 'eight', 'nine', 'three', 'eleven', 'ten', 'four'], maxtags = 4, key='1') NLUApply text mining on a dataframe. Created by @JohnSnowLabs.nlu.load('sentiment').predict('I love NLU! <3') Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.mention(label=""An awesome Streamlit App"", icon=""streamlit"", url=""https://extras.streamlit.app"",) Annotated textDisplay annotated text in Streamlit apps. Created by @tvst.annotated_text(""This "", (""is"", ""verb""), "" some "", (""annotated"", ""adj""), (""text"", ""noun""), "" for those of "", (""you"", ""pronoun""), "" who "", (""like"", ""verb""), "" this sort of "", (""thing"", ""noun""), ""."") Drawable CanvasProvides a sketching canvas using Fabric.js. Created by @andfanilo.st_canvas(fill_color=""rgba(255, 165, 0, 0.3)"", stroke_width=stroke_width, stroke_color=stroke_color, background_color=bg_color, background_image=Image.open(bg_image) if bg_image else None, update_streamlit=realtime_update, height=150, drawing_mode=drawing_mode, point_display_radius=point_display_radius if drawing_mode == 'point' else 0, key=""canvas"",) TagsAdd tags to your Streamlit apps. Created by @gagan3012.st_tags(label='# Enter Keywords:', text='Press enter to add more', value=['Zero', 'One', 'Two'], suggestions=['five', 'six', 'seven', 'eight', 'nine', 'three', 'eleven', 'ten', 'four'], maxtags = 4, key='1') NLUApply text mining on a dataframe. Created by @JohnSnowLabs.nlu.load('sentiment').predict('I love NLU! <3') Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.mention(label=""An awesome Streamlit App"", icon=""streamlit"", url=""https://extras.streamlit.app"",) Next Data elements DataframesDisplay a dataframe as an interactive table.st.dataframe(my_data_frame) Data editorDisplay a data editor widget.edited = st.data_editor(df, num_rows=""dynamic"") Column configurationConfigure the display and editing behavior of dataframes and data editors.st.column_config.NumberColumn(""Price (in USD)"", min_value=0, format=""$%d"") Static tablesDisplay a static table.st.table(my_data_frame) MetricsDisplay a metric in big bold font, with an optional indicator of how the metric changed.st.metric(""My metric"", 42, 2) Dicts and JSONDisplay object or string as a pretty-printed JSON string.st.json(my_dict) Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration! PreviousImage CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates value = streamlit_image_coordinates(""https://placekitten.com/200/300"") st.write(value) Plotly EventsMake Plotly charts interactive!. Created by @null-jones.from streamlit_plotly_events import plotly_events fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.metric_cards import style_metric_cards col3.metric(label=""No Change"", value=5000, delta=0) style_metric_cards() Streamlit AggridImplementation of Ag-Grid component for Streamlit. Created by @PablocFonseca.df = pd.DataFrame({'col1': [1, 2, 3], 'col2': [4, 5, 6]}) grid_return = AgGrid(df, editable=True) new_df = grid_return['data'] Streamlit FoliumStreamlit Component for rendering Folium maps. Created by @randyzwitch.m = folium.Map(location=[39.949610, -75.150282], zoom_start=16) folium.Marker([39.949610, -75.150282], popup=""Liberty Bell"", tooltip=""Liberty Bell"").add_to(m) st_data = st_folium(m, width=725) Pandas ProfilingPandas profiling component for Streamlit. Created by @okld.df = pd.read_csv(""https://storage.googleapis.com/tf-datasets/titanic/train.csv"") pr = df.profile_report() st_profile_report(pr) Image CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates value = streamlit_image_coordinates(""https://placekitten.com/200/300"") st.write(value) Plotly EventsMake Plotly charts interactive!. Created by @null-jones.from streamlit_plotly_events import plotly_events fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.metric_cards import style_metric_cards col3.metric(label=""No Change"", value=5000, delta=0) style_metric_cards() Streamlit AggridImplementation of Ag-Grid component for Streamlit. Created by @PablocFonseca.df = pd.DataFrame({'col1': [1, 2, 3], 'col2': [4, 5, 6]}) grid_return = AgGrid(df, editable=True) new_df = grid_return['data'] Streamlit FoliumStreamlit Component for rendering Folium maps. Created by @randyzwitch.m = folium.Map(location=[39.949610, -75.150282], zoom_start=16) folium.Marker([39.949610, -75.150282], popup=""Liberty Bell"", tooltip=""Liberty Bell"").add_to(m) st_data = st_folium(m, width=725) Pandas ProfilingPandas profiling component for Streamlit. Created by @okld.df = pd.read_csv(""https://storage.googleapis.com/tf-datasets/titanic/train.csv"") pr = df.profile_report() st_profile_report(pr) Image CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates value = streamlit_image_coordinates(""https://placekitten.com/200/300"") st.write(value) Plotly EventsMake Plotly charts interactive!. Created by @null-jones.from streamlit_plotly_events import plotly_events fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.metric_cards import style_metric_cards col3.metric(label=""No Change"", value=5000, delta=0) style_metric_cards() Next Chart elements Simple area chartsDisplay an area chart.st.area_chart(my_data_frame) Simple bar chartsDisplay a bar chart.st.bar_chart(my_data_frame) Simple line chartsDisplay a line chart.st.line_chart(my_data_frame) Simple scatter chartsDisplay a line chart.st.scatter_chart(my_data_frame) Scatterplots on mapsDisplay a map with points on it.st.map(my_data_frame) MatplotlibDisplay a matplotlib.pyplot figure.st.pyplot(my_mpl_figure) AltairDisplay a chart using the Altair library.st.altair_chart(my_altair_chart) Vega-LiteDisplay a chart using the Vega-Lite library.st.vega_lite_chart(my_vega_lite_chart) PlotlyDisplay an interactive Plotly chart.st.plotly_chart(my_plotly_chart) BokehDisplay an interactive Bokeh chart.st.bokeh_chart(my_bokeh_chart) PyDeckDisplay a chart using the PyDeck library.st.pydeck_chart(my_pydeck_chart) GraphVizDisplay a graph using the dagre-d3 library.st.graphviz_chart(my_graphviz_spec) Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration! PreviousStreamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl(""https://assets5.lottiefiles.com/packages/lf20_V9t630.json"") st_lottie(lottie_hello, key=""hello"") Plotly EventsMake Plotly charts interactive!. Created by @null-jones.fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.chart += get_annotations_chart(annotations=[(""Mar 01, 2008"", ""Pretty good day for GOOG""), (""Dec 01, 2007"", ""Something's going wrong for GOOG & AAPL""), (""Nov 01, 2008"", ""Market starts again thanks to...""), (""Dec 01, 2009"", ""Small crash for GOOG after...""),],) st.altair_chart(chart, use_container_width=True) PlostA deceptively simple plotting library for Streamlit. Created by @tvst.import plost plost.line_chart(my_dataframe, x='time', y='stock_value', color='stock_name',) HiPlotHigh dimensional Interactive Plotting. Created by @facebookresearch.data = [{'dropout':0.1, 'lr': 0.001, 'loss': 10.0, 'optimizer': 'SGD'}, {'dropout':0.15, 'lr': 0.01, 'loss': 3.5, 'optimizer': 'Adam'}, {'dropout':0.3, 'lr': 0.1, 'loss': 4.5, 'optimizer': 'Adam'}] hip.Experiment.from_iterable(data).display() EChartsHigh dimensional Interactive Plotting. Created by @andfanilo.from streamlit_echarts import st_echarts st_echarts(options=options) Streamlit FoliumStreamlit Component for rendering Folium maps. Created by @randyzwitch.m = folium.Map(location=[39.949610, -75.150282], zoom_start=16) st_data = st_folium(m, width=725) Spacy-StreamlitspaCy building blocks and visualizers for Streamlit apps. Created by @explosion.models = [""en_core_web_sm"", ""en_core_web_md""] spacy_streamlit.visualize(models, ""Sundar Pichai is the CEO of Google."") Streamlit AgraphA Streamlit Graph Vis, based on react-grah-vis. Created by @ChrisDelClea.from streamlit_agraph import agraph, Node, Edge, Config agraph(nodes=nodes, edges=edges, config=config) Streamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl(""https://assets5.lottiefiles.com/packages/lf20_V9t630.json"") st_lottie(lottie_hello, key=""hello"") Plotly EventsMake Plotly charts interactive!. Created by @null-jones.fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.chart += get_annotations_chart(annotations=[(""Mar 01, 2008"", ""Pretty good day for GOOG""), (""Dec 01, 2007"", ""Something's going wrong for GOOG & AAPL""), (""Nov 01, 2008"", ""Market starts again thanks to...""), (""Dec 01, 2009"", ""Small crash for GOOG after...""),],) st.altair_chart(chart, use_container_width=True) PlostA deceptively simple plotting library for Streamlit. Created by @tvst.import plost plost.line_chart(my_dataframe, x='time', y='stock_value', color='stock_name',) HiPlotHigh dimensional Interactive Plotting. Created by @facebookresearch.data = [{'dropout':0.1, 'lr': 0.001, 'loss': 10.0, 'optimizer': 'SGD'}, {'dropout':0.15, 'lr': 0.01, 'loss': 3.5, 'optimizer': 'Adam'}, {'dropout':0.3, 'lr': 0.1, 'loss': 4.5, 'optimizer': 'Adam'}] hip.Experiment.from_iterable(data).display() EChartsHigh dimensional Interactive Plotting. Created by @andfanilo.from streamlit_echarts import st_echarts st_echarts(options=options) Streamlit FoliumStreamlit Component for rendering Folium maps. Created by @randyzwitch.m = folium.Map(location=[39.949610, -75.150282], zoom_start=16) st_data = st_folium(m, width=725) Spacy-StreamlitspaCy building blocks and visualizers for Streamlit apps. Created by @explosion.models = [""en_core_web_sm"", ""en_core_web_md""] spacy_streamlit.visualize(models, ""Sundar Pichai is the CEO of Google."") Streamlit AgraphA Streamlit Graph Vis, based on react-grah-vis. Created by @ChrisDelClea.from streamlit_agraph import agraph, Node, Edge, Config agraph(nodes=nodes, edges=edges, config=config) Streamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl(""https://assets5.lottiefiles.com/packages/lf20_V9t630.json"") st_lottie(lottie_hello, key=""hello"") Plotly EventsMake Plotly charts interactive!. Created by @null-jones.fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.chart += get_annotations_chart(annotations=[(""Mar 01, 2008"", ""Pretty good day for GOOG""), (""Dec 01, 2007"", ""Something's going wrong for GOOG & AAPL""), (""Nov 01, 2008"", ""Market starts again thanks to...""), (""Dec 01, 2009"", ""Small crash for GOOG after...""),],) st.altair_chart(chart, use_container_width=True) Next Input widgets ButtonDisplay a button widget.clicked = st.button(""Click me"") Download buttonDisplay a download button widget.st.download_button(""Download file"", file) Form buttonDisplay a form submit button. For use with st.form.st.form_submit_button(""Sign up"") Link buttonDisplay a link button.st.link_button(""Go to gallery"", url) Page linkDisplay a link to another page in a multipage app.st.page_link(""app.py"", label=""Home"", icon=""🏠"") st.page_link(""pages/profile.py"", label=""My profile"") CheckboxDisplay a checkbox widget.selected = st.checkbox(""I agree"") Color pickerDisplay a color picker widget.color = st.color_picker(""Pick a color"") MultiselectDisplay a multiselect widget. The multiselect widget starts as empty.choices = st.multiselect(""Buy"", [""milk"", ""apples"", ""potatoes""]) RadioDisplay a radio button widget.choice = st.radio(""Pick one"", [""cats"", ""dogs""]) SelectboxDisplay a select widget.choice = st.selectbox(""Pick one"", [""cats"", ""dogs""]) Select-sliderDisplay a slider widget to select items from a list.size = st.select_slider(""Pick a size"", [""S"", ""M"", ""L""]) ToggleDisplay a toggle widget.activated = st.toggle(""Activate"") Number inputDisplay a numeric input widget.choice = st.number_input(""Pick a number"", 0, 10) SliderDisplay a slider widget.number = st.slider(""Pick a number"", 0, 100) Date inputDisplay a date input widget.date = st.date_input(""Your birthday"") Time inputDisplay a time input widget.time = st.time_input(""Meeting time"") Chat inputDisplay a chat input widget.prompt = st.chat_input(""Say something"") if prompt: st.write(f""The user has sent: {prompt}"") Text-areaDisplay a multi-line text input widget.text = st.text_area(""Text to translate"") Text inputDisplay a single-line text input widget.name = st.text_input(""First name"") Data editorDisplay a data editor widget.edited = st.experimental_data_editor(df, num_rows=""dynamic"") File UploaderDisplay a file uploader widget.data = st.file_uploader(""Upload a CSV"") Camera inputDisplay a widget that allows users to upload images directly from a camera.image = st.camera_input(""Take a picture"") Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration! PreviousStreamlit ChatStreamlit Component for a Chatbot UI. Created by @AI-Yash.from streamlit_chat import message message(""My message"") message(""Hello bot!"", is_user=True) # align's the message to the right Streamlit Option MenuSelect a single item from a list of options in a menu. Created by @victoryhb.from streamlit_option_menu import option_menu option_menu(""Main Menu"", [""Home"", 'Settings'], icons=['house', 'gear'], menu_icon=""cast"", default_index=1) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.stoggle import stoggle stoggle( ""Click me!"", """"""🥷 Surprise! Here's some additional content"""""",) Streamlit ElementsCreate a draggable and resizable dashboard in Streamlit. Created by @okls.from streamlit_elements import elements, mui, html with elements(""new_element""): mui.Typography(""Hello world"") TagsAdd tags to your Streamlit apps. Created by @gagan3012.from streamlit_tags import st_tags st_tags(label='# Enter Keywords:', text='Press enter to add more', value=['Zero', 'One', 'Two'], suggestions=['five', 'six', 'seven', 'eight', 'nine', 'three', 'eleven', 'ten', 'four'], maxtags = 4, key='1') StqdmThe simplest way to handle a progress bar in streamlit app. Created by @Wirg.from stqdm import stqdm for _ in stqdm(range(50)): sleep(0.5) TimelineDisplay a Timeline in Streamlit apps using TimelineJS. Created by @innerdoc.from streamlit_timeline import timeline with open('example.json', ""r"") as f: timeline(f.read(), height=800) Camera input liveAlternative for st.camera_input which returns the webcam images live. Created by @blackary.from camera_input_live import camera_input_live image = camera_input_live() st.image(value) Streamlit AceAce editor component for Streamlit. Created by @okld.from streamlit_ace import st_ace content = st_ace() content Streamlit ChatStreamlit Component for a Chatbot UI. Created by @AI-Yash.from streamlit_chat import message message(""My message"") message(""Hello bot!"", is_user=True) # align's the message to the right Streamlit Option MenuSelect a single item from a list of options in a menu. Created by @victoryhb.from streamlit_option_menu import option_menu option_menu(""Main Menu"", [""Home"", 'Settings'], icons=['house', 'gear'], menu_icon=""cast"", default_index=1) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.stoggle import stoggle stoggle( ""Click me!"", """"""🥷 Surprise! Here's some additional content"""""",) Streamlit ElementsCreate a draggable and resizable dashboard in Streamlit. Created by @okls.from streamlit_elements import elements, mui, html with elements(""new_element""): mui.Typography(""Hello world"") TagsAdd tags to your Streamlit apps. Created by @gagan3012.from streamlit_tags import st_tags st_tags(label='# Enter Keywords:', text='Press enter to add more', value=['Zero', 'One', 'Two'], suggestions=['five', 'six', 'seven', 'eight', 'nine', 'three', 'eleven', 'ten', 'four'], maxtags = 4, key='1') StqdmThe simplest way to handle a progress bar in streamlit app. Created by @Wirg.from stqdm import stqdm for _ in stqdm(range(50)): sleep(0.5) TimelineDisplay a Timeline in Streamlit apps using TimelineJS. Created by @innerdoc.from streamlit_timeline import timeline with open('example.json', ""r"") as f: timeline(f.read(), height=800) Camera input liveAlternative for st.camera_input which returns the webcam images live. Created by @blackary.from camera_input_live import camera_input_live image = camera_input_live() st.image(value) Streamlit AceAce editor component for Streamlit. Created by @okld.from streamlit_ace import st_ace content = st_ace() content Streamlit ChatStreamlit Component for a Chatbot UI. Created by @AI-Yash.from streamlit_chat import message message(""My message"") message(""Hello bot!"", is_user=True) # align's the message to the right Streamlit Option MenuSelect a single item from a list of options in a menu. Created by @victoryhb.from streamlit_option_menu import option_menu option_menu(""Main Menu"", [""Home"", 'Settings'], icons=['house', 'gear'], menu_icon=""cast"", default_index=1) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.stoggle import stoggle stoggle( ""Click me!"", """"""🥷 Surprise! Here's some additional content"""""",) Next Media elements ImageDisplay an image or list of images.st.image(numpy_array) st.image(image_bytes) st.image(file) st.image(""https://example.com/myimage.jpg"") AudioDisplay an audio player.st.audio(numpy_array) st.audio(audio_bytes) st.audio(file) st.audio(""https://example.com/myaudio.mp3"", format=""audio/mp3"") VideoDisplay a video player.st.video(numpy_array) st.video(video_bytes) st.video(file) st.video(""https://example.com/myvideo.mp4"", format=""video/mp4"") Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration! PreviousStreamlit CropperA simple image cropper for Streamlit. Created by @turner-anderson.from streamlit_cropper import st_cropper st_cropper(img, realtime_update=realtime_update, box_color=box_color, aspect_ratio=aspect_ratio) Image CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates streamlit_image_coordinates(""https://placekitten.com/200/300"") Streamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl(""https://assets5.lottiefiles.com/packages/lf20_V9t630.json"") st_lottie(lottie_hello, key=""hello"") Streamlit WebrtcHandling and transmitting real-time video/audio streams with Streamlit. Created by @whitphx.from streamlit_webrtc import webrtc_streamer webrtc_streamer(key=""sample"") Drawable CanvasProvides a sketching canvas using Fabric.js. Created by @andfanilo.from streamlit_drawable_canvas import st_canvas st_canvas(fill_color=""rgba(255, 165, 0, 0.3)"", stroke_width=stroke_width, stroke_color=stroke_color, background_color=bg_color, background_image=Image.open(bg_image) if bg_image else None, update_streamlit=realtime_update, height=150, drawing_mode=drawing_mode, point_display_radius=point_display_radius if drawing_mode == 'point' else 0, key=""canvas"",) Image ComparisonCompare images with a slider using JuxtaposeJS. Created by @fcakyon.from streamlit_image_comparison import image_comparison image_comparison(img1=""image1.jpg"", img2=""image2.jpg"",) Streamlit CropperA simple image cropper for Streamlit. Created by @turner-anderson.from streamlit_cropper import st_cropper st_cropper(img, realtime_update=realtime_update, box_color=box_color, aspect_ratio=aspect_ratio) Image CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates streamlit_image_coordinates(""https://placekitten.com/200/300"") Streamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl(""https://assets5.lottiefiles.com/packages/lf20_V9t630.json"") st_lottie(lottie_hello, key=""hello"") Streamlit WebrtcHandling and transmitting real-time video/audio streams with Streamlit. Created by @whitphx.from streamlit_webrtc import webrtc_streamer webrtc_streamer(key=""sample"") Drawable CanvasProvides a sketching canvas using Fabric.js. Created by @andfanilo.from streamlit_drawable_canvas import st_canvas st_canvas(fill_color=""rgba(255, 165, 0, 0.3)"", stroke_width=stroke_width, stroke_color=stroke_color, background_color=bg_color, background_image=Image.open(bg_image) if bg_image else None, update_streamlit=realtime_update, height=150, drawing_mode=drawing_mode, point_display_radius=point_display_radius if drawing_mode == 'point' else 0, key=""canvas"",) Image ComparisonCompare images with a slider using JuxtaposeJS. Created by @fcakyon.from streamlit_image_comparison import image_comparison image_comparison(img1=""image1.jpg"", img2=""image2.jpg"",) Streamlit CropperA simple image cropper for Streamlit. Created by @turner-anderson.from streamlit_cropper import st_cropper st_cropper(img, realtime_update=realtime_update, box_color=box_color, aspect_ratio=aspect_ratio) Image CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates streamlit_image_coordinates(""https://placekitten.com/200/300"") Streamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl(""https://assets5.lottiefiles.com/packages/lf20_V9t630.json"") st_lottie(lottie_hello, key=""hello"") Next Layouts and containers ColumnsInsert containers laid out as side-by-side columns.col1, col2 = st.columns(2) col1.write(""this is column 1"") col2.write(""this is column 2"") ContainerInsert a multi-element container.c = st.container() st.write(""This will show last"") c.write(""This will show first"") c.write(""This will show second"") Modal dialogsInsert a modal dialog that can rerun independently from the rest of the script.@st.experimental_dialog(""Sign up"") def email_form(): name = st.text_input(""Name"") email = st.text_input(""Email"") EmptyInsert a single-element container.c = st.empty() st.write(""This will show last"") c.write(""This will be replaced"") c.write(""This will show first"") ExpanderInsert a multi-element container that can be expanded/collapsed.with st.expander(""Open to see more""): st.write(""This is more content"") PopoverInsert a multi-element popover container that can be opened/closed.with st.popover(""Settings""): st.checkbox(""Show completed"") SidebarDisplay items in a sidebar.st.sidebar.write(""This lives in the sidebar"") st.sidebar.button(""Click me!"") TabsInsert containers separated into tabs.tab1, tab2 = st.tabs([""Tab 1"", ""Tab2""]) tab1.write(""this is tab 1"") tab2.write(""this is tab 2"") Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration!Streamlit ElementsCreate a draggable and resizable dashboard in Streamlit. Created by @okls.from streamlit_elements import elements, mui, html with elements(""new_element""): mui.Typography(""Hello world"") PydanticAuto-generate Streamlit UI from Pydantic Models and Dataclasses. Created by @lukasmasuch.import streamlit_pydantic as sp sp.pydantic_form(key=""my_form"", model=ExampleModel) Streamlit PagesAn experimental version of Streamlit Multi-Page Apps. Created by @blackary.from st_pages import Page, show_pages, add_page_title show_pages([ Page(""streamlit_app.py"", ""Home"", ""🏠""), Page(""other_pages/page2.py"", ""Page 2"", "":books:""), ]) Chat elements Streamlit provides a few commands to help you build conversational apps. These chat elements are designed to be used in conjunction with each other, but you can also use them separately. st.chat_message lets you insert a chat message container into the app so you can display messages from the user or the app. Chat containers can contain other Streamlit elements, including charts, tables, text, and more. st.chat_input lets you display a chat input widget so the user can type in a message. Chat inputDisplay a chat input widget.prompt = st.chat_input(""Say something"") if prompt: st.write(f""The user has sent: {prompt}"") Chat messageInsert a chat message container.import numpy as np with st.chat_message(""user""): st.write(""Hello 👋"") st.line_chart(np.random.randn(30, 3)) Status containerDisplay output of long-running tasks in a container.with st.status('Running'): do_something_slow() st.write_streamWrite generators or streams to the app with a typewriter effect.st.write_stream(my_generator) st.write_stream(my_llm_stream) Status elements Progress barDisplay a progress bar.for i in range(101): st.progress(i) do_something_slow() SpinnerTemporarily displays a message while executing a block of code.with st.spinner(""Please wait...""): do_something_slow() Status containerDisplay output of long-running tasks in a container.with st.status('Running'): do_something_slow() ToastBriefly displays a toast message in the bottom-right corner.st.toast('Butter!', icon='🧈') BalloonsDisplay celebratory balloons!do_something() # Celebrate when all done! st.balloons() SnowflakesDisplay celebratory snowflakes!do_something() # Celebrate when all done! st.snow() Success boxDisplay a success message.st.success(""Match found!"") Info boxDisplay an informational message.st.info(""Dataset is updated every day at midnight."") Warning boxDisplay warning message.st.warning(""Unable to fetch image. Skipping..."") Error boxDisplay error message.st.error(""We encountered an error"") Exception outputDisplay an exception.e = RuntimeError(""This is an exception of type RuntimeError"") st.exception(e) Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration!StqdmThe simplest way to handle a progress bar in streamlit app. Created by @Wirg.from stqdm import stqdm for _ in stqdm(range(50)): sleep(0.5) Custom notification boxA custom notification box with the ability to close it out. Created by @Socvest.from streamlit_custom_notification_box import custom_notification_box styles = {'material-icons':{'color': 'red'}, 'text-icon-link-close-container': {'box-shadow': '#3896de 0px 4px'}, 'notification-text': {'':''}, 'close-button':{'':''}, 'link':{'':''}} custom_notification_box(icon='info', textDisplay='We are almost done with your registration...', externalLink='more info', url='#', styles=styles, key=""foo"") Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.let_it_rain import rain rain(emoji=""🎈"", font_size=54, falling_speed=5, animation_length=""infinite"",) App logic and configuration Navigation and pages Switch pageProgrammatically navigates to a specified page.st.switch_page(""pages/my_page.py"") Page linkDisplay a link to another page in a multipage app.st.page_link(""app.py"", label=""Home"", icon=""🏠"") st.page_link(""pages/profile.py"", label=""My profile"") Execution flow Modal dialogsInsert a modal dialog that can rerun independently from the rest of the script.@st.experimental_dialog(""Sign up"") def email_form(): name = st.text_input(""Name"") email = st.text_input(""Email"") FormsCreate a form that batches elements together with a “Submit"" button.with st.form(key='my_form'): name = st.text_input(""Name"") email = st.text_input(""Email"") st.form_submit_button(""Sign up"") Partial rerunsDefine a fragment to rerun independently from the rest of the script.@st.experimental_fragment(run_every=""10s"") def fragment(): df = get_data() st.line_chart(df) Rerun scriptRerun the script immediately.st.rerun() Stop executionStops execution immediately.st.stop() Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration!AutorefreshForce a refresh without tying up a script. Created by @kmcgrady.from streamlit_autorefresh import st_autorefresh st_autorefresh(interval=2000, limit=100, key=""fizzbuzzcounter"") PydanticAuto-generate Streamlit UI from Pydantic Models and Dataclasses. Created by @lukasmasuch.import streamlit_pydantic as sp sp.pydantic_form(key=""my_form"", model=ExampleModel) Streamlit PagesAn experimental version of Streamlit Multi-Page Apps. Created by @blackary.from st_pages import Page, show_pages, add_page_title show_pages([ Page(""streamlit_app.py"", ""Home"", ""🏠""), Page(""other_pages/page2.py"", ""Page 2"", "":books:""), ]) Caching and state Cache dataFunction decorator to cache functions that return data (e.g. dataframe transforms, database queries, ML inference).@st.cache_data def long_function(param1, param2): # Perform expensive computation here or # fetch data from the web here return data Cache resourceFunction decorator to cache functions that return global resources (e.g. database connections, ML models).@st.cache_resource def init_model(): # Return a global resource here return pipeline( ""sentiment-analysis"", model=""distilbert-base-uncased-finetuned-sst-2-english"" ) Session stateSession state is a way to share variables between reruns, for each user session.st.session_state['key'] = value Query parametersGet, set, or clear the query parameters that are shown in the browser's URL bar.st.query_params[key] = value st.query_params.clear() Connections and databases Setup your connection Create a connectionConnect to a data source or APIconn = st.connection('pets_db', type='sql') pet_owners = conn.query('select * from pet_owners') st.dataframe(pet_owners) Built-in connections SnowflakeConnectionA connection to Snowflake.conn = st.connection('snowflake') SQLConnectionA connection to a SQL database using SQLAlchemy.conn = st.connection('sql') Build your own connections Connection base classBuild your own connection with BaseConnection.class MyConnection(BaseConnection[myconn.MyConnection]): def _connect(self, **kwargs) -> MyConnection: return myconn.connect(**self._secrets, **kwargs) def query(self, query): return self._instance.query(query) Secrets management Secrets singletonAccess secrets from a local TOML file.key = st.secrets[""OpenAI_key""] Secrets fileSave your secrets in a per-project or per-profile TOML file.OpenAI_key = """" Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration!AuthenticatorA secure authentication module to validate user credentials. Created by @mkhorasani.import streamlit_authenticator as stauth authenticator = stauth.Authenticate( config['credentials'], config['cookie']['name'], config['cookie']['key'], config['cookie']['expiry_days'], config['preauthorized']) WS localStorageA simple synchronous way of accessing localStorage from your app. Created by @gagangoku.from streamlit_ws_localstorage import injectWebsocketCode ret = conn.setLocalStorageVal(key='k1', val='v1') st.write('ret: ' + ret) Streamlit Auth0The fastest way to provide comprehensive login inside Streamlit. Created by @conradbez.from auth0_component import login_button user_info = login_button(clientId, domain = domain) st.write(user_info) Custom Components Declare a componentCreate and register a custom component.st.components.v1.declare_component( ""custom_slider"", ""/frontend"", ) HTMLDisplay an HTML string in an iframe.st.components.v1.html( ""

Foo bar.

"" ) iframeLoad a remote URL in an iframe.st.components.v1.iframe( ""docs.streamlit.io"" ) Utilities and user info User infost.experimental_user returns information about the logged-in user of private apps on Streamlit Community Cloud.if st.experimental_user.email == ""foo@corp.com"": st.write(""Welcome back, "", st.experimental_user.email) else: st.write(""You are not authorized to view this page."") Get helpDisplay object’s doc string, nicely formatted.st.help(st.write) st.help(pd.DataFrame) Render HTMLRenders HTML strings to your app.css = """""" """""" st.html(css) Configuration Configuration fileConfigures the default settings for your app.your-project/ ├── .streamlit/ │ └── config.toml └── your_app.py Set page title, favicon, and moreConfigures the default settings of the page.st.set_page_config( page_title=""My app"", page_icon="":shark:"", ) Developer tools App testing st.testing.v1.AppTestst.testing.v1.AppTest simulates a running Streamlit app for testing.from streamlit.testing.v1 import AppTest at = AppTest.from_file(""streamlit_app.py"") at.secrets[""WORD""] = ""Foobar"" at.run() assert not at.exception at.text_input(""word"").input(""Bazbat"").run() assert at.warning[0].value == ""Try again."" AppTest.from_filest.testing.v1.AppTest.from_file initializes a simulated app from a file.from streamlit.testing.v1 import AppTest at = AppTest.from_file(""streamlit_app.py"") at.run() AppTest.from_stringst.testing.v1.AppTest.from_string initializes a simulated app from a string.from streamlit.testing.v1 import AppTest at = AppTest.from_string(app_script_as_string) at.run() AppTest.from_functionst.testing.v1.AppTest.from_function initializes a simulated app from a function.from streamlit.testing.v1 import AppTest at = AppTest.from_function(app_script_as_callable) at.run() BlockA representation of container elements, including: st.chat_message st.columns st.sidebar st.tabs The main body of the app. # at.sidebar returns a Block at.sidebar.button[0].click().run() assert not at.exception ElementThe base class for representation of all elements, including: st.title st.header st.markdown st.dataframe # at.title returns a sequence of Title # Title inherits from Element assert at.title[0].value == ""My awesome app"" ButtonA representation of st.button and st.form_submit_button.at.button[0].click().run() ChatInputA representation of st.chat_input.at.chat_input[0].set_value(""What is Streamlit?"").run() CheckboxA representation of st.checkbox.at.checkbox[0].check().run() ColorPickerA representation of st.color_picker.at.color_picker[0].pick(""#FF4B4B"").run() DateInputA representation of st.date_input.release_date = datetime.date(2023, 10, 26) at.date_input[0].set_value(release_date).run() MultiselectA representation of st.multiselect.at.multiselect[0].select(""New York"").run() NumberInputA representation of st.number_input.at.number_input[0].increment().run() RadioA representation of st.radio.at.radio[0].set_value(""New York"").run() SelectSliderA representation of st.select_slider.at.select_slider[0].set_range(""A"",""C"").run() SelectboxA representation of st.selectbox.at.selectbox[0].select(""New York"").run() SliderA representation of st.slider.at.slider[0].set_range(2,5).run() TextAreaA representation of st.text_area.at.text_area[0].input(""Streamlit is awesome!"").run() TextInputA representation of st.text_input.at.text_input[0].input(""Streamlit"").run() TimeInputA representation of st.time_input.at.time_input[0].increment().run() ToggleA representation of st.toggle.at.toggle[0].set_value(""True"").run() Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration!Pandas ProfilingPandas profiling component for Streamlit. Created by @okld.df = pd.read_csv(""https://storage.googleapis.com/tf-datasets/titanic/train.csv"") pr = df.profile_report() st_profile_report(pr) Streamlit AceAce editor component for Streamlit. Created by @okld.from streamlit_ace import st_ace content = st_ace() content Streamlit AnalyticsTrack & visualize user interactions with your streamlit app. Created by @jrieke.import streamlit_analytics with streamlit_analytics.track(): st.text_input(""Write something"") Previous: ConceptsNext: Write and magicforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy" https://docs.streamlit.io/develop/api-reference#api-reference,"DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceremovePAGE ELEMENTSWrite and magicaddText elementsaddData elementsaddChart elementsaddInput widgetsaddMedia elementsaddLayouts and containersaddChat elementsaddStatus elementsaddThird-party componentsopen_in_newAPPLICATION LOGICNavigation and pagesaddExecution flowaddCaching and stateaddConnections and secretsaddCustom componentsaddUtilitiesaddConfigurationaddTOOLSApp testingaddCommand lineaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Develop/API referenceAPI reference Streamlit makes it easy for you to visualize, mutate, and share data. The API reference is organized by activity type, like displaying data or optimizing performance. Each section includes methods associated with the activity type, including examples. Browse our API below and click to learn more about any of our available commands! 🎈 Display almost anything Write and magic st.writeWrite arguments to the app.st.write(""Hello **world**!"") st.write(my_data_frame) st.write(my_mpl_figure) st.write_streamWrite generators or streams to the app with a typewriter effect.st.write_stream(my_generator) st.write_stream(my_llm_stream) MagicAny time Streamlit sees either a variable or literal value on its own line, it automatically writes that to your app using st.write""Hello **world**!"" my_data_frame my_mpl_figure Text elements MarkdownDisplay string formatted as Markdown.st.markdown(""Hello **world**!"") TitleDisplay text in title formatting.st.title(""The app title"") HeaderDisplay text in header formatting.st.header(""This is a header"") SubheaderDisplay text in subheader formatting.st.subheader(""This is a subheader"") CaptionDisplay text in small font.st.caption(""This is written small caption text"") Code blockDisplay a code block with optional syntax highlighting.st.code(""a = 1234"") EchoDisplay some code in the app, then execute it. Useful for tutorials.with st.echo(): st.write('This code will be printed') LaTeXDisplay mathematical expressions formatted as LaTeX.st.latex(""\int a x^2 \,dx"") Preformatted textWrite fixed-width and preformatted text.st.text(""Hello world"") DividerDisplay a horizontal rule.st.divider() Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration! PreviousTagsAdd tags to your Streamlit apps. Created by @gagan3012.st_tags(label='# Enter Keywords:', text='Press enter to add more', value=['Zero', 'One', 'Two'], suggestions=['five', 'six', 'seven', 'eight', 'nine', 'three', 'eleven', 'ten', 'four'], maxtags = 4, key='1') NLUApply text mining on a dataframe. Created by @JohnSnowLabs.nlu.load('sentiment').predict('I love NLU! <3') Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.mention(label=""An awesome Streamlit App"", icon=""streamlit"", url=""https://extras.streamlit.app"",) Annotated textDisplay annotated text in Streamlit apps. Created by @tvst.annotated_text(""This "", (""is"", ""verb""), "" some "", (""annotated"", ""adj""), (""text"", ""noun""), "" for those of "", (""you"", ""pronoun""), "" who "", (""like"", ""verb""), "" this sort of "", (""thing"", ""noun""), ""."") Drawable CanvasProvides a sketching canvas using Fabric.js. Created by @andfanilo.st_canvas(fill_color=""rgba(255, 165, 0, 0.3)"", stroke_width=stroke_width, stroke_color=stroke_color, background_color=bg_color, background_image=Image.open(bg_image) if bg_image else None, update_streamlit=realtime_update, height=150, drawing_mode=drawing_mode, point_display_radius=point_display_radius if drawing_mode == 'point' else 0, key=""canvas"",) TagsAdd tags to your Streamlit apps. Created by @gagan3012.st_tags(label='# Enter Keywords:', text='Press enter to add more', value=['Zero', 'One', 'Two'], suggestions=['five', 'six', 'seven', 'eight', 'nine', 'three', 'eleven', 'ten', 'four'], maxtags = 4, key='1') NLUApply text mining on a dataframe. Created by @JohnSnowLabs.nlu.load('sentiment').predict('I love NLU! <3') Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.mention(label=""An awesome Streamlit App"", icon=""streamlit"", url=""https://extras.streamlit.app"",) Annotated textDisplay annotated text in Streamlit apps. Created by @tvst.annotated_text(""This "", (""is"", ""verb""), "" some "", (""annotated"", ""adj""), (""text"", ""noun""), "" for those of "", (""you"", ""pronoun""), "" who "", (""like"", ""verb""), "" this sort of "", (""thing"", ""noun""), ""."") Drawable CanvasProvides a sketching canvas using Fabric.js. Created by @andfanilo.st_canvas(fill_color=""rgba(255, 165, 0, 0.3)"", stroke_width=stroke_width, stroke_color=stroke_color, background_color=bg_color, background_image=Image.open(bg_image) if bg_image else None, update_streamlit=realtime_update, height=150, drawing_mode=drawing_mode, point_display_radius=point_display_radius if drawing_mode == 'point' else 0, key=""canvas"",) TagsAdd tags to your Streamlit apps. Created by @gagan3012.st_tags(label='# Enter Keywords:', text='Press enter to add more', value=['Zero', 'One', 'Two'], suggestions=['five', 'six', 'seven', 'eight', 'nine', 'three', 'eleven', 'ten', 'four'], maxtags = 4, key='1') NLUApply text mining on a dataframe. Created by @JohnSnowLabs.nlu.load('sentiment').predict('I love NLU! <3') Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.mention(label=""An awesome Streamlit App"", icon=""streamlit"", url=""https://extras.streamlit.app"",) Next Data elements DataframesDisplay a dataframe as an interactive table.st.dataframe(my_data_frame) Data editorDisplay a data editor widget.edited = st.data_editor(df, num_rows=""dynamic"") Column configurationConfigure the display and editing behavior of dataframes and data editors.st.column_config.NumberColumn(""Price (in USD)"", min_value=0, format=""$%d"") Static tablesDisplay a static table.st.table(my_data_frame) MetricsDisplay a metric in big bold font, with an optional indicator of how the metric changed.st.metric(""My metric"", 42, 2) Dicts and JSONDisplay object or string as a pretty-printed JSON string.st.json(my_dict) Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration! PreviousImage CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates value = streamlit_image_coordinates(""https://placekitten.com/200/300"") st.write(value) Plotly EventsMake Plotly charts interactive!. Created by @null-jones.from streamlit_plotly_events import plotly_events fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.metric_cards import style_metric_cards col3.metric(label=""No Change"", value=5000, delta=0) style_metric_cards() Streamlit AggridImplementation of Ag-Grid component for Streamlit. Created by @PablocFonseca.df = pd.DataFrame({'col1': [1, 2, 3], 'col2': [4, 5, 6]}) grid_return = AgGrid(df, editable=True) new_df = grid_return['data'] Streamlit FoliumStreamlit Component for rendering Folium maps. Created by @randyzwitch.m = folium.Map(location=[39.949610, -75.150282], zoom_start=16) folium.Marker([39.949610, -75.150282], popup=""Liberty Bell"", tooltip=""Liberty Bell"").add_to(m) st_data = st_folium(m, width=725) Pandas ProfilingPandas profiling component for Streamlit. Created by @okld.df = pd.read_csv(""https://storage.googleapis.com/tf-datasets/titanic/train.csv"") pr = df.profile_report() st_profile_report(pr) Image CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates value = streamlit_image_coordinates(""https://placekitten.com/200/300"") st.write(value) Plotly EventsMake Plotly charts interactive!. Created by @null-jones.from streamlit_plotly_events import plotly_events fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.metric_cards import style_metric_cards col3.metric(label=""No Change"", value=5000, delta=0) style_metric_cards() Streamlit AggridImplementation of Ag-Grid component for Streamlit. Created by @PablocFonseca.df = pd.DataFrame({'col1': [1, 2, 3], 'col2': [4, 5, 6]}) grid_return = AgGrid(df, editable=True) new_df = grid_return['data'] Streamlit FoliumStreamlit Component for rendering Folium maps. Created by @randyzwitch.m = folium.Map(location=[39.949610, -75.150282], zoom_start=16) folium.Marker([39.949610, -75.150282], popup=""Liberty Bell"", tooltip=""Liberty Bell"").add_to(m) st_data = st_folium(m, width=725) Pandas ProfilingPandas profiling component for Streamlit. Created by @okld.df = pd.read_csv(""https://storage.googleapis.com/tf-datasets/titanic/train.csv"") pr = df.profile_report() st_profile_report(pr) Image CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates value = streamlit_image_coordinates(""https://placekitten.com/200/300"") st.write(value) Plotly EventsMake Plotly charts interactive!. Created by @null-jones.from streamlit_plotly_events import plotly_events fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.metric_cards import style_metric_cards col3.metric(label=""No Change"", value=5000, delta=0) style_metric_cards() Next Chart elements Simple area chartsDisplay an area chart.st.area_chart(my_data_frame) Simple bar chartsDisplay a bar chart.st.bar_chart(my_data_frame) Simple line chartsDisplay a line chart.st.line_chart(my_data_frame) Simple scatter chartsDisplay a line chart.st.scatter_chart(my_data_frame) Scatterplots on mapsDisplay a map with points on it.st.map(my_data_frame) MatplotlibDisplay a matplotlib.pyplot figure.st.pyplot(my_mpl_figure) AltairDisplay a chart using the Altair library.st.altair_chart(my_altair_chart) Vega-LiteDisplay a chart using the Vega-Lite library.st.vega_lite_chart(my_vega_lite_chart) PlotlyDisplay an interactive Plotly chart.st.plotly_chart(my_plotly_chart) BokehDisplay an interactive Bokeh chart.st.bokeh_chart(my_bokeh_chart) PyDeckDisplay a chart using the PyDeck library.st.pydeck_chart(my_pydeck_chart) GraphVizDisplay a graph using the dagre-d3 library.st.graphviz_chart(my_graphviz_spec) Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration! PreviousStreamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl(""https://assets5.lottiefiles.com/packages/lf20_V9t630.json"") st_lottie(lottie_hello, key=""hello"") Plotly EventsMake Plotly charts interactive!. Created by @null-jones.fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.chart += get_annotations_chart(annotations=[(""Mar 01, 2008"", ""Pretty good day for GOOG""), (""Dec 01, 2007"", ""Something's going wrong for GOOG & AAPL""), (""Nov 01, 2008"", ""Market starts again thanks to...""), (""Dec 01, 2009"", ""Small crash for GOOG after...""),],) st.altair_chart(chart, use_container_width=True) PlostA deceptively simple plotting library for Streamlit. Created by @tvst.import plost plost.line_chart(my_dataframe, x='time', y='stock_value', color='stock_name',) HiPlotHigh dimensional Interactive Plotting. Created by @facebookresearch.data = [{'dropout':0.1, 'lr': 0.001, 'loss': 10.0, 'optimizer': 'SGD'}, {'dropout':0.15, 'lr': 0.01, 'loss': 3.5, 'optimizer': 'Adam'}, {'dropout':0.3, 'lr': 0.1, 'loss': 4.5, 'optimizer': 'Adam'}] hip.Experiment.from_iterable(data).display() EChartsHigh dimensional Interactive Plotting. Created by @andfanilo.from streamlit_echarts import st_echarts st_echarts(options=options) Streamlit FoliumStreamlit Component for rendering Folium maps. Created by @randyzwitch.m = folium.Map(location=[39.949610, -75.150282], zoom_start=16) st_data = st_folium(m, width=725) Spacy-StreamlitspaCy building blocks and visualizers for Streamlit apps. Created by @explosion.models = [""en_core_web_sm"", ""en_core_web_md""] spacy_streamlit.visualize(models, ""Sundar Pichai is the CEO of Google."") Streamlit AgraphA Streamlit Graph Vis, based on react-grah-vis. Created by @ChrisDelClea.from streamlit_agraph import agraph, Node, Edge, Config agraph(nodes=nodes, edges=edges, config=config) Streamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl(""https://assets5.lottiefiles.com/packages/lf20_V9t630.json"") st_lottie(lottie_hello, key=""hello"") Plotly EventsMake Plotly charts interactive!. Created by @null-jones.fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.chart += get_annotations_chart(annotations=[(""Mar 01, 2008"", ""Pretty good day for GOOG""), (""Dec 01, 2007"", ""Something's going wrong for GOOG & AAPL""), (""Nov 01, 2008"", ""Market starts again thanks to...""), (""Dec 01, 2009"", ""Small crash for GOOG after...""),],) st.altair_chart(chart, use_container_width=True) PlostA deceptively simple plotting library for Streamlit. Created by @tvst.import plost plost.line_chart(my_dataframe, x='time', y='stock_value', color='stock_name',) HiPlotHigh dimensional Interactive Plotting. Created by @facebookresearch.data = [{'dropout':0.1, 'lr': 0.001, 'loss': 10.0, 'optimizer': 'SGD'}, {'dropout':0.15, 'lr': 0.01, 'loss': 3.5, 'optimizer': 'Adam'}, {'dropout':0.3, 'lr': 0.1, 'loss': 4.5, 'optimizer': 'Adam'}] hip.Experiment.from_iterable(data).display() EChartsHigh dimensional Interactive Plotting. Created by @andfanilo.from streamlit_echarts import st_echarts st_echarts(options=options) Streamlit FoliumStreamlit Component for rendering Folium maps. Created by @randyzwitch.m = folium.Map(location=[39.949610, -75.150282], zoom_start=16) st_data = st_folium(m, width=725) Spacy-StreamlitspaCy building blocks and visualizers for Streamlit apps. Created by @explosion.models = [""en_core_web_sm"", ""en_core_web_md""] spacy_streamlit.visualize(models, ""Sundar Pichai is the CEO of Google."") Streamlit AgraphA Streamlit Graph Vis, based on react-grah-vis. Created by @ChrisDelClea.from streamlit_agraph import agraph, Node, Edge, Config agraph(nodes=nodes, edges=edges, config=config) Streamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl(""https://assets5.lottiefiles.com/packages/lf20_V9t630.json"") st_lottie(lottie_hello, key=""hello"") Plotly EventsMake Plotly charts interactive!. Created by @null-jones.fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.chart += get_annotations_chart(annotations=[(""Mar 01, 2008"", ""Pretty good day for GOOG""), (""Dec 01, 2007"", ""Something's going wrong for GOOG & AAPL""), (""Nov 01, 2008"", ""Market starts again thanks to...""), (""Dec 01, 2009"", ""Small crash for GOOG after...""),],) st.altair_chart(chart, use_container_width=True) Next Input widgets ButtonDisplay a button widget.clicked = st.button(""Click me"") Download buttonDisplay a download button widget.st.download_button(""Download file"", file) Form buttonDisplay a form submit button. For use with st.form.st.form_submit_button(""Sign up"") Link buttonDisplay a link button.st.link_button(""Go to gallery"", url) Page linkDisplay a link to another page in a multipage app.st.page_link(""app.py"", label=""Home"", icon=""🏠"") st.page_link(""pages/profile.py"", label=""My profile"") CheckboxDisplay a checkbox widget.selected = st.checkbox(""I agree"") Color pickerDisplay a color picker widget.color = st.color_picker(""Pick a color"") MultiselectDisplay a multiselect widget. The multiselect widget starts as empty.choices = st.multiselect(""Buy"", [""milk"", ""apples"", ""potatoes""]) RadioDisplay a radio button widget.choice = st.radio(""Pick one"", [""cats"", ""dogs""]) SelectboxDisplay a select widget.choice = st.selectbox(""Pick one"", [""cats"", ""dogs""]) Select-sliderDisplay a slider widget to select items from a list.size = st.select_slider(""Pick a size"", [""S"", ""M"", ""L""]) ToggleDisplay a toggle widget.activated = st.toggle(""Activate"") Number inputDisplay a numeric input widget.choice = st.number_input(""Pick a number"", 0, 10) SliderDisplay a slider widget.number = st.slider(""Pick a number"", 0, 100) Date inputDisplay a date input widget.date = st.date_input(""Your birthday"") Time inputDisplay a time input widget.time = st.time_input(""Meeting time"") Chat inputDisplay a chat input widget.prompt = st.chat_input(""Say something"") if prompt: st.write(f""The user has sent: {prompt}"") Text-areaDisplay a multi-line text input widget.text = st.text_area(""Text to translate"") Text inputDisplay a single-line text input widget.name = st.text_input(""First name"") Data editorDisplay a data editor widget.edited = st.experimental_data_editor(df, num_rows=""dynamic"") File UploaderDisplay a file uploader widget.data = st.file_uploader(""Upload a CSV"") Camera inputDisplay a widget that allows users to upload images directly from a camera.image = st.camera_input(""Take a picture"") Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration! PreviousStreamlit ChatStreamlit Component for a Chatbot UI. Created by @AI-Yash.from streamlit_chat import message message(""My message"") message(""Hello bot!"", is_user=True) # align's the message to the right Streamlit Option MenuSelect a single item from a list of options in a menu. Created by @victoryhb.from streamlit_option_menu import option_menu option_menu(""Main Menu"", [""Home"", 'Settings'], icons=['house', 'gear'], menu_icon=""cast"", default_index=1) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.stoggle import stoggle stoggle( ""Click me!"", """"""🥷 Surprise! Here's some additional content"""""",) Streamlit ElementsCreate a draggable and resizable dashboard in Streamlit. Created by @okls.from streamlit_elements import elements, mui, html with elements(""new_element""): mui.Typography(""Hello world"") TagsAdd tags to your Streamlit apps. Created by @gagan3012.from streamlit_tags import st_tags st_tags(label='# Enter Keywords:', text='Press enter to add more', value=['Zero', 'One', 'Two'], suggestions=['five', 'six', 'seven', 'eight', 'nine', 'three', 'eleven', 'ten', 'four'], maxtags = 4, key='1') StqdmThe simplest way to handle a progress bar in streamlit app. Created by @Wirg.from stqdm import stqdm for _ in stqdm(range(50)): sleep(0.5) TimelineDisplay a Timeline in Streamlit apps using TimelineJS. Created by @innerdoc.from streamlit_timeline import timeline with open('example.json', ""r"") as f: timeline(f.read(), height=800) Camera input liveAlternative for st.camera_input which returns the webcam images live. Created by @blackary.from camera_input_live import camera_input_live image = camera_input_live() st.image(value) Streamlit AceAce editor component for Streamlit. Created by @okld.from streamlit_ace import st_ace content = st_ace() content Streamlit ChatStreamlit Component for a Chatbot UI. Created by @AI-Yash.from streamlit_chat import message message(""My message"") message(""Hello bot!"", is_user=True) # align's the message to the right Streamlit Option MenuSelect a single item from a list of options in a menu. Created by @victoryhb.from streamlit_option_menu import option_menu option_menu(""Main Menu"", [""Home"", 'Settings'], icons=['house', 'gear'], menu_icon=""cast"", default_index=1) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.stoggle import stoggle stoggle( ""Click me!"", """"""🥷 Surprise! Here's some additional content"""""",) Streamlit ElementsCreate a draggable and resizable dashboard in Streamlit. Created by @okls.from streamlit_elements import elements, mui, html with elements(""new_element""): mui.Typography(""Hello world"") TagsAdd tags to your Streamlit apps. Created by @gagan3012.from streamlit_tags import st_tags st_tags(label='# Enter Keywords:', text='Press enter to add more', value=['Zero', 'One', 'Two'], suggestions=['five', 'six', 'seven', 'eight', 'nine', 'three', 'eleven', 'ten', 'four'], maxtags = 4, key='1') StqdmThe simplest way to handle a progress bar in streamlit app. Created by @Wirg.from stqdm import stqdm for _ in stqdm(range(50)): sleep(0.5) TimelineDisplay a Timeline in Streamlit apps using TimelineJS. Created by @innerdoc.from streamlit_timeline import timeline with open('example.json', ""r"") as f: timeline(f.read(), height=800) Camera input liveAlternative for st.camera_input which returns the webcam images live. Created by @blackary.from camera_input_live import camera_input_live image = camera_input_live() st.image(value) Streamlit AceAce editor component for Streamlit. Created by @okld.from streamlit_ace import st_ace content = st_ace() content Streamlit ChatStreamlit Component for a Chatbot UI. Created by @AI-Yash.from streamlit_chat import message message(""My message"") message(""Hello bot!"", is_user=True) # align's the message to the right Streamlit Option MenuSelect a single item from a list of options in a menu. Created by @victoryhb.from streamlit_option_menu import option_menu option_menu(""Main Menu"", [""Home"", 'Settings'], icons=['house', 'gear'], menu_icon=""cast"", default_index=1) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.stoggle import stoggle stoggle( ""Click me!"", """"""🥷 Surprise! Here's some additional content"""""",) Next Media elements ImageDisplay an image or list of images.st.image(numpy_array) st.image(image_bytes) st.image(file) st.image(""https://example.com/myimage.jpg"") AudioDisplay an audio player.st.audio(numpy_array) st.audio(audio_bytes) st.audio(file) st.audio(""https://example.com/myaudio.mp3"", format=""audio/mp3"") VideoDisplay a video player.st.video(numpy_array) st.video(video_bytes) st.video(file) st.video(""https://example.com/myvideo.mp4"", format=""video/mp4"") Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration! PreviousStreamlit CropperA simple image cropper for Streamlit. Created by @turner-anderson.from streamlit_cropper import st_cropper st_cropper(img, realtime_update=realtime_update, box_color=box_color, aspect_ratio=aspect_ratio) Image CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates streamlit_image_coordinates(""https://placekitten.com/200/300"") Streamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl(""https://assets5.lottiefiles.com/packages/lf20_V9t630.json"") st_lottie(lottie_hello, key=""hello"") Streamlit WebrtcHandling and transmitting real-time video/audio streams with Streamlit. Created by @whitphx.from streamlit_webrtc import webrtc_streamer webrtc_streamer(key=""sample"") Drawable CanvasProvides a sketching canvas using Fabric.js. Created by @andfanilo.from streamlit_drawable_canvas import st_canvas st_canvas(fill_color=""rgba(255, 165, 0, 0.3)"", stroke_width=stroke_width, stroke_color=stroke_color, background_color=bg_color, background_image=Image.open(bg_image) if bg_image else None, update_streamlit=realtime_update, height=150, drawing_mode=drawing_mode, point_display_radius=point_display_radius if drawing_mode == 'point' else 0, key=""canvas"",) Image ComparisonCompare images with a slider using JuxtaposeJS. Created by @fcakyon.from streamlit_image_comparison import image_comparison image_comparison(img1=""image1.jpg"", img2=""image2.jpg"",) Streamlit CropperA simple image cropper for Streamlit. Created by @turner-anderson.from streamlit_cropper import st_cropper st_cropper(img, realtime_update=realtime_update, box_color=box_color, aspect_ratio=aspect_ratio) Image CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates streamlit_image_coordinates(""https://placekitten.com/200/300"") Streamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl(""https://assets5.lottiefiles.com/packages/lf20_V9t630.json"") st_lottie(lottie_hello, key=""hello"") Streamlit WebrtcHandling and transmitting real-time video/audio streams with Streamlit. Created by @whitphx.from streamlit_webrtc import webrtc_streamer webrtc_streamer(key=""sample"") Drawable CanvasProvides a sketching canvas using Fabric.js. Created by @andfanilo.from streamlit_drawable_canvas import st_canvas st_canvas(fill_color=""rgba(255, 165, 0, 0.3)"", stroke_width=stroke_width, stroke_color=stroke_color, background_color=bg_color, background_image=Image.open(bg_image) if bg_image else None, update_streamlit=realtime_update, height=150, drawing_mode=drawing_mode, point_display_radius=point_display_radius if drawing_mode == 'point' else 0, key=""canvas"",) Image ComparisonCompare images with a slider using JuxtaposeJS. Created by @fcakyon.from streamlit_image_comparison import image_comparison image_comparison(img1=""image1.jpg"", img2=""image2.jpg"",) Streamlit CropperA simple image cropper for Streamlit. Created by @turner-anderson.from streamlit_cropper import st_cropper st_cropper(img, realtime_update=realtime_update, box_color=box_color, aspect_ratio=aspect_ratio) Image CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates streamlit_image_coordinates(""https://placekitten.com/200/300"") Streamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl(""https://assets5.lottiefiles.com/packages/lf20_V9t630.json"") st_lottie(lottie_hello, key=""hello"") Next Layouts and containers ColumnsInsert containers laid out as side-by-side columns.col1, col2 = st.columns(2) col1.write(""this is column 1"") col2.write(""this is column 2"") ContainerInsert a multi-element container.c = st.container() st.write(""This will show last"") c.write(""This will show first"") c.write(""This will show second"") Modal dialogsInsert a modal dialog that can rerun independently from the rest of the script.@st.experimental_dialog(""Sign up"") def email_form(): name = st.text_input(""Name"") email = st.text_input(""Email"") EmptyInsert a single-element container.c = st.empty() st.write(""This will show last"") c.write(""This will be replaced"") c.write(""This will show first"") ExpanderInsert a multi-element container that can be expanded/collapsed.with st.expander(""Open to see more""): st.write(""This is more content"") PopoverInsert a multi-element popover container that can be opened/closed.with st.popover(""Settings""): st.checkbox(""Show completed"") SidebarDisplay items in a sidebar.st.sidebar.write(""This lives in the sidebar"") st.sidebar.button(""Click me!"") TabsInsert containers separated into tabs.tab1, tab2 = st.tabs([""Tab 1"", ""Tab2""]) tab1.write(""this is tab 1"") tab2.write(""this is tab 2"") Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration!Streamlit ElementsCreate a draggable and resizable dashboard in Streamlit. Created by @okls.from streamlit_elements import elements, mui, html with elements(""new_element""): mui.Typography(""Hello world"") PydanticAuto-generate Streamlit UI from Pydantic Models and Dataclasses. Created by @lukasmasuch.import streamlit_pydantic as sp sp.pydantic_form(key=""my_form"", model=ExampleModel) Streamlit PagesAn experimental version of Streamlit Multi-Page Apps. Created by @blackary.from st_pages import Page, show_pages, add_page_title show_pages([ Page(""streamlit_app.py"", ""Home"", ""🏠""), Page(""other_pages/page2.py"", ""Page 2"", "":books:""), ]) Chat elements Streamlit provides a few commands to help you build conversational apps. These chat elements are designed to be used in conjunction with each other, but you can also use them separately. st.chat_message lets you insert a chat message container into the app so you can display messages from the user or the app. Chat containers can contain other Streamlit elements, including charts, tables, text, and more. st.chat_input lets you display a chat input widget so the user can type in a message. Chat inputDisplay a chat input widget.prompt = st.chat_input(""Say something"") if prompt: st.write(f""The user has sent: {prompt}"") Chat messageInsert a chat message container.import numpy as np with st.chat_message(""user""): st.write(""Hello 👋"") st.line_chart(np.random.randn(30, 3)) Status containerDisplay output of long-running tasks in a container.with st.status('Running'): do_something_slow() st.write_streamWrite generators or streams to the app with a typewriter effect.st.write_stream(my_generator) st.write_stream(my_llm_stream) Status elements Progress barDisplay a progress bar.for i in range(101): st.progress(i) do_something_slow() SpinnerTemporarily displays a message while executing a block of code.with st.spinner(""Please wait...""): do_something_slow() Status containerDisplay output of long-running tasks in a container.with st.status('Running'): do_something_slow() ToastBriefly displays a toast message in the bottom-right corner.st.toast('Butter!', icon='🧈') BalloonsDisplay celebratory balloons!do_something() # Celebrate when all done! st.balloons() SnowflakesDisplay celebratory snowflakes!do_something() # Celebrate when all done! st.snow() Success boxDisplay a success message.st.success(""Match found!"") Info boxDisplay an informational message.st.info(""Dataset is updated every day at midnight."") Warning boxDisplay warning message.st.warning(""Unable to fetch image. Skipping..."") Error boxDisplay error message.st.error(""We encountered an error"") Exception outputDisplay an exception.e = RuntimeError(""This is an exception of type RuntimeError"") st.exception(e) Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration!StqdmThe simplest way to handle a progress bar in streamlit app. Created by @Wirg.from stqdm import stqdm for _ in stqdm(range(50)): sleep(0.5) Custom notification boxA custom notification box with the ability to close it out. Created by @Socvest.from streamlit_custom_notification_box import custom_notification_box styles = {'material-icons':{'color': 'red'}, 'text-icon-link-close-container': {'box-shadow': '#3896de 0px 4px'}, 'notification-text': {'':''}, 'close-button':{'':''}, 'link':{'':''}} custom_notification_box(icon='info', textDisplay='We are almost done with your registration...', externalLink='more info', url='#', styles=styles, key=""foo"") Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.let_it_rain import rain rain(emoji=""🎈"", font_size=54, falling_speed=5, animation_length=""infinite"",) App logic and configuration Navigation and pages Switch pageProgrammatically navigates to a specified page.st.switch_page(""pages/my_page.py"") Page linkDisplay a link to another page in a multipage app.st.page_link(""app.py"", label=""Home"", icon=""🏠"") st.page_link(""pages/profile.py"", label=""My profile"") Execution flow Modal dialogsInsert a modal dialog that can rerun independently from the rest of the script.@st.experimental_dialog(""Sign up"") def email_form(): name = st.text_input(""Name"") email = st.text_input(""Email"") FormsCreate a form that batches elements together with a “Submit"" button.with st.form(key='my_form'): name = st.text_input(""Name"") email = st.text_input(""Email"") st.form_submit_button(""Sign up"") Partial rerunsDefine a fragment to rerun independently from the rest of the script.@st.experimental_fragment(run_every=""10s"") def fragment(): df = get_data() st.line_chart(df) Rerun scriptRerun the script immediately.st.rerun() Stop executionStops execution immediately.st.stop() Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration!AutorefreshForce a refresh without tying up a script. Created by @kmcgrady.from streamlit_autorefresh import st_autorefresh st_autorefresh(interval=2000, limit=100, key=""fizzbuzzcounter"") PydanticAuto-generate Streamlit UI from Pydantic Models and Dataclasses. Created by @lukasmasuch.import streamlit_pydantic as sp sp.pydantic_form(key=""my_form"", model=ExampleModel) Streamlit PagesAn experimental version of Streamlit Multi-Page Apps. Created by @blackary.from st_pages import Page, show_pages, add_page_title show_pages([ Page(""streamlit_app.py"", ""Home"", ""🏠""), Page(""other_pages/page2.py"", ""Page 2"", "":books:""), ]) Caching and state Cache dataFunction decorator to cache functions that return data (e.g. dataframe transforms, database queries, ML inference).@st.cache_data def long_function(param1, param2): # Perform expensive computation here or # fetch data from the web here return data Cache resourceFunction decorator to cache functions that return global resources (e.g. database connections, ML models).@st.cache_resource def init_model(): # Return a global resource here return pipeline( ""sentiment-analysis"", model=""distilbert-base-uncased-finetuned-sst-2-english"" ) Session stateSession state is a way to share variables between reruns, for each user session.st.session_state['key'] = value Query parametersGet, set, or clear the query parameters that are shown in the browser's URL bar.st.query_params[key] = value st.query_params.clear() Connections and databases Setup your connection Create a connectionConnect to a data source or APIconn = st.connection('pets_db', type='sql') pet_owners = conn.query('select * from pet_owners') st.dataframe(pet_owners) Built-in connections SnowflakeConnectionA connection to Snowflake.conn = st.connection('snowflake') SQLConnectionA connection to a SQL database using SQLAlchemy.conn = st.connection('sql') Build your own connections Connection base classBuild your own connection with BaseConnection.class MyConnection(BaseConnection[myconn.MyConnection]): def _connect(self, **kwargs) -> MyConnection: return myconn.connect(**self._secrets, **kwargs) def query(self, query): return self._instance.query(query) Secrets management Secrets singletonAccess secrets from a local TOML file.key = st.secrets[""OpenAI_key""] Secrets fileSave your secrets in a per-project or per-profile TOML file.OpenAI_key = """" Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration!AuthenticatorA secure authentication module to validate user credentials. Created by @mkhorasani.import streamlit_authenticator as stauth authenticator = stauth.Authenticate( config['credentials'], config['cookie']['name'], config['cookie']['key'], config['cookie']['expiry_days'], config['preauthorized']) WS localStorageA simple synchronous way of accessing localStorage from your app. Created by @gagangoku.from streamlit_ws_localstorage import injectWebsocketCode ret = conn.setLocalStorageVal(key='k1', val='v1') st.write('ret: ' + ret) Streamlit Auth0The fastest way to provide comprehensive login inside Streamlit. Created by @conradbez.from auth0_component import login_button user_info = login_button(clientId, domain = domain) st.write(user_info) Custom Components Declare a componentCreate and register a custom component.st.components.v1.declare_component( ""custom_slider"", ""/frontend"", ) HTMLDisplay an HTML string in an iframe.st.components.v1.html( ""

Foo bar.

"" ) iframeLoad a remote URL in an iframe.st.components.v1.iframe( ""docs.streamlit.io"" ) Utilities and user info User infost.experimental_user returns information about the logged-in user of private apps on Streamlit Community Cloud.if st.experimental_user.email == ""foo@corp.com"": st.write(""Welcome back, "", st.experimental_user.email) else: st.write(""You are not authorized to view this page."") Get helpDisplay object’s doc string, nicely formatted.st.help(st.write) st.help(pd.DataFrame) Render HTMLRenders HTML strings to your app.css = """""" """""" st.html(css) Configuration Configuration fileConfigures the default settings for your app.your-project/ ├── .streamlit/ │ └── config.toml └── your_app.py Set page title, favicon, and moreConfigures the default settings of the page.st.set_page_config( page_title=""My app"", page_icon="":shark:"", ) Developer tools App testing st.testing.v1.AppTestst.testing.v1.AppTest simulates a running Streamlit app for testing.from streamlit.testing.v1 import AppTest at = AppTest.from_file(""streamlit_app.py"") at.secrets[""WORD""] = ""Foobar"" at.run() assert not at.exception at.text_input(""word"").input(""Bazbat"").run() assert at.warning[0].value == ""Try again."" AppTest.from_filest.testing.v1.AppTest.from_file initializes a simulated app from a file.from streamlit.testing.v1 import AppTest at = AppTest.from_file(""streamlit_app.py"") at.run() AppTest.from_stringst.testing.v1.AppTest.from_string initializes a simulated app from a string.from streamlit.testing.v1 import AppTest at = AppTest.from_string(app_script_as_string) at.run() AppTest.from_functionst.testing.v1.AppTest.from_function initializes a simulated app from a function.from streamlit.testing.v1 import AppTest at = AppTest.from_function(app_script_as_callable) at.run() BlockA representation of container elements, including: st.chat_message st.columns st.sidebar st.tabs The main body of the app. # at.sidebar returns a Block at.sidebar.button[0].click().run() assert not at.exception ElementThe base class for representation of all elements, including: st.title st.header st.markdown st.dataframe # at.title returns a sequence of Title # Title inherits from Element assert at.title[0].value == ""My awesome app"" ButtonA representation of st.button and st.form_submit_button.at.button[0].click().run() ChatInputA representation of st.chat_input.at.chat_input[0].set_value(""What is Streamlit?"").run() CheckboxA representation of st.checkbox.at.checkbox[0].check().run() ColorPickerA representation of st.color_picker.at.color_picker[0].pick(""#FF4B4B"").run() DateInputA representation of st.date_input.release_date = datetime.date(2023, 10, 26) at.date_input[0].set_value(release_date).run() MultiselectA representation of st.multiselect.at.multiselect[0].select(""New York"").run() NumberInputA representation of st.number_input.at.number_input[0].increment().run() RadioA representation of st.radio.at.radio[0].set_value(""New York"").run() SelectSliderA representation of st.select_slider.at.select_slider[0].set_range(""A"",""C"").run() SelectboxA representation of st.selectbox.at.selectbox[0].select(""New York"").run() SliderA representation of st.slider.at.slider[0].set_range(2,5).run() TextAreaA representation of st.text_area.at.text_area[0].input(""Streamlit is awesome!"").run() TextInputA representation of st.text_input.at.text_input[0].input(""Streamlit"").run() TimeInputA representation of st.time_input.at.time_input[0].increment().run() ToggleA representation of st.toggle.at.toggle[0].set_value(""True"").run() Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration!Pandas ProfilingPandas profiling component for Streamlit. Created by @okld.df = pd.read_csv(""https://storage.googleapis.com/tf-datasets/titanic/train.csv"") pr = df.profile_report() st_profile_report(pr) Streamlit AceAce editor component for Streamlit. Created by @okld.from streamlit_ace import st_ace content = st_ace() content Streamlit AnalyticsTrack & visualize user interactions with your streamlit app. Created by @jrieke.import streamlit_analytics with streamlit_analytics.track(): st.text_input(""Write something"") Previous: ConceptsNext: Write and magicforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy" https://docs.streamlit.io/develop/api-reference/navigation#navigation-and-pages,"DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceremovePAGE ELEMENTSWrite and magicaddText elementsaddData elementsaddChart elementsaddInput widgetsaddMedia elementsaddLayouts and containersaddChat elementsaddStatus elementsaddThird-party componentsopen_in_newAPPLICATION LOGICNavigation and pagesremovest.page_linklinkst.switch_pageExecution flowaddCaching and stateaddConnections and secretsaddCustom componentsaddUtilitiesaddConfigurationaddTOOLSApp testingaddCommand lineaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Develop/API reference/Navigation and pagesNavigation and pages Page linkDisplay a link to another page in a multipage app.st.page_link(""app.py"", label=""Home"", icon=""🏠"") st.page_link(""pages/profile.py"", label=""Profile"") Switch pageProgrammatically navigates to a specified page.st.switch_page(""pages/my_page.py"") Previous: Third-party componentsNext: st.page_linkforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy" https://docs.streamlit.io/develop/api-reference/connections/st.connection,"DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceremovePAGE ELEMENTSWrite and magicaddText elementsaddData elementsaddChart elementsaddInput widgetsaddMedia elementsaddLayouts and containersaddChat elementsaddStatus elementsaddThird-party componentsopen_in_newAPPLICATION LOGICNavigation and pagesaddExecution flowaddCaching and stateaddConnections and secretsremoveSECRETSst.secretssecrets.tomlCONNECTIONSst.connectionSnowflakeConnectionSQLConnectionBaseConnectionSnowparkConnectiondeleteCustom componentsaddUtilitiesaddConfigurationaddTOOLSApp testingaddCommand lineaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Develop/API reference/Connections and secrets/st.connectionstarTipThis page only contains the st.connection API. For a deeper dive into creating and managing data connections within Streamlit apps, read Connecting to data. st.connectionStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeCreate a new connection to a data store or API, or return an existing one. Config options, credentials, secrets, etc. for connections are taken from various sources: Any connection-specific configuration files. An app's secrets.toml files. The kwargs passed to this function. Function signature[source] st.connection(name, type=None, max_entries=None, ttl=None, **kwargs) Parameters name (str) The connection name used for secrets lookup in [connections.]. Type will be inferred from passing ""sql"", ""snowflake"", or ""snowpark"". type (str, connection class, or None) The type of connection to create. It can be a keyword (""sql"", ""snowflake"", or ""snowpark""), a path to an importable class, or an imported class reference. All classes must extend st.connections.BaseConnection and implement the _connect() method. If the type kwarg is None, a type field must be set in the connection's section in secrets.toml. max_entries (int or None) The maximum number of connections to keep in the cache, or None for an unbounded cache. (When a new entry is added to a full cache, the oldest cached entry will be removed.) The default is None. ttl (float, timedelta, or None) The maximum number of seconds to keep results in the cache, or None if cached results should not expire. The default is None. **kwargs (any) Additional connection specific kwargs that are passed to the Connection's _connect() method. Learn more from the specific Connection's documentation. Returns(Connection object) An initialized Connection object of the specified type. Examples The easiest way to create a first-party (SQL, Snowflake, or Snowpark) connection is to use their default names and define corresponding sections in your secrets.toml file. import streamlit as st conn = st.connection(""sql"") # Config section defined in [connections.sql] in secrets.toml. Creating a SQLConnection with a custom name requires you to explicitly specify the type. If type is not passed as a kwarg, it must be set in the appropriate section of secrets.toml. import streamlit as st conn1 = st.connection(""my_sql_connection"", type=""sql"") # Config section defined in [connections.my_sql_connection]. conn2 = st.connection(""my_other_sql_connection"") # type must be set in [connections.my_other_sql_connection]. Passing the full module path to the connection class that you want to use can be useful, especially when working with a custom connection: import streamlit as st conn = st.connection(""my_sql_connection"", type=""streamlit.connections.SQLConnection"") Finally, you can pass the connection class to use directly to this function. Doing so allows static type checking tools such as mypy to infer the exact return type of st.connection. import streamlit as st from streamlit.connections import SQLConnection conn = st.connection(""my_sql_connection"", type=SQLConnection) For a comprehensive overview of this feature, check out this video tutorial by Joshua Carroll, Streamlit's Product Manager for Developer Experience. You'll learn about the feature's utility in creating and managing data connections within your apps by using real-world examples. Previous: secrets.tomlNext: SnowflakeConnectionforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy" https://docs.streamlit.io/get-started/installation/anaconda-distribution#install-streamlit-in-your-environment,"DocumentationsearchSearchrocket_launchGet startedInstallationremoveUse command lineUse Anaconda DistributionUse GitHub CodespacesUse SnowflakeFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Get started/Installation/Use Anaconda DistributionInstall Streamlit using Anaconda Distribution This page walks you through installing Streamlit locally using Anaconda Distribution. At the end, you'll build a simple ""Hello world"" app and run it. You can read more about Getting started with Anaconda Distribution in Anaconda's docs. If you prefer to manage your Python environments via command line, check out how to Install Streamlit using command line. Prerequisites A code editor Anaconda Distribution includes Python and basically everything you need to get started. The only thing left for you to choose is a code editor. Our favorite editor is VS Code, which is also what we use in all our tutorials. Knowledge about environment managers Environment managers create virtual environments to isolate Python package installations between projects. For a detailed introduction to Python environments, check out Python Virtual Environments: A Primer. But don't worry! In this guide we'll teach you how to install and use an environment manager (Anaconda). Install Anaconda Distribution Go to anaconda.com/download. Install Anaconda Distribution for your OS. Create an environment using Anaconda Navigator Open Anaconda Navigator (the graphical interface included with Anaconda Distribution). You can decline signing in to Anaconda if prompted. In the left menu, click ""Environments"". At the bottom of your environments list, click ""Create"". Enter ""streamlitenv"" for the name of your environment. Click ""Create."" Activate your environment Click the green play icon (play_circle) next to your environment. Click ""Open Terminal."" A terminal will open with your environment activated. Your environment's name will appear in parentheses at the beginning of your terminal's prompt to show that it's activated. Install Streamlit in your environment In your terminal, type: pip install streamlit To validate your installation, enter: streamlit hello If this doesn't work, use the long-form command: python -m streamlit hello The Streamlit Hello example app will automatically open in your browser. If it doesn't, open your browser and go to the localhost address indicated in your terminal, typically http://localhost:8501. Play around with the app! Close your terminal. Create a Hello World app and run it Open VS Code with a new project. Create a Python file named app.py in your project folder. Copy the following code into app.py and save it. import streamlit as st st.write(""Hello World"") Click your Python interpreter in the lower-right corner, then choose your streamlitenv environment from the drop-down. Right-click app.py in your file navigation and click ""Open in integrated terminal"". A terminal will open with your environment activated. Confirm this by looking for ""(streamlitenv)"" at the beginning of your next prompt. If it is not there, manually activate your environment with the command: conda activate streamlitenv In your terminal, type: streamlit run app.py If this doesn't work, use the long-form command: python -m streamlit run app.py Your app will automatically open in your browser. If it doesn't for any reason, open your browser and go to the localhost address indicated in your terminal, typically http://localhost:8501. Change st.write to st.title and save your file: import streamlit as st st.title(""Hello World"") In your browser, click ""Always rerun"" to instantly rerun your app whenever you save a change to your file. Your app will update! Keep making changes and you will see your changes as soon as you save your file. When you're done, you can stop your app with Ctrl+C in your terminal or just by closing your terminal. What's next? Read about our Basic concepts and try out more commands in your app.Previous: Use command lineNext: Use GitHub CodespacesforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy" https://docs.streamlit.io/develop/api-reference/app-testing/st.testing.v1.apptest#apptesttext_area,"DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceremovePAGE ELEMENTSWrite and magicaddText elementsaddData elementsaddChart elementsaddInput widgetsaddMedia elementsaddLayouts and containersaddChat elementsaddStatus elementsaddThird-party componentsopen_in_newAPPLICATION LOGICNavigation and pagesaddExecution flowaddCaching and stateaddConnections and secretsaddCustom componentsaddUtilitiesaddConfigurationaddTOOLSApp testingremovest.testing.v1.AppTestTesting element classesCommand lineaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Develop/API reference/App testing/st.testing.v1.AppTest The AppTest class st.testing.v1.AppTestStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA simulated Streamlit app to check the correctness of displayed elements and outputs. An instance of AppTest simulates a running Streamlit app. This class provides methods to set up, manipulate, and inspect the app contents via API instead of a browser UI. It can be used to write automated tests of an app in various scenarios. These can then be run using a tool like pytest. AppTest can be initialized by one of three class methods: st.testing.v1.AppTest.from_file (recommended) st.testing.v1.AppTest.from_string st.testing.v1.AppTest.from_function Once initialized, Session State and widget values can be updated and the script can be run. Unlike an actual live-running Streamlit app, you need to call AppTest.run() explicitly to re-run the app after changing a widget value. Switching pages also requires an explicit, follow-up call to AppTest.run(). AppTest enables developers to build tests on their app as-is, in the familiar python test format, without major refactoring or abstracting out logic to be tested separately from the UI. Tests can run quickly with very low overhead. A typical pattern is to build a suite of tests for an app that ensure consistent functionality as the app evolves, and run the tests locally and/or in a CI environment like Github Actions. Note AppTest only supports testing a single page of an app per instance. For multipage apps, each page will need to be tested separately. No methods exist to programatically switch pages within AppTest. Class description[source] st.testing.v1.AppTest(script_path, *, default_timeout, args=None, kwargs=None) Methods get(element_type) Get elements or widgets of the specified type. run(*, timeout=None) Run the script from the current state. switch_page(page_path) Switch to another page of the app. Attributes secrets (dict[str, Any]) Dictionary of secrets to be used the simulated app. Use dict-like syntax to set secret values for the simulated app. session_state (SafeSessionState) Session State for the simulated app. SafeSessionState object supports read and write operations as usual for Streamlit apps. query_params (dict[str, Any]) Dictionary of query parameters to be used by the simluated app. Use dict-like syntax to set query_params values for the simulated app. button Sequence of all st.button and st.form_submit_button widgets. caption Sequence of all st.caption elements. chat_input Sequence of all st.chat_input widgets. chat_message Sequence of all st.chat_message elements. checkbox Sequence of all st.checkbox widgets. code Sequence of all st.code elements. color_picker Sequence of all st.color_picker widgets. columns Sequence of all columns within st.columns elements. dataframe Sequence of all st.dataframe elements. date_input Sequence of all st.date_input widgets. divider Sequence of all st.divider elements. error Sequence of all st.error elements. exception Sequence of all st.exception elements. expander Sequence of all st.expander elements. header Sequence of all st.header elements. info Sequence of all st.info elements. json Sequence of all st.json elements. latex Sequence of all st.latex elements. main Sequence of elements within the main body of the app. markdown Sequence of all st.markdown elements. metric Sequence of all st.metric elements. multiselect Sequence of all st.multiselect widgets. number_input Sequence of all st.number_input widgets. radio Sequence of all st.radio widgets. select_slider Sequence of all st.select_slider widgets. selectbox Sequence of all st.selectbox widgets. sidebar Sequence of all elements within st.sidebar. slider Sequence of all st.slider widgets. status Sequence of all st.status elements. subheader Sequence of all st.subheader elements. success Sequence of all st.success elements. table Sequence of all st.table elements. tabs Sequence of all tabs within st.tabs elements. text Sequence of all st.text elements. text_area Sequence of all st.text_area widgets. text_input Sequence of all st.text_input widgets. time_input Sequence of all st.time_input widgets. title Sequence of all st.title elements. toast Sequence of all st.toast elements. toggle Sequence of all st.toggle widgets. warning Sequence of all st.warning elements. Initialize a simulated app using AppTest AppTest.from_fileStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeCreate an instance of AppTest to simulate an app page defined within a file. This option is most convenient for CI workflows and testing of published apps. The script must be executable on its own and so must contain all necessary imports. Function signature[source] AppTest.from_file(cls, script_path, *, default_timeout=3) Parameters script_path (str) Path to a script file. The path should be absolute or relative to the file calling .from_file. default_timeout (float) Default time in seconds before a script run is timed out. Can be overridden for individual .run() calls. Returns(AppTest) A simulated Streamlit app for testing. The simulated app can be executed via .run(). AppTest.from_stringStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeCreate an instance of AppTest to simulate an app page defined within a string. This is useful for testing short scripts that fit comfortably as an inline string in the test itself, without having to create a separate file for it. The script must be executable on its own and so must contain all necessary imports. Function signature[source] AppTest.from_string(cls, script, *, default_timeout=3) Parameters script (str) The string contents of the script to be run. default_timeout (float) Default time in seconds before a script run is timed out. Can be overridden for individual .run() calls. Returns(AppTest) A simulated Streamlit app for testing. The simulated app can be executed via .run(). AppTest.from_functionStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeCreate an instance of AppTest to simulate an app page defined within a function. This is similar to AppTest.from_string(), but more convenient to write with IDE assistance. The script must be executable on its own and so must contain all necessary imports. Function signature[source] AppTest.from_function(cls, script, *, default_timeout=3, args=None, kwargs=None) Parameters script (Callable) A function whose body will be used as a script. Must be runnable in isolation, so it must include any necessary imports. default_timeout (float) Default time in seconds before a script run is timed out. Can be overridden for individual .run() calls. args (tuple) An optional tuple of args to pass to the script function. kwargs (dict) An optional dict of kwargs to pass to the script function. Returns(AppTest) A simulated Streamlit app for testing. The simulated app can be executed via .run(). Run an AppTest script AppTest.runStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeRun the script from the current state. This is equivalent to manually rerunning the app or the rerun that occurs upon user interaction. AppTest.run() must be manually called after updating a widget value or switching pages as script reruns do not occur automatically as they do for live-running Streamlit apps. Function signature[source] AppTest.run(*, timeout=None) Parameters timeout (null) The maximum number of seconds to run the script. None means use the default timeout set for the instance of AppTest. Returns(AppTest) self AppTest.switch_pageStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSwitch to another page of the app. This method does not automatically rerun the app. Use a follow-up call to AppTest.run() to obtain the elements on the selected page. Function signature[source] AppTest.switch_page(page_path) Parameters page_path (str) Path of the page to switch to. The path must be relative to the main script's location (e.g. ""pages/my_page.py""). Returns(AppTest) self Get AppTest script elements The main value of AppTest is providing an API to programmatically inspect and interact with the elements and widgets produced by a running Streamlit app. Using the AppTest. properties or AppTest.get() method returns a collection of all the elements or widgets of the specified type that would have been displayed by running the app. Note that you can also retrieve elements within a specific container in the same way - first retrieve the container, then retrieve the elements just in that container. AppTest.getStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeGet elements or widgets of the specified type. This method returns the collection of all elements or widgets of the specified type on the current page. Retrieve a specific element by using its index (order on page) or key lookup. Function signature[source] AppTest.get(element_type) Parameters element_type (str) An element attribute of AppTest. For example, ""button"", ""caption"", or ""chat_input"". Returns(Sequence of Elements) Sequence of elements of the given type. Individual elements can be accessed from a Sequence by index (order on the page). When getting and element_type that is a widget, individual widgets can be accessed by key. For example, at.get(""text"")[0] for the first st.text element or at.get(""slider"")(key=""my_key"") for the st.slider widget with a given key. AppTest.buttonStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.button and st.form_submit_button widgets. Function signature[source] AppTest.button Returns(WidgetList of Button) Sequence of all st.button and st.form_submit_button widgets. Individual widgets can be accessed from a WidgetList by index (order on the page) or key. For example, at.button[0] for the first widget or at.button(key=""my_key"") for a widget with a given key. AppTest.captionStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.caption elements. Function signature[source] AppTest.caption Returns(ElementList of Caption) Sequence of all st.caption elements. Individual elements can be accessed from an ElementList by index (order on the page). For example, at.caption[0] for the first element. Caption is an extension of the Element class. AppTest.chat_inputStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.chat_input widgets. Function signature[source] AppTest.chat_input Returns(WidgetList of ChatInput) Sequence of all st.chat_input widgets. Individual widgets can be accessed from a WidgetList by index (order on the page) or key. For example, at.chat_input[0] for the first widget or at.chat_input(key=""my_key"") for a widget with a given key. AppTest.chat_messageStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.chat_message elements. Function signature[source] AppTest.chat_message Returns(Sequence of ChatMessage) Sequence of all st.chat_message elements. Individual elements can be accessed from an ElementList by index (order on the page). For example, at.chat_message[0] for the first element. ChatMessage is an extension of the Block class. AppTest.checkboxStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.checkbox widgets. Function signature[source] AppTest.checkbox Returns(WidgetList of Checkbox) Sequence of all st.checkbox widgets. Individual widgets can be accessed from a WidgetList by index (order on the page) or key. For example, at.checkbox[0] for the first widget or at.checkbox(key=""my_key"") for a widget with a given key. AppTest.codeStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.code elements. Function signature[source] AppTest.code Returns(ElementList of Code) Sequence of all st.code elements. Individual elements can be accessed from an ElementList by index (order on the page). For example, at.code[0] for the first element. Code is an extension of the Element class. AppTest.color_pickerStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.color_picker widgets. Function signature[source] AppTest.color_picker Returns(WidgetList of ColorPicker) Sequence of all st.color_picker widgets. Individual widgets can be accessed from a WidgetList by index (order on the page) or key. For example, at.color_picker[0] for the first widget or at.color_picker(key=""my_key"") for a widget with a given key. AppTest.columnsStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all columns within st.columns elements. Each column within a single st.columns will be returned as a separate Column in the Sequence. Function signature[source] AppTest.columns Returns(Sequence of Column) Sequence of all columns within st.columns elements. Individual columns can be accessed from an ElementList by index (order on the page). For example, at.columns[0] for the first column. Column is an extension of the Block class. AppTest.dataframeStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.dataframe elements. Function signature[source] AppTest.dataframe Returns(ElementList of Dataframe) Sequence of all st.dataframe elements. Individual elements can be accessed from an ElementList by index (order on the page). For example, at.dataframe[0] for the first element. Dataframe is an extension of the Element class. AppTest.date_inputStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.date_input widgets. Function signature[source] AppTest.date_input Returns(WidgetList of DateInput) Sequence of all st.date_input widgets. Individual widgets can be accessed from a WidgetList by index (order on the page) or key. For example, at.date_input[0] for the first widget or at.date_input(key=""my_key"") for a widget with a given key. AppTest.dividerStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.divider elements. Function signature[source] AppTest.divider Returns(ElementList of Divider) Sequence of all st.divider elements. Individual elements can be accessed from an ElementList by index (order on the page). For example, at.divider[0] for the first element. Divider is an extension of the Element class. AppTest.errorStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.error elements. Function signature[source] AppTest.error Returns(ElementList of Error) Sequence of all st.error elements. Individual elements can be accessed from an ElementList by index (order on the page). For example, at.error[0] for the first element. Error is an extension of the Element class. AppTest.exceptionStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.exception elements. Function signature[source] AppTest.exception Returns(ElementList of Exception) Sequence of all st.exception elements. Individual elements can be accessed from an ElementList by index (order on the page). For example, at.exception[0] for the first element. Exception is an extension of the Element class. AppTest.expanderStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.expander elements. Function signature[source] AppTest.expander Returns(Sequence of Expandable) Sequence of all st.expander elements. Individual elements can be accessed from a Sequence by index (order on the page). For example, at.expander[0] for the first element. Expandable is an extension of the Block class. AppTest.headerStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.header elements. Function signature[source] AppTest.header Returns(ElementList of Header) Sequence of all st.header elements. Individual elements can be accessed from an ElementList by index (order on the page). For example, at.header[0] for the first element. Header is an extension of the Element class. AppTest.infoStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.info elements. Function signature[source] AppTest.info Returns(ElementList of Info) Sequence of all st.info elements. Individual elements can be accessed from an ElementList by index (order on the page). For example, at.info[0] for the first element. Info is an extension of the Element class. AppTest.jsonStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.json elements. Function signature[source] AppTest.json Returns(ElementList of Json) Sequence of all st.json elements. Individual elements can be accessed from an ElementList by index (order on the page). For example, at.json[0] for the first element. Json is an extension of the Element class. AppTest.latexStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.latex elements. Function signature[source] AppTest.latex Returns(ElementList of Latex) Sequence of all st.latex elements. Individual elements can be accessed from an ElementList by index (order on the page). For example, at.latex[0] for the first element. Latex is an extension of the Element class. AppTest.mainStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of elements within the main body of the app. Function signature[source] AppTest.main Returns(Block) A container of elements. Block can be queried for elements in the same manner as AppTest. For example, Block.checkbox will return all st.checkbox within the associated container. AppTest.markdownStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.markdown elements. Function signature[source] AppTest.markdown Returns(ElementList of Markdown) Sequence of all st.markdown elements. Individual elements can be accessed from an ElementList by index (order on the page). For example, at.markdown[0] for the first element. Markdown is an extension of the Element class. AppTest.metricStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.metric elements. Function signature[source] AppTest.metric Returns(ElementList of Metric) Sequence of all st.metric elements. Individual elements can be accessed from an ElementList by index (order on the page). For example, at.metric[0] for the first element. Metric is an extension of the Element class. AppTest.multiselectStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.multiselect widgets. Function signature[source] AppTest.multiselect Returns(WidgetList of Multiselect) Sequence of all st.multiselect widgets. Individual widgets can be accessed from a WidgetList by index (order on the page) or key. For example, at.multiselect[0] for the first widget or at.multiselect(key=""my_key"") for a widget with a given key. AppTest.number_inputStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.number_input widgets. Function signature[source] AppTest.number_input Returns(WidgetList of NumberInput) Sequence of all st.number_input widgets. Individual widgets can be accessed from a WidgetList by index (order on the page) or key. For example, at.number_input[0] for the first widget or at.number_input(key=""my_key"") for a widget with a given key. AppTest.radioStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.radio widgets. Function signature[source] AppTest.radio Returns(WidgetList of Radio) Sequence of all st.radio widgets. Individual widgets can be accessed from a WidgetList by index (order on the page) or key. For example, at.radio[0] for the first widget or at.radio(key=""my_key"") for a widget with a given key. AppTest.select_sliderStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.select_slider widgets. Function signature[source] AppTest.select_slider Returns(WidgetList of SelectSlider) Sequence of all st.select_slider widgets. Individual widgets can be accessed from a WidgetList by index (order on the page) or key. For example, at.select_slider[0] for the first widget or at.select_slider(key=""my_key"") for a widget with a given key. AppTest.selectboxStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.selectbox widgets. Function signature[source] AppTest.selectbox Returns(WidgetList of Selectbox) Sequence of all st.selectbox widgets. Individual widgets can be accessed from a WidgetList by index (order on the page) or key. For example, at.selectbox[0] for the first widget or at.selectbox(key=""my_key"") for a widget with a given key. AppTest.sidebarStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all elements within st.sidebar. Function signature[source] AppTest.sidebar Returns(Block) A container of elements. Block can be queried for elements in the same manner as AppTest. For example, Block.checkbox will return all st.checkbox within the associated container. AppTest.sliderStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.slider widgets. Function signature[source] AppTest.slider Returns(WidgetList of Slider) Sequence of all st.slider widgets. Individual widgets can be accessed from a WidgetList by index (order on the page) or key. For example, at.slider[0] for the first widget or at.slider(key=""my_key"") for a widget with a given key. AppTest.subheaderStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.subheader elements. Function signature[source] AppTest.subheader Returns(ElementList of Subheader) Sequence of all st.subheader elements. Individual elements can be accessed from an ElementList by index (order on the page). For example, at.subheader[0] for the first element. Subheader is an extension of the Element class. AppTest.successStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.success elements. Function signature[source] AppTest.success Returns(ElementList of Success) Sequence of all st.success elements. Individual elements can be accessed from an ElementList by index (order on the page). For example, at.success[0] for the first element. Success is an extension of the Element class. AppTest.statusStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.status elements. Function signature[source] AppTest.status Returns(Sequence of Status) Sequence of all st.status elements. Individual elements can be accessed from a Sequence by index (order on the page). For example, at.status[0] for the first element. Status is an extension of the Block class. AppTest.tableStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.table elements. Function signature[source] AppTest.table Returns(ElementList of Table) Sequence of all st.table elements. Individual elements can be accessed from an ElementList by index (order on the page). For example, at.table[0] for the first element. Table is an extension of the Element class. AppTest.tabsStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all tabs within st.tabs elements. Each tab within a single st.tabs will be returned as a separate Tab in the Sequence. Additionally, the tab labels are forwarded to each Tab element as a property. For example, st.tabs(""A"",""B"") will yield two Tab objects, with Tab.label returning ""A"" and ""B"", respectively. Function signature[source] AppTest.tabs Returns(Sequence of Tab) Sequence of all tabs within st.tabs elements. Individual tabs can be accessed from an ElementList by index (order on the page). For example, at.tabs[0] for the first tab. Tab is an extension of the Block class. AppTest.textStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.text elements. Function signature[source] AppTest.text Returns(ElementList of Text) Sequence of all st.text elements. Individual elements can be accessed from an ElementList by index (order on the page). For example, at.text[0] for the first element. Text is an extension of the Element class. AppTest.text_areaStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.text_area widgets. Function signature[source] AppTest.text_area Returns(WidgetList of TextArea) Sequence of all st.text_area widgets. Individual widgets can be accessed from a WidgetList by index (order on the page) or key. For example, at.text_area[0] for the first widget or at.text_area(key=""my_key"") for a widget with a given key. AppTest.text_inputStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.text_input widgets. Function signature[source] AppTest.text_input Returns(WidgetList of TextInput) Sequence of all st.text_input widgets. Individual widgets can be accessed from a WidgetList by index (order on the page) or key. For example, at.text_input[0] for the first widget or at.text_input(key=""my_key"") for a widget with a given key. AppTest.time_inputStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.time_input widgets. Function signature[source] AppTest.time_input Returns(WidgetList of TimeInput) Sequence of all st.time_input widgets. Individual widgets can be accessed from a WidgetList by index (order on the page) or key. For example, at.time_input[0] for the first widget or at.time_input(key=""my_key"") for a widget with a given key. AppTest.titleStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.title elements. Function signature[source] AppTest.title Returns(ElementList of Title) Sequence of all st.title elements. Individual elements can be accessed from an ElementList by index (order on the page). For example, at.title[0] for the first element. Title is an extension of the Element class. AppTest.toastStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.toast elements. Function signature[source] AppTest.toast Returns(ElementList of Toast) Sequence of all st.toast elements. Individual elements can be accessed from an ElementList by index (order on the page). For example, at.toast[0] for the first element. Toast is an extension of the Element class. AppTest.toggleStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.toggle widgets. Function signature[source] AppTest.toggle Returns(WidgetList of Toggle) Sequence of all st.toggle widgets. Individual widgets can be accessed from a WidgetList by index (order on the page) or key. For example, at.toggle[0] for the first widget or at.toggle(key=""my_key"") for a widget with a given key. AppTest.warningStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.warning elements. Function signature[source] AppTest.warning Returns(ElementList of Warning) Sequence of all st.warning elements. Individual elements can be accessed from an ElementList by index (order on the page). For example, at.warning[0] for the first element. Warning is an extension of the Element class. Previous: App testingNext: Testing element classesforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy" https://docs.streamlit.io/develop/api-reference/app-testing/testing-element-classes#buttonclick,"DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceremovePAGE ELEMENTSWrite and magicaddText elementsaddData elementsaddChart elementsaddInput widgetsaddMedia elementsaddLayouts and containersaddChat elementsaddStatus elementsaddThird-party componentsopen_in_newAPPLICATION LOGICNavigation and pagesaddExecution flowaddCaching and stateaddConnections and secretsaddCustom componentsaddUtilitiesaddConfigurationaddTOOLSApp testingremovest.testing.v1.AppTestTesting element classesCommand lineaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Develop/API reference/App testing/Testing element classesTesting element classes st.testing.v1.element_tree.Block The Block class has the same methods and attributes as AppTest. A Block instance represents a container of elements just as AppTest represents the entire app. For example, Block.button will produce a WidgetList of Button in the same manner as AppTest.button. ChatMessage, Column, and Tab all inherit from Block. For all container classes, parameters of the original element can be obtained as properties. For example, ChatMessage.avatar and Tab.label. st.testing.v1.element_tree.ElementStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeElement base class for testing. This class's methods and attributes are universal for all elements implemented in testing. For example, Caption, Code, Text, and Title inherit from Element. All widget classes also inherit from Element, but have additional methods specific to each widget type. See the AppTest class for the full list of supported elements. For all element classes, parameters of the original element can be obtained as properties. For example, Button.label, Caption.help, and Toast.icon. Class description[source] st.testing.v1.element_tree.Element(proto, root) Methods run(*, timeout=None) Run the AppTest script which contains the element. Attributes value The value or contents of the element. st.testing.v1.element_tree.ButtonStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.button and st.form_submit_button. Class description[source] st.testing.v1.element_tree.Button(proto, root) Methods click() Set the value of the button to True. run(*, timeout=None) Run the AppTest script which contains the element. set_value(v) Set the value of the button. Attributes value The value of the button. (bool) st.testing.v1.element_tree.ChatInputStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.chat_input. Class description[source] st.testing.v1.element_tree.ChatInput(proto, root) Methods run(*, timeout=None) Run the AppTest script which contains the element. set_value(v) Set the value of the widget. Attributes value The value of the widget. (str) st.testing.v1.element_tree.CheckboxStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.checkbox. Class description[source] st.testing.v1.element_tree.Checkbox(proto, root) Methods check() Set the value of the widget to True. run(*, timeout=None) Run the AppTest script which contains the element. set_value(v) Set the value of the widget. uncheck() Set the value of the widget to False. Attributes value The value of the widget. (bool) st.testing.v1.element_tree.ColorPickerStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.color_picker. Class description[source] st.testing.v1.element_tree.ColorPicker(proto, root) Methods pick(v) Set the value of the widget as a hex string. May omit the ""#"" prefix. run(*, timeout=None) Run the AppTest script which contains the element. set_value(v) Set the value of the widget as a hex string. Attributes value The currently selected value as a hex string. (str) st.testing.v1.element_tree.DateInputStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.date_input. Class description[source] st.testing.v1.element_tree.DateInput(proto, root) Methods run(*, timeout=None) Run the AppTest script which contains the element. set_value(v) Set the value of the widget. Attributes value The value of the widget. (date or Tuple of date) st.testing.v1.element_tree.MultiselectStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.multiselect. Class description[source] st.testing.v1.element_tree.Multiselect(proto, root) Methods run(*, timeout=None) Run the AppTest script which contains the element. select(v) Add a selection to the widget. Do nothing if the value is already selected. If testing a multiselect widget with repeated options, use set_value instead. set_value(v) Set the value of the multiselect widget. (list) unselect(v) Remove a selection from the widget. Do nothing if the value is not already selected. If a value is selected multiple times, the first instance is removed. Attributes format_func The widget's formatting function for displaying options. (callable) indices The indices of the currently selected values from the options. (list) value The currently selected values from the options. (list) st.testing.v1.element_tree.NumberInputStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.number_input. Class description[source] st.testing.v1.element_tree.NumberInput(proto, root) Methods decrement() Decrement the st.number_input widget as if the user clicked ""-"". increment() Increment the st.number_input widget as if the user clicked ""+"". run(*, timeout=None) Run the AppTest script which contains the element. set_value(v) Set the value of the st.number_input widget. Attributes value Get the current value of the st.number_input widget. st.testing.v1.element_tree.RadioStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.radio. Class description[source] st.testing.v1.element_tree.Radio(proto, root) Methods run(*, timeout=None) Run the AppTest script which contains the element. set_value(v) Set the selection by value. Attributes format_func The widget's formatting function for displaying options. (callable) index The index of the current selection. (int) value The currently selected value from the options. (Any) st.testing.v1.element_tree.SelectSliderStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.select_slider. Class description[source] st.testing.v1.element_tree.SelectSlider(proto, root) Methods run(*, timeout=None) Run the AppTest script which contains the element. set_range(lower, upper) Set the ranged selection by values. set_value(v) Set the (single) selection by value. Attributes format_func The widget's formatting function for displaying options. (callable) value The currently selected value or range. (Any or Sequence of Any) st.testing.v1.element_tree.SelectboxStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.selectbox. Class description[source] st.testing.v1.element_tree.Selectbox(proto, root) Methods run(*, timeout=None) Run the AppTest script which contains the element. select(v) Set the selection by value. select_index(index) Set the selection by index. set_value(v) Set the selection by value. Attributes format_func The widget's formatting function for displaying options. (callable) index The index of the current selection. (int) value The currently selected value from the options. (Any) st.testing.v1.element_tree.SliderStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.slider. Class description[source] st.testing.v1.element_tree.Slider(proto, root) Methods run(*, timeout=None) Run the AppTest script which contains the element. set_range(lower, upper) Set the ranged value of the slider. set_value(v) Set the (single) value of the slider. Attributes value The currently selected value or range. (Any or Sequence of Any) st.testing.v1.element_tree.TextAreaStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.text_area. Class description[source] st.testing.v1.element_tree.TextArea(proto, root) Methods input(v) Set the value of the widget only if the value does not exceed the maximum allowed characters. run(*, timeout=None) Run the AppTest script which contains the element. set_value(v) Set the value of the widget. Attributes value The current value of the widget. (str) st.testing.v1.element_tree.TextInputStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.text_input. Class description[source] st.testing.v1.element_tree.TextInput(proto, root) Methods input(v) Set the value of the widget only if the value does not exceed the maximum allowed characters. run(*, timeout=None) Run the AppTest script which contains the element. set_value(v) Set the value of the widget. Attributes value The current value of the widget. (str) st.testing.v1.element_tree.TimeInputStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.time_input. Class description[source] st.testing.v1.element_tree.TimeInput(proto, root) Methods decrement() Select the previous available time. increment() Select the next available time. run(*, timeout=None) Run the AppTest script which contains the element. set_value(v) Set the value of the widget. Attributes value The current value of the widget. (time) st.testing.v1.element_tree.ToggleStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.toggle. Class description[source] st.testing.v1.element_tree.Toggle(proto, root) Methods run(*, timeout=None) Run the AppTest script which contains the element. set_value(v) Set the value of the widget. Attributes value The current value of the widget. (bool) Previous: st.testing.v1.AppTestNext: Command lineforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy" https://docs.streamlit.io/develop/tutorials/databases/private-gsheet#enable-the-sheets-api,"DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceaddTutorialsremoveExecution flowaddConnect to data sourcesremoveAWS S3BigQueryDeta BaseFirestoreopen_in_newGoogle Cloud StorageMicrosoft SQL ServerMongoDBMySQLNeonPostgreSQLPrivate Google SheetPublic Google SheetSnowflakeSupabaseTableauTiDBTigerGraphMultipage appsaddWork with LLMsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Develop/Tutorials/Connect to data sources/Private Google SheetConnect Streamlit to a private Google Sheet Introduction This guide explains how to securely access a private Google Sheet from Streamlit Community Cloud. It uses st.connection, Streamlit GSheetsConnection, and Streamlit's Secrets management. If you are fine with enabling link sharing for your Google Sheet (i.e. everyone with the link can view it), the guide Connect Streamlit to a public Google Sheet shows a simpler method of doing this. If your Sheet contains sensitive information and you cannot enable link sharing, keep on reading. Prerequisites This tutorial requires streamlit>=1.28 and st-gsheets-connection in your Python environment. Create a Google Sheet If you already have a Sheet that you want to use, feel free to skip to the next step. Create a spreadsheet with this example data. namepetMarydogJohncatRobertbird Enable the Sheets API Programmatic access to Google Sheets is controlled through Google Cloud Platform. Create an account or sign in and head over to the APIs & Services dashboard (select or create a project if asked). As shown below, search for the Sheets API and enable it: Create a service account & key file To use the Sheets API from Streamlit Community Cloud, you need a Google Cloud Platform service account (a special account type for programmatic data access). Go to the Service Accounts page and create an account with the Viewer permission (this will let the account access data but not change it): push_pinNoteThe button ""CREATE SERVICE ACCOUNT"" is gray, you don't have the correct permissions. Ask the admin of your Google Cloud project for help. After clicking ""DONE"", you should be back on the service accounts overview. First, note down the email address of the account you just created (important for next step!). Then, create a JSON key file for the new account and download it: Share the Google Sheet with the service account By default, the service account you just created cannot access your Google Sheet. To give it access, click on the ""Share"" button in the Google Sheet, add the email of the service account (noted down in step 2), and choose the correct permission (if you just want to read the data, ""Viewer"" is enough): Add the key file to your local app secrets Your local Streamlit app will read secrets from a file .streamlit/secrets.toml in your app's root directory. Create this file if it doesn't exist yet and add the URL of your Google Sheet plus the content of the key file you downloaded to it as shown below: # .streamlit/secrets.toml [connections.gsheets] spreadsheet = ""https://docs.google.com/spreadsheets/d/xxxxxxx/edit#gid=0"" # From your JSON key file type = ""service_account"" project_id = ""xxx"" private_key_id = ""xxx"" private_key = ""xxx"" client_email = ""xxx"" client_id = ""xxx"" auth_uri = ""https://accounts.google.com/o/oauth2/auth"" token_uri = ""https://oauth2.googleapis.com/token"" auth_provider_x509_cert_url = ""https://www.googleapis.com/oauth2/v1/certs"" client_x509_cert_url = ""xxx"" priority_highImportantAdd this file to .gitignore and don't commit it to your GitHub repo! Write your Streamlit app Copy the code below to your Streamlit app and run it. # streamlit_app.py import streamlit as st from streamlit_gsheets import GSheetsConnection # Create a connection object. conn = st.connection(""gsheets"", type=GSheetsConnection) df = conn.read() # Print results. for row in df.itertuples(): st.write(f""{row.name} has a :{row.pet}:"") See st.connection above? This handles secrets retrieval, setup, query caching and retries. By default, .read() results are cached without expiring. You can pass optional parameters to .read() to customize your connection. For example, you can specify the name of a worksheet, cache expiration time, or pass-through parameters for pandas.read_csv like this: df = conn.read( worksheet=""Sheet1"", ttl=""10m"", usecols=[0, 1], nrows=3, ) In this case, we set ttl=""10m"" to ensure the query result is cached for no longer than 10 minutes. You can also set ttl=0 to disable caching. Learn more in Caching. We've declared optional parameters usecols=[0,1] and nrows=3 for pandas to use under the hood. If everything worked out (and you used the example table we created above), your app should look like this: Connecting to a Google Sheet from Community Cloud This tutorial assumes a local Streamlit app, however you can also connect to Google Sheets from apps hosted in Community Cloud. The main additional steps are: Include information about dependencies using a requirements.txt file with st-gsheets-connection and any other dependencies. Add your secrets to your Community Cloud app. Previous: PostgreSQLNext: Public Google SheetforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy" https://docs.streamlit.io/develop/api-reference/execution-flow,"DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceremovePAGE ELEMENTSWrite and magicaddText elementsaddData elementsaddChart elementsaddInput widgetsaddMedia elementsaddLayouts and containersaddChat elementsaddStatus elementsaddThird-party componentsopen_in_newAPPLICATION LOGICNavigation and pagesaddExecution flowremovest.dialogst.formst.form_submit_buttonst.fragmentst.rerunst.stopCaching and stateaddConnections and secretsaddCustom componentsaddUtilitiesaddConfigurationaddTOOLSApp testingaddCommand lineaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Develop/API reference/Execution flowExecution flow Change execution By default, Streamlit apps execute the script entirely, but we allow some functionality to handle control flow in your applications. Modal dialogsInsert a modal dialog that can rerun independently from the rest of the script.@st.experimental_dialog(""Sign up"") def email_form(): name = st.text_input(""Name"") email = st.text_input(""Email"") Partial rerunsDefine a fragment to rerun independently from the rest of the script.@st.experimental_fragment(run_every=""10s"") def fragment(): df = get_data() st.line_chart(df) Rerun scriptRerun the script immediately.st.rerun() Stop executionStops execution immediately.st.stop() Group multiple widgets By default, Streamlit reruns your script everytime a user interacts with your app. However, sometimes it's a better user experience to wait until a group of related widgets is filled before actually rerunning the script. That's what st.form is for! FormsCreate a form that batches elements together with a “Submit"" button.with st.form(key='my_form'): name = st.text_input(""Name"") email = st.text_input(""Email"") st.form_submit_button(""Sign up"") Form submit buttonDisplay a form submit button.with st.form(key='my_form'): name = st.text_input(""Name"") email = st.text_input(""Email"") st.form_submit_button(""Sign up"") Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration!AutorefreshForce a refresh without tying up a script. Created by @kmcgrady.from streamlit_autorefresh import st_autorefresh st_autorefresh(interval=2000, limit=100, key=""fizzbuzzcounter"") PydanticAuto-generate Streamlit UI from Pydantic Models and Dataclasses. Created by @lukasmasuch.import streamlit_pydantic as sp sp.pydantic_form(key=""my_form"", model=ExampleModel) Streamlit PagesAn experimental version of Streamlit Multi-Page Apps. Created by @blackary.from st_pages import Page, show_pages, add_page_title show_pages([ Page(""streamlit_app.py"", ""Home"", ""🏠""), Page(""other_pages/page2.py"", ""Page 2"", "":books:""), ]) Previous: Navigation and pagesNext: st.dialogforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy" https://docs.streamlit.io/develop/tutorials/execution-flow/start-and-stop-fragment-auto-reruns#start-and-stop-a-streaming-fragment,"DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceaddTutorialsremoveExecution flowremoveFRAGMENTSRerun your app from a fragmentCreate a multiple-container fragmentStart and stop a streaming fragmentConnect to data sourcesaddMultipage appsaddWork with LLMsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Develop/Tutorials/Execution flow/Start and stop a streaming fragmentStart and stop a streaming fragment Streamlit lets you turn functions into fragments, which can rerun independently from the full script. Additionally, you can tell Streamlit to rerun a fragment at a set time interval. This is great for streaming data or monitoring processes. You may want the user to start and stop this live streaming. To do this, programmatically set the run_every parameter for your fragment. Applied concepts Use a fragment to stream live data. Start and stop a fragment from automatically rerunning. Prerequisites streamlit>=1.33.0 This tutorial uses fragments, which require Streamlit version 1.33.0 or later. This tutorial assumes you have a clean working directory called your-repository. You should have a basic understanding of fragments. Summary In this example, you'll build an app that streams two data series in a line chart. Your app will gather recent data on the first load of a session and statically display the line chart. Two buttons in the sidebar will allow users to start and stop data streaming to update the chart in real time. You'll use a fragment to manage the frequency and scope of the live updates. Here's a look at what you'll build: Complete codeexpand_moreimport streamlit as st import pandas as pd import numpy as np from datetime import datetime, timedelta def get_recent_data(last_timestamp): """"""Generate and return data from last timestamp to now, at most 60 seconds."""""" now = datetime.now() if now - last_timestamp > timedelta(seconds=60): last_timestamp = now - timedelta(seconds=60) sample_time = timedelta(seconds=0.5) # time between data points next_timestamp = last_timestamp + sample_time timestamps = np.arange(next_timestamp, now, sample_time) sample_values = np.random.randn(len(timestamps), 2) data = pd.DataFrame(sample_values, index=timestamps, columns=[""A"", ""B""]) return data if ""data"" not in st.session_state: st.session_state.data = get_recent_data(datetime.now() - timedelta(seconds=60)) if ""stream"" not in st.session_state: st.session_state.stream = False def toggle_streaming(): st.session_state.stream = not st.session_state.stream st.title(""Data feed"") st.sidebar.slider( ""Check for updates every: (seconds)"", 0.5, 5.0, value=1.0, key=""run_every"" ) st.sidebar.button( ""Start streaming"", disabled=st.session_state.stream, on_click=toggle_streaming ) st.sidebar.button( ""Stop streaming"", disabled=not st.session_state.stream, on_click=toggle_streaming ) if st.session_state.stream is True: run_every = st.session_state.run_every else: run_every = None @st.experimental_fragment(run_every=run_every) def show_latest_data(): last_timestamp = st.session_state.data.index[-1] st.session_state.data = pd.concat( [st.session_state.data, get_recent_data(last_timestamp)] ) st.session_state.data = st.session_state.data[-100:] st.line_chart(st.session_state.data) show_latest_data() Built with Streamlit 🎈Fullscreen open_in_new Build the example Initialize your app In your_repository, create a file named app.py. In a terminal, change directories to your_repository and start your app. streamlit run app.py Your app will be blank since you still need to add code. In app.py, write the following: import streamlit as st import pandas as pd import numpy as np from datetime import datetime, timedelta You'll be using these libraries as follows: You'll work with two data series in a pandas.DataFrame. You'll generate random data with numpy. The data will have datetime.datetime index values. Save your app.py file and view your running app. Click ""Always rerun"" or hit your ""A"" key in your running app. Your running preview will automatically update as you save changes to app.py. Your preview will still be blank. Return to your code. Build a function to generate random, recent data To begin with, you'll define a function to randomly generate some data for two time series, which you'll call ""A"" and ""B."" It's okay to skip this section if you just want to copy the function. Complete function to randomly generate sales dataexpand_moredef get_recent_data(last_timestamp): """"""Generate and return data from last timestamp to now, at most 60 seconds."""""" now = datetime.now() if now - last_timestamp > timedelta(seconds=60): last_timestamp = now - timedelta(seconds=60) sample_time = timedelta(seconds=0.5) # time between data points next_timestamp = last_timestamp + sample_time timestamps = np.arange(next_timestamp, now, sample_time) sample_values = np.random.randn(len(timestamps), 2) data = pd.DataFrame(sample_values, index=timestamps, columns=[""A"", ""B""]) return data Start your function definition. def get_recent_data(last_timestamp): """"""Generate and return data from last timestamp to now, at most 60 seconds."""""" You'll pass the timestamp of your most recent datapoint to your data-generating function. Your function will use this to only return new data. Get the current time and adjust the last timestamp if it is over 60 seconds ago. now = datetime.now() if now - last_timestamp > timedelta(seconds=60): last_timestamp = now - timedelta(seconds=60) By updating the last timestamp, you'll ensure the function never returns more than 60 seconds of data. Declare a new variable, sample_time, to define the time between datapoints. Calculate the timestamp of the first, new datapoint. sample_time = timedelta(seconds=0.5) # time between data points next_timestamp = last_timestamp + sample_time Create a datetime.datetime index and generate two data series of the same length. timestamps = np.arange(next_timestamp, now, sample_time) sample_values = np.random.randn(len(timestamps), 2) Combine the data series with the index into a pandas.DataFrame and return the data. data = pd.DataFrame(sample_values, index=timestamps, columns=[""A"", ""B""]) return data (Optional) Test out your function by calling it and displaying the data. data = get_recent_data(datetime.now() - timedelta(seconds=60)) data Save your app.py file to see the preview. Delete these two lines when finished. Initialize Session State values for your app Since you will dynamically change the run_every parameter of @st.experimental_fragment(), you'll need to initialize the associated variables and Session State values before defining your fragment function. Your fragment function will also read and update values in Session State, so you can define those now to make the fragment function easier to understand. Initialize your data for the first app load in a session. if ""data"" not in st.session_state: st.session_state.data = get_recent_data(datetime.now() - timedelta(seconds=60)) Your app will display this initial data in a static line chart before a user starts streaming data. Initialize ""stream"" in Session State to turn streaming on and off. Set the default to off (False). if ""stream"" not in st.session_state: st.session_state.stream = False Create a callback function to toggle ""stream"" between True and False. def toggle_streaming(): st.session_state.stream = not st.session_state.stream Add a title to your app. st.title(""Data feed"") Add a slider to the sidebar to set how frequently to check for data while streaming. st.sidebar.slider( ""Check for updates every: (seconds)"", 0.5, 5.0, value=1.0, key=""run_every"" ) Add buttons to the sidebar to turn streaming on and off. st.sidebar.button( ""Start streaming"", disabled=st.session_state.stream, on_click=toggle_streaming ) st.sidebar.button( ""Stop streaming"", disabled=not st.session_state.stream, on_click=toggle_streaming ) Both functions use the same callback to toggle ""stream"" in Session State. Use the current value ""stream"" to disable one of the buttons. This ensures the buttons are always consistent with the current state; ""Start streaming"" is only clickable when streaming is off, and ""Stop streaming"" is only clickable when streaming is on. The buttons also provide status to the user by highlighting which action is available to them. Create and set a new variable, run_every, that will determine whether or not the fragment function will rerun automatically (and how fast). if st.session_state.stream is True: run_every = st.session_state.run_every else: run_every = None Build a fragment function to stream data To allow the user to turn data streaming on and off, you must set the run_every parameter in the @st.experimental_fragment() decorator. Complete function to show and stream dataexpand_more@st.experimental_fragment(run_every=run_every) def show_latest_data(): last_timestamp = st.session_state.data.index[-1] st.session_state.data = pd.concat( [st.session_state.data, get_recent_data(last_timestamp)] ) st.session_state.data = st.session_state.data[-100:] st.line_chart(st.session_state.data) Use an @st.experimental_fragment decorator and start your function definition. @st.experimental_fragment(run_every=run_every) def show_latest_data(): Use the run_every variable declared above to set the parameter of the same name. Retrieve the timestamp of the last datapoint in Session State. last_timestamp = st.session_state.data.index[-1] Update the data in Session State and trim to keep only the last 100 timestamps. st.session_state.data = pd.concat( [st.session_state.data, get_recent_data(last_timestamp)] ) st.session_state.data = st.session_state.data[-100:] Show the data in a line chart. st.line_chart(st.session_state.data) Your fragment-function definition is complete. Call and test out your fragment function Call your function at the bottom of your code. show_latest_data() Test out your app by clicking ""Start streaming."" Try adjusting the frequency of updates. Next steps Try adjusting the frequency of data generation or how much data is kept in Session State. Within get_recent_data try setting sample_time with a widget. Try using st.plotly_chart or st.altair_chart to add labels to your chart.Previous: Create a multiple-container fragmentNext: Connect to data sourcesforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy" https://docs.streamlit.io/develop/api-reference/text/st.title#sttitle,"DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceremovePAGE ELEMENTSWrite and magicaddText elementsremoveHEADINGS & BODYst.titlest.headerst.subheaderst.markdownFORMATTED TEXTst.captionst.codest.dividerst.echost.latexst.textData elementsaddChart elementsaddInput widgetsaddMedia elementsaddLayouts and containersaddChat elementsaddStatus elementsaddThird-party componentsopen_in_newAPPLICATION LOGICNavigation and pagesaddExecution flowaddCaching and stateaddConnections and secretsaddCustom componentsaddUtilitiesaddConfigurationaddTOOLSApp testingaddCommand lineaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Develop/API reference/Text elements/st.titlest.titleStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeDisplay text in title formatting. Each document should have a single st.title(), although this is not enforced. Function signature[source] st.title(body, anchor=None, *, help=None) Parameters body (str) The text to display as Github-flavored Markdown. Syntax information can be found at: https://github.github.com/gfm. This also supports: Emoji shortcodes, such as :+1: and :sunglasses:. For a list of all supported codes, see https://share.streamlit.io/streamlit/emoji-shortcodes. LaTeX expressions, by wrapping them in ""$"" or ""$$"" (the ""$$"" must be on their own lines). Supported LaTeX functions are listed at https://katex.org/docs/supported.html. Colored text and background colors for text, using the syntax :color[text to be colored] and :color-background[text to be colored], respectively. color must be replaced with any of the following supported colors: blue, green, orange, red, violet, gray/grey, rainbow. For example, you can use :orange[your text here] or :blue-background[your text here]. anchor (str or False) The anchor name of the header that can be accessed with #anchor in the URL. If omitted, it generates an anchor using the body. If False, the anchor is not shown in the UI. help (str) An optional tooltip that gets displayed next to the title. Examples import streamlit as st st.title('This is a title') st.title('_Streamlit_ is :blue[cool] :sunglasses:') Built with Streamlit 🎈Fullscreen open_in_new Previous: Text elementsNext: st.headerforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy" https://docs.streamlit.io/develop/api-reference/connections/st.connections.sqlconnection#stconnectionssqlconnection,"DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceremovePAGE ELEMENTSWrite and magicaddText elementsaddData elementsaddChart elementsaddInput widgetsaddMedia elementsaddLayouts and containersaddChat elementsaddStatus elementsaddThird-party componentsopen_in_newAPPLICATION LOGICNavigation and pagesaddExecution flowaddCaching and stateaddConnections and secretsremoveSECRETSst.secretssecrets.tomlCONNECTIONSst.connectionSnowflakeConnectionSQLConnectionBaseConnectionSnowparkConnectiondeleteCustom componentsaddUtilitiesaddConfigurationaddTOOLSApp testingaddCommand lineaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Develop/API reference/Connections and secrets/SQLConnectionstarTipThis page only contains the st.connections.SQLConnection class. For a deeper dive into creating and managing data connections within Streamlit apps, read Connecting to data. st.connections.SQLConnectionStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA connection to a SQL database using a SQLAlchemy Engine. Initialize using st.connection("""", type=""sql""). SQLConnection provides the query() convenience method, which can be used to run simple read-only queries with both caching and simple error handling/retries. More complex DB interactions can be performed by using the .session property to receive a regular SQLAlchemy Session. SQLConnections should always be created using st.connection(), not initialized directly. Connection parameters for a SQLConnection can be specified using either st.secrets or **kwargs. Some frequently used parameters include: url or arguments for sqlalchemy.engine.URL.create(). Most commonly it includes a dialect, host, database, username and password. create_engine_kwargs can be passed via st.secrets, such as for snowflake-sqlalchemy or Google BigQuery. These can also be passed directly as **kwargs to connection(). autocommit=True to run with isolation level AUTOCOMMIT. Default is False. Class description[source] st.connections.SQLConnection(connection_name, **kwargs) Methods connect() Call .connect() on the underlying SQLAlchemy Engine, returning a new sqlalchemy.engine.Connection object. query(sql, *, show_spinner=""Running `sql.query(...)`."", ttl=None, index_col=None, chunksize=None, params=None, **kwargs) Run a read-only query. reset() Reset this connection so that it gets reinitialized the next time it's used. Attributes driver The name of the driver used by the underlying SQLAlchemy Engine. engine The underlying SQLAlchemy Engine. session Return a SQLAlchemy Session. Example import streamlit as st conn = st.connection(""sql"") df = conn.query(""select * from pet_owners"") st.dataframe(df) Basic usage: SQLAlchemy and any required drivers must be installed to use this connection. import streamlit as st conn = st.connection(""sql"") df = conn.query(""select * from pet_owners"") st.dataframe(df) In case you want to pass a connection URL (or other parameters) directly, it also works: conn = st.connection( ""local_db"", type=""sql"", url=""mysql://user:pass@localhost:3306/mydb"" ) Or specify parameters in secrets: # .streamlit/secrets.toml [connections.mydb] dialect = ""mysql"" username = ""myuser"" password = ""password"" host = ""localhost"" database = ""mydb"" # streamlit_app.py conn = st.connection(""mydb"", type=""sql"", autocommit=True) As described above, some cloud databases use extra **kwargs to specify credentials. These can be passed via secrets using the create_engine_kwargs section: # .streamlit/secrets.toml [connections.snowflake] url = ""snowflake://@/"" [connections.snowflake.create_engine_kwargs.connect_args] authenticator = ""externalbrowser"" role = ""..."" # ... SQLConnection.connectStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeCall .connect() on the underlying SQLAlchemy Engine, returning a new sqlalchemy.engine.Connection object. Calling this method is equivalent to calling self._instance.connect(). NOTE: This method should not be confused with the internal _connect method used to implement a Streamlit Connection. Function signature[source] SQLConnection.connect() SQLConnection.queryStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeRun a read-only query. This method implements both query result caching (with caching behavior identical to that of using @st.cache_data) as well as simple error handling/retries. Note Queries that are run without a specified ttl are cached indefinitely. Aside from the ttl kwarg, all kwargs passed to this function are passed down to pandas.read_sql and have the behavior described in the pandas documentation. Function signature[source] SQLConnection.query(sql, *, show_spinner=""Running `sql.query(...)`."", ttl=None, index_col=None, chunksize=None, params=None, **kwargs) Parameters sql (str) The read-only SQL query to execute. show_spinner (boolean or string) Enable the spinner. The default is to show a spinner when there is a ""cache miss"" and the cached resource is being created. If a string, the value of the show_spinner param will be used for the spinner text. ttl (float, int, timedelta or None) The maximum number of seconds to keep results in the cache, or None if cached results should not expire. The default is None. index_col (str, list of str, or None) Column(s) to set as index(MultiIndex). Default is None. chunksize (int or None) If specified, return an iterator where chunksize is the number of rows to include in each chunk. Default is None. params (list, tuple, dict or None) List of parameters to pass to the execute method. The syntax used to pass parameters is database driver dependent. Check your database driver documentation for which of the five syntax styles, described in PEP 249 paramstyle, is supported. Default is None. **kwargs (dict) Additional keyword arguments are passed to pandas.read_sql. Returns(pandas.DataFrame) The result of running the query, formatted as a pandas DataFrame. Example import streamlit as st conn = st.connection(""sql"") df = conn.query(""select * from pet_owners where owner = :owner"", ttl=3600, params={""owner"":""barbara""}) st.dataframe(df) SQLConnection.resetStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeReset this connection so that it gets reinitialized the next time it's used. This method can be useful when a connection has become stale, an auth token has expired, or in similar scenarios where a broken connection might be fixed by reinitializing it. Note that some connection methods may already use reset() in their error handling code. Function signature[source] SQLConnection.reset() Example import streamlit as st conn = st.connection(""my_conn"") # Reset the connection before using it if it isn't healthy # Note: is_healthy() isn't a real method and is just shown for example here. if not conn.is_healthy(): conn.reset() # Do stuff with conn... SQLConnection.driverStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeThe name of the driver used by the underlying SQLAlchemy Engine. This is equivalent to accessing self._instance.driver. Function signature[source] SQLConnection.driver SQLConnection.engineStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeThe underlying SQLAlchemy Engine. This is equivalent to accessing self._instance. Function signature[source] SQLConnection.engine SQLConnection.sessionStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeReturn a SQLAlchemy Session. Users of this connection should use the contextmanager pattern for writes, transactions, and anything more complex than simple read queries. See the usage example below, which assumes we have a table numbers with a single integer column val. The SQLAlchemy docs also contain much more information on the usage of sessions. Function signature[source] SQLConnection.session Example import streamlit as st conn = st.connection(""sql"") n = st.slider(""Pick a number"") if st.button(""Add the number!""): with conn.session as session: session.execute(""INSERT INTO numbers (val) VALUES (:n);"", {""n"": n}) session.commit() Previous: SnowflakeConnectionNext: BaseConnectionforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy" https://docs.streamlit.io/develop/api-reference/app-testing/testing-element-classes#timeinputvalue,"DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceremovePAGE ELEMENTSWrite and magicaddText elementsaddData elementsaddChart elementsaddInput widgetsaddMedia elementsaddLayouts and containersaddChat elementsaddStatus elementsaddThird-party componentsopen_in_newAPPLICATION LOGICNavigation and pagesaddExecution flowaddCaching and stateaddConnections and secretsaddCustom componentsaddUtilitiesaddConfigurationaddTOOLSApp testingremovest.testing.v1.AppTestTesting element classesCommand lineaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Develop/API reference/App testing/Testing element classesTesting element classes st.testing.v1.element_tree.Block The Block class has the same methods and attributes as AppTest. A Block instance represents a container of elements just as AppTest represents the entire app. For example, Block.button will produce a WidgetList of Button in the same manner as AppTest.button. ChatMessage, Column, and Tab all inherit from Block. For all container classes, parameters of the original element can be obtained as properties. For example, ChatMessage.avatar and Tab.label. st.testing.v1.element_tree.ElementStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeElement base class for testing. This class's methods and attributes are universal for all elements implemented in testing. For example, Caption, Code, Text, and Title inherit from Element. All widget classes also inherit from Element, but have additional methods specific to each widget type. See the AppTest class for the full list of supported elements. For all element classes, parameters of the original element can be obtained as properties. For example, Button.label, Caption.help, and Toast.icon. Class description[source] st.testing.v1.element_tree.Element(proto, root) Methods run(*, timeout=None) Run the AppTest script which contains the element. Attributes value The value or contents of the element. st.testing.v1.element_tree.ButtonStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.button and st.form_submit_button. Class description[source] st.testing.v1.element_tree.Button(proto, root) Methods click() Set the value of the button to True. run(*, timeout=None) Run the AppTest script which contains the element. set_value(v) Set the value of the button. Attributes value The value of the button. (bool) st.testing.v1.element_tree.ChatInputStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.chat_input. Class description[source] st.testing.v1.element_tree.ChatInput(proto, root) Methods run(*, timeout=None) Run the AppTest script which contains the element. set_value(v) Set the value of the widget. Attributes value The value of the widget. (str) st.testing.v1.element_tree.CheckboxStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.checkbox. Class description[source] st.testing.v1.element_tree.Checkbox(proto, root) Methods check() Set the value of the widget to True. run(*, timeout=None) Run the AppTest script which contains the element. set_value(v) Set the value of the widget. uncheck() Set the value of the widget to False. Attributes value The value of the widget. (bool) st.testing.v1.element_tree.ColorPickerStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.color_picker. Class description[source] st.testing.v1.element_tree.ColorPicker(proto, root) Methods pick(v) Set the value of the widget as a hex string. May omit the ""#"" prefix. run(*, timeout=None) Run the AppTest script which contains the element. set_value(v) Set the value of the widget as a hex string. Attributes value The currently selected value as a hex string. (str) st.testing.v1.element_tree.DateInputStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.date_input. Class description[source] st.testing.v1.element_tree.DateInput(proto, root) Methods run(*, timeout=None) Run the AppTest script which contains the element. set_value(v) Set the value of the widget. Attributes value The value of the widget. (date or Tuple of date) st.testing.v1.element_tree.MultiselectStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.multiselect. Class description[source] st.testing.v1.element_tree.Multiselect(proto, root) Methods run(*, timeout=None) Run the AppTest script which contains the element. select(v) Add a selection to the widget. Do nothing if the value is already selected. If testing a multiselect widget with repeated options, use set_value instead. set_value(v) Set the value of the multiselect widget. (list) unselect(v) Remove a selection from the widget. Do nothing if the value is not already selected. If a value is selected multiple times, the first instance is removed. Attributes format_func The widget's formatting function for displaying options. (callable) indices The indices of the currently selected values from the options. (list) value The currently selected values from the options. (list) st.testing.v1.element_tree.NumberInputStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.number_input. Class description[source] st.testing.v1.element_tree.NumberInput(proto, root) Methods decrement() Decrement the st.number_input widget as if the user clicked ""-"". increment() Increment the st.number_input widget as if the user clicked ""+"". run(*, timeout=None) Run the AppTest script which contains the element. set_value(v) Set the value of the st.number_input widget. Attributes value Get the current value of the st.number_input widget. st.testing.v1.element_tree.RadioStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.radio. Class description[source] st.testing.v1.element_tree.Radio(proto, root) Methods run(*, timeout=None) Run the AppTest script which contains the element. set_value(v) Set the selection by value. Attributes format_func The widget's formatting function for displaying options. (callable) index The index of the current selection. (int) value The currently selected value from the options. (Any) st.testing.v1.element_tree.SelectSliderStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.select_slider. Class description[source] st.testing.v1.element_tree.SelectSlider(proto, root) Methods run(*, timeout=None) Run the AppTest script which contains the element. set_range(lower, upper) Set the ranged selection by values. set_value(v) Set the (single) selection by value. Attributes format_func The widget's formatting function for displaying options. (callable) value The currently selected value or range. (Any or Sequence of Any) st.testing.v1.element_tree.SelectboxStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.selectbox. Class description[source] st.testing.v1.element_tree.Selectbox(proto, root) Methods run(*, timeout=None) Run the AppTest script which contains the element. select(v) Set the selection by value. select_index(index) Set the selection by index. set_value(v) Set the selection by value. Attributes format_func The widget's formatting function for displaying options. (callable) index The index of the current selection. (int) value The currently selected value from the options. (Any) st.testing.v1.element_tree.SliderStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.slider. Class description[source] st.testing.v1.element_tree.Slider(proto, root) Methods run(*, timeout=None) Run the AppTest script which contains the element. set_range(lower, upper) Set the ranged value of the slider. set_value(v) Set the (single) value of the slider. Attributes value The currently selected value or range. (Any or Sequence of Any) st.testing.v1.element_tree.TextAreaStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.text_area. Class description[source] st.testing.v1.element_tree.TextArea(proto, root) Methods input(v) Set the value of the widget only if the value does not exceed the maximum allowed characters. run(*, timeout=None) Run the AppTest script which contains the element. set_value(v) Set the value of the widget. Attributes value The current value of the widget. (str) st.testing.v1.element_tree.TextInputStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.text_input. Class description[source] st.testing.v1.element_tree.TextInput(proto, root) Methods input(v) Set the value of the widget only if the value does not exceed the maximum allowed characters. run(*, timeout=None) Run the AppTest script which contains the element. set_value(v) Set the value of the widget. Attributes value The current value of the widget. (str) st.testing.v1.element_tree.TimeInputStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.time_input. Class description[source] st.testing.v1.element_tree.TimeInput(proto, root) Methods decrement() Select the previous available time. increment() Select the next available time. run(*, timeout=None) Run the AppTest script which contains the element. set_value(v) Set the value of the widget. Attributes value The current value of the widget. (time) st.testing.v1.element_tree.ToggleStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.toggle. Class description[source] st.testing.v1.element_tree.Toggle(proto, root) Methods run(*, timeout=None) Run the AppTest script which contains the element. set_value(v) Set the value of the widget. Attributes value The current value of the widget. (bool) Previous: st.testing.v1.AppTestNext: Command lineforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy" https://docs.streamlit.io/develop/api-reference/layout#layouts-and-containers,"DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceremovePAGE ELEMENTSWrite and magicaddText elementsaddData elementsaddChart elementsaddInput widgetsaddMedia elementsaddLayouts and containersremovest.columnsst.containerst.dialoglinkst.emptyst.expanderst.formlinkst.popoverst.sidebarst.tabsChat elementsaddStatus elementsaddThird-party componentsopen_in_newAPPLICATION LOGICNavigation and pagesaddExecution flowaddCaching and stateaddConnections and secretsaddCustom componentsaddUtilitiesaddConfigurationaddTOOLSApp testingaddCommand lineaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Develop/API reference/Layouts and containersLayouts and Containers Complex layouts Streamlit provides several options for controlling how different elements are laid out on the screen. ColumnsInsert containers laid out as side-by-side columns.col1, col2 = st.columns(2) col1.write(""this is column 1"") col2.write(""this is column 2"") ContainerInsert a multi-element container.c = st.container() st.write(""This will show last"") c.write(""This will show first"") c.write(""This will show second"") Modal dialogsInsert a modal dialog that can rerun independently from the rest of the script.@st.experimental_dialog() def email_form(): name = st.text_input(""Name"") email = st.text_input(""Email"") EmptyInsert a single-element container.c = st.empty() st.write(""This will show last"") c.write(""This will be replaced"") c.write(""This will show first"") ExpanderInsert a multi-element container that can be expanded/collapsed.with st.expander(""Open to see more""): st.write(""This is more content"") PopoverInsert a multi-element popover container that can be opened/closed.with st.popover(""Settings""): st.checkbox(""Show completed"") SidebarDisplay items in a sidebar.st.sidebar.write(""This lives in the sidebar"") st.sidebar.button(""Click me!"") TabsInsert containers separated into tabs.tab1, tab2 = st.tabs([""Tab 1"", ""Tab2""]) tab1.write(""this is tab 1"") tab2.write(""this is tab 2"") Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration!Streamlit ElementsCreate a draggable and resizable dashboard in Streamlit. Created by @okls.from streamlit_elements import elements, mui, html with elements(""new_element""): mui.Typography(""Hello world"") PydanticAuto-generate Streamlit UI from Pydantic Models and Dataclasses. Created by @lukasmasuch.import streamlit_pydantic as sp sp.pydantic_form(key=""my_form"", model=ExampleModel) Streamlit PagesAn experimental version of Streamlit Multi-Page Apps. Created by @blackary.from st_pages import Page, show_pages, add_page_title show_pages([ Page(""streamlit_app.py"", ""Home"", ""🏠""), Page(""other_pages/page2.py"", ""Page 2"", "":books:""), ]) Previous: Media elementsNext: st.columnsforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy" https://docs.streamlit.io/develop/concepts/app-testing/get-started#handling-file-paths-and-imports-with-pytest,"DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsremoveCOREArchitecture & executionaddMultipage appsaddApp designaddADDITIONALConnections and secretsaddCustom componentsaddConfiguration and themingaddApp testingremoveGet startedBeyond the basicsAutomate your testsExampleCheat sheetAPI referenceaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Develop/Concepts/App testing/Get startedGet started with app testing This guide will cover a simple example of how tests are structured within a project and how to execute them with pytest. After seeing the big picture, keep reading to learn about the Fundamentals of app testing: Initializing and running a simulated app Retrieving elements Manipulating widgets Inspecting the results Streamlit's app testing framework is not tied to any particular testing tool, but we'll use pytest for our examples since it is one of the most common Python test frameworks. To try out the examples in this guide, be sure to install pytest into your Streamlit development environment before you begin: pip install pytest A simple testing example with pytest This section explains how a simple test is structured and executed with pytest. For a comprehensive introduction to pytest, check out Real Python's guide to Effective Python testing with pytest. How pytest is structured pytest uses a naming convention for files and functions to execute tests conveniently. Name your test scripts of the form test_.py or _test.py. For example, you can use test_myapp.py or myapp_test.py. Within your test scripts, each test is written as a function. Each function is named to begin or end with test. We will prefix all our test scripts and test functions with test_ for our examples in this guide. You can write as many tests (functions) within a single test script as you want. When calling pytest in a directory, all test_.py files within it will be used for testing. This includes files within subdirectories. Each test_ function within those files will be executed as a test. You can place test files anywhere in your project directory, but it is common to collect tests into a designated tests/ directory. For other ways to structure and execute tests, check out How to invoke pytest in the pytest docs. Example project with app testing Consider the following project: myproject/ ├── app.py └── tests/ └── test_app.py Main app file: """"""app.py"""""" import streamlit as st # Initialize st.session_state.beans st.session_state.beans = st.session_state.get(""beans"", 0) st.title(""Bean counter :paw_prints:"") addend = st.number_input(""Beans to add"", 0, 10) if st.button(""Add""): st.session_state.beans += addend st.markdown(f""Beans counted: {st.session_state.beans}"") Testing file: """"""test_app.py"""""" from streamlit.testing.v1 import AppTest def test_increment_and_add(): """"""A user increments the number input, then clicks Add"""""" at = AppTest.from_file(""app.py"").run() at.number_input[0].increment().run() at.button[0].click().run() assert at.markdown[0].value == ""Beans counted: 1"" Let's take a quick look at what's in this app and test before we run it. The main app file (app.py) contains four elements when rendered: st.title, st.number_input, st.button, and st.markdown. The test script (test_app.py) includes a single test (the function named test_increment_and_add). We'll cover test syntax in more detail in the latter half of this guide, but here's a brief explanation of what this test does: Initialize the simulated app and execute the first script run. at = AppTest.from_file(""app.py"").run() Simulate a user clicking the plus icon (add) to increment the number input (and the resulting script rerun). at.number_input[0].increment().run() Simulate a user clicking the ""Add"" button (and the resulting script rerun). at.button[0].click().run() Check if the correct message is displayed at the end. assert at.markdown[0].value == ""Beans counted: 1"" Assertions are the heart of tests. When the assertion is true, the test passes. When the assertion is false, the test fails. A test can have multiple assertions, but keeping tests tightly focused is good practice. When tests focus on a single behavior, it is easier to understand and respond to failure. Try out a simple test with pytest Copy the files above into a new ""myproject"" directory. Open a terminal and change directory to your project. cd myproject Execute pytest: pytest The test should execute successfully. Your terminal should show something like this: By executing pytest at the root of your project directory, all Python files with the test prefix (test_.py) will be scanned for test functions. Within each test file, each function with the test prefix will be executed as a test. pytest then counts successes and itemizes failures. You can also direct pytest to only scan your testing directory. For example, from the root of your project directory, execute: pytest tests/ Handling file paths and imports with pytest Imports and paths within a test script should be relative to the directory where pytest is called. That is why the test function uses the path app.py instead of ../app.py even though the app file is one directory up from the test script. You'll usually call pytest from the directory containing your main app file. This is typically the root of your project directory. Additionally, if .streamlit/ is present in the directory where you call pytest, any config.toml and secrets.toml within it will be accessible to your simulated app. For example, your simulated app will have access to the config.toml and secrets.toml files in this common setup: Project structure: myproject/ ├── .streamlit/ │ ├── config.toml │ └── secrets.toml ├── app.py └── tests/ └── test_app.py Initialization within test_app.py: # Path to app file is relative to myproject/ at = AppTest.from_file(""app.py"").run() Command to execute tests: cd myproject pytest tests/ Fundamentals of app testing Now that you understand the basics of pytest let's dive into using Streamlit's app testing framework. Every test begins with initializing and running your simulated app. Additional commands are used to retrieve, manipulate, and inspect elements. On the next page, we'll go Beyond the basics and cover more advanced scenarios like working with secrets, Session State, or multipage apps. How to initialize and run a simulated app To test a Streamlit app, you must first initialize an instance of AppTest with the code for one page of your app. There are three methods for initializing a simulated app. These are provided as class methods to AppTest. We will focus on AppTest.from_file() which allows you to provide a path to a page of your app. This is the most common scenario for building automated tests during app development. AppTest.from_string() and AppTest.from_function() may be helpful for some simple or experimental scenarios. Let's continue with the example from above. Recall the testing file: """"""test_app.py"""""" from streamlit.testing.v1 import AppTest def test_increment_and_add(): """"""A user increments the number input, then clicks Add"""""" at = AppTest.from_file(""app.py"").run() at.number_input[0].increment().run() at.button[0].click().run() assert at.markdown[0].value == ""Beans counted: 1"" Look at the first line in the test function: at = AppTest.from_file(""app.py"").run() This is doing two things and is equivalent to: # Initialize the app. at = AppTest.from_file(""app.py"") # Run the app. at.run() AppTest.from_file() returns an instance of AppTest, initialized with the contents of app.py. The .run() method is used to run the app for the first time. Looking at the test, notice that the .run() method manually executes each script run. A test must explicitly run the app each time. This applies to the app's first run and any rerun resulting from simulated user input. How to retrieve elements The attributes of the AppTest class return sequences of elements. The elements are sorted according to display order in the rendered app. Specific elements can be retrieved by index. Additionally, widgets with keys can be retrieved by key. Retrieve elements by index Each attribute of AppTest returns a sequence of the associated element type. Specific elements can be retrieved by index. In the above example, at.number_input returns a sequence of all st.number_input elements in the app. Thus, at.number_input[0] is the first such element in the app. Similarly, at.markdown returns a collection of all st.markdown elements where at.markdown[0] is the first such element. Check out the current list of supported elements in the ""Attributes"" section of the AppTest class or the App testing cheat sheet. You can also use the .get() method and pass the attribute's name. at.get(""number_input"") and at.get(""markdown"") are equivalent to at.number_input and at.markdown, respectively. The returned sequence of elements is ordered by appearance on the page. If containers are used to insert elements in a different order, these sequences may not match the order within your code. Consider the following example where containers are used to switch the order of two buttons on the page: import streamlit as st first = st.container() second = st.container() second.button(""A"") first.button(""B"") If the above app was tested, the first button (at.button[0]) would be labeled ""B"" and the second button (at.button[1]) would be labeled ""A."" As true assertions, these would be: assert at.button[0].label == ""B"" assert at.button[1].label == ""A"" Retrieve widgets by key You can retrieve keyed widgets by their keys instead of their order on the page. The key of the widget is passed as either an arg or kwarg. For example, look at this app and the following (true) assertions: import streamlit as st st.button(""Next"", key=""submit"") st.button(""Back"", key=""cancel"") assert at.button(key=""submit"").label == ""Next"" assert at.button(""cancel"").label == ""Back"" Retrieve containers You can also narrow down your sequences of elements by retrieving specific containers. Each retrieved container has the same attributes as AppTest. For example, at.sidebar.checkbox returns a sequence of all checkboxes in the sidebar. at.main.selectbox returns the sequence of all selectboxes in the main body of the app (not in the sidebar). For AppTest.columns and AppTest.tabs, a sequence of containers is returned. So at.columns[0].button would be the sequence of all buttons in the first column appearing in the app. How to manipulate widgets All widgets have a universal .set_value() method. Additionally, many widgets have specific methods for manipulating their value. The names of Testing element classes closely match the names of the AppTest attributes. For example, look at the return type of AppTest.button to see the corresponding class of Button. Aside from setting the value of a button with .set_value(), you can also use .click(). Check out each testing element class for its specific methods. How to inspect elements All elements, including widgets, have a universal .value property. This returns the contents of the element. For widgets, this is the same as the return value or value in Session State. For non-input elements, this will be the value of the primary contents argument. For example, .value returns the value of body for st.markdown or st.error. It returns the value of data for st.dataframe or st.table. Additionally, you can check many other details for widgets like labels or disabled status. Many parameters are available for inspection, but not all. Use linting software to see what is currently supported. Here's an example: import streamlit as st st.selectbox(""A"", [1,2,3], None, help=""Pick a number"", placeholder=""Pick me"") assert at.selectbox[0].value == None assert at.selectbox[0].label == ""A"" assert at.selectbox[0].options == [""1"",""2"",""3""] assert at.selectbox[0].index == None assert at.selectbox[0].help == ""Pick a number"" assert at.selectbox[0].placeholder == ""Pick me"" assert at.selectbox[0].disabled == False starTipNote that the options for st.selectbox were declared as integers but asserted as strings. As noted in the documentation for st.selectbox, options are cast internally to strings. If you ever find yourself getting unexpected results, check the documentation carefully for any notes about recasting types internally.Previous: App testingNext: Beyond the basicsforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy" https://docs.streamlit.io/develop/api-reference/execution-flow/st.stop,"DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceremovePAGE ELEMENTSWrite and magicaddText elementsaddData elementsaddChart elementsaddInput widgetsaddMedia elementsaddLayouts and containersaddChat elementsaddStatus elementsaddThird-party componentsopen_in_newAPPLICATION LOGICNavigation and pagesaddExecution flowremovest.dialogst.formst.form_submit_buttonst.fragmentst.rerunst.stopCaching and stateaddConnections and secretsaddCustom componentsaddUtilitiesaddConfigurationaddTOOLSApp testingaddCommand lineaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Develop/API reference/Execution flow/st.stopst.stopStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeStops execution immediately. Streamlit will not run any statements after st.stop(). We recommend rendering a message to explain why the script has stopped. Function signature[source] st.stop() Example import streamlit as st name = st.text_input('Name') if not name: st.warning('Please input a name.') st.stop() st.success('Thank you for inputting a name.') Previous: st.rerunNext: st.experimental_rerunforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy" https://docs.streamlit.io/deploy/streamlit-community-cloud/manage-your-app/app-settings#change-your-app-settings,"DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudremoveGet startedaddDeploy your appaddManage your appremoveApp analyticsApp settingsDelete your appEdit your appFavorite your appReboot your appShare your appaddManage your accountaddTroubleshootingStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Deploy/Streamlit Community Cloud/Manage your app/App settingsApp settings This page is about your app settings on Streamlit Community Cloud. From your app settings you can view or modify your app's URL, manage public or private access to your apps and update your saved secrets for your apps. If you access ""Settings"" from your App menu in the upper-right corner of your running app, you can access features to control the appearance of your app while its running. Access your app settings You can get to your app's settings: From your workspace. From your Cloud logs. Access app settings from your workspace From your workspace at share.streamlit.io, click the overflow icon (more_vert) next to your app. Click ""Settings"". Access app settings from your Cloud logs From your app at .streamlit.app, click ""Manage app"" in the lower-right corner. Click the overflow menu icon (more_vert) and click ""Settings"". Change your app settings View or change your app's URL Read more about Custom subdomains. Update your app's share settings Learn how to Share your app. Update your secrets Learn more about Secrets management. Previous: App analyticsNext: Delete your appforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy" https://docs.streamlit.io/develop/api-reference/charts/st.area_chart#elementadd_rows,"DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceremovePAGE ELEMENTSWrite and magicaddText elementsaddData elementsaddChart elementsremoveSIMPLEst.area_chartst.bar_chartst.line_chartst.mapst.scatter_chartADVANCEDst.altair_chartst.bokeh_chartst.graphviz_chartst.plotly_chartst.pydeck_chartst.pyplotst.vega_lite_chartInput widgetsaddMedia elementsaddLayouts and containersaddChat elementsaddStatus elementsaddThird-party componentsopen_in_newAPPLICATION LOGICNavigation and pagesaddExecution flowaddCaching and stateaddConnections and secretsaddCustom componentsaddUtilitiesaddConfigurationaddTOOLSApp testingaddCommand lineaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Develop/API reference/Chart elements/st.area_chartst.area_chartStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeDisplay an area chart. This is syntax-sugar around st.altair_chart. The main difference is this command uses the data's own column and indices to figure out the chart's spec. As a result this is easier to use for many ""just plot this"" scenarios, while being less customizable. If st.area_chart does not guess the data specification correctly, try specifying your desired chart using st.altair_chart. Function signature[source] st.area_chart(data=None, *, x=None, y=None, color=None, width=0, height=0, use_container_width=True) Parameters data (pandas.DataFrame, pandas.Styler, pyarrow.Table, numpy.ndarray, pyspark.sql.DataFrame, snowflake.snowpark.dataframe.DataFrame, snowflake.snowpark.table.Table, Iterable, or dict) Data to be plotted. x (str or None) Column name to use for the x-axis. If None, uses the data index for the x-axis. y (str, Sequence of str, or None) Column name(s) to use for the y-axis. If a Sequence of strings, draws several series on the same chart by melting your wide-format table into a long-format table behind the scenes. If None, draws the data of all remaining columns as data series. color (str, tuple, Sequence of str, Sequence of tuple, or None) The color to use for different series in this chart. For an area chart with just 1 series, this can be: None, to use the default color. A hex string like ""#ffaa00"" or ""#ffaa0088"". An RGB or RGBA tuple with the red, green, blue, and alpha components specified as ints from 0 to 255 or floats from 0.0 to 1.0. For an area chart with multiple series, where the dataframe is in long format (that is, y is None or just one column), this can be: None, to use the default colors. The name of a column in the dataset. Data points will be grouped into series of the same color based on the value of this column. In addition, if the values in this column match one of the color formats above (hex string or color tuple), then that color will be used. For example: if the dataset has 1000 rows, but this column only contains the values ""adult"", ""child"", and ""baby"", then those 1000 datapoints will be grouped into three series whose colors will be automatically selected from the default palette. But, if for the same 1000-row dataset, this column contained the values ""#ffaa00"", ""#f0f"", ""#0000ff"", then then those 1000 datapoints would still be grouped into 3 series, but their colors would be ""#ffaa00"", ""#f0f"", ""#0000ff"" this time around. For an area chart with multiple series, where the dataframe is in wide format (that is, y is a Sequence of columns), this can be: None, to use the default colors. A list of string colors or color tuples to be used for each of the series in the chart. This list should have the same length as the number of y values (e.g. color=[""#fd0"", ""#f0f"", ""#04f""] for three lines). width (int) The chart width in pixels. If 0, selects the width automatically. height (int) The chart height in pixels. If 0, selects the height automatically. use_container_width (bool) If True, set the chart width to the column width. This takes precedence over the width argument. Examples import streamlit as st import pandas as pd import numpy as np chart_data = pd.DataFrame(np.random.randn(20, 3), columns=[""a"", ""b"", ""c""]) st.area_chart(chart_data) Built with Streamlit 🎈Fullscreen open_in_new You can also choose different columns to use for x and y, as well as set the color dynamically based on a 3rd column (assuming your dataframe is in long format): import streamlit as st import pandas as pd import numpy as np chart_data = pd.DataFrame( { ""col1"": np.random.randn(20), ""col2"": np.random.randn(20), ""col3"": np.random.choice([""A"", ""B"", ""C""], 20), } ) st.area_chart(chart_data, x=""col1"", y=""col2"", color=""col3"") Built with Streamlit 🎈Fullscreen open_in_new Finally, if your dataframe is in wide format, you can group multiple columns under the y argument to show multiple series with different colors: import streamlit as st import pandas as pd import numpy as np chart_data = pd.DataFrame(np.random.randn(20, 3), columns=[""col1"", ""col2"", ""col3""]) st.area_chart( chart_data, x=""col1"", y=[""col2"", ""col3""], color=[""#FF0000"", ""#0000FF""] # Optional ) Built with Streamlit 🎈Fullscreen open_in_new element.add_rowsStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeConcatenate a dataframe to the bottom of the current one. Function signature[source] element.add_rows(data=None, **kwargs) Parameters data (pandas.DataFrame, pandas.Styler, pyarrow.Table, numpy.ndarray, pyspark.sql.DataFrame, snowflake.snowpark.dataframe.DataFrame, Iterable, dict, or None) Table to concat. Optional. **kwargs (pandas.DataFrame, numpy.ndarray, Iterable, dict, or None) The named dataset to concat. Optional. You can only pass in 1 dataset (including the one in the data parameter). Example import streamlit as st import pandas as pd import numpy as np df1 = pd.DataFrame(np.random.randn(50, 20), columns=(""col %d"" % i for i in range(20))) my_table = st.table(df1) df2 = pd.DataFrame(np.random.randn(50, 20), columns=(""col %d"" % i for i in range(20))) my_table.add_rows(df2) # Now the table shown in the Streamlit app contains the data for # df1 followed by the data for df2. You can do the same thing with plots. For example, if you want to add more data to a line chart: # Assuming df1 and df2 from the example above still exist... my_chart = st.line_chart(df1) my_chart.add_rows(df2) # Now the chart shown in the Streamlit app contains the data for # df1 followed by the data for df2. And for plots whose datasets are named, you can pass the data with a keyword argument where the key is the name: my_chart = st.vega_lite_chart({ 'mark': 'line', 'encoding': {'x': 'a', 'y': 'b'}, 'datasets': { 'some_fancy_name': df1, # <-- named dataset }, 'data': {'name': 'some_fancy_name'}, }), my_chart.add_rows(some_fancy_name=df2) # <-- name used as keyword Previous: Chart elementsNext: st.bar_chartforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy" https://docs.streamlit.io/develop/tutorials/databases/tidb,"DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceaddTutorialsremoveExecution flowaddConnect to data sourcesremoveAWS S3BigQueryDeta BaseFirestoreopen_in_newGoogle Cloud StorageMicrosoft SQL ServerMongoDBMySQLNeonPostgreSQLPrivate Google SheetPublic Google SheetSnowflakeSupabaseTableauTiDBTigerGraphMultipage appsaddWork with LLMsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Develop/Tutorials/Connect to data sources/TiDBConnect Streamlit to TiDB Introduction This guide explains how to securely access a remote TiDB database from Streamlit Community Cloud. It uses st.connection and Streamlit's Secrets management. The below example code will only work on Streamlit version >= 1.28, when st.connection was added. TiDB is an open-source, MySQL-compatible database that supports Hybrid Transactional and Analytical Processing (HTAP) workloads. TiDB Cloud is a fully managed cloud database service that simplifies the deployment and management of TiDB databases for developers. Sign in to TiDB Cloud and create a cluster First, head over to TiDB Cloud and sign up for a free account, using either Google, GitHub, Microsoft or E-mail: Once you've signed in, you will already have a TiDB cluster: You can create more clusters if you want to. Click the cluster name to enter cluster overview page: Then click Connect to easily get the connection arguments to access the cluster. On the popup, click Generate password to set the password. priority_highImportantMake sure to note down the password. It won't be available on TiDB Cloud after this step. Create a TiDB database push_pinNoteIf you already have a database that you want to use, feel free to skip to the next step. Once your TiDB cluster is up and running, connect to it with the mysql client(or with Chat2Query tab on the console) and enter the following commands to create a database and a table with some example values: CREATE DATABASE pets; USE pets; CREATE TABLE mytable ( name varchar(80), pet varchar(80) ); INSERT INTO mytable VALUES ('Mary', 'dog'), ('John', 'cat'), ('Robert', 'bird'); Add username and password to your local app secrets Your local Streamlit app will read secrets from a file .streamlit/secrets.toml in your app's root directory. Learn more about Streamlit secrets management here. Create this file if it doesn't exist yet and add host, username and password of your TiDB cluster as shown below: # .streamlit/secrets.toml [connections.tidb] dialect = ""mysql"" host = """" port = 4000 database = ""pets"" username = """" password = """" priority_highImportantWhen copying your app secrets to Streamlit Community Cloud, be sure to replace the values of host, username and password with those of your remote TiDB cluster!Add this file to .gitignore and don't commit it to your GitHub repo! Copy your app secrets to the cloud As the secrets.toml file above is not committed to GitHub, you need to pass its content to your deployed app (on Streamlit Community Cloud) separately. Go to the app dashboard and in the app's dropdown menu, click on Edit Secrets. Copy the content of secrets.toml into the text area. More information is available at Secrets management. Add dependencies to your requirements file Add the mysqlclient and SQLAlchemy packages to your requirements.txt file, preferably pinning its version (replace x.x.x with the version you want installed): # requirements.txt mysqlclient==x.x.x SQLAlchemy==x.x.x Write your Streamlit app Copy the code below to your Streamlit app and run it. Make sure to adapt query to use the name of your table. # streamlit_app.py import streamlit as st # Initialize connection. conn = st.connection('tidb', type='sql') # Perform query. df = conn.query('SELECT * from mytable;', ttl=600) # Print results. for row in df.itertuples(): st.write(f""{row.name} has a :{row.pet}:"") See st.connection above? This handles secrets retrieval, setup, query caching and retries. By default, query() results are cached without expiring. In this case, we set ttl=600 to ensure the query result is cached for no longer than 10 minutes. You can also set ttl=0 to disable caching. Learn more in Caching. If everything worked out (and you used the example table we created above), your app should look like this: Connect with PyMySQL Other than mysqlclient, PyMySQL is another popular MySQL Python client. To use PyMySQL, first you need to adapt your requirements file: # requirements.txt PyMySQL==x.x.x SQLAlchemy==x.x.x Then adapt your secrets file: # .streamlit/secrets.toml [connections.tidb] dialect = ""mysql"" driver = ""pymysql"" host = """" port = 4000 database = ""pets"" username = """" password = """" create_engine_kwargs = { connect_args = { ssl = { ca = """" }}} Previous: TableauNext: TigerGraphforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy" https://docs.streamlit.io/deploy/concepts/secrets#managing-secrets-when-deploying-your-app,"DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceaddTutorialsaddQuick referenceaddweb_assetDeployConceptsremoveDependenciesSecretsStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Deploy/Concepts/SecretsManaging secrets when deploying your app If you are connecting to data sources or external services, you will likely be handling secret information like credentials or keys. Secret information should be stored and transmitted in a secure manner. When you deploy your app, ensure that you understand your platform's features and mechanisms for handling secrets so you can follow best practice. Avoid saving secrets directly in your code and keep .gitignore updated to prevent accidentally committing a local secret to your repository. For helpful reminders, see Security reminders. If you are using Streamlit Community Cloud, Secrets management allows you save environment variables and store secrets outside of your code. If you are using another platform designed for Streamlit, check if they have a built-in mechanism for working with secrets. In some cases, they may even support st.secrets or securely uploading your secrets.toml file. For information about using st.connection with environment variables, see Global secrets, managing multiple apps and multiple data stores.Previous: DependenciesNext: Streamlit Community CloudforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy" https://docs.streamlit.io/develop/api-reference/app-testing/st.testing.v1.apptest#apptesttable,"DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceremovePAGE ELEMENTSWrite and magicaddText elementsaddData elementsaddChart elementsaddInput widgetsaddMedia elementsaddLayouts and containersaddChat elementsaddStatus elementsaddThird-party componentsopen_in_newAPPLICATION LOGICNavigation and pagesaddExecution flowaddCaching and stateaddConnections and secretsaddCustom componentsaddUtilitiesaddConfigurationaddTOOLSApp testingremovest.testing.v1.AppTestTesting element classesCommand lineaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Develop/API reference/App testing/st.testing.v1.AppTest The AppTest class st.testing.v1.AppTestStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA simulated Streamlit app to check the correctness of displayed elements and outputs. An instance of AppTest simulates a running Streamlit app. This class provides methods to set up, manipulate, and inspect the app contents via API instead of a browser UI. It can be used to write automated tests of an app in various scenarios. These can then be run using a tool like pytest. AppTest can be initialized by one of three class methods: st.testing.v1.AppTest.from_file (recommended) st.testing.v1.AppTest.from_string st.testing.v1.AppTest.from_function Once initialized, Session State and widget values can be updated and the script can be run. Unlike an actual live-running Streamlit app, you need to call AppTest.run() explicitly to re-run the app after changing a widget value. Switching pages also requires an explicit, follow-up call to AppTest.run(). AppTest enables developers to build tests on their app as-is, in the familiar python test format, without major refactoring or abstracting out logic to be tested separately from the UI. Tests can run quickly with very low overhead. A typical pattern is to build a suite of tests for an app that ensure consistent functionality as the app evolves, and run the tests locally and/or in a CI environment like Github Actions. Note AppTest only supports testing a single page of an app per instance. For multipage apps, each page will need to be tested separately. No methods exist to programatically switch pages within AppTest. Class description[source] st.testing.v1.AppTest(script_path, *, default_timeout, args=None, kwargs=None) Methods get(element_type) Get elements or widgets of the specified type. run(*, timeout=None) Run the script from the current state. switch_page(page_path) Switch to another page of the app. Attributes secrets (dict[str, Any]) Dictionary of secrets to be used the simulated app. Use dict-like syntax to set secret values for the simulated app. session_state (SafeSessionState) Session State for the simulated app. SafeSessionState object supports read and write operations as usual for Streamlit apps. query_params (dict[str, Any]) Dictionary of query parameters to be used by the simluated app. Use dict-like syntax to set query_params values for the simulated app. button Sequence of all st.button and st.form_submit_button widgets. caption Sequence of all st.caption elements. chat_input Sequence of all st.chat_input widgets. chat_message Sequence of all st.chat_message elements. checkbox Sequence of all st.checkbox widgets. code Sequence of all st.code elements. color_picker Sequence of all st.color_picker widgets. columns Sequence of all columns within st.columns elements. dataframe Sequence of all st.dataframe elements. date_input Sequence of all st.date_input widgets. divider Sequence of all st.divider elements. error Sequence of all st.error elements. exception Sequence of all st.exception elements. expander Sequence of all st.expander elements. header Sequence of all st.header elements. info Sequence of all st.info elements. json Sequence of all st.json elements. latex Sequence of all st.latex elements. main Sequence of elements within the main body of the app. markdown Sequence of all st.markdown elements. metric Sequence of all st.metric elements. multiselect Sequence of all st.multiselect widgets. number_input Sequence of all st.number_input widgets. radio Sequence of all st.radio widgets. select_slider Sequence of all st.select_slider widgets. selectbox Sequence of all st.selectbox widgets. sidebar Sequence of all elements within st.sidebar. slider Sequence of all st.slider widgets. status Sequence of all st.status elements. subheader Sequence of all st.subheader elements. success Sequence of all st.success elements. table Sequence of all st.table elements. tabs Sequence of all tabs within st.tabs elements. text Sequence of all st.text elements. text_area Sequence of all st.text_area widgets. text_input Sequence of all st.text_input widgets. time_input Sequence of all st.time_input widgets. title Sequence of all st.title elements. toast Sequence of all st.toast elements. toggle Sequence of all st.toggle widgets. warning Sequence of all st.warning elements. Initialize a simulated app using AppTest AppTest.from_fileStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeCreate an instance of AppTest to simulate an app page defined within a file. This option is most convenient for CI workflows and testing of published apps. The script must be executable on its own and so must contain all necessary imports. Function signature[source] AppTest.from_file(cls, script_path, *, default_timeout=3) Parameters script_path (str) Path to a script file. The path should be absolute or relative to the file calling .from_file. default_timeout (float) Default time in seconds before a script run is timed out. Can be overridden for individual .run() calls. Returns(AppTest) A simulated Streamlit app for testing. The simulated app can be executed via .run(). AppTest.from_stringStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeCreate an instance of AppTest to simulate an app page defined within a string. This is useful for testing short scripts that fit comfortably as an inline string in the test itself, without having to create a separate file for it. The script must be executable on its own and so must contain all necessary imports. Function signature[source] AppTest.from_string(cls, script, *, default_timeout=3) Parameters script (str) The string contents of the script to be run. default_timeout (float) Default time in seconds before a script run is timed out. Can be overridden for individual .run() calls. Returns(AppTest) A simulated Streamlit app for testing. The simulated app can be executed via .run(). AppTest.from_functionStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeCreate an instance of AppTest to simulate an app page defined within a function. This is similar to AppTest.from_string(), but more convenient to write with IDE assistance. The script must be executable on its own and so must contain all necessary imports. Function signature[source] AppTest.from_function(cls, script, *, default_timeout=3, args=None, kwargs=None) Parameters script (Callable) A function whose body will be used as a script. Must be runnable in isolation, so it must include any necessary imports. default_timeout (float) Default time in seconds before a script run is timed out. Can be overridden for individual .run() calls. args (tuple) An optional tuple of args to pass to the script function. kwargs (dict) An optional dict of kwargs to pass to the script function. Returns(AppTest) A simulated Streamlit app for testing. The simulated app can be executed via .run(). Run an AppTest script AppTest.runStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeRun the script from the current state. This is equivalent to manually rerunning the app or the rerun that occurs upon user interaction. AppTest.run() must be manually called after updating a widget value or switching pages as script reruns do not occur automatically as they do for live-running Streamlit apps. Function signature[source] AppTest.run(*, timeout=None) Parameters timeout (null) The maximum number of seconds to run the script. None means use the default timeout set for the instance of AppTest. Returns(AppTest) self AppTest.switch_pageStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSwitch to another page of the app. This method does not automatically rerun the app. Use a follow-up call to AppTest.run() to obtain the elements on the selected page. Function signature[source] AppTest.switch_page(page_path) Parameters page_path (str) Path of the page to switch to. The path must be relative to the main script's location (e.g. ""pages/my_page.py""). Returns(AppTest) self Get AppTest script elements The main value of AppTest is providing an API to programmatically inspect and interact with the elements and widgets produced by a running Streamlit app. Using the AppTest. properties or AppTest.get() method returns a collection of all the elements or widgets of the specified type that would have been displayed by running the app. Note that you can also retrieve elements within a specific container in the same way - first retrieve the container, then retrieve the elements just in that container. AppTest.getStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeGet elements or widgets of the specified type. This method returns the collection of all elements or widgets of the specified type on the current page. Retrieve a specific element by using its index (order on page) or key lookup. Function signature[source] AppTest.get(element_type) Parameters element_type (str) An element attribute of AppTest. For example, ""button"", ""caption"", or ""chat_input"". Returns(Sequence of Elements) Sequence of elements of the given type. Individual elements can be accessed from a Sequence by index (order on the page). When getting and element_type that is a widget, individual widgets can be accessed by key. For example, at.get(""text"")[0] for the first st.text element or at.get(""slider"")(key=""my_key"") for the st.slider widget with a given key. AppTest.buttonStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.button and st.form_submit_button widgets. Function signature[source] AppTest.button Returns(WidgetList of Button) Sequence of all st.button and st.form_submit_button widgets. Individual widgets can be accessed from a WidgetList by index (order on the page) or key. For example, at.button[0] for the first widget or at.button(key=""my_key"") for a widget with a given key. AppTest.captionStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.caption elements. Function signature[source] AppTest.caption Returns(ElementList of Caption) Sequence of all st.caption elements. Individual elements can be accessed from an ElementList by index (order on the page). For example, at.caption[0] for the first element. Caption is an extension of the Element class. AppTest.chat_inputStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.chat_input widgets. Function signature[source] AppTest.chat_input Returns(WidgetList of ChatInput) Sequence of all st.chat_input widgets. Individual widgets can be accessed from a WidgetList by index (order on the page) or key. For example, at.chat_input[0] for the first widget or at.chat_input(key=""my_key"") for a widget with a given key. AppTest.chat_messageStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.chat_message elements. Function signature[source] AppTest.chat_message Returns(Sequence of ChatMessage) Sequence of all st.chat_message elements. Individual elements can be accessed from an ElementList by index (order on the page). For example, at.chat_message[0] for the first element. ChatMessage is an extension of the Block class. AppTest.checkboxStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.checkbox widgets. Function signature[source] AppTest.checkbox Returns(WidgetList of Checkbox) Sequence of all st.checkbox widgets. Individual widgets can be accessed from a WidgetList by index (order on the page) or key. For example, at.checkbox[0] for the first widget or at.checkbox(key=""my_key"") for a widget with a given key. AppTest.codeStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.code elements. Function signature[source] AppTest.code Returns(ElementList of Code) Sequence of all st.code elements. Individual elements can be accessed from an ElementList by index (order on the page). For example, at.code[0] for the first element. Code is an extension of the Element class. AppTest.color_pickerStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.color_picker widgets. Function signature[source] AppTest.color_picker Returns(WidgetList of ColorPicker) Sequence of all st.color_picker widgets. Individual widgets can be accessed from a WidgetList by index (order on the page) or key. For example, at.color_picker[0] for the first widget or at.color_picker(key=""my_key"") for a widget with a given key. AppTest.columnsStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all columns within st.columns elements. Each column within a single st.columns will be returned as a separate Column in the Sequence. Function signature[source] AppTest.columns Returns(Sequence of Column) Sequence of all columns within st.columns elements. Individual columns can be accessed from an ElementList by index (order on the page). For example, at.columns[0] for the first column. Column is an extension of the Block class. AppTest.dataframeStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.dataframe elements. Function signature[source] AppTest.dataframe Returns(ElementList of Dataframe) Sequence of all st.dataframe elements. Individual elements can be accessed from an ElementList by index (order on the page). For example, at.dataframe[0] for the first element. Dataframe is an extension of the Element class. AppTest.date_inputStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.date_input widgets. Function signature[source] AppTest.date_input Returns(WidgetList of DateInput) Sequence of all st.date_input widgets. Individual widgets can be accessed from a WidgetList by index (order on the page) or key. For example, at.date_input[0] for the first widget or at.date_input(key=""my_key"") for a widget with a given key. AppTest.dividerStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.divider elements. Function signature[source] AppTest.divider Returns(ElementList of Divider) Sequence of all st.divider elements. Individual elements can be accessed from an ElementList by index (order on the page). For example, at.divider[0] for the first element. Divider is an extension of the Element class. AppTest.errorStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.error elements. Function signature[source] AppTest.error Returns(ElementList of Error) Sequence of all st.error elements. Individual elements can be accessed from an ElementList by index (order on the page). For example, at.error[0] for the first element. Error is an extension of the Element class. AppTest.exceptionStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.exception elements. Function signature[source] AppTest.exception Returns(ElementList of Exception) Sequence of all st.exception elements. Individual elements can be accessed from an ElementList by index (order on the page). For example, at.exception[0] for the first element. Exception is an extension of the Element class. AppTest.expanderStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.expander elements. Function signature[source] AppTest.expander Returns(Sequence of Expandable) Sequence of all st.expander elements. Individual elements can be accessed from a Sequence by index (order on the page). For example, at.expander[0] for the first element. Expandable is an extension of the Block class. AppTest.headerStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.header elements. Function signature[source] AppTest.header Returns(ElementList of Header) Sequence of all st.header elements. Individual elements can be accessed from an ElementList by index (order on the page). For example, at.header[0] for the first element. Header is an extension of the Element class. AppTest.infoStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.info elements. Function signature[source] AppTest.info Returns(ElementList of Info) Sequence of all st.info elements. Individual elements can be accessed from an ElementList by index (order on the page). For example, at.info[0] for the first element. Info is an extension of the Element class. AppTest.jsonStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.json elements. Function signature[source] AppTest.json Returns(ElementList of Json) Sequence of all st.json elements. Individual elements can be accessed from an ElementList by index (order on the page). For example, at.json[0] for the first element. Json is an extension of the Element class. AppTest.latexStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.latex elements. Function signature[source] AppTest.latex Returns(ElementList of Latex) Sequence of all st.latex elements. Individual elements can be accessed from an ElementList by index (order on the page). For example, at.latex[0] for the first element. Latex is an extension of the Element class. AppTest.mainStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of elements within the main body of the app. Function signature[source] AppTest.main Returns(Block) A container of elements. Block can be queried for elements in the same manner as AppTest. For example, Block.checkbox will return all st.checkbox within the associated container. AppTest.markdownStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.markdown elements. Function signature[source] AppTest.markdown Returns(ElementList of Markdown) Sequence of all st.markdown elements. Individual elements can be accessed from an ElementList by index (order on the page). For example, at.markdown[0] for the first element. Markdown is an extension of the Element class. AppTest.metricStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.metric elements. Function signature[source] AppTest.metric Returns(ElementList of Metric) Sequence of all st.metric elements. Individual elements can be accessed from an ElementList by index (order on the page). For example, at.metric[0] for the first element. Metric is an extension of the Element class. AppTest.multiselectStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.multiselect widgets. Function signature[source] AppTest.multiselect Returns(WidgetList of Multiselect) Sequence of all st.multiselect widgets. Individual widgets can be accessed from a WidgetList by index (order on the page) or key. For example, at.multiselect[0] for the first widget or at.multiselect(key=""my_key"") for a widget with a given key. AppTest.number_inputStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.number_input widgets. Function signature[source] AppTest.number_input Returns(WidgetList of NumberInput) Sequence of all st.number_input widgets. Individual widgets can be accessed from a WidgetList by index (order on the page) or key. For example, at.number_input[0] for the first widget or at.number_input(key=""my_key"") for a widget with a given key. AppTest.radioStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.radio widgets. Function signature[source] AppTest.radio Returns(WidgetList of Radio) Sequence of all st.radio widgets. Individual widgets can be accessed from a WidgetList by index (order on the page) or key. For example, at.radio[0] for the first widget or at.radio(key=""my_key"") for a widget with a given key. AppTest.select_sliderStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.select_slider widgets. Function signature[source] AppTest.select_slider Returns(WidgetList of SelectSlider) Sequence of all st.select_slider widgets. Individual widgets can be accessed from a WidgetList by index (order on the page) or key. For example, at.select_slider[0] for the first widget or at.select_slider(key=""my_key"") for a widget with a given key. AppTest.selectboxStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.selectbox widgets. Function signature[source] AppTest.selectbox Returns(WidgetList of Selectbox) Sequence of all st.selectbox widgets. Individual widgets can be accessed from a WidgetList by index (order on the page) or key. For example, at.selectbox[0] for the first widget or at.selectbox(key=""my_key"") for a widget with a given key. AppTest.sidebarStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all elements within st.sidebar. Function signature[source] AppTest.sidebar Returns(Block) A container of elements. Block can be queried for elements in the same manner as AppTest. For example, Block.checkbox will return all st.checkbox within the associated container. AppTest.sliderStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.slider widgets. Function signature[source] AppTest.slider Returns(WidgetList of Slider) Sequence of all st.slider widgets. Individual widgets can be accessed from a WidgetList by index (order on the page) or key. For example, at.slider[0] for the first widget or at.slider(key=""my_key"") for a widget with a given key. AppTest.subheaderStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.subheader elements. Function signature[source] AppTest.subheader Returns(ElementList of Subheader) Sequence of all st.subheader elements. Individual elements can be accessed from an ElementList by index (order on the page). For example, at.subheader[0] for the first element. Subheader is an extension of the Element class. AppTest.successStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.success elements. Function signature[source] AppTest.success Returns(ElementList of Success) Sequence of all st.success elements. Individual elements can be accessed from an ElementList by index (order on the page). For example, at.success[0] for the first element. Success is an extension of the Element class. AppTest.statusStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.status elements. Function signature[source] AppTest.status Returns(Sequence of Status) Sequence of all st.status elements. Individual elements can be accessed from a Sequence by index (order on the page). For example, at.status[0] for the first element. Status is an extension of the Block class. AppTest.tableStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.table elements. Function signature[source] AppTest.table Returns(ElementList of Table) Sequence of all st.table elements. Individual elements can be accessed from an ElementList by index (order on the page). For example, at.table[0] for the first element. Table is an extension of the Element class. AppTest.tabsStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all tabs within st.tabs elements. Each tab within a single st.tabs will be returned as a separate Tab in the Sequence. Additionally, the tab labels are forwarded to each Tab element as a property. For example, st.tabs(""A"",""B"") will yield two Tab objects, with Tab.label returning ""A"" and ""B"", respectively. Function signature[source] AppTest.tabs Returns(Sequence of Tab) Sequence of all tabs within st.tabs elements. Individual tabs can be accessed from an ElementList by index (order on the page). For example, at.tabs[0] for the first tab. Tab is an extension of the Block class. AppTest.textStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.text elements. Function signature[source] AppTest.text Returns(ElementList of Text) Sequence of all st.text elements. Individual elements can be accessed from an ElementList by index (order on the page). For example, at.text[0] for the first element. Text is an extension of the Element class. AppTest.text_areaStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.text_area widgets. Function signature[source] AppTest.text_area Returns(WidgetList of TextArea) Sequence of all st.text_area widgets. Individual widgets can be accessed from a WidgetList by index (order on the page) or key. For example, at.text_area[0] for the first widget or at.text_area(key=""my_key"") for a widget with a given key. AppTest.text_inputStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.text_input widgets. Function signature[source] AppTest.text_input Returns(WidgetList of TextInput) Sequence of all st.text_input widgets. Individual widgets can be accessed from a WidgetList by index (order on the page) or key. For example, at.text_input[0] for the first widget or at.text_input(key=""my_key"") for a widget with a given key. AppTest.time_inputStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.time_input widgets. Function signature[source] AppTest.time_input Returns(WidgetList of TimeInput) Sequence of all st.time_input widgets. Individual widgets can be accessed from a WidgetList by index (order on the page) or key. For example, at.time_input[0] for the first widget or at.time_input(key=""my_key"") for a widget with a given key. AppTest.titleStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.title elements. Function signature[source] AppTest.title Returns(ElementList of Title) Sequence of all st.title elements. Individual elements can be accessed from an ElementList by index (order on the page). For example, at.title[0] for the first element. Title is an extension of the Element class. AppTest.toastStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.toast elements. Function signature[source] AppTest.toast Returns(ElementList of Toast) Sequence of all st.toast elements. Individual elements can be accessed from an ElementList by index (order on the page). For example, at.toast[0] for the first element. Toast is an extension of the Element class. AppTest.toggleStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.toggle widgets. Function signature[source] AppTest.toggle Returns(WidgetList of Toggle) Sequence of all st.toggle widgets. Individual widgets can be accessed from a WidgetList by index (order on the page) or key. For example, at.toggle[0] for the first widget or at.toggle(key=""my_key"") for a widget with a given key. AppTest.warningStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.warning elements. Function signature[source] AppTest.warning Returns(ElementList of Warning) Sequence of all st.warning elements. Individual elements can be accessed from an ElementList by index (order on the page). For example, at.warning[0] for the first element. Warning is an extension of the Element class. Previous: App testingNext: Testing element classesforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy" https://docs.streamlit.io/develop/api-reference#app-logic-and-configuration,"DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceremovePAGE ELEMENTSWrite and magicaddText elementsaddData elementsaddChart elementsaddInput widgetsaddMedia elementsaddLayouts and containersaddChat elementsaddStatus elementsaddThird-party componentsopen_in_newAPPLICATION LOGICNavigation and pagesaddExecution flowaddCaching and stateaddConnections and secretsaddCustom componentsaddUtilitiesaddConfigurationaddTOOLSApp testingaddCommand lineaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Develop/API referenceAPI reference Streamlit makes it easy for you to visualize, mutate, and share data. The API reference is organized by activity type, like displaying data or optimizing performance. Each section includes methods associated with the activity type, including examples. Browse our API below and click to learn more about any of our available commands! 🎈 Display almost anything Write and magic st.writeWrite arguments to the app.st.write(""Hello **world**!"") st.write(my_data_frame) st.write(my_mpl_figure) st.write_streamWrite generators or streams to the app with a typewriter effect.st.write_stream(my_generator) st.write_stream(my_llm_stream) MagicAny time Streamlit sees either a variable or literal value on its own line, it automatically writes that to your app using st.write""Hello **world**!"" my_data_frame my_mpl_figure Text elements MarkdownDisplay string formatted as Markdown.st.markdown(""Hello **world**!"") TitleDisplay text in title formatting.st.title(""The app title"") HeaderDisplay text in header formatting.st.header(""This is a header"") SubheaderDisplay text in subheader formatting.st.subheader(""This is a subheader"") CaptionDisplay text in small font.st.caption(""This is written small caption text"") Code blockDisplay a code block with optional syntax highlighting.st.code(""a = 1234"") EchoDisplay some code in the app, then execute it. Useful for tutorials.with st.echo(): st.write('This code will be printed') LaTeXDisplay mathematical expressions formatted as LaTeX.st.latex(""\int a x^2 \,dx"") Preformatted textWrite fixed-width and preformatted text.st.text(""Hello world"") DividerDisplay a horizontal rule.st.divider() Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration! PreviousTagsAdd tags to your Streamlit apps. Created by @gagan3012.st_tags(label='# Enter Keywords:', text='Press enter to add more', value=['Zero', 'One', 'Two'], suggestions=['five', 'six', 'seven', 'eight', 'nine', 'three', 'eleven', 'ten', 'four'], maxtags = 4, key='1') NLUApply text mining on a dataframe. Created by @JohnSnowLabs.nlu.load('sentiment').predict('I love NLU! <3') Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.mention(label=""An awesome Streamlit App"", icon=""streamlit"", url=""https://extras.streamlit.app"",) Annotated textDisplay annotated text in Streamlit apps. Created by @tvst.annotated_text(""This "", (""is"", ""verb""), "" some "", (""annotated"", ""adj""), (""text"", ""noun""), "" for those of "", (""you"", ""pronoun""), "" who "", (""like"", ""verb""), "" this sort of "", (""thing"", ""noun""), ""."") Drawable CanvasProvides a sketching canvas using Fabric.js. Created by @andfanilo.st_canvas(fill_color=""rgba(255, 165, 0, 0.3)"", stroke_width=stroke_width, stroke_color=stroke_color, background_color=bg_color, background_image=Image.open(bg_image) if bg_image else None, update_streamlit=realtime_update, height=150, drawing_mode=drawing_mode, point_display_radius=point_display_radius if drawing_mode == 'point' else 0, key=""canvas"",) TagsAdd tags to your Streamlit apps. Created by @gagan3012.st_tags(label='# Enter Keywords:', text='Press enter to add more', value=['Zero', 'One', 'Two'], suggestions=['five', 'six', 'seven', 'eight', 'nine', 'three', 'eleven', 'ten', 'four'], maxtags = 4, key='1') NLUApply text mining on a dataframe. Created by @JohnSnowLabs.nlu.load('sentiment').predict('I love NLU! <3') Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.mention(label=""An awesome Streamlit App"", icon=""streamlit"", url=""https://extras.streamlit.app"",) Annotated textDisplay annotated text in Streamlit apps. Created by @tvst.annotated_text(""This "", (""is"", ""verb""), "" some "", (""annotated"", ""adj""), (""text"", ""noun""), "" for those of "", (""you"", ""pronoun""), "" who "", (""like"", ""verb""), "" this sort of "", (""thing"", ""noun""), ""."") Drawable CanvasProvides a sketching canvas using Fabric.js. Created by @andfanilo.st_canvas(fill_color=""rgba(255, 165, 0, 0.3)"", stroke_width=stroke_width, stroke_color=stroke_color, background_color=bg_color, background_image=Image.open(bg_image) if bg_image else None, update_streamlit=realtime_update, height=150, drawing_mode=drawing_mode, point_display_radius=point_display_radius if drawing_mode == 'point' else 0, key=""canvas"",) TagsAdd tags to your Streamlit apps. Created by @gagan3012.st_tags(label='# Enter Keywords:', text='Press enter to add more', value=['Zero', 'One', 'Two'], suggestions=['five', 'six', 'seven', 'eight', 'nine', 'three', 'eleven', 'ten', 'four'], maxtags = 4, key='1') NLUApply text mining on a dataframe. Created by @JohnSnowLabs.nlu.load('sentiment').predict('I love NLU! <3') Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.mention(label=""An awesome Streamlit App"", icon=""streamlit"", url=""https://extras.streamlit.app"",) Next Data elements DataframesDisplay a dataframe as an interactive table.st.dataframe(my_data_frame) Data editorDisplay a data editor widget.edited = st.data_editor(df, num_rows=""dynamic"") Column configurationConfigure the display and editing behavior of dataframes and data editors.st.column_config.NumberColumn(""Price (in USD)"", min_value=0, format=""$%d"") Static tablesDisplay a static table.st.table(my_data_frame) MetricsDisplay a metric in big bold font, with an optional indicator of how the metric changed.st.metric(""My metric"", 42, 2) Dicts and JSONDisplay object or string as a pretty-printed JSON string.st.json(my_dict) Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration! PreviousImage CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates value = streamlit_image_coordinates(""https://placekitten.com/200/300"") st.write(value) Plotly EventsMake Plotly charts interactive!. Created by @null-jones.from streamlit_plotly_events import plotly_events fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.metric_cards import style_metric_cards col3.metric(label=""No Change"", value=5000, delta=0) style_metric_cards() Streamlit AggridImplementation of Ag-Grid component for Streamlit. Created by @PablocFonseca.df = pd.DataFrame({'col1': [1, 2, 3], 'col2': [4, 5, 6]}) grid_return = AgGrid(df, editable=True) new_df = grid_return['data'] Streamlit FoliumStreamlit Component for rendering Folium maps. Created by @randyzwitch.m = folium.Map(location=[39.949610, -75.150282], zoom_start=16) folium.Marker([39.949610, -75.150282], popup=""Liberty Bell"", tooltip=""Liberty Bell"").add_to(m) st_data = st_folium(m, width=725) Pandas ProfilingPandas profiling component for Streamlit. Created by @okld.df = pd.read_csv(""https://storage.googleapis.com/tf-datasets/titanic/train.csv"") pr = df.profile_report() st_profile_report(pr) Image CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates value = streamlit_image_coordinates(""https://placekitten.com/200/300"") st.write(value) Plotly EventsMake Plotly charts interactive!. Created by @null-jones.from streamlit_plotly_events import plotly_events fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.metric_cards import style_metric_cards col3.metric(label=""No Change"", value=5000, delta=0) style_metric_cards() Streamlit AggridImplementation of Ag-Grid component for Streamlit. Created by @PablocFonseca.df = pd.DataFrame({'col1': [1, 2, 3], 'col2': [4, 5, 6]}) grid_return = AgGrid(df, editable=True) new_df = grid_return['data'] Streamlit FoliumStreamlit Component for rendering Folium maps. Created by @randyzwitch.m = folium.Map(location=[39.949610, -75.150282], zoom_start=16) folium.Marker([39.949610, -75.150282], popup=""Liberty Bell"", tooltip=""Liberty Bell"").add_to(m) st_data = st_folium(m, width=725) Pandas ProfilingPandas profiling component for Streamlit. Created by @okld.df = pd.read_csv(""https://storage.googleapis.com/tf-datasets/titanic/train.csv"") pr = df.profile_report() st_profile_report(pr) Image CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates value = streamlit_image_coordinates(""https://placekitten.com/200/300"") st.write(value) Plotly EventsMake Plotly charts interactive!. Created by @null-jones.from streamlit_plotly_events import plotly_events fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.metric_cards import style_metric_cards col3.metric(label=""No Change"", value=5000, delta=0) style_metric_cards() Next Chart elements Simple area chartsDisplay an area chart.st.area_chart(my_data_frame) Simple bar chartsDisplay a bar chart.st.bar_chart(my_data_frame) Simple line chartsDisplay a line chart.st.line_chart(my_data_frame) Simple scatter chartsDisplay a line chart.st.scatter_chart(my_data_frame) Scatterplots on mapsDisplay a map with points on it.st.map(my_data_frame) MatplotlibDisplay a matplotlib.pyplot figure.st.pyplot(my_mpl_figure) AltairDisplay a chart using the Altair library.st.altair_chart(my_altair_chart) Vega-LiteDisplay a chart using the Vega-Lite library.st.vega_lite_chart(my_vega_lite_chart) PlotlyDisplay an interactive Plotly chart.st.plotly_chart(my_plotly_chart) BokehDisplay an interactive Bokeh chart.st.bokeh_chart(my_bokeh_chart) PyDeckDisplay a chart using the PyDeck library.st.pydeck_chart(my_pydeck_chart) GraphVizDisplay a graph using the dagre-d3 library.st.graphviz_chart(my_graphviz_spec) Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration! PreviousStreamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl(""https://assets5.lottiefiles.com/packages/lf20_V9t630.json"") st_lottie(lottie_hello, key=""hello"") Plotly EventsMake Plotly charts interactive!. Created by @null-jones.fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.chart += get_annotations_chart(annotations=[(""Mar 01, 2008"", ""Pretty good day for GOOG""), (""Dec 01, 2007"", ""Something's going wrong for GOOG & AAPL""), (""Nov 01, 2008"", ""Market starts again thanks to...""), (""Dec 01, 2009"", ""Small crash for GOOG after...""),],) st.altair_chart(chart, use_container_width=True) PlostA deceptively simple plotting library for Streamlit. Created by @tvst.import plost plost.line_chart(my_dataframe, x='time', y='stock_value', color='stock_name',) HiPlotHigh dimensional Interactive Plotting. Created by @facebookresearch.data = [{'dropout':0.1, 'lr': 0.001, 'loss': 10.0, 'optimizer': 'SGD'}, {'dropout':0.15, 'lr': 0.01, 'loss': 3.5, 'optimizer': 'Adam'}, {'dropout':0.3, 'lr': 0.1, 'loss': 4.5, 'optimizer': 'Adam'}] hip.Experiment.from_iterable(data).display() EChartsHigh dimensional Interactive Plotting. Created by @andfanilo.from streamlit_echarts import st_echarts st_echarts(options=options) Streamlit FoliumStreamlit Component for rendering Folium maps. Created by @randyzwitch.m = folium.Map(location=[39.949610, -75.150282], zoom_start=16) st_data = st_folium(m, width=725) Spacy-StreamlitspaCy building blocks and visualizers for Streamlit apps. Created by @explosion.models = [""en_core_web_sm"", ""en_core_web_md""] spacy_streamlit.visualize(models, ""Sundar Pichai is the CEO of Google."") Streamlit AgraphA Streamlit Graph Vis, based on react-grah-vis. Created by @ChrisDelClea.from streamlit_agraph import agraph, Node, Edge, Config agraph(nodes=nodes, edges=edges, config=config) Streamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl(""https://assets5.lottiefiles.com/packages/lf20_V9t630.json"") st_lottie(lottie_hello, key=""hello"") Plotly EventsMake Plotly charts interactive!. Created by @null-jones.fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.chart += get_annotations_chart(annotations=[(""Mar 01, 2008"", ""Pretty good day for GOOG""), (""Dec 01, 2007"", ""Something's going wrong for GOOG & AAPL""), (""Nov 01, 2008"", ""Market starts again thanks to...""), (""Dec 01, 2009"", ""Small crash for GOOG after...""),],) st.altair_chart(chart, use_container_width=True) PlostA deceptively simple plotting library for Streamlit. Created by @tvst.import plost plost.line_chart(my_dataframe, x='time', y='stock_value', color='stock_name',) HiPlotHigh dimensional Interactive Plotting. Created by @facebookresearch.data = [{'dropout':0.1, 'lr': 0.001, 'loss': 10.0, 'optimizer': 'SGD'}, {'dropout':0.15, 'lr': 0.01, 'loss': 3.5, 'optimizer': 'Adam'}, {'dropout':0.3, 'lr': 0.1, 'loss': 4.5, 'optimizer': 'Adam'}] hip.Experiment.from_iterable(data).display() EChartsHigh dimensional Interactive Plotting. Created by @andfanilo.from streamlit_echarts import st_echarts st_echarts(options=options) Streamlit FoliumStreamlit Component for rendering Folium maps. Created by @randyzwitch.m = folium.Map(location=[39.949610, -75.150282], zoom_start=16) st_data = st_folium(m, width=725) Spacy-StreamlitspaCy building blocks and visualizers for Streamlit apps. Created by @explosion.models = [""en_core_web_sm"", ""en_core_web_md""] spacy_streamlit.visualize(models, ""Sundar Pichai is the CEO of Google."") Streamlit AgraphA Streamlit Graph Vis, based on react-grah-vis. Created by @ChrisDelClea.from streamlit_agraph import agraph, Node, Edge, Config agraph(nodes=nodes, edges=edges, config=config) Streamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl(""https://assets5.lottiefiles.com/packages/lf20_V9t630.json"") st_lottie(lottie_hello, key=""hello"") Plotly EventsMake Plotly charts interactive!. Created by @null-jones.fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.chart += get_annotations_chart(annotations=[(""Mar 01, 2008"", ""Pretty good day for GOOG""), (""Dec 01, 2007"", ""Something's going wrong for GOOG & AAPL""), (""Nov 01, 2008"", ""Market starts again thanks to...""), (""Dec 01, 2009"", ""Small crash for GOOG after...""),],) st.altair_chart(chart, use_container_width=True) Next Input widgets ButtonDisplay a button widget.clicked = st.button(""Click me"") Download buttonDisplay a download button widget.st.download_button(""Download file"", file) Form buttonDisplay a form submit button. For use with st.form.st.form_submit_button(""Sign up"") Link buttonDisplay a link button.st.link_button(""Go to gallery"", url) Page linkDisplay a link to another page in a multipage app.st.page_link(""app.py"", label=""Home"", icon=""🏠"") st.page_link(""pages/profile.py"", label=""My profile"") CheckboxDisplay a checkbox widget.selected = st.checkbox(""I agree"") Color pickerDisplay a color picker widget.color = st.color_picker(""Pick a color"") MultiselectDisplay a multiselect widget. The multiselect widget starts as empty.choices = st.multiselect(""Buy"", [""milk"", ""apples"", ""potatoes""]) RadioDisplay a radio button widget.choice = st.radio(""Pick one"", [""cats"", ""dogs""]) SelectboxDisplay a select widget.choice = st.selectbox(""Pick one"", [""cats"", ""dogs""]) Select-sliderDisplay a slider widget to select items from a list.size = st.select_slider(""Pick a size"", [""S"", ""M"", ""L""]) ToggleDisplay a toggle widget.activated = st.toggle(""Activate"") Number inputDisplay a numeric input widget.choice = st.number_input(""Pick a number"", 0, 10) SliderDisplay a slider widget.number = st.slider(""Pick a number"", 0, 100) Date inputDisplay a date input widget.date = st.date_input(""Your birthday"") Time inputDisplay a time input widget.time = st.time_input(""Meeting time"") Chat inputDisplay a chat input widget.prompt = st.chat_input(""Say something"") if prompt: st.write(f""The user has sent: {prompt}"") Text-areaDisplay a multi-line text input widget.text = st.text_area(""Text to translate"") Text inputDisplay a single-line text input widget.name = st.text_input(""First name"") Data editorDisplay a data editor widget.edited = st.experimental_data_editor(df, num_rows=""dynamic"") File UploaderDisplay a file uploader widget.data = st.file_uploader(""Upload a CSV"") Camera inputDisplay a widget that allows users to upload images directly from a camera.image = st.camera_input(""Take a picture"") Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration! PreviousStreamlit ChatStreamlit Component for a Chatbot UI. Created by @AI-Yash.from streamlit_chat import message message(""My message"") message(""Hello bot!"", is_user=True) # align's the message to the right Streamlit Option MenuSelect a single item from a list of options in a menu. Created by @victoryhb.from streamlit_option_menu import option_menu option_menu(""Main Menu"", [""Home"", 'Settings'], icons=['house', 'gear'], menu_icon=""cast"", default_index=1) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.stoggle import stoggle stoggle( ""Click me!"", """"""🥷 Surprise! Here's some additional content"""""",) Streamlit ElementsCreate a draggable and resizable dashboard in Streamlit. Created by @okls.from streamlit_elements import elements, mui, html with elements(""new_element""): mui.Typography(""Hello world"") TagsAdd tags to your Streamlit apps. Created by @gagan3012.from streamlit_tags import st_tags st_tags(label='# Enter Keywords:', text='Press enter to add more', value=['Zero', 'One', 'Two'], suggestions=['five', 'six', 'seven', 'eight', 'nine', 'three', 'eleven', 'ten', 'four'], maxtags = 4, key='1') StqdmThe simplest way to handle a progress bar in streamlit app. Created by @Wirg.from stqdm import stqdm for _ in stqdm(range(50)): sleep(0.5) TimelineDisplay a Timeline in Streamlit apps using TimelineJS. Created by @innerdoc.from streamlit_timeline import timeline with open('example.json', ""r"") as f: timeline(f.read(), height=800) Camera input liveAlternative for st.camera_input which returns the webcam images live. Created by @blackary.from camera_input_live import camera_input_live image = camera_input_live() st.image(value) Streamlit AceAce editor component for Streamlit. Created by @okld.from streamlit_ace import st_ace content = st_ace() content Streamlit ChatStreamlit Component for a Chatbot UI. Created by @AI-Yash.from streamlit_chat import message message(""My message"") message(""Hello bot!"", is_user=True) # align's the message to the right Streamlit Option MenuSelect a single item from a list of options in a menu. Created by @victoryhb.from streamlit_option_menu import option_menu option_menu(""Main Menu"", [""Home"", 'Settings'], icons=['house', 'gear'], menu_icon=""cast"", default_index=1) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.stoggle import stoggle stoggle( ""Click me!"", """"""🥷 Surprise! Here's some additional content"""""",) Streamlit ElementsCreate a draggable and resizable dashboard in Streamlit. Created by @okls.from streamlit_elements import elements, mui, html with elements(""new_element""): mui.Typography(""Hello world"") TagsAdd tags to your Streamlit apps. Created by @gagan3012.from streamlit_tags import st_tags st_tags(label='# Enter Keywords:', text='Press enter to add more', value=['Zero', 'One', 'Two'], suggestions=['five', 'six', 'seven', 'eight', 'nine', 'three', 'eleven', 'ten', 'four'], maxtags = 4, key='1') StqdmThe simplest way to handle a progress bar in streamlit app. Created by @Wirg.from stqdm import stqdm for _ in stqdm(range(50)): sleep(0.5) TimelineDisplay a Timeline in Streamlit apps using TimelineJS. Created by @innerdoc.from streamlit_timeline import timeline with open('example.json', ""r"") as f: timeline(f.read(), height=800) Camera input liveAlternative for st.camera_input which returns the webcam images live. Created by @blackary.from camera_input_live import camera_input_live image = camera_input_live() st.image(value) Streamlit AceAce editor component for Streamlit. Created by @okld.from streamlit_ace import st_ace content = st_ace() content Streamlit ChatStreamlit Component for a Chatbot UI. Created by @AI-Yash.from streamlit_chat import message message(""My message"") message(""Hello bot!"", is_user=True) # align's the message to the right Streamlit Option MenuSelect a single item from a list of options in a menu. Created by @victoryhb.from streamlit_option_menu import option_menu option_menu(""Main Menu"", [""Home"", 'Settings'], icons=['house', 'gear'], menu_icon=""cast"", default_index=1) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.stoggle import stoggle stoggle( ""Click me!"", """"""🥷 Surprise! Here's some additional content"""""",) Next Media elements ImageDisplay an image or list of images.st.image(numpy_array) st.image(image_bytes) st.image(file) st.image(""https://example.com/myimage.jpg"") AudioDisplay an audio player.st.audio(numpy_array) st.audio(audio_bytes) st.audio(file) st.audio(""https://example.com/myaudio.mp3"", format=""audio/mp3"") VideoDisplay a video player.st.video(numpy_array) st.video(video_bytes) st.video(file) st.video(""https://example.com/myvideo.mp4"", format=""video/mp4"") Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration! PreviousStreamlit CropperA simple image cropper for Streamlit. Created by @turner-anderson.from streamlit_cropper import st_cropper st_cropper(img, realtime_update=realtime_update, box_color=box_color, aspect_ratio=aspect_ratio) Image CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates streamlit_image_coordinates(""https://placekitten.com/200/300"") Streamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl(""https://assets5.lottiefiles.com/packages/lf20_V9t630.json"") st_lottie(lottie_hello, key=""hello"") Streamlit WebrtcHandling and transmitting real-time video/audio streams with Streamlit. Created by @whitphx.from streamlit_webrtc import webrtc_streamer webrtc_streamer(key=""sample"") Drawable CanvasProvides a sketching canvas using Fabric.js. Created by @andfanilo.from streamlit_drawable_canvas import st_canvas st_canvas(fill_color=""rgba(255, 165, 0, 0.3)"", stroke_width=stroke_width, stroke_color=stroke_color, background_color=bg_color, background_image=Image.open(bg_image) if bg_image else None, update_streamlit=realtime_update, height=150, drawing_mode=drawing_mode, point_display_radius=point_display_radius if drawing_mode == 'point' else 0, key=""canvas"",) Image ComparisonCompare images with a slider using JuxtaposeJS. Created by @fcakyon.from streamlit_image_comparison import image_comparison image_comparison(img1=""image1.jpg"", img2=""image2.jpg"",) Streamlit CropperA simple image cropper for Streamlit. Created by @turner-anderson.from streamlit_cropper import st_cropper st_cropper(img, realtime_update=realtime_update, box_color=box_color, aspect_ratio=aspect_ratio) Image CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates streamlit_image_coordinates(""https://placekitten.com/200/300"") Streamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl(""https://assets5.lottiefiles.com/packages/lf20_V9t630.json"") st_lottie(lottie_hello, key=""hello"") Streamlit WebrtcHandling and transmitting real-time video/audio streams with Streamlit. Created by @whitphx.from streamlit_webrtc import webrtc_streamer webrtc_streamer(key=""sample"") Drawable CanvasProvides a sketching canvas using Fabric.js. Created by @andfanilo.from streamlit_drawable_canvas import st_canvas st_canvas(fill_color=""rgba(255, 165, 0, 0.3)"", stroke_width=stroke_width, stroke_color=stroke_color, background_color=bg_color, background_image=Image.open(bg_image) if bg_image else None, update_streamlit=realtime_update, height=150, drawing_mode=drawing_mode, point_display_radius=point_display_radius if drawing_mode == 'point' else 0, key=""canvas"",) Image ComparisonCompare images with a slider using JuxtaposeJS. Created by @fcakyon.from streamlit_image_comparison import image_comparison image_comparison(img1=""image1.jpg"", img2=""image2.jpg"",) Streamlit CropperA simple image cropper for Streamlit. Created by @turner-anderson.from streamlit_cropper import st_cropper st_cropper(img, realtime_update=realtime_update, box_color=box_color, aspect_ratio=aspect_ratio) Image CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates streamlit_image_coordinates(""https://placekitten.com/200/300"") Streamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl(""https://assets5.lottiefiles.com/packages/lf20_V9t630.json"") st_lottie(lottie_hello, key=""hello"") Next Layouts and containers ColumnsInsert containers laid out as side-by-side columns.col1, col2 = st.columns(2) col1.write(""this is column 1"") col2.write(""this is column 2"") ContainerInsert a multi-element container.c = st.container() st.write(""This will show last"") c.write(""This will show first"") c.write(""This will show second"") Modal dialogsInsert a modal dialog that can rerun independently from the rest of the script.@st.experimental_dialog(""Sign up"") def email_form(): name = st.text_input(""Name"") email = st.text_input(""Email"") EmptyInsert a single-element container.c = st.empty() st.write(""This will show last"") c.write(""This will be replaced"") c.write(""This will show first"") ExpanderInsert a multi-element container that can be expanded/collapsed.with st.expander(""Open to see more""): st.write(""This is more content"") PopoverInsert a multi-element popover container that can be opened/closed.with st.popover(""Settings""): st.checkbox(""Show completed"") SidebarDisplay items in a sidebar.st.sidebar.write(""This lives in the sidebar"") st.sidebar.button(""Click me!"") TabsInsert containers separated into tabs.tab1, tab2 = st.tabs([""Tab 1"", ""Tab2""]) tab1.write(""this is tab 1"") tab2.write(""this is tab 2"") Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration!Streamlit ElementsCreate a draggable and resizable dashboard in Streamlit. Created by @okls.from streamlit_elements import elements, mui, html with elements(""new_element""): mui.Typography(""Hello world"") PydanticAuto-generate Streamlit UI from Pydantic Models and Dataclasses. Created by @lukasmasuch.import streamlit_pydantic as sp sp.pydantic_form(key=""my_form"", model=ExampleModel) Streamlit PagesAn experimental version of Streamlit Multi-Page Apps. Created by @blackary.from st_pages import Page, show_pages, add_page_title show_pages([ Page(""streamlit_app.py"", ""Home"", ""🏠""), Page(""other_pages/page2.py"", ""Page 2"", "":books:""), ]) Chat elements Streamlit provides a few commands to help you build conversational apps. These chat elements are designed to be used in conjunction with each other, but you can also use them separately. st.chat_message lets you insert a chat message container into the app so you can display messages from the user or the app. Chat containers can contain other Streamlit elements, including charts, tables, text, and more. st.chat_input lets you display a chat input widget so the user can type in a message. Chat inputDisplay a chat input widget.prompt = st.chat_input(""Say something"") if prompt: st.write(f""The user has sent: {prompt}"") Chat messageInsert a chat message container.import numpy as np with st.chat_message(""user""): st.write(""Hello 👋"") st.line_chart(np.random.randn(30, 3)) Status containerDisplay output of long-running tasks in a container.with st.status('Running'): do_something_slow() st.write_streamWrite generators or streams to the app with a typewriter effect.st.write_stream(my_generator) st.write_stream(my_llm_stream) Status elements Progress barDisplay a progress bar.for i in range(101): st.progress(i) do_something_slow() SpinnerTemporarily displays a message while executing a block of code.with st.spinner(""Please wait...""): do_something_slow() Status containerDisplay output of long-running tasks in a container.with st.status('Running'): do_something_slow() ToastBriefly displays a toast message in the bottom-right corner.st.toast('Butter!', icon='🧈') BalloonsDisplay celebratory balloons!do_something() # Celebrate when all done! st.balloons() SnowflakesDisplay celebratory snowflakes!do_something() # Celebrate when all done! st.snow() Success boxDisplay a success message.st.success(""Match found!"") Info boxDisplay an informational message.st.info(""Dataset is updated every day at midnight."") Warning boxDisplay warning message.st.warning(""Unable to fetch image. Skipping..."") Error boxDisplay error message.st.error(""We encountered an error"") Exception outputDisplay an exception.e = RuntimeError(""This is an exception of type RuntimeError"") st.exception(e) Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration!StqdmThe simplest way to handle a progress bar in streamlit app. Created by @Wirg.from stqdm import stqdm for _ in stqdm(range(50)): sleep(0.5) Custom notification boxA custom notification box with the ability to close it out. Created by @Socvest.from streamlit_custom_notification_box import custom_notification_box styles = {'material-icons':{'color': 'red'}, 'text-icon-link-close-container': {'box-shadow': '#3896de 0px 4px'}, 'notification-text': {'':''}, 'close-button':{'':''}, 'link':{'':''}} custom_notification_box(icon='info', textDisplay='We are almost done with your registration...', externalLink='more info', url='#', styles=styles, key=""foo"") Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.let_it_rain import rain rain(emoji=""🎈"", font_size=54, falling_speed=5, animation_length=""infinite"",) App logic and configuration Navigation and pages Switch pageProgrammatically navigates to a specified page.st.switch_page(""pages/my_page.py"") Page linkDisplay a link to another page in a multipage app.st.page_link(""app.py"", label=""Home"", icon=""🏠"") st.page_link(""pages/profile.py"", label=""My profile"") Execution flow Modal dialogsInsert a modal dialog that can rerun independently from the rest of the script.@st.experimental_dialog(""Sign up"") def email_form(): name = st.text_input(""Name"") email = st.text_input(""Email"") FormsCreate a form that batches elements together with a “Submit"" button.with st.form(key='my_form'): name = st.text_input(""Name"") email = st.text_input(""Email"") st.form_submit_button(""Sign up"") Partial rerunsDefine a fragment to rerun independently from the rest of the script.@st.experimental_fragment(run_every=""10s"") def fragment(): df = get_data() st.line_chart(df) Rerun scriptRerun the script immediately.st.rerun() Stop executionStops execution immediately.st.stop() Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration!AutorefreshForce a refresh without tying up a script. Created by @kmcgrady.from streamlit_autorefresh import st_autorefresh st_autorefresh(interval=2000, limit=100, key=""fizzbuzzcounter"") PydanticAuto-generate Streamlit UI from Pydantic Models and Dataclasses. Created by @lukasmasuch.import streamlit_pydantic as sp sp.pydantic_form(key=""my_form"", model=ExampleModel) Streamlit PagesAn experimental version of Streamlit Multi-Page Apps. Created by @blackary.from st_pages import Page, show_pages, add_page_title show_pages([ Page(""streamlit_app.py"", ""Home"", ""🏠""), Page(""other_pages/page2.py"", ""Page 2"", "":books:""), ]) Caching and state Cache dataFunction decorator to cache functions that return data (e.g. dataframe transforms, database queries, ML inference).@st.cache_data def long_function(param1, param2): # Perform expensive computation here or # fetch data from the web here return data Cache resourceFunction decorator to cache functions that return global resources (e.g. database connections, ML models).@st.cache_resource def init_model(): # Return a global resource here return pipeline( ""sentiment-analysis"", model=""distilbert-base-uncased-finetuned-sst-2-english"" ) Session stateSession state is a way to share variables between reruns, for each user session.st.session_state['key'] = value Query parametersGet, set, or clear the query parameters that are shown in the browser's URL bar.st.query_params[key] = value st.query_params.clear() Connections and databases Setup your connection Create a connectionConnect to a data source or APIconn = st.connection('pets_db', type='sql') pet_owners = conn.query('select * from pet_owners') st.dataframe(pet_owners) Built-in connections SnowflakeConnectionA connection to Snowflake.conn = st.connection('snowflake') SQLConnectionA connection to a SQL database using SQLAlchemy.conn = st.connection('sql') Build your own connections Connection base classBuild your own connection with BaseConnection.class MyConnection(BaseConnection[myconn.MyConnection]): def _connect(self, **kwargs) -> MyConnection: return myconn.connect(**self._secrets, **kwargs) def query(self, query): return self._instance.query(query) Secrets management Secrets singletonAccess secrets from a local TOML file.key = st.secrets[""OpenAI_key""] Secrets fileSave your secrets in a per-project or per-profile TOML file.OpenAI_key = """" Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration!AuthenticatorA secure authentication module to validate user credentials. Created by @mkhorasani.import streamlit_authenticator as stauth authenticator = stauth.Authenticate( config['credentials'], config['cookie']['name'], config['cookie']['key'], config['cookie']['expiry_days'], config['preauthorized']) WS localStorageA simple synchronous way of accessing localStorage from your app. Created by @gagangoku.from streamlit_ws_localstorage import injectWebsocketCode ret = conn.setLocalStorageVal(key='k1', val='v1') st.write('ret: ' + ret) Streamlit Auth0The fastest way to provide comprehensive login inside Streamlit. Created by @conradbez.from auth0_component import login_button user_info = login_button(clientId, domain = domain) st.write(user_info) Custom Components Declare a componentCreate and register a custom component.st.components.v1.declare_component( ""custom_slider"", ""/frontend"", ) HTMLDisplay an HTML string in an iframe.st.components.v1.html( ""

Foo bar.

"" ) iframeLoad a remote URL in an iframe.st.components.v1.iframe( ""docs.streamlit.io"" ) Utilities and user info User infost.experimental_user returns information about the logged-in user of private apps on Streamlit Community Cloud.if st.experimental_user.email == ""foo@corp.com"": st.write(""Welcome back, "", st.experimental_user.email) else: st.write(""You are not authorized to view this page."") Get helpDisplay object’s doc string, nicely formatted.st.help(st.write) st.help(pd.DataFrame) Render HTMLRenders HTML strings to your app.css = """""" """""" st.html(css) Configuration Configuration fileConfigures the default settings for your app.your-project/ ├── .streamlit/ │ └── config.toml └── your_app.py Set page title, favicon, and moreConfigures the default settings of the page.st.set_page_config( page_title=""My app"", page_icon="":shark:"", ) Developer tools App testing st.testing.v1.AppTestst.testing.v1.AppTest simulates a running Streamlit app for testing.from streamlit.testing.v1 import AppTest at = AppTest.from_file(""streamlit_app.py"") at.secrets[""WORD""] = ""Foobar"" at.run() assert not at.exception at.text_input(""word"").input(""Bazbat"").run() assert at.warning[0].value == ""Try again."" AppTest.from_filest.testing.v1.AppTest.from_file initializes a simulated app from a file.from streamlit.testing.v1 import AppTest at = AppTest.from_file(""streamlit_app.py"") at.run() AppTest.from_stringst.testing.v1.AppTest.from_string initializes a simulated app from a string.from streamlit.testing.v1 import AppTest at = AppTest.from_string(app_script_as_string) at.run() AppTest.from_functionst.testing.v1.AppTest.from_function initializes a simulated app from a function.from streamlit.testing.v1 import AppTest at = AppTest.from_function(app_script_as_callable) at.run() BlockA representation of container elements, including: st.chat_message st.columns st.sidebar st.tabs The main body of the app. # at.sidebar returns a Block at.sidebar.button[0].click().run() assert not at.exception ElementThe base class for representation of all elements, including: st.title st.header st.markdown st.dataframe # at.title returns a sequence of Title # Title inherits from Element assert at.title[0].value == ""My awesome app"" ButtonA representation of st.button and st.form_submit_button.at.button[0].click().run() ChatInputA representation of st.chat_input.at.chat_input[0].set_value(""What is Streamlit?"").run() CheckboxA representation of st.checkbox.at.checkbox[0].check().run() ColorPickerA representation of st.color_picker.at.color_picker[0].pick(""#FF4B4B"").run() DateInputA representation of st.date_input.release_date = datetime.date(2023, 10, 26) at.date_input[0].set_value(release_date).run() MultiselectA representation of st.multiselect.at.multiselect[0].select(""New York"").run() NumberInputA representation of st.number_input.at.number_input[0].increment().run() RadioA representation of st.radio.at.radio[0].set_value(""New York"").run() SelectSliderA representation of st.select_slider.at.select_slider[0].set_range(""A"",""C"").run() SelectboxA representation of st.selectbox.at.selectbox[0].select(""New York"").run() SliderA representation of st.slider.at.slider[0].set_range(2,5).run() TextAreaA representation of st.text_area.at.text_area[0].input(""Streamlit is awesome!"").run() TextInputA representation of st.text_input.at.text_input[0].input(""Streamlit"").run() TimeInputA representation of st.time_input.at.time_input[0].increment().run() ToggleA representation of st.toggle.at.toggle[0].set_value(""True"").run() Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration!Pandas ProfilingPandas profiling component for Streamlit. Created by @okld.df = pd.read_csv(""https://storage.googleapis.com/tf-datasets/titanic/train.csv"") pr = df.profile_report() st_profile_report(pr) Streamlit AceAce editor component for Streamlit. Created by @okld.from streamlit_ace import st_ace content = st_ace() content Streamlit AnalyticsTrack & visualize user interactions with your streamlit app. Created by @jrieke.import streamlit_analytics with streamlit_analytics.track(): st.text_input(""Write something"") Previous: ConceptsNext: Write and magicforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy" https://docs.streamlit.io/develop/api-reference/app-testing/testing-element-classes#sttestingv1element_treebutton,"DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceremovePAGE ELEMENTSWrite and magicaddText elementsaddData elementsaddChart elementsaddInput widgetsaddMedia elementsaddLayouts and containersaddChat elementsaddStatus elementsaddThird-party componentsopen_in_newAPPLICATION LOGICNavigation and pagesaddExecution flowaddCaching and stateaddConnections and secretsaddCustom componentsaddUtilitiesaddConfigurationaddTOOLSApp testingremovest.testing.v1.AppTestTesting element classesCommand lineaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Develop/API reference/App testing/Testing element classesTesting element classes st.testing.v1.element_tree.Block The Block class has the same methods and attributes as AppTest. A Block instance represents a container of elements just as AppTest represents the entire app. For example, Block.button will produce a WidgetList of Button in the same manner as AppTest.button. ChatMessage, Column, and Tab all inherit from Block. For all container classes, parameters of the original element can be obtained as properties. For example, ChatMessage.avatar and Tab.label. st.testing.v1.element_tree.ElementStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeElement base class for testing. This class's methods and attributes are universal for all elements implemented in testing. For example, Caption, Code, Text, and Title inherit from Element. All widget classes also inherit from Element, but have additional methods specific to each widget type. See the AppTest class for the full list of supported elements. For all element classes, parameters of the original element can be obtained as properties. For example, Button.label, Caption.help, and Toast.icon. Class description[source] st.testing.v1.element_tree.Element(proto, root) Methods run(*, timeout=None) Run the AppTest script which contains the element. Attributes value The value or contents of the element. st.testing.v1.element_tree.ButtonStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.button and st.form_submit_button. Class description[source] st.testing.v1.element_tree.Button(proto, root) Methods click() Set the value of the button to True. run(*, timeout=None) Run the AppTest script which contains the element. set_value(v) Set the value of the button. Attributes value The value of the button. (bool) st.testing.v1.element_tree.ChatInputStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.chat_input. Class description[source] st.testing.v1.element_tree.ChatInput(proto, root) Methods run(*, timeout=None) Run the AppTest script which contains the element. set_value(v) Set the value of the widget. Attributes value The value of the widget. (str) st.testing.v1.element_tree.CheckboxStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.checkbox. Class description[source] st.testing.v1.element_tree.Checkbox(proto, root) Methods check() Set the value of the widget to True. run(*, timeout=None) Run the AppTest script which contains the element. set_value(v) Set the value of the widget. uncheck() Set the value of the widget to False. Attributes value The value of the widget. (bool) st.testing.v1.element_tree.ColorPickerStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.color_picker. Class description[source] st.testing.v1.element_tree.ColorPicker(proto, root) Methods pick(v) Set the value of the widget as a hex string. May omit the ""#"" prefix. run(*, timeout=None) Run the AppTest script which contains the element. set_value(v) Set the value of the widget as a hex string. Attributes value The currently selected value as a hex string. (str) st.testing.v1.element_tree.DateInputStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.date_input. Class description[source] st.testing.v1.element_tree.DateInput(proto, root) Methods run(*, timeout=None) Run the AppTest script which contains the element. set_value(v) Set the value of the widget. Attributes value The value of the widget. (date or Tuple of date) st.testing.v1.element_tree.MultiselectStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.multiselect. Class description[source] st.testing.v1.element_tree.Multiselect(proto, root) Methods run(*, timeout=None) Run the AppTest script which contains the element. select(v) Add a selection to the widget. Do nothing if the value is already selected. If testing a multiselect widget with repeated options, use set_value instead. set_value(v) Set the value of the multiselect widget. (list) unselect(v) Remove a selection from the widget. Do nothing if the value is not already selected. If a value is selected multiple times, the first instance is removed. Attributes format_func The widget's formatting function for displaying options. (callable) indices The indices of the currently selected values from the options. (list) value The currently selected values from the options. (list) st.testing.v1.element_tree.NumberInputStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.number_input. Class description[source] st.testing.v1.element_tree.NumberInput(proto, root) Methods decrement() Decrement the st.number_input widget as if the user clicked ""-"". increment() Increment the st.number_input widget as if the user clicked ""+"". run(*, timeout=None) Run the AppTest script which contains the element. set_value(v) Set the value of the st.number_input widget. Attributes value Get the current value of the st.number_input widget. st.testing.v1.element_tree.RadioStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.radio. Class description[source] st.testing.v1.element_tree.Radio(proto, root) Methods run(*, timeout=None) Run the AppTest script which contains the element. set_value(v) Set the selection by value. Attributes format_func The widget's formatting function for displaying options. (callable) index The index of the current selection. (int) value The currently selected value from the options. (Any) st.testing.v1.element_tree.SelectSliderStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.select_slider. Class description[source] st.testing.v1.element_tree.SelectSlider(proto, root) Methods run(*, timeout=None) Run the AppTest script which contains the element. set_range(lower, upper) Set the ranged selection by values. set_value(v) Set the (single) selection by value. Attributes format_func The widget's formatting function for displaying options. (callable) value The currently selected value or range. (Any or Sequence of Any) st.testing.v1.element_tree.SelectboxStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.selectbox. Class description[source] st.testing.v1.element_tree.Selectbox(proto, root) Methods run(*, timeout=None) Run the AppTest script which contains the element. select(v) Set the selection by value. select_index(index) Set the selection by index. set_value(v) Set the selection by value. Attributes format_func The widget's formatting function for displaying options. (callable) index The index of the current selection. (int) value The currently selected value from the options. (Any) st.testing.v1.element_tree.SliderStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.slider. Class description[source] st.testing.v1.element_tree.Slider(proto, root) Methods run(*, timeout=None) Run the AppTest script which contains the element. set_range(lower, upper) Set the ranged value of the slider. set_value(v) Set the (single) value of the slider. Attributes value The currently selected value or range. (Any or Sequence of Any) st.testing.v1.element_tree.TextAreaStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.text_area. Class description[source] st.testing.v1.element_tree.TextArea(proto, root) Methods input(v) Set the value of the widget only if the value does not exceed the maximum allowed characters. run(*, timeout=None) Run the AppTest script which contains the element. set_value(v) Set the value of the widget. Attributes value The current value of the widget. (str) st.testing.v1.element_tree.TextInputStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.text_input. Class description[source] st.testing.v1.element_tree.TextInput(proto, root) Methods input(v) Set the value of the widget only if the value does not exceed the maximum allowed characters. run(*, timeout=None) Run the AppTest script which contains the element. set_value(v) Set the value of the widget. Attributes value The current value of the widget. (str) st.testing.v1.element_tree.TimeInputStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.time_input. Class description[source] st.testing.v1.element_tree.TimeInput(proto, root) Methods decrement() Select the previous available time. increment() Select the next available time. run(*, timeout=None) Run the AppTest script which contains the element. set_value(v) Set the value of the widget. Attributes value The current value of the widget. (time) st.testing.v1.element_tree.ToggleStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.toggle. Class description[source] st.testing.v1.element_tree.Toggle(proto, root) Methods run(*, timeout=None) Run the AppTest script which contains the element. set_value(v) Set the value of the widget. Attributes value The current value of the widget. (bool) Previous: st.testing.v1.AppTestNext: Command lineforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy" https://docs.streamlit.io/develop/concepts/custom-components#custom-components,"DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsremoveCOREArchitecture & executionaddMultipage appsaddApp designaddADDITIONALConnections and secretsaddCustom componentsremoveIntro to custom componentsCreate a ComponentPublish a ComponentLimitationsComponent galleryopen_in_newConfiguration and themingaddApp testingaddAPI referenceaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Develop/Concepts/Custom componentsCustom Components Components are third-party Python modules that extend what's possible with Streamlit. How to use a Component Components are super easy to use: Start by finding the Component you'd like to use. Two great resources for this are: The Component gallery This thread, by Fanilo A. from our forums. Install the Component using your favorite Python package manager. This step and all following steps are described in your component's instructions. For example, to use the fantastic AgGrid Component, you first install it with: pip install streamlit-aggrid In your Python code, import the Component as described in its instructions. For AgGrid, this step is: from st_aggrid import AgGrid ...now you're ready to use it! For AgGrid, that's: AgGrid(my_dataframe) Making your own Component If you're interested in making your own component, check out the following resources: Create a Component Publish a Component Components API Blog post for when we launched Components! Alternatively, if you prefer to learn using videos, our engineer Tim Conkling has put together some amazing tutorials: Video tutorial, part 1 Video tutorial, part 2 Previous: Connections and secretsNext: Intro to custom componentsforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy" https://docs.streamlit.io/deploy/tutorials/kubernetes#create-a-docker-container,"DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsremoveDockerKubernetesschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Deploy/Other platforms/KubernetesDeploy Streamlit using Kubernetes Introduction So you have an amazing app and you want to start sharing it with other people, what do you do? You have a few options. First, where do you want to run your Streamlit app, and how do you want to access it? On your corporate network - Most corporate networks are closed to the outside world. You typically use a VPN to log onto your corporate network and access resources there. You could run your Streamlit app on a server in your corporate network for security reasons, to ensure that only folks internal to your company can access it. On the cloud - If you'd like to access your Streamlit app from outside of a corporate network, or share your app with folks outside of your home network or laptop, you might choose this option. In this case, it'll depend on your hosting provider. We have community-submitted guides from Heroku, AWS, and other providers. Wherever you decide to deploy your app, you will first need to containerize it. This guide walks you through using Kubernetes to deploy your app. If you prefer Docker see Deploy Streamlit using Docker. Prerequisites Install Docker Engine Install the gcloud CLI Install Docker Engine If you haven't already done so, install Docker on your server. Docker provides .deb and .rpm packages from many Linux distributions, including: Debian Ubuntu Verify that Docker Engine is installed correctly by running the hello-world Docker image: sudo docker run hello-world starTipFollow Docker's official post-installation steps for Linux to run Docker as a non-root user, so that you don't have to preface the docker command with sudo. Install the gcloud CLI In this guide, we will orchestrate Docker containers with Kubernetes and host docker images on the Google Container Registry (GCR). As GCR is a Google-supported Docker registry, we need to register gcloud as the Docker credential helper. Follow the official documentation to Install the gcloud CLI and initialize it. Create a Docker container We need to create a docker container which contains all the dependencies and the application code. Below you can see the entrypoint, i.e. the command run when the container starts, and the Dockerfile definition. Create an entrypoint script Create a run.sh script containing the following: #!/bin/bash APP_PID= stopRunningProcess() { # Based on https://linuxconfig.org/how-to-propagate-a-signal-to-child-processes-from-a-bash-script if test ! ""${APP_PID}"" = '' && ps -p ${APP_PID} > /dev/null ; then > /proc/1/fd/1 echo ""Stopping ${COMMAND_PATH} which is running with process ID ${APP_PID}"" kill -TERM ${APP_PID} > /proc/1/fd/1 echo ""Waiting for ${COMMAND_PATH} to process SIGTERM signal"" wait ${APP_PID} > /proc/1/fd/1 echo ""All processes have stopped running"" else > /proc/1/fd/1 echo ""${COMMAND_PATH} was not started when the signal was sent or it has already been stopped"" fi } trap stopRunningProcess EXIT TERM source ${VIRTUAL_ENV}/bin/activate streamlit run ${HOME}/app/streamlit_app.py & APP_ID=${!} wait ${APP_ID} Create a Dockerfile Docker builds images by reading the instructions from a Dockerfile. A Dockerfile is a text document that contains all the commands a user could call on the command line to assemble an image. Learn more in the Dockerfile reference. The docker build command builds an image from a Dockerfile. The docker run command first creates a container over the specified image, and then starts it using the specified command. Here's an example Dockerfile that you can add to the root of your directory. FROM python:3.8-slim RUN groupadd --gid 1000 appuser \ && useradd --uid 1000 --gid 1000 -ms /bin/bash appuser RUN pip3 install --no-cache-dir --upgrade \ pip \ virtualenv RUN apt-get update && apt-get install -y \ build-essential \ software-properties-common \ git USER appuser WORKDIR /home/appuser RUN git clone https://github.com/streamlit/streamlit-example.git app ENV VIRTUAL_ENV=/home/appuser/venv RUN virtualenv ${VIRTUAL_ENV} RUN . ${VIRTUAL_ENV}/bin/activate && pip install -r app/requirements.txt EXPOSE 8501 COPY run.sh /home/appuser ENTRYPOINT [""./run.sh""] priority_highImportantAs mentioned in Development flow, for Streamlit version 1.10.0 and higher, Streamlit apps cannot be run from the root directory of Linux distributions. Your main script should live in a directory other than the root directory. If you try to run a Streamlit app from the root directory, Streamlit will throw a FileNotFoundError: [Errno 2] No such file or directory error. For more information, see GitHub issue #5239.If you are using Streamlit version 1.10.0 or higher, you must set the WORKDIR to a directory other than the root directory. For example, you can set the WORKDIR to /home/appuser as shown in the example Dockerfile above. Build a Docker image Put the above files (run.sh and Dockerfile) in the same folder and build the docker image: docker build --platform linux/amd64 -t gcr.io/$GCP_PROJECT_ID/k8s-streamlit:test . priority_highImportantReplace $GCP_PROJECT_ID in the above command with the name of your Google Cloud project. Upload the Docker image to a container registry The next step is to upload the Docker image to a container registry. In this example, we will use the Google Container Registry (GCR). Start by enabling the Container Registry API. Sign in to Google Cloud and navigate to your project’s Container Registry and click Enable. We can now build the Docker image from the previous step and push it to our project’s GCR. Be sure to replace $GCP_PROJECT_ID in the docker push command with the name of your project: gcloud auth configure-docker docker push gcr.io/$GCP_PROJECT_ID/k8s-streamlit:test Create a Kubernetes deployment For this step you will need a: Running Kubernetes service Custom domain for which you can generate a TLS certificate DNS service where you can configure your custom domain to point to the application IP As the image was uploaded to the container registry in the previous step, we can run it in Kubernetes using the below configurations. Install and run Kubernetes Make sure your Kubernetes client, kubectl, is installed and running on your machine. Configure a Google OAuth Client and oauth2-proxy For configuring the Google OAuth Client, please see Google Auth Provider. Configure oauth2-proxy to use the desired OAuth Provider Configuration and update the oath2-proxy config in the config map. The below configuration contains a ouath2-proxy sidecar container which handles the authentication with Google. You can learn more from the oauth2-proxy repository. Create a Kubernetes configuration file Create a YAML configuration file named k8s-streamlit.yaml: apiVersion: v1 kind: ConfigMap metadata: name: streamlit-configmap data: oauth2-proxy.cfg: |- http_address = ""0.0.0.0:4180"" upstreams = [""http://127.0.0.1:8501/""] email_domains = [""*""] client_id = """" client_secret = """" cookie_secret = ""<16, 24, or 32 bytes>"" redirect_url = --- apiVersion: apps/v1 kind: Deployment metadata: name: streamlit-deployment labels: app: streamlit spec: replicas: 1 selector: matchLabels: app: streamlit template: metadata: labels: app: streamlit spec: containers: - name: oauth2-proxy image: quay.io/oauth2-proxy/oauth2-proxy:v7.2.0 args: [""--config"", ""/etc/oauth2-proxy/oauth2-proxy.cfg""] ports: - containerPort: 4180 livenessProbe: httpGet: path: /ping port: 4180 scheme: HTTP readinessProbe: httpGet: path: /ping port: 4180 scheme: HTTP volumeMounts: - mountPath: ""/etc/oauth2-proxy"" name: oauth2-config - name: streamlit image: gcr.io/GCP_PROJECT_ID/k8s-streamlit:test imagePullPolicy: Always ports: - containerPort: 8501 livenessProbe: httpGet: path: /_stcore/health port: 8501 scheme: HTTP timeoutSeconds: 1 readinessProbe: httpGet: path: /_stcore/health port: 8501 scheme: HTTP timeoutSeconds: 1 resources: limits: cpu: 1 memory: 2Gi requests: cpu: 100m memory: 745Mi volumes: - name: oauth2-config configMap: name: streamlit-configmap --- apiVersion: v1 kind: Service metadata: name: streamlit-service spec: type: LoadBalancer selector: app: streamlit ports: - name: streamlit-port protocol: TCP port: 80 targetPort: 4180 priority_highImportantWhile the above configurations can be copied verbatim, you will have to configure the oauth2-proxy yourself and use the correct GOOGLE_CLIENT_ID, GOOGLE_CLIENT_ID, GCP_PROJECT_ID, and REDIRECT_URL. Now create the configuration from the file in Kubernetes with the kubectl create command: kubctl create -f k8s-streamlit.yaml Set up TLS support Since you are using the Google authentication, you will need to set up TLS support. Find out how in TLS Configuration. Verify the deployment Once the deployment and the service are created, we need to wait a couple of minutes for the public IP address to become available. We can check when that is ready by running: kubectl get service streamlit-service -o jsonpath='{.status.loadBalancer.ingress[0].ip}' After the public IP is assigned, you will need to configure in your DNS service an A record pointing to the above IP address.Previous: DockerNext: Knowledge baseforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy" https://docs.streamlit.io/develop/api-reference/utilities/st.experimental_user#examples,"DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceremovePAGE ELEMENTSWrite and magicaddText elementsaddData elementsaddChart elementsaddInput widgetsaddMedia elementsaddLayouts and containersaddChat elementsaddStatus elementsaddThird-party componentsopen_in_newAPPLICATION LOGICNavigation and pagesaddExecution flowaddCaching and stateaddConnections and secretsaddCustom componentsaddUtilitiesremovest.experimental_userst.helpst.htmlConfigurationaddTOOLSApp testingaddCommand lineaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Develop/API reference/Utilities/st.experimental_userpriority_highImportantThis is an experimental feature. Experimental features and their APIs may change or be removed at any time. To learn more, click here. st.experimental_userStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA read-only, dict-like object for accessing information about current user. st.experimental_user is dependant on the host platform running the Streamlit app. If the host platform has not configured the function, it will behave as it does in a locally running app. Properties can by accessed via key or attribute notation. For example, st.experimental_user[""email""] or st.experimental_user.email. Class description[source] st.experimental_user() Methods to_dict() Get user info as a dictionary. Attributes email (str) If running locally, this property returns the string literal ""test@example.com"". If running on Streamlit Community Cloud, this property returns one of two values: None if the user is not logged in or not a member of the app's workspace. Such users appear under anonymous pseudonyms in the app's analytics. The user's email if the the user is logged in and a member of the app's workspace. Such users are identified by their email in the app's analytics. Examples The ability to personalize apps for the user viewing the app is a great way to make your app more engaging. It unlocks a plethora of use-cases for developers, some of which could include: showing additional controls for admins, visualizing a user's Streamlit history, a personalized stock ticker, a chatbot app, and much more. We're excited to see what you build with this feature! Here's a code snippet that shows extra buttons for admins: # Show extra buttons for admin users. ADMIN_USERS = { 'person1@email.com', 'person2@email.com', 'person3@email.com' } if st.experimental_user.email in ADMIN_USERS: display_the_extra_admin_buttons() display_the_interface_everyone_sees() Show different content to users based on their email address: # Show different content based on the user's email address. if st.experimental_user.email == 'jane@email.com': display_jane_content() elif st.experimental_user.email == 'adam@foocorp.io': display_adam_content() else: st.write(""Please contact us to get access!"") Greet users with their name that's stored in a database: # Greet the user by their name. if st.experimental_user.email: # Get the user's name from the database. name = get_name_from_db(st.experimental_user.email) st.write('Hello, %s!' % name) st.experimental_user.to_dictStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeGet user info as a dictionary. This method primarily exists for internal use and is not needed for most cases. st.experimental_user returns an object that inherits from dict by default. Function signature[source] st.experimental_user.to_dict() Returns(Dict[str,str]) A dictionary of the current user's information. Previous: UtilitiesNext: st.helpforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy" https://docs.streamlit.io/develop/api-reference/text#formatted-text,"DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceremovePAGE ELEMENTSWrite and magicaddText elementsremoveHEADINGS & BODYst.titlest.headerst.subheaderst.markdownFORMATTED TEXTst.captionst.codest.dividerst.echost.latexst.textData elementsaddChart elementsaddInput widgetsaddMedia elementsaddLayouts and containersaddChat elementsaddStatus elementsaddThird-party componentsopen_in_newAPPLICATION LOGICNavigation and pagesaddExecution flowaddCaching and stateaddConnections and secretsaddCustom componentsaddUtilitiesaddConfigurationaddTOOLSApp testingaddCommand lineaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Develop/API reference/Text elementsText elements Streamlit apps usually start with a call to st.title to set the app's title. After that, there are 2 heading levels you can use: st.header and st.subheader. Pure text is entered with st.text, and Markdown with st.markdown. We also offer a ""swiss-army knife"" command called st.write, which accepts multiple arguments, and multiple data types. And as described above, you can also use magic commands in place of st.write. Headings and body text MarkdownDisplay string formatted as Markdown.st.markdown(""Hello **world**!"") TitleDisplay text in title formatting.st.title(""The app title"") HeaderDisplay text in header formatting.st.header(""This is a header"") SubheaderDisplay text in subheader formatting.st.subheader(""This is a subheader"") Formatted text CaptionDisplay text in small font.st.caption(""This is written small caption text"") Code blockDisplay a code block with optional syntax highlighting.st.code(""a = 1234"") EchoDisplay some code on the app, then execute it. Useful for tutorials.with st.echo(): st.write('This code will be printed') Preformatted textWrite fixed-width and preformatted text.st.text(""Hello world"") LaTeXDisplay mathematical expressions formatted as LaTeX.st.latex(""\int a x^2 \,dx"") DividerDisplay a horizontal rule.st.divider() Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration! PreviousTagsAdd tags to your Streamlit apps. Created by @gagan3012.st_tags(label='# Enter Keywords:', text='Press enter to add more', value=['Zero', 'One', 'Two'], suggestions=['five', 'six', 'seven', 'eight', 'nine', 'three', 'eleven', 'ten', 'four'], maxtags = 4, key='1') NLUApply text mining on a dataframe. Created by @JohnSnowLabs.nlu.load('sentiment').predict('I love NLU! <3') Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.mention(label=""An awesome Streamlit App"", icon=""streamlit"", url=""https://extras.streamlit.app"",) Annotated textDisplay annotated text in Streamlit apps. Created by @tvst.annotated_text(""This "", (""is"", ""verb""), "" some "", (""annotated"", ""adj""), (""text"", ""noun""), "" for those of "", (""you"", ""pronoun""), "" who "", (""like"", ""verb""), "" this sort of "", (""thing"", ""noun""), ""."") Drawable CanvasProvides a sketching canvas using Fabric.js. Created by @andfanilo.st_canvas(fill_color=""rgba(255, 165, 0, 0.3)"", stroke_width=stroke_width, stroke_color=stroke_color, background_color=bg_color, background_image=Image.open(bg_image) if bg_image else None, update_streamlit=realtime_update, height=150, drawing_mode=drawing_mode, point_display_radius=point_display_radius if drawing_mode == 'point' else 0, key=""canvas"",) TagsAdd tags to your Streamlit apps. Created by @gagan3012.st_tags(label='# Enter Keywords:', text='Press enter to add more', value=['Zero', 'One', 'Two'], suggestions=['five', 'six', 'seven', 'eight', 'nine', 'three', 'eleven', 'ten', 'four'], maxtags = 4, key='1') NLUApply text mining on a dataframe. Created by @JohnSnowLabs.nlu.load('sentiment').predict('I love NLU! <3') Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.mention(label=""An awesome Streamlit App"", icon=""streamlit"", url=""https://extras.streamlit.app"",) Annotated textDisplay annotated text in Streamlit apps. Created by @tvst.annotated_text(""This "", (""is"", ""verb""), "" some "", (""annotated"", ""adj""), (""text"", ""noun""), "" for those of "", (""you"", ""pronoun""), "" who "", (""like"", ""verb""), "" this sort of "", (""thing"", ""noun""), ""."") Drawable CanvasProvides a sketching canvas using Fabric.js. Created by @andfanilo.st_canvas(fill_color=""rgba(255, 165, 0, 0.3)"", stroke_width=stroke_width, stroke_color=stroke_color, background_color=bg_color, background_image=Image.open(bg_image) if bg_image else None, update_streamlit=realtime_update, height=150, drawing_mode=drawing_mode, point_display_radius=point_display_radius if drawing_mode == 'point' else 0, key=""canvas"",) TagsAdd tags to your Streamlit apps. Created by @gagan3012.st_tags(label='# Enter Keywords:', text='Press enter to add more', value=['Zero', 'One', 'Two'], suggestions=['five', 'six', 'seven', 'eight', 'nine', 'three', 'eleven', 'ten', 'four'], maxtags = 4, key='1') NLUApply text mining on a dataframe. Created by @JohnSnowLabs.nlu.load('sentiment').predict('I love NLU! <3') Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.mention(label=""An awesome Streamlit App"", icon=""streamlit"", url=""https://extras.streamlit.app"",) NextPrevious: Write and magicNext: st.titleforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy" https://docs.streamlit.io/develop/tutorials/execution-flow/create-a-multiple-container-fragment#create-a-fragment-across-multiple-containers,"DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceaddTutorialsremoveExecution flowremoveFRAGMENTSRerun your app from a fragmentCreate a multiple-container fragmentStart and stop a streaming fragmentConnect to data sourcesaddMultipage appsaddWork with LLMsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Develop/Tutorials/Execution flow/Create a multiple container fragmentCreate a fragment across multiple containers Streamlit lets you turn functions into fragments, which can rerun independently from the full script. If your fragment doesn't write to outside containers, Streamlit will clear and redraw all the fragment elements with each fragment rerun. However, if your fragment does write elements to outside containers, Streamlit will not clear those elements during a fragment rerun. Instead, those elements accumulate with each fragment rerun until the next full-script rerun. If you want a fragment to update multiple containers in your app, use st.empty() containers to prevent accumulating elements. Applied concepts Use fragments to run two independent processes separately. Distribute a fragment across multiple containers. Prerequisites streamlit>=1.33.0 This tutorial uses fragments, which require Streamlit version 1.33.0 or later. This tutorial assumes you have a clean working directory called your-repository. You should have a basic understanding of fragments and st.empty(). Summary In this toy example, you'll build an app with six containers. Three containers will have orange cats. The other three containers will have black cats. You'll have three buttons in the sidebar: ""Herd the black cats,"" ""Herd the orange cats,"" and ""Herd all the cats."" Since herding cats is slow, you'll use fragments to help Streamlit run the associated processes efficiently. You'll create two fragments, one for the black cats and one for the orange cats. Since the buttons will be in the sidebar and the fragments will update containers in the main body, you'll use a trick with st.empty() to ensure you don't end up with too many cats in your app (if it's even possible to have too many cats). 😻 Here's a look at what you'll build: Complete codeexpand_moreimport streamlit as st import time st.title(""Cats!"") row1 = st.columns(3) row2 = st.columns(3) grid = [col.container(height=200) for col in row1 + row2] safe_grid = [card.empty() for card in grid] def black_cats(): time.sleep(1) st.title(""🐈‍⬛ 🐈‍⬛"") st.markdown(""🐾 🐾 🐾 🐾"") def orange_cats(): time.sleep(1) st.title(""🐈 🐈"") st.markdown(""🐾 🐾 🐾 🐾"") @st.experimental_fragment def herd_black_cats(card_a, card_b, card_c): st.button(""Herd the black cats"") container_a = card_a.container() container_b = card_b.container() container_c = card_c.container() with container_a: black_cats() with container_b: black_cats() with container_c: black_cats() @st.experimental_fragment def herd_orange_cats(card_a, card_b, card_c): st.button(""Herd the orange cats"") container_a = card_a.container() container_b = card_b.container() container_c = card_c.container() with container_a: orange_cats() with container_b: orange_cats() with container_c: orange_cats() with st.sidebar: herd_black_cats(grid[0].empty(), grid[2].empty(), grid[4].empty()) herd_orange_cats(grid[1].empty(), grid[3].empty(), grid[5].empty()) st.button(""Herd all the cats"") Built with Streamlit 🎈Fullscreen open_in_new Build the example Initialize your app In your_repository, create a file named app.py. In a terminal, change directories to your_repository and start your app. streamlit run app.py Your app will be blank since you still need to add code. In app.py, write the following: import streamlit as st import time You'll use time.sleep() to slow things down and see the fragments working. Save your app.py file and view your running app. Click ""Always rerun"" or hit your ""A"" key in your running app. Your running preview will automatically update as you save changes to app.py. Your preview will still be blank. Return to your code. Frame out your app's containers Add a title to your app and two rows of three containers. st.title(""Cats!"") row1 = st.columns(3) row2 = st.columns(3) grid = [col.container(height=200) for col in row1 + row2] Save your file to see your updated preview. Define a helper function to draw two black cats. def black_cats(): time.sleep(1) st.title(""🐈‍⬛ 🐈‍⬛"") st.markdown(""🐾 🐾 🐾 🐾"") This function represents ""herding two cats"" and uses time.sleep() to simulate a slower process. You will use this to draw two cats in one of your grid cards later on. Define another helper function to draw two orange cats. def orange_cats(): time.sleep(1) st.title(""🐈 🐈"") st.markdown(""🐾 🐾 🐾 🐾"") (Optional) Test out your functions by calling each one within a grid card. with grid[0]: black_cats() with grid[1]: orange_cats() Save your app.py file to see the preview. Delete these four lines when finished. Define your fragments Since each fragment will span across the sidebar and three additional containers, you'll use the sidebar to hold the main body of the fragment and pass the three containers as function arguments. Use an @st.experimental_fragment decorator and start your black-cat fragment definition. @st.experimental_fragment def herd_black_cats(card_a, card_b, card_c): Add a button for rerunning this fragment. st.button(""Herd the black cats"") Write to each container using your helper function. with card_a: black_cats() with card_b: black_cats() with card_c: black_cats() This code above will not behave as desired, but you'll explore and correct this in the following steps. Test out your code. Call your fragment function in the sidebar. with st.sidebar: herd_black_cats(grid[0], grid[2], grid[4]) Save your file and try using the button in the sidebar. More and more cats are appear in the cards with each fragment rerun! This is the expected behavior when fragments write to outside containers. To fix this, you will pass st.empty() containers to your fragment function. Delete the lines of code from the previous two steps. To prepare for using st.empty() containers, correct your cat-herding function as follows. After the button, define containers to place in the st.empty() cards you'll pass to your fragment. container_a = card_a.container() container_b = card_b.container() container_c = card_c.container() with container_a: black_cats() with container_b: black_cats() with container_c: black_cats() In this new version, card_a, card_b, and card_c will be st.empty() containers. You create container_a, container_b, and container_c to allow Streamlit to draw multiple elements on each grid card. Similarly define your orange-cat fragment function. @st.experimental_fragment def herd_orange_cats(card_a, card_b, card_c): st.button(""Herd the orange cats"") container_a = card_a.container() container_b = card_b.container() container_c = card_c.container() with container_a: orange_cats() with container_b: orange_cats() with container_c: orange_cats() Put the functions together together to create an app Call both of your fragments in the sidebar. with st.sidebar: herd_black_cats(grid[0].empty(), grid[2].empty(), grid[4].empty()) herd_orange_cats(grid[1].empty(), grid[3].empty(), grid[5].empty()) By creating st.empty() containers in each card and passing them to your fragments, you prevent elements from accumulating in the cards with each fragment rerun. If you create the st.empty() containers earlier in your app, full-script reruns will clear the orange-cat cards while (first) rendering the black-cat cards. Include a button outside of your fragments. When clicked, the button will trigger a full-script rerun since you're calling its widget function outside of any fragment. st.button(""Herd all the cats"") Save your file and try out the app! When you click ""Herd the black cats"" or ""Herd the orange cats,"" Streamlit will only redraw the three related cards. When you click ""Herd all the cats,"" Streamlit redraws all six cards. Previous: Rerun your app from a fragmentNext: Start and stop a streaming fragmentforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy" https://docs.streamlit.io/develop/api-reference/charts/st.altair_chart#step-2-annotate-the-chart,"DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceremovePAGE ELEMENTSWrite and magicaddText elementsaddData elementsaddChart elementsremoveSIMPLEst.area_chartst.bar_chartst.line_chartst.mapst.scatter_chartADVANCEDst.altair_chartst.bokeh_chartst.graphviz_chartst.plotly_chartst.pydeck_chartst.pyplotst.vega_lite_chartInput widgetsaddMedia elementsaddLayouts and containersaddChat elementsaddStatus elementsaddThird-party componentsopen_in_newAPPLICATION LOGICNavigation and pagesaddExecution flowaddCaching and stateaddConnections and secretsaddCustom componentsaddUtilitiesaddConfigurationaddTOOLSApp testingaddCommand lineaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Develop/API reference/Chart elements/st.altair_chartst.altair_chartStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeDisplay a chart using the Altair library. Function signature[source] st.altair_chart(altair_chart, use_container_width=False, theme=""streamlit"") Parameters altair_chart (altair.Chart) The Altair chart object to display. use_container_width (bool) If True, set the chart width to the column width. This takes precedence over Altair's native width value. theme (""streamlit"" or None) The theme of the chart. Currently, we only support ""streamlit"" for the Streamlit defined design or None to fallback to the default behavior of the library. Example import streamlit as st import pandas as pd import numpy as np import altair as alt chart_data = pd.DataFrame(np.random.randn(20, 3), columns=[""a"", ""b"", ""c""]) c = ( alt.Chart(chart_data) .mark_circle() .encode(x=""a"", y=""b"", size=""c"", color=""c"", tooltip=[""a"", ""b"", ""c""]) ) st.altair_chart(c, use_container_width=True) Built with Streamlit 🎈Fullscreen open_in_new Examples of Altair charts can be found at https://altair-viz.github.io/gallery/. Theming Altair charts are displayed using the Streamlit theme by default. This theme is sleek, user-friendly, and incorporates Streamlit's color palette. The added benefit is that your charts better integrate with the rest of your app's design. The Streamlit theme is available from Streamlit 1.16.0 through the theme=""streamlit"" keyword argument. To disable it, and use Altair's native theme, use theme=None instead. Let's look at an example of charts with the Streamlit theme and the native Altair theme: import altair as alt from vega_datasets import data source = data.cars() chart = alt.Chart(source).mark_circle().encode( x='Horsepower', y='Miles_per_Gallon', color='Origin', ).interactive() tab1, tab2 = st.tabs([""Streamlit theme (default)"", ""Altair native theme""]) with tab1: # Use the Streamlit theme. # This is the default. So you can also omit the theme argument. st.altair_chart(chart, theme=""streamlit"", use_container_width=True) with tab2: # Use the native Altair theme. st.altair_chart(chart, theme=None, use_container_width=True) Click the tabs in the interactive app below to see the charts with the Streamlit theme enabled and disabled. Built with Streamlit 🎈Fullscreen open_in_new If you're wondering if your own customizations will still be taken into account, don't worry! You can still make changes to your chart configurations. In other words, although we now enable the Streamlit theme by default, you can overwrite it with custom colors or fonts. For example, if you want a chart line to be green instead of the default red, you can do it! Here's an example of an Altair chart where manual color passing is done and reflected: See the codeexpand_moreimport altair as alt import streamlit as st from vega_datasets import data source = data.seattle_weather() scale = alt.Scale( domain=[""sun"", ""fog"", ""drizzle"", ""rain"", ""snow""], range=[""#e7ba52"", ""#a7a7a7"", ""#aec7e8"", ""#1f77b4"", ""#9467bd""], ) color = alt.Color(""weather:N"", scale=scale) # We create two selections: # - a brush that is active on the top panel # - a multi-click that is active on the bottom panel brush = alt.selection_interval(encodings=[""x""]) click = alt.selection_multi(encodings=[""color""]) # Top panel is scatter plot of temperature vs time points = ( alt.Chart() .mark_point() .encode( alt.X(""monthdate(date):T"", title=""Date""), alt.Y( ""temp_max:Q"", title=""Maximum Daily Temperature (C)"", scale=alt.Scale(domain=[-5, 40]), ), color=alt.condition(brush, color, alt.value(""lightgray"")), size=alt.Size(""precipitation:Q"", scale=alt.Scale(range=[5, 200])), ) .properties(width=550, height=300) .add_selection(brush) .transform_filter(click) ) # Bottom panel is a bar chart of weather type bars = ( alt.Chart() .mark_bar() .encode( x=""count()"", y=""weather:N"", color=alt.condition(click, color, alt.value(""lightgray"")), ) .transform_filter(brush) .properties( width=550, ) .add_selection(click) ) chart = alt.vconcat(points, bars, data=source, title=""Seattle Weather: 2012-2015"") tab1, tab2 = st.tabs([""Streamlit theme (default)"", ""Altair native theme""]) with tab1: st.altair_chart(chart, theme=""streamlit"", use_container_width=True) with tab2: st.altair_chart(chart, theme=None, use_container_width=True) Notice how the custom colors are still reflected in the chart, even when the Streamlit theme is enabled 👇 Built with Streamlit 🎈Fullscreen open_in_new For many more examples of Altair charts with and without the Streamlit theme, check out the altair.streamlit.app. Annotating charts Altair also allows you to annotate your charts with text, images, and emojis. You can do this by creating layered charts, which let you overlay two different charts on top of each other. The idea is to use the first chart to show the data, and the second chart to show the annotations. The second chart can then be overlaid on top of the first chart using the + operator to create a layered chart. Let's walk through an example of annotating a time-series chart with text and an emoji. Step 1: Create the base chart In this example, we create a time-series chart to track the evolution of stock prices. The chart is interactive and contains a multi-line tooltip. Click here to learn more about multi-line tooltips in Altair. First, we import the required libraries and load the example stocks dataset using the vega_datasets package: import altair as alt import pandas as pd import streamlit as st from vega_datasets import data # We use @st.cache_data to keep the dataset in cache @st.cache_data def get_data(): source = data.stocks() source = source[source.date.gt(""2004-01-01"")] return source source = get_data() Next, we define a function get_chart() to create the interactive time-series chart of the stock prices with a multi-line tooltip. The x-axis represents the date, and the y-axis represents the stock price. We then invoke get_chart() that takes the stock prices dataframe as an input and returns a chart object. This is going to be our base chart on which we will overlay the annotations in Step 2. # Define the base time-series chart. def get_chart(data): hover = alt.selection_single( fields=[""date""], nearest=True, on=""mouseover"", empty=""none"", ) lines = ( alt.Chart(data, title=""Evolution of stock prices"") .mark_line() .encode( x=""date"", y=""price"", color=""symbol"", ) ) # Draw points on the line, and highlight based on selection points = lines.transform_filter(hover).mark_circle(size=65) # Draw a rule at the location of the selection tooltips = ( alt.Chart(data) .mark_rule() .encode( x=""yearmonthdate(date)"", y=""price"", opacity=alt.condition(hover, alt.value(0.3), alt.value(0)), tooltip=[ alt.Tooltip(""date"", title=""Date""), alt.Tooltip(""price"", title=""Price (USD)""), ], ) .add_selection(hover) ) return (lines + points + tooltips).interactive() chart = get_chart(source) Step 2: Annotate the chart Now that we have our first chart that shows the data, we can annotate it with text and an emoji. Let's overlay the ⬇ emoji on top of the time-series chart at specifc points of interest. We want users to hover over the ⬇ emoji to see the associated annotation text. For simplicity, let's annotate four specific dates and set the height of the annotations at constant value of 10. starTipYou can vary the horizontal and vertical postions of the annotations by replacing the hard-coded values with the output of Streamlit widgets! Click here to jump to a live example below, and develop an intuition for the ideal horizontal and vertical positions of the annotations by playing with Streamlit widgets. To do so, we create a dataframe annotations_df containing the dates, annotation text, and the height of the annotations: # Add annotations ANNOTATIONS = [ (""Mar 01, 2008"", ""Pretty good day for GOOG""), (""Dec 01, 2007"", ""Something's going wrong for GOOG & AAPL""), (""Nov 01, 2008"", ""Market starts again thanks to...""), (""Dec 01, 2009"", ""Small crash for GOOG after...""), ] annotations_df = pd.DataFrame(ANNOTATIONS, columns=[""date"", ""event""]) annotations_df.date = pd.to_datetime(annotations_df.date) annotations_df[""y""] = 10 Using this dataframe, we create a scatter plot with the x-axis representing the date, and the y-axis representing the height of the annotation. The data point at the specific date and height is represented by the ⬇ emoji, using Altair's mark_text() mark. The annotation text is displayed as a tooltip when users hover over the ⬇ emoji. This is achieved using Altair's encode() method to map the event column containing the annotation text to the visual attribute ⬇ of the plot. annotation_layer = ( alt.Chart(annotations_df) .mark_text(size=20, text=""⬇"", dx=-8, dy=-10, align=""left"") .encode( x=""date:T"", y=alt.Y(""y:Q""), tooltip=[""event""], ) .interactive() ) Finally, we overlay the annotations on top of the base chart using the + operator to create the final layered chart! 🎈 st.altair_chart( (chart + annotation_layer).interactive(), use_container_width=True ) To use images instead of emojis, replace the line containing .mark_text() with .mark_image(), and replace image_url below with the URL of the image: .mark_image( width=12, height=12, url=""image_url"", ) Interactive example Now that you've learned how to annotate charts, the sky's the limit! We've extended the above example to let you interactively paste your favorite emoji and set its position on the chart with Streamlit widgets. 👇 Built with Streamlit 🎈Fullscreen open_in_newPrevious: st.scatter_chartNext: st.bokeh_chartforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy" https://docs.streamlit.io/knowledge-base/dependencies/module-not-found-error#solution,"DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Knowledge base/Installing dependencies/ModuleNotFoundError No module namedModuleNotFoundError: No module named Problem You receive the error ModuleNotFoundError: No module named when you deploy an app on Streamlit Community Cloud. Solution This error occurs when you import a module on Streamlit Community Cloud that isn’t included in your requirements file. Any external Python dependencies that are not distributed with a standard Python installation should be included in your requirements file. E.g. You will see ModuleNotFoundError: No module named 'sklearn' if you don’t include scikit-learn in your requirements file and import sklearn in your app. Related forum posts: https://discuss.streamlit.io/t/getting-error-modulenotfounderror-no-module-named-beautifulsoup/9126 https://discuss.streamlit.io/t/modulenotfounderror-no-module-named-vega-datasets/16354 Previous: ImportError libGL.so.1 cannot open shared object file No such file or directoryNext: ERROR No matching distribution found forforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy" https://docs.streamlit.io/develop/api-reference/app-testing/testing-element-classes#togglerun,"DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceremovePAGE ELEMENTSWrite and magicaddText elementsaddData elementsaddChart elementsaddInput widgetsaddMedia elementsaddLayouts and containersaddChat elementsaddStatus elementsaddThird-party componentsopen_in_newAPPLICATION LOGICNavigation and pagesaddExecution flowaddCaching and stateaddConnections and secretsaddCustom componentsaddUtilitiesaddConfigurationaddTOOLSApp testingremovest.testing.v1.AppTestTesting element classesCommand lineaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Develop/API reference/App testing/Testing element classesTesting element classes st.testing.v1.element_tree.Block The Block class has the same methods and attributes as AppTest. A Block instance represents a container of elements just as AppTest represents the entire app. For example, Block.button will produce a WidgetList of Button in the same manner as AppTest.button. ChatMessage, Column, and Tab all inherit from Block. For all container classes, parameters of the original element can be obtained as properties. For example, ChatMessage.avatar and Tab.label. st.testing.v1.element_tree.ElementStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeElement base class for testing. This class's methods and attributes are universal for all elements implemented in testing. For example, Caption, Code, Text, and Title inherit from Element. All widget classes also inherit from Element, but have additional methods specific to each widget type. See the AppTest class for the full list of supported elements. For all element classes, parameters of the original element can be obtained as properties. For example, Button.label, Caption.help, and Toast.icon. Class description[source] st.testing.v1.element_tree.Element(proto, root) Methods run(*, timeout=None) Run the AppTest script which contains the element. Attributes value The value or contents of the element. st.testing.v1.element_tree.ButtonStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.button and st.form_submit_button. Class description[source] st.testing.v1.element_tree.Button(proto, root) Methods click() Set the value of the button to True. run(*, timeout=None) Run the AppTest script which contains the element. set_value(v) Set the value of the button. Attributes value The value of the button. (bool) st.testing.v1.element_tree.ChatInputStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.chat_input. Class description[source] st.testing.v1.element_tree.ChatInput(proto, root) Methods run(*, timeout=None) Run the AppTest script which contains the element. set_value(v) Set the value of the widget. Attributes value The value of the widget. (str) st.testing.v1.element_tree.CheckboxStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.checkbox. Class description[source] st.testing.v1.element_tree.Checkbox(proto, root) Methods check() Set the value of the widget to True. run(*, timeout=None) Run the AppTest script which contains the element. set_value(v) Set the value of the widget. uncheck() Set the value of the widget to False. Attributes value The value of the widget. (bool) st.testing.v1.element_tree.ColorPickerStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.color_picker. Class description[source] st.testing.v1.element_tree.ColorPicker(proto, root) Methods pick(v) Set the value of the widget as a hex string. May omit the ""#"" prefix. run(*, timeout=None) Run the AppTest script which contains the element. set_value(v) Set the value of the widget as a hex string. Attributes value The currently selected value as a hex string. (str) st.testing.v1.element_tree.DateInputStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.date_input. Class description[source] st.testing.v1.element_tree.DateInput(proto, root) Methods run(*, timeout=None) Run the AppTest script which contains the element. set_value(v) Set the value of the widget. Attributes value The value of the widget. (date or Tuple of date) st.testing.v1.element_tree.MultiselectStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.multiselect. Class description[source] st.testing.v1.element_tree.Multiselect(proto, root) Methods run(*, timeout=None) Run the AppTest script which contains the element. select(v) Add a selection to the widget. Do nothing if the value is already selected. If testing a multiselect widget with repeated options, use set_value instead. set_value(v) Set the value of the multiselect widget. (list) unselect(v) Remove a selection from the widget. Do nothing if the value is not already selected. If a value is selected multiple times, the first instance is removed. Attributes format_func The widget's formatting function for displaying options. (callable) indices The indices of the currently selected values from the options. (list) value The currently selected values from the options. (list) st.testing.v1.element_tree.NumberInputStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.number_input. Class description[source] st.testing.v1.element_tree.NumberInput(proto, root) Methods decrement() Decrement the st.number_input widget as if the user clicked ""-"". increment() Increment the st.number_input widget as if the user clicked ""+"". run(*, timeout=None) Run the AppTest script which contains the element. set_value(v) Set the value of the st.number_input widget. Attributes value Get the current value of the st.number_input widget. st.testing.v1.element_tree.RadioStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.radio. Class description[source] st.testing.v1.element_tree.Radio(proto, root) Methods run(*, timeout=None) Run the AppTest script which contains the element. set_value(v) Set the selection by value. Attributes format_func The widget's formatting function for displaying options. (callable) index The index of the current selection. (int) value The currently selected value from the options. (Any) st.testing.v1.element_tree.SelectSliderStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.select_slider. Class description[source] st.testing.v1.element_tree.SelectSlider(proto, root) Methods run(*, timeout=None) Run the AppTest script which contains the element. set_range(lower, upper) Set the ranged selection by values. set_value(v) Set the (single) selection by value. Attributes format_func The widget's formatting function for displaying options. (callable) value The currently selected value or range. (Any or Sequence of Any) st.testing.v1.element_tree.SelectboxStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.selectbox. Class description[source] st.testing.v1.element_tree.Selectbox(proto, root) Methods run(*, timeout=None) Run the AppTest script which contains the element. select(v) Set the selection by value. select_index(index) Set the selection by index. set_value(v) Set the selection by value. Attributes format_func The widget's formatting function for displaying options. (callable) index The index of the current selection. (int) value The currently selected value from the options. (Any) st.testing.v1.element_tree.SliderStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.slider. Class description[source] st.testing.v1.element_tree.Slider(proto, root) Methods run(*, timeout=None) Run the AppTest script which contains the element. set_range(lower, upper) Set the ranged value of the slider. set_value(v) Set the (single) value of the slider. Attributes value The currently selected value or range. (Any or Sequence of Any) st.testing.v1.element_tree.TextAreaStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.text_area. Class description[source] st.testing.v1.element_tree.TextArea(proto, root) Methods input(v) Set the value of the widget only if the value does not exceed the maximum allowed characters. run(*, timeout=None) Run the AppTest script which contains the element. set_value(v) Set the value of the widget. Attributes value The current value of the widget. (str) st.testing.v1.element_tree.TextInputStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.text_input. Class description[source] st.testing.v1.element_tree.TextInput(proto, root) Methods input(v) Set the value of the widget only if the value does not exceed the maximum allowed characters. run(*, timeout=None) Run the AppTest script which contains the element. set_value(v) Set the value of the widget. Attributes value The current value of the widget. (str) st.testing.v1.element_tree.TimeInputStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.time_input. Class description[source] st.testing.v1.element_tree.TimeInput(proto, root) Methods decrement() Select the previous available time. increment() Select the next available time. run(*, timeout=None) Run the AppTest script which contains the element. set_value(v) Set the value of the widget. Attributes value The current value of the widget. (time) st.testing.v1.element_tree.ToggleStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.toggle. Class description[source] st.testing.v1.element_tree.Toggle(proto, root) Methods run(*, timeout=None) Run the AppTest script which contains the element. set_value(v) Set the value of the widget. Attributes value The current value of the widget. (bool) Previous: st.testing.v1.AppTestNext: Command lineforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy" https://docs.streamlit.io/knowledge-base/using-streamlit/widget-updating-session-state#overview,"DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Knowledge base/FAQ/Widget updating for every second input when using session stateWidget updating for every second input when using session state Overview You are using session state to store page interactions in your app. When users interact with a widget in your app (e.g., click a button), you expect your app to update its widget states and reflect the new values. However, you notice that it doesn't. Instead, users have to interact with the widget twice (e.g., click a button twice) for the app to show the correct values. What do you do now? 🤔 Let's walk through the solution in the section below. Solution When using session state to update widgets or values in your script, you need to use the unique key you assigned to the widget, not the variable that you assigned your widget to. In the example code block below, the unique key assigned to the slider widget is slider, and the variable the widget is assigned to is slide_val. Let's see this in an example. Say you want a user to click a button that resets a slider. To have the slider's value update on the button click, you need to use a callback function with the on_click parameter of st.button: # the callback function for the button will add 1 to the # slider value up to 10 def plus_one(): if st.session_state[""slider""] < 10: st.session_state.slider += 1 else: pass return # when creating the button, assign the name of your callback # function to the on_click parameter add_one = st.button(""Add one to the slider"", on_click=plus_one, key=""add_one"") # create the slider slide_val = st.slider(""Pick a number"", 0, 10, key=""slider"") Relevant resources Caching Sqlite DB connection resulting in glitchy rendering of the page Select all checkbox that is linked to selectbox of options Previous: Where does st.file_uploader store uploaded files and when do they get deleted?Next: Why does Streamlit restrict nested st.columns?forumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy" https://docs.streamlit.io/deploy/streamlit-community-cloud/get-started/trust-and-security,"DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudremoveGet startedremoveQuickstartCreate your accountConnect your GitHub accountExplore your workspaceFork and edit a public appTrust and securityDeploy your appaddManage your appaddShare your appaddManage your accountaddTroubleshootingStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Deploy/Streamlit Community Cloud/Get started/Trust and securityStreamlit trust and security Streamlit is a framework that turns Python scripts into interactive apps, giving data scientists the ability to quickly create data and model-based apps for the entire company. A simple Streamlit app is: import streamlit as st number = st.slider(""Pick a number: "", min_value=1, max_value=10) st.text(""Your number is "" + str(number)) When you streamlit run my_app.py, you start a web server that runs the interactive application on your local computer at http://localhost:8501. This is great for local development. When you want to share with your colleagues, Streamlit Community Cloud enables you to deploy and run these applications in the cloud. Streamlit Community Cloud handles the details of containerization and provides you an interface for easily managing your deployed apps. This document provides an overview of the security safeguards we've implemented to protect you and your data. Security, however, is a shared responsibility and you are ultimately responsible for making appropriate use of Streamlit and the Streamlit Community Cloud, including implementation of appropriate user-configurable security safeguards and best practices. Product security Authentication You must authenticate through GitHub to deploy or administer an app. Authentication through Google or single-use emailed links are required to view a private app when you don't have push or admin permissions on the associated GitHub repository. The single-use emailed links are valid for 15 minutes once requested. Permissions Streamlit Community Cloud inherits the permissions you have assigned in GitHub. Users with write access to a GitHub repository for a given app will be able to make changes in the Streamlit administrative console. However, only users with admin access to a repository are able to deploy and delete apps. Network and application security Data hosting Our physical infrastructure is hosted and managed within secure data centers maintained by infrastructure-as-a-service cloud providers. Streamlit leverages many of these platforms' built-in security, privacy, and redundancy features. Our cloud providers continually monitor their data centers for risk and undergo assessments to ensure compliance with industry standards. Data deletion Community Cloud users have the option to delete any apps they’ve deployed as well as their entire account. When a user deletes their application from the admin console, we delete their source code, including any files copied from their GitHub repository or created within our system from the running app. However, we keep a record representing the application in our database. This record contains the coordinates of the application: the GitHub organization or user, the GitHub repository, the branch, and the path of the main module file. When a user deletes their account, we perform a hard deletion of their data and a hard deletion of all the apps that belong to the GitHub identity associated with their account. In this case, we do not maintain the records of application coordinates described above. When an account is deleted, we also delete any HubSpot contact associated with the Community Cloud account. Virtual private cloud All of our servers are within a virtual private cloud (VPC) with firewalls and network access control lists (ACLs) to allow external access to a select few API endpoints; all other internal services are only accessible within the VPC. Encryption Streamlit apps are served entirely over HTTPS. We use only strong cipher suites and HTTP Strict Transport Security (HSTS) to ensure browsers interact with Streamlit apps over HTTPS. All data sent to or from Streamlit over the public internet is encrypted in transit using 256-bit encryption. Our API and application endpoints use Transport Layer Security (TLS) 1.2 (or better). We also encrypt data at rest on disk using AES-256. Permissions and authentication Access to Community Cloud user account data is limited to authorized personnel. We run a zero-trust corporate network, utilize single sign-on and multi-factor authentication (MFA), and enforce strong password policies to ensure access to cloud-related services is protected. Incident response Our internal protocol for handling security events includes detection, analysis, response, escalation, and mitigation. Security advisories are made available at https://streamlit.io/advisories. Penetration testing Streamlit uses third-party security tools to scan for vulnerabilities on a regular basis. Our security teams conduct periodic, intensive penetration tests on the Streamlit platform. Our product development team responds to any identified issues or potential vulnerabilities to ensure the quality, security, and availability of Streamlit applications. Vulnerability management We keep our systems up-to-date with the latest security patches and continuously monitor for new vulnerabilities. This includes automated scanning of our code repositories for vulnerable dependencies. If you discover a vulnerability in one of our products or websites, please report the issue to HackerOne.Previous: Fork and edit a public appNext: Deploy your appforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy" https://docs.streamlit.io/en/0.68.0/api.html#chart-elements,"DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceremovePAGE ELEMENTSWrite and magicaddText elementsaddData elementsaddChart elementsaddInput widgetsaddMedia elementsaddLayouts and containersaddChat elementsaddStatus elementsaddThird-party componentsopen_in_newAPPLICATION LOGICNavigation and pagesaddExecution flowaddCaching and stateaddConnections and secretsaddCustom componentsaddUtilitiesaddConfigurationaddTOOLSApp testingaddCommand lineaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Develop/API referenceAPI reference Streamlit makes it easy for you to visualize, mutate, and share data. The API reference is organized by activity type, like displaying data or optimizing performance. Each section includes methods associated with the activity type, including examples. Browse our API below and click to learn more about any of our available commands! 🎈 Display almost anything Write and magic st.writeWrite arguments to the app.st.write(""Hello **world**!"") st.write(my_data_frame) st.write(my_mpl_figure) st.write_streamWrite generators or streams to the app with a typewriter effect.st.write_stream(my_generator) st.write_stream(my_llm_stream) MagicAny time Streamlit sees either a variable or literal value on its own line, it automatically writes that to your app using st.write""Hello **world**!"" my_data_frame my_mpl_figure Text elements MarkdownDisplay string formatted as Markdown.st.markdown(""Hello **world**!"") TitleDisplay text in title formatting.st.title(""The app title"") HeaderDisplay text in header formatting.st.header(""This is a header"") SubheaderDisplay text in subheader formatting.st.subheader(""This is a subheader"") CaptionDisplay text in small font.st.caption(""This is written small caption text"") Code blockDisplay a code block with optional syntax highlighting.st.code(""a = 1234"") EchoDisplay some code in the app, then execute it. Useful for tutorials.with st.echo(): st.write('This code will be printed') LaTeXDisplay mathematical expressions formatted as LaTeX.st.latex(""\int a x^2 \,dx"") Preformatted textWrite fixed-width and preformatted text.st.text(""Hello world"") DividerDisplay a horizontal rule.st.divider() Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration! PreviousTagsAdd tags to your Streamlit apps. Created by @gagan3012.st_tags(label='# Enter Keywords:', text='Press enter to add more', value=['Zero', 'One', 'Two'], suggestions=['five', 'six', 'seven', 'eight', 'nine', 'three', 'eleven', 'ten', 'four'], maxtags = 4, key='1') NLUApply text mining on a dataframe. Created by @JohnSnowLabs.nlu.load('sentiment').predict('I love NLU! <3') Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.mention(label=""An awesome Streamlit App"", icon=""streamlit"", url=""https://extras.streamlit.app"",) Annotated textDisplay annotated text in Streamlit apps. Created by @tvst.annotated_text(""This "", (""is"", ""verb""), "" some "", (""annotated"", ""adj""), (""text"", ""noun""), "" for those of "", (""you"", ""pronoun""), "" who "", (""like"", ""verb""), "" this sort of "", (""thing"", ""noun""), ""."") Drawable CanvasProvides a sketching canvas using Fabric.js. Created by @andfanilo.st_canvas(fill_color=""rgba(255, 165, 0, 0.3)"", stroke_width=stroke_width, stroke_color=stroke_color, background_color=bg_color, background_image=Image.open(bg_image) if bg_image else None, update_streamlit=realtime_update, height=150, drawing_mode=drawing_mode, point_display_radius=point_display_radius if drawing_mode == 'point' else 0, key=""canvas"",) TagsAdd tags to your Streamlit apps. Created by @gagan3012.st_tags(label='# Enter Keywords:', text='Press enter to add more', value=['Zero', 'One', 'Two'], suggestions=['five', 'six', 'seven', 'eight', 'nine', 'three', 'eleven', 'ten', 'four'], maxtags = 4, key='1') NLUApply text mining on a dataframe. Created by @JohnSnowLabs.nlu.load('sentiment').predict('I love NLU! <3') Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.mention(label=""An awesome Streamlit App"", icon=""streamlit"", url=""https://extras.streamlit.app"",) Annotated textDisplay annotated text in Streamlit apps. Created by @tvst.annotated_text(""This "", (""is"", ""verb""), "" some "", (""annotated"", ""adj""), (""text"", ""noun""), "" for those of "", (""you"", ""pronoun""), "" who "", (""like"", ""verb""), "" this sort of "", (""thing"", ""noun""), ""."") Drawable CanvasProvides a sketching canvas using Fabric.js. Created by @andfanilo.st_canvas(fill_color=""rgba(255, 165, 0, 0.3)"", stroke_width=stroke_width, stroke_color=stroke_color, background_color=bg_color, background_image=Image.open(bg_image) if bg_image else None, update_streamlit=realtime_update, height=150, drawing_mode=drawing_mode, point_display_radius=point_display_radius if drawing_mode == 'point' else 0, key=""canvas"",) TagsAdd tags to your Streamlit apps. Created by @gagan3012.st_tags(label='# Enter Keywords:', text='Press enter to add more', value=['Zero', 'One', 'Two'], suggestions=['five', 'six', 'seven', 'eight', 'nine', 'three', 'eleven', 'ten', 'four'], maxtags = 4, key='1') NLUApply text mining on a dataframe. Created by @JohnSnowLabs.nlu.load('sentiment').predict('I love NLU! <3') Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.mention(label=""An awesome Streamlit App"", icon=""streamlit"", url=""https://extras.streamlit.app"",) Next Data elements DataframesDisplay a dataframe as an interactive table.st.dataframe(my_data_frame) Data editorDisplay a data editor widget.edited = st.data_editor(df, num_rows=""dynamic"") Column configurationConfigure the display and editing behavior of dataframes and data editors.st.column_config.NumberColumn(""Price (in USD)"", min_value=0, format=""$%d"") Static tablesDisplay a static table.st.table(my_data_frame) MetricsDisplay a metric in big bold font, with an optional indicator of how the metric changed.st.metric(""My metric"", 42, 2) Dicts and JSONDisplay object or string as a pretty-printed JSON string.st.json(my_dict) Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration! PreviousImage CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates value = streamlit_image_coordinates(""https://placekitten.com/200/300"") st.write(value) Plotly EventsMake Plotly charts interactive!. Created by @null-jones.from streamlit_plotly_events import plotly_events fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.metric_cards import style_metric_cards col3.metric(label=""No Change"", value=5000, delta=0) style_metric_cards() Streamlit AggridImplementation of Ag-Grid component for Streamlit. Created by @PablocFonseca.df = pd.DataFrame({'col1': [1, 2, 3], 'col2': [4, 5, 6]}) grid_return = AgGrid(df, editable=True) new_df = grid_return['data'] Streamlit FoliumStreamlit Component for rendering Folium maps. Created by @randyzwitch.m = folium.Map(location=[39.949610, -75.150282], zoom_start=16) folium.Marker([39.949610, -75.150282], popup=""Liberty Bell"", tooltip=""Liberty Bell"").add_to(m) st_data = st_folium(m, width=725) Pandas ProfilingPandas profiling component for Streamlit. Created by @okld.df = pd.read_csv(""https://storage.googleapis.com/tf-datasets/titanic/train.csv"") pr = df.profile_report() st_profile_report(pr) Image CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates value = streamlit_image_coordinates(""https://placekitten.com/200/300"") st.write(value) Plotly EventsMake Plotly charts interactive!. Created by @null-jones.from streamlit_plotly_events import plotly_events fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.metric_cards import style_metric_cards col3.metric(label=""No Change"", value=5000, delta=0) style_metric_cards() Streamlit AggridImplementation of Ag-Grid component for Streamlit. Created by @PablocFonseca.df = pd.DataFrame({'col1': [1, 2, 3], 'col2': [4, 5, 6]}) grid_return = AgGrid(df, editable=True) new_df = grid_return['data'] Streamlit FoliumStreamlit Component for rendering Folium maps. Created by @randyzwitch.m = folium.Map(location=[39.949610, -75.150282], zoom_start=16) folium.Marker([39.949610, -75.150282], popup=""Liberty Bell"", tooltip=""Liberty Bell"").add_to(m) st_data = st_folium(m, width=725) Pandas ProfilingPandas profiling component for Streamlit. Created by @okld.df = pd.read_csv(""https://storage.googleapis.com/tf-datasets/titanic/train.csv"") pr = df.profile_report() st_profile_report(pr) Image CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates value = streamlit_image_coordinates(""https://placekitten.com/200/300"") st.write(value) Plotly EventsMake Plotly charts interactive!. Created by @null-jones.from streamlit_plotly_events import plotly_events fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.metric_cards import style_metric_cards col3.metric(label=""No Change"", value=5000, delta=0) style_metric_cards() Next Chart elements Simple area chartsDisplay an area chart.st.area_chart(my_data_frame) Simple bar chartsDisplay a bar chart.st.bar_chart(my_data_frame) Simple line chartsDisplay a line chart.st.line_chart(my_data_frame) Simple scatter chartsDisplay a line chart.st.scatter_chart(my_data_frame) Scatterplots on mapsDisplay a map with points on it.st.map(my_data_frame) MatplotlibDisplay a matplotlib.pyplot figure.st.pyplot(my_mpl_figure) AltairDisplay a chart using the Altair library.st.altair_chart(my_altair_chart) Vega-LiteDisplay a chart using the Vega-Lite library.st.vega_lite_chart(my_vega_lite_chart) PlotlyDisplay an interactive Plotly chart.st.plotly_chart(my_plotly_chart) BokehDisplay an interactive Bokeh chart.st.bokeh_chart(my_bokeh_chart) PyDeckDisplay a chart using the PyDeck library.st.pydeck_chart(my_pydeck_chart) GraphVizDisplay a graph using the dagre-d3 library.st.graphviz_chart(my_graphviz_spec) Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration! PreviousStreamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl(""https://assets5.lottiefiles.com/packages/lf20_V9t630.json"") st_lottie(lottie_hello, key=""hello"") Plotly EventsMake Plotly charts interactive!. Created by @null-jones.fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.chart += get_annotations_chart(annotations=[(""Mar 01, 2008"", ""Pretty good day for GOOG""), (""Dec 01, 2007"", ""Something's going wrong for GOOG & AAPL""), (""Nov 01, 2008"", ""Market starts again thanks to...""), (""Dec 01, 2009"", ""Small crash for GOOG after...""),],) st.altair_chart(chart, use_container_width=True) PlostA deceptively simple plotting library for Streamlit. Created by @tvst.import plost plost.line_chart(my_dataframe, x='time', y='stock_value', color='stock_name',) HiPlotHigh dimensional Interactive Plotting. Created by @facebookresearch.data = [{'dropout':0.1, 'lr': 0.001, 'loss': 10.0, 'optimizer': 'SGD'}, {'dropout':0.15, 'lr': 0.01, 'loss': 3.5, 'optimizer': 'Adam'}, {'dropout':0.3, 'lr': 0.1, 'loss': 4.5, 'optimizer': 'Adam'}] hip.Experiment.from_iterable(data).display() EChartsHigh dimensional Interactive Plotting. Created by @andfanilo.from streamlit_echarts import st_echarts st_echarts(options=options) Streamlit FoliumStreamlit Component for rendering Folium maps. Created by @randyzwitch.m = folium.Map(location=[39.949610, -75.150282], zoom_start=16) st_data = st_folium(m, width=725) Spacy-StreamlitspaCy building blocks and visualizers for Streamlit apps. Created by @explosion.models = [""en_core_web_sm"", ""en_core_web_md""] spacy_streamlit.visualize(models, ""Sundar Pichai is the CEO of Google."") Streamlit AgraphA Streamlit Graph Vis, based on react-grah-vis. Created by @ChrisDelClea.from streamlit_agraph import agraph, Node, Edge, Config agraph(nodes=nodes, edges=edges, config=config) Streamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl(""https://assets5.lottiefiles.com/packages/lf20_V9t630.json"") st_lottie(lottie_hello, key=""hello"") Plotly EventsMake Plotly charts interactive!. Created by @null-jones.fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.chart += get_annotations_chart(annotations=[(""Mar 01, 2008"", ""Pretty good day for GOOG""), (""Dec 01, 2007"", ""Something's going wrong for GOOG & AAPL""), (""Nov 01, 2008"", ""Market starts again thanks to...""), (""Dec 01, 2009"", ""Small crash for GOOG after...""),],) st.altair_chart(chart, use_container_width=True) PlostA deceptively simple plotting library for Streamlit. Created by @tvst.import plost plost.line_chart(my_dataframe, x='time', y='stock_value', color='stock_name',) HiPlotHigh dimensional Interactive Plotting. Created by @facebookresearch.data = [{'dropout':0.1, 'lr': 0.001, 'loss': 10.0, 'optimizer': 'SGD'}, {'dropout':0.15, 'lr': 0.01, 'loss': 3.5, 'optimizer': 'Adam'}, {'dropout':0.3, 'lr': 0.1, 'loss': 4.5, 'optimizer': 'Adam'}] hip.Experiment.from_iterable(data).display() EChartsHigh dimensional Interactive Plotting. Created by @andfanilo.from streamlit_echarts import st_echarts st_echarts(options=options) Streamlit FoliumStreamlit Component for rendering Folium maps. Created by @randyzwitch.m = folium.Map(location=[39.949610, -75.150282], zoom_start=16) st_data = st_folium(m, width=725) Spacy-StreamlitspaCy building blocks and visualizers for Streamlit apps. Created by @explosion.models = [""en_core_web_sm"", ""en_core_web_md""] spacy_streamlit.visualize(models, ""Sundar Pichai is the CEO of Google."") Streamlit AgraphA Streamlit Graph Vis, based on react-grah-vis. Created by @ChrisDelClea.from streamlit_agraph import agraph, Node, Edge, Config agraph(nodes=nodes, edges=edges, config=config) Streamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl(""https://assets5.lottiefiles.com/packages/lf20_V9t630.json"") st_lottie(lottie_hello, key=""hello"") Plotly EventsMake Plotly charts interactive!. Created by @null-jones.fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.chart += get_annotations_chart(annotations=[(""Mar 01, 2008"", ""Pretty good day for GOOG""), (""Dec 01, 2007"", ""Something's going wrong for GOOG & AAPL""), (""Nov 01, 2008"", ""Market starts again thanks to...""), (""Dec 01, 2009"", ""Small crash for GOOG after...""),],) st.altair_chart(chart, use_container_width=True) Next Input widgets ButtonDisplay a button widget.clicked = st.button(""Click me"") Download buttonDisplay a download button widget.st.download_button(""Download file"", file) Form buttonDisplay a form submit button. For use with st.form.st.form_submit_button(""Sign up"") Link buttonDisplay a link button.st.link_button(""Go to gallery"", url) Page linkDisplay a link to another page in a multipage app.st.page_link(""app.py"", label=""Home"", icon=""🏠"") st.page_link(""pages/profile.py"", label=""My profile"") CheckboxDisplay a checkbox widget.selected = st.checkbox(""I agree"") Color pickerDisplay a color picker widget.color = st.color_picker(""Pick a color"") MultiselectDisplay a multiselect widget. The multiselect widget starts as empty.choices = st.multiselect(""Buy"", [""milk"", ""apples"", ""potatoes""]) RadioDisplay a radio button widget.choice = st.radio(""Pick one"", [""cats"", ""dogs""]) SelectboxDisplay a select widget.choice = st.selectbox(""Pick one"", [""cats"", ""dogs""]) Select-sliderDisplay a slider widget to select items from a list.size = st.select_slider(""Pick a size"", [""S"", ""M"", ""L""]) ToggleDisplay a toggle widget.activated = st.toggle(""Activate"") Number inputDisplay a numeric input widget.choice = st.number_input(""Pick a number"", 0, 10) SliderDisplay a slider widget.number = st.slider(""Pick a number"", 0, 100) Date inputDisplay a date input widget.date = st.date_input(""Your birthday"") Time inputDisplay a time input widget.time = st.time_input(""Meeting time"") Chat inputDisplay a chat input widget.prompt = st.chat_input(""Say something"") if prompt: st.write(f""The user has sent: {prompt}"") Text-areaDisplay a multi-line text input widget.text = st.text_area(""Text to translate"") Text inputDisplay a single-line text input widget.name = st.text_input(""First name"") Data editorDisplay a data editor widget.edited = st.experimental_data_editor(df, num_rows=""dynamic"") File UploaderDisplay a file uploader widget.data = st.file_uploader(""Upload a CSV"") Camera inputDisplay a widget that allows users to upload images directly from a camera.image = st.camera_input(""Take a picture"") Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration! PreviousStreamlit ChatStreamlit Component for a Chatbot UI. Created by @AI-Yash.from streamlit_chat import message message(""My message"") message(""Hello bot!"", is_user=True) # align's the message to the right Streamlit Option MenuSelect a single item from a list of options in a menu. Created by @victoryhb.from streamlit_option_menu import option_menu option_menu(""Main Menu"", [""Home"", 'Settings'], icons=['house', 'gear'], menu_icon=""cast"", default_index=1) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.stoggle import stoggle stoggle( ""Click me!"", """"""🥷 Surprise! Here's some additional content"""""",) Streamlit ElementsCreate a draggable and resizable dashboard in Streamlit. Created by @okls.from streamlit_elements import elements, mui, html with elements(""new_element""): mui.Typography(""Hello world"") TagsAdd tags to your Streamlit apps. Created by @gagan3012.from streamlit_tags import st_tags st_tags(label='# Enter Keywords:', text='Press enter to add more', value=['Zero', 'One', 'Two'], suggestions=['five', 'six', 'seven', 'eight', 'nine', 'three', 'eleven', 'ten', 'four'], maxtags = 4, key='1') StqdmThe simplest way to handle a progress bar in streamlit app. Created by @Wirg.from stqdm import stqdm for _ in stqdm(range(50)): sleep(0.5) TimelineDisplay a Timeline in Streamlit apps using TimelineJS. Created by @innerdoc.from streamlit_timeline import timeline with open('example.json', ""r"") as f: timeline(f.read(), height=800) Camera input liveAlternative for st.camera_input which returns the webcam images live. Created by @blackary.from camera_input_live import camera_input_live image = camera_input_live() st.image(value) Streamlit AceAce editor component for Streamlit. Created by @okld.from streamlit_ace import st_ace content = st_ace() content Streamlit ChatStreamlit Component for a Chatbot UI. Created by @AI-Yash.from streamlit_chat import message message(""My message"") message(""Hello bot!"", is_user=True) # align's the message to the right Streamlit Option MenuSelect a single item from a list of options in a menu. Created by @victoryhb.from streamlit_option_menu import option_menu option_menu(""Main Menu"", [""Home"", 'Settings'], icons=['house', 'gear'], menu_icon=""cast"", default_index=1) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.stoggle import stoggle stoggle( ""Click me!"", """"""🥷 Surprise! Here's some additional content"""""",) Streamlit ElementsCreate a draggable and resizable dashboard in Streamlit. Created by @okls.from streamlit_elements import elements, mui, html with elements(""new_element""): mui.Typography(""Hello world"") TagsAdd tags to your Streamlit apps. Created by @gagan3012.from streamlit_tags import st_tags st_tags(label='# Enter Keywords:', text='Press enter to add more', value=['Zero', 'One', 'Two'], suggestions=['five', 'six', 'seven', 'eight', 'nine', 'three', 'eleven', 'ten', 'four'], maxtags = 4, key='1') StqdmThe simplest way to handle a progress bar in streamlit app. Created by @Wirg.from stqdm import stqdm for _ in stqdm(range(50)): sleep(0.5) TimelineDisplay a Timeline in Streamlit apps using TimelineJS. Created by @innerdoc.from streamlit_timeline import timeline with open('example.json', ""r"") as f: timeline(f.read(), height=800) Camera input liveAlternative for st.camera_input which returns the webcam images live. Created by @blackary.from camera_input_live import camera_input_live image = camera_input_live() st.image(value) Streamlit AceAce editor component for Streamlit. Created by @okld.from streamlit_ace import st_ace content = st_ace() content Streamlit ChatStreamlit Component for a Chatbot UI. Created by @AI-Yash.from streamlit_chat import message message(""My message"") message(""Hello bot!"", is_user=True) # align's the message to the right Streamlit Option MenuSelect a single item from a list of options in a menu. Created by @victoryhb.from streamlit_option_menu import option_menu option_menu(""Main Menu"", [""Home"", 'Settings'], icons=['house', 'gear'], menu_icon=""cast"", default_index=1) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.stoggle import stoggle stoggle( ""Click me!"", """"""🥷 Surprise! Here's some additional content"""""",) Next Media elements ImageDisplay an image or list of images.st.image(numpy_array) st.image(image_bytes) st.image(file) st.image(""https://example.com/myimage.jpg"") AudioDisplay an audio player.st.audio(numpy_array) st.audio(audio_bytes) st.audio(file) st.audio(""https://example.com/myaudio.mp3"", format=""audio/mp3"") VideoDisplay a video player.st.video(numpy_array) st.video(video_bytes) st.video(file) st.video(""https://example.com/myvideo.mp4"", format=""video/mp4"") Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration! PreviousStreamlit CropperA simple image cropper for Streamlit. Created by @turner-anderson.from streamlit_cropper import st_cropper st_cropper(img, realtime_update=realtime_update, box_color=box_color, aspect_ratio=aspect_ratio) Image CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates streamlit_image_coordinates(""https://placekitten.com/200/300"") Streamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl(""https://assets5.lottiefiles.com/packages/lf20_V9t630.json"") st_lottie(lottie_hello, key=""hello"") Streamlit WebrtcHandling and transmitting real-time video/audio streams with Streamlit. Created by @whitphx.from streamlit_webrtc import webrtc_streamer webrtc_streamer(key=""sample"") Drawable CanvasProvides a sketching canvas using Fabric.js. Created by @andfanilo.from streamlit_drawable_canvas import st_canvas st_canvas(fill_color=""rgba(255, 165, 0, 0.3)"", stroke_width=stroke_width, stroke_color=stroke_color, background_color=bg_color, background_image=Image.open(bg_image) if bg_image else None, update_streamlit=realtime_update, height=150, drawing_mode=drawing_mode, point_display_radius=point_display_radius if drawing_mode == 'point' else 0, key=""canvas"",) Image ComparisonCompare images with a slider using JuxtaposeJS. Created by @fcakyon.from streamlit_image_comparison import image_comparison image_comparison(img1=""image1.jpg"", img2=""image2.jpg"",) Streamlit CropperA simple image cropper for Streamlit. Created by @turner-anderson.from streamlit_cropper import st_cropper st_cropper(img, realtime_update=realtime_update, box_color=box_color, aspect_ratio=aspect_ratio) Image CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates streamlit_image_coordinates(""https://placekitten.com/200/300"") Streamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl(""https://assets5.lottiefiles.com/packages/lf20_V9t630.json"") st_lottie(lottie_hello, key=""hello"") Streamlit WebrtcHandling and transmitting real-time video/audio streams with Streamlit. Created by @whitphx.from streamlit_webrtc import webrtc_streamer webrtc_streamer(key=""sample"") Drawable CanvasProvides a sketching canvas using Fabric.js. Created by @andfanilo.from streamlit_drawable_canvas import st_canvas st_canvas(fill_color=""rgba(255, 165, 0, 0.3)"", stroke_width=stroke_width, stroke_color=stroke_color, background_color=bg_color, background_image=Image.open(bg_image) if bg_image else None, update_streamlit=realtime_update, height=150, drawing_mode=drawing_mode, point_display_radius=point_display_radius if drawing_mode == 'point' else 0, key=""canvas"",) Image ComparisonCompare images with a slider using JuxtaposeJS. Created by @fcakyon.from streamlit_image_comparison import image_comparison image_comparison(img1=""image1.jpg"", img2=""image2.jpg"",) Streamlit CropperA simple image cropper for Streamlit. Created by @turner-anderson.from streamlit_cropper import st_cropper st_cropper(img, realtime_update=realtime_update, box_color=box_color, aspect_ratio=aspect_ratio) Image CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates streamlit_image_coordinates(""https://placekitten.com/200/300"") Streamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl(""https://assets5.lottiefiles.com/packages/lf20_V9t630.json"") st_lottie(lottie_hello, key=""hello"") Next Layouts and containers ColumnsInsert containers laid out as side-by-side columns.col1, col2 = st.columns(2) col1.write(""this is column 1"") col2.write(""this is column 2"") ContainerInsert a multi-element container.c = st.container() st.write(""This will show last"") c.write(""This will show first"") c.write(""This will show second"") Modal dialogsInsert a modal dialog that can rerun independently from the rest of the script.@st.experimental_dialog(""Sign up"") def email_form(): name = st.text_input(""Name"") email = st.text_input(""Email"") EmptyInsert a single-element container.c = st.empty() st.write(""This will show last"") c.write(""This will be replaced"") c.write(""This will show first"") ExpanderInsert a multi-element container that can be expanded/collapsed.with st.expander(""Open to see more""): st.write(""This is more content"") PopoverInsert a multi-element popover container that can be opened/closed.with st.popover(""Settings""): st.checkbox(""Show completed"") SidebarDisplay items in a sidebar.st.sidebar.write(""This lives in the sidebar"") st.sidebar.button(""Click me!"") TabsInsert containers separated into tabs.tab1, tab2 = st.tabs([""Tab 1"", ""Tab2""]) tab1.write(""this is tab 1"") tab2.write(""this is tab 2"") Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration!Streamlit ElementsCreate a draggable and resizable dashboard in Streamlit. Created by @okls.from streamlit_elements import elements, mui, html with elements(""new_element""): mui.Typography(""Hello world"") PydanticAuto-generate Streamlit UI from Pydantic Models and Dataclasses. Created by @lukasmasuch.import streamlit_pydantic as sp sp.pydantic_form(key=""my_form"", model=ExampleModel) Streamlit PagesAn experimental version of Streamlit Multi-Page Apps. Created by @blackary.from st_pages import Page, show_pages, add_page_title show_pages([ Page(""streamlit_app.py"", ""Home"", ""🏠""), Page(""other_pages/page2.py"", ""Page 2"", "":books:""), ]) Chat elements Streamlit provides a few commands to help you build conversational apps. These chat elements are designed to be used in conjunction with each other, but you can also use them separately. st.chat_message lets you insert a chat message container into the app so you can display messages from the user or the app. Chat containers can contain other Streamlit elements, including charts, tables, text, and more. st.chat_input lets you display a chat input widget so the user can type in a message. Chat inputDisplay a chat input widget.prompt = st.chat_input(""Say something"") if prompt: st.write(f""The user has sent: {prompt}"") Chat messageInsert a chat message container.import numpy as np with st.chat_message(""user""): st.write(""Hello 👋"") st.line_chart(np.random.randn(30, 3)) Status containerDisplay output of long-running tasks in a container.with st.status('Running'): do_something_slow() st.write_streamWrite generators or streams to the app with a typewriter effect.st.write_stream(my_generator) st.write_stream(my_llm_stream) Status elements Progress barDisplay a progress bar.for i in range(101): st.progress(i) do_something_slow() SpinnerTemporarily displays a message while executing a block of code.with st.spinner(""Please wait...""): do_something_slow() Status containerDisplay output of long-running tasks in a container.with st.status('Running'): do_something_slow() ToastBriefly displays a toast message in the bottom-right corner.st.toast('Butter!', icon='🧈') BalloonsDisplay celebratory balloons!do_something() # Celebrate when all done! st.balloons() SnowflakesDisplay celebratory snowflakes!do_something() # Celebrate when all done! st.snow() Success boxDisplay a success message.st.success(""Match found!"") Info boxDisplay an informational message.st.info(""Dataset is updated every day at midnight."") Warning boxDisplay warning message.st.warning(""Unable to fetch image. Skipping..."") Error boxDisplay error message.st.error(""We encountered an error"") Exception outputDisplay an exception.e = RuntimeError(""This is an exception of type RuntimeError"") st.exception(e) Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration!StqdmThe simplest way to handle a progress bar in streamlit app. Created by @Wirg.from stqdm import stqdm for _ in stqdm(range(50)): sleep(0.5) Custom notification boxA custom notification box with the ability to close it out. Created by @Socvest.from streamlit_custom_notification_box import custom_notification_box styles = {'material-icons':{'color': 'red'}, 'text-icon-link-close-container': {'box-shadow': '#3896de 0px 4px'}, 'notification-text': {'':''}, 'close-button':{'':''}, 'link':{'':''}} custom_notification_box(icon='info', textDisplay='We are almost done with your registration...', externalLink='more info', url='#', styles=styles, key=""foo"") Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.let_it_rain import rain rain(emoji=""🎈"", font_size=54, falling_speed=5, animation_length=""infinite"",) App logic and configuration Navigation and pages Switch pageProgrammatically navigates to a specified page.st.switch_page(""pages/my_page.py"") Page linkDisplay a link to another page in a multipage app.st.page_link(""app.py"", label=""Home"", icon=""🏠"") st.page_link(""pages/profile.py"", label=""My profile"") Execution flow Modal dialogsInsert a modal dialog that can rerun independently from the rest of the script.@st.experimental_dialog(""Sign up"") def email_form(): name = st.text_input(""Name"") email = st.text_input(""Email"") FormsCreate a form that batches elements together with a “Submit"" button.with st.form(key='my_form'): name = st.text_input(""Name"") email = st.text_input(""Email"") st.form_submit_button(""Sign up"") Partial rerunsDefine a fragment to rerun independently from the rest of the script.@st.experimental_fragment(run_every=""10s"") def fragment(): df = get_data() st.line_chart(df) Rerun scriptRerun the script immediately.st.rerun() Stop executionStops execution immediately.st.stop() Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration!AutorefreshForce a refresh without tying up a script. Created by @kmcgrady.from streamlit_autorefresh import st_autorefresh st_autorefresh(interval=2000, limit=100, key=""fizzbuzzcounter"") PydanticAuto-generate Streamlit UI from Pydantic Models and Dataclasses. Created by @lukasmasuch.import streamlit_pydantic as sp sp.pydantic_form(key=""my_form"", model=ExampleModel) Streamlit PagesAn experimental version of Streamlit Multi-Page Apps. Created by @blackary.from st_pages import Page, show_pages, add_page_title show_pages([ Page(""streamlit_app.py"", ""Home"", ""🏠""), Page(""other_pages/page2.py"", ""Page 2"", "":books:""), ]) Caching and state Cache dataFunction decorator to cache functions that return data (e.g. dataframe transforms, database queries, ML inference).@st.cache_data def long_function(param1, param2): # Perform expensive computation here or # fetch data from the web here return data Cache resourceFunction decorator to cache functions that return global resources (e.g. database connections, ML models).@st.cache_resource def init_model(): # Return a global resource here return pipeline( ""sentiment-analysis"", model=""distilbert-base-uncased-finetuned-sst-2-english"" ) Session stateSession state is a way to share variables between reruns, for each user session.st.session_state['key'] = value Query parametersGet, set, or clear the query parameters that are shown in the browser's URL bar.st.query_params[key] = value st.query_params.clear() Connections and databases Setup your connection Create a connectionConnect to a data source or APIconn = st.connection('pets_db', type='sql') pet_owners = conn.query('select * from pet_owners') st.dataframe(pet_owners) Built-in connections SnowflakeConnectionA connection to Snowflake.conn = st.connection('snowflake') SQLConnectionA connection to a SQL database using SQLAlchemy.conn = st.connection('sql') Build your own connections Connection base classBuild your own connection with BaseConnection.class MyConnection(BaseConnection[myconn.MyConnection]): def _connect(self, **kwargs) -> MyConnection: return myconn.connect(**self._secrets, **kwargs) def query(self, query): return self._instance.query(query) Secrets management Secrets singletonAccess secrets from a local TOML file.key = st.secrets[""OpenAI_key""] Secrets fileSave your secrets in a per-project or per-profile TOML file.OpenAI_key = """" Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration!AuthenticatorA secure authentication module to validate user credentials. Created by @mkhorasani.import streamlit_authenticator as stauth authenticator = stauth.Authenticate( config['credentials'], config['cookie']['name'], config['cookie']['key'], config['cookie']['expiry_days'], config['preauthorized']) WS localStorageA simple synchronous way of accessing localStorage from your app. Created by @gagangoku.from streamlit_ws_localstorage import injectWebsocketCode ret = conn.setLocalStorageVal(key='k1', val='v1') st.write('ret: ' + ret) Streamlit Auth0The fastest way to provide comprehensive login inside Streamlit. Created by @conradbez.from auth0_component import login_button user_info = login_button(clientId, domain = domain) st.write(user_info) Custom Components Declare a componentCreate and register a custom component.st.components.v1.declare_component( ""custom_slider"", ""/frontend"", ) HTMLDisplay an HTML string in an iframe.st.components.v1.html( ""

Foo bar.

"" ) iframeLoad a remote URL in an iframe.st.components.v1.iframe( ""docs.streamlit.io"" ) Utilities and user info User infost.experimental_user returns information about the logged-in user of private apps on Streamlit Community Cloud.if st.experimental_user.email == ""foo@corp.com"": st.write(""Welcome back, "", st.experimental_user.email) else: st.write(""You are not authorized to view this page."") Get helpDisplay object’s doc string, nicely formatted.st.help(st.write) st.help(pd.DataFrame) Render HTMLRenders HTML strings to your app.css = """""" """""" st.html(css) Configuration Configuration fileConfigures the default settings for your app.your-project/ ├── .streamlit/ │ └── config.toml └── your_app.py Set page title, favicon, and moreConfigures the default settings of the page.st.set_page_config( page_title=""My app"", page_icon="":shark:"", ) Developer tools App testing st.testing.v1.AppTestst.testing.v1.AppTest simulates a running Streamlit app for testing.from streamlit.testing.v1 import AppTest at = AppTest.from_file(""streamlit_app.py"") at.secrets[""WORD""] = ""Foobar"" at.run() assert not at.exception at.text_input(""word"").input(""Bazbat"").run() assert at.warning[0].value == ""Try again."" AppTest.from_filest.testing.v1.AppTest.from_file initializes a simulated app from a file.from streamlit.testing.v1 import AppTest at = AppTest.from_file(""streamlit_app.py"") at.run() AppTest.from_stringst.testing.v1.AppTest.from_string initializes a simulated app from a string.from streamlit.testing.v1 import AppTest at = AppTest.from_string(app_script_as_string) at.run() AppTest.from_functionst.testing.v1.AppTest.from_function initializes a simulated app from a function.from streamlit.testing.v1 import AppTest at = AppTest.from_function(app_script_as_callable) at.run() BlockA representation of container elements, including: st.chat_message st.columns st.sidebar st.tabs The main body of the app. # at.sidebar returns a Block at.sidebar.button[0].click().run() assert not at.exception ElementThe base class for representation of all elements, including: st.title st.header st.markdown st.dataframe # at.title returns a sequence of Title # Title inherits from Element assert at.title[0].value == ""My awesome app"" ButtonA representation of st.button and st.form_submit_button.at.button[0].click().run() ChatInputA representation of st.chat_input.at.chat_input[0].set_value(""What is Streamlit?"").run() CheckboxA representation of st.checkbox.at.checkbox[0].check().run() ColorPickerA representation of st.color_picker.at.color_picker[0].pick(""#FF4B4B"").run() DateInputA representation of st.date_input.release_date = datetime.date(2023, 10, 26) at.date_input[0].set_value(release_date).run() MultiselectA representation of st.multiselect.at.multiselect[0].select(""New York"").run() NumberInputA representation of st.number_input.at.number_input[0].increment().run() RadioA representation of st.radio.at.radio[0].set_value(""New York"").run() SelectSliderA representation of st.select_slider.at.select_slider[0].set_range(""A"",""C"").run() SelectboxA representation of st.selectbox.at.selectbox[0].select(""New York"").run() SliderA representation of st.slider.at.slider[0].set_range(2,5).run() TextAreaA representation of st.text_area.at.text_area[0].input(""Streamlit is awesome!"").run() TextInputA representation of st.text_input.at.text_input[0].input(""Streamlit"").run() TimeInputA representation of st.time_input.at.time_input[0].increment().run() ToggleA representation of st.toggle.at.toggle[0].set_value(""True"").run() Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration!Pandas ProfilingPandas profiling component for Streamlit. Created by @okld.df = pd.read_csv(""https://storage.googleapis.com/tf-datasets/titanic/train.csv"") pr = df.profile_report() st_profile_report(pr) Streamlit AceAce editor component for Streamlit. Created by @okld.from streamlit_ace import st_ace content = st_ace() content Streamlit AnalyticsTrack & visualize user interactions with your streamlit app. Created by @jrieke.import streamlit_analytics with streamlit_analytics.track(): st.text_input(""Write something"") Previous: ConceptsNext: Write and magicforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy" https://docs.streamlit.io/deploy/streamlit-community-cloud/share-your-app/embed-your-app#iframe-versus-oembed,"DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudremoveGet startedaddDeploy your appaddManage your appaddShare your appremoveEmbed your appSearch indexabilityShare previewsManage your accountaddTroubleshootingStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Deploy/Streamlit Community Cloud/Share your app/Embed your appEmbed your app Embedding Streamlit Community Cloud apps enriches your content by integrating interactive, data-driven applications directly within your pages. Whether you're writing a blog post, a technical document, or sharing resources on platforms like Medium, Notion, or even StackOverflow, embedding Streamlit apps adds a dynamic component to your content. This allows your audience to interact with your ideas, rather than merely reading about them or looking at screenshots. Streamlit Community Cloud supports both iframe and oEmbed methods for embedding public apps. This flexibility enables you to share your apps across a wide array of platforms, broadening your app's visibility and impact. In this guide, we'll cover how to use both methods effectively to share your Streamlit apps with the world. Embedding with iframes Streamlit Community Cloud supports embedding public apps using the subdomain scheme. To embed a public app, add the query parameter /?embed=true to the end of the *.streamlit.app URL. For example, say you want to embed the 30DaysOfStreamlit app. The URL to include in your iframe is: https://30days.streamlit.app/?embed=true: Built with Streamlit 🎈Fullscreen open_in_new priority_highImportantThere will be no official support for embedding private apps. In addition to allowing you to embed apps via iframes, the ?embed=true query parameter also does the following: Removes the toolbar with the app menu icon (more_vert). Removes the padding at the top and bottom of the app. Removes the footer. Removes the colored line from the top of the app. For granular control over the embedding behavior, Streamlit allows you to specify one or more instances of the ?embed_options query parameter (e.g. to show the toolbar, open the app in dark theme, etc). Click here for a full list of Embed options. Embedding with oEmbed Streamlit's oEmbed support allows for a simpler embedding experience. You can directly drop a Streamlit app's URL into a Medium, Ghost, or Notion page (or any of more than 700 content providers that supports oEmbed or embed.ly). The embedded app will automatically appear! This helps Streamlit Community Cloud apps seamlessly integrate into these platforms, improving the visibility and accessibility of your apps. Example When creating content in a Notion page, Medium article, or Ghost blog, you only need to paste the app's URL and hit ""Enter"". The app will then render automatically at that spot in your content. You can use your undecorated app URL without the ?embed=true query parameter. https://30days.streamlit.app/ Here's an example of @chrieke's Prettymapp app embedded in a Medium article: starTipEnsure the platform hosting the embedded Streamlit app supports oEmbed or embed.ly. Key Sites for oEmbed oEmbed should work out of the box for several platforms including but not limited to: Medium Notion Looker Tableau Ghost Discourse StackOverflow W3 Reddit Please check the specific platform's documentation to verify support for oEmbed. iframe versus oEmbed The only noteworthy differences between the methods is that iframing allows you to customize the app's embedding behavior (e.g. showing the toolbar, opening the app in dark theme, etc) using the various ?embed_options described in the next section. Embed options When Embedding with iframes, Streamlit allows you to specify one or more instances of the ?embed_options query parameter for granular control over the embedding behavior. Both ?embed and ?embed_options are invisible to st.query_params and its precursors, st.experimental_get_query_params and st.experimental_set_query_params. You can't get or set their values. The supported values for ?embed_options are listed below: Show the toolbar at the top right of the app which includes the app menu (more_vert), running man, and link to GitHub. /?embed=true&embed_options=show_toolbar Show padding at the top and bottom of the app. /?embed=true&embed_options=show_padding Show the footer reading ""Made with Streamlit."" (This doesn't apply to Streamlit versions 1.29.0 and later since the footer was removed from the library.) /?embed=true&embed_options=show_footer Show the colored line at the top of the app. /?embed=true&embed_options=show_colored_line Hide the ""skeleton"" that appears while an app is loading. /?embed=true&embed_options=hide_loading_screen Disable scrolling for the main body of the app. (The sidebar will still be scrollable.) /?embed=true&embed_options=disable_scrolling Open the app with light theme. /?embed=true&embed_options=light_theme Open the app with dark theme. /?embed=true&embed_options=dark_theme You can also combine the params: /?embed=true&embed_options=show_toolbar&embed_options=show_padding&embed_options=show_footer&embed_options=show_colored_line&embed_options=disable_scrolling Build an embed link You can conveniently build an embed link for your app — right from your app! From your app at .streamlit.app, click ""Share"" in the upper-right corner. Click ""Embed"" to access a list of selectable embed options. Select your embed options and click ""Get embed link"" to copy the embed link to your clipboard. Previous: Share your appNext: Search indexabilityforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy" https://docs.streamlit.io/en/0.76.0/api.html#text-elements,"DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceremovePAGE ELEMENTSWrite and magicaddText elementsaddData elementsaddChart elementsaddInput widgetsaddMedia elementsaddLayouts and containersaddChat elementsaddStatus elementsaddThird-party componentsopen_in_newAPPLICATION LOGICNavigation and pagesaddExecution flowaddCaching and stateaddConnections and secretsaddCustom componentsaddUtilitiesaddConfigurationaddTOOLSApp testingaddCommand lineaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Develop/API referenceAPI reference Streamlit makes it easy for you to visualize, mutate, and share data. The API reference is organized by activity type, like displaying data or optimizing performance. Each section includes methods associated with the activity type, including examples. Browse our API below and click to learn more about any of our available commands! 🎈 Display almost anything Write and magic st.writeWrite arguments to the app.st.write(""Hello **world**!"") st.write(my_data_frame) st.write(my_mpl_figure) st.write_streamWrite generators or streams to the app with a typewriter effect.st.write_stream(my_generator) st.write_stream(my_llm_stream) MagicAny time Streamlit sees either a variable or literal value on its own line, it automatically writes that to your app using st.write""Hello **world**!"" my_data_frame my_mpl_figure Text elements MarkdownDisplay string formatted as Markdown.st.markdown(""Hello **world**!"") TitleDisplay text in title formatting.st.title(""The app title"") HeaderDisplay text in header formatting.st.header(""This is a header"") SubheaderDisplay text in subheader formatting.st.subheader(""This is a subheader"") CaptionDisplay text in small font.st.caption(""This is written small caption text"") Code blockDisplay a code block with optional syntax highlighting.st.code(""a = 1234"") EchoDisplay some code in the app, then execute it. Useful for tutorials.with st.echo(): st.write('This code will be printed') LaTeXDisplay mathematical expressions formatted as LaTeX.st.latex(""\int a x^2 \,dx"") Preformatted textWrite fixed-width and preformatted text.st.text(""Hello world"") DividerDisplay a horizontal rule.st.divider() Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration! PreviousTagsAdd tags to your Streamlit apps. Created by @gagan3012.st_tags(label='# Enter Keywords:', text='Press enter to add more', value=['Zero', 'One', 'Two'], suggestions=['five', 'six', 'seven', 'eight', 'nine', 'three', 'eleven', 'ten', 'four'], maxtags = 4, key='1') NLUApply text mining on a dataframe. Created by @JohnSnowLabs.nlu.load('sentiment').predict('I love NLU! <3') Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.mention(label=""An awesome Streamlit App"", icon=""streamlit"", url=""https://extras.streamlit.app"",) Annotated textDisplay annotated text in Streamlit apps. Created by @tvst.annotated_text(""This "", (""is"", ""verb""), "" some "", (""annotated"", ""adj""), (""text"", ""noun""), "" for those of "", (""you"", ""pronoun""), "" who "", (""like"", ""verb""), "" this sort of "", (""thing"", ""noun""), ""."") Drawable CanvasProvides a sketching canvas using Fabric.js. Created by @andfanilo.st_canvas(fill_color=""rgba(255, 165, 0, 0.3)"", stroke_width=stroke_width, stroke_color=stroke_color, background_color=bg_color, background_image=Image.open(bg_image) if bg_image else None, update_streamlit=realtime_update, height=150, drawing_mode=drawing_mode, point_display_radius=point_display_radius if drawing_mode == 'point' else 0, key=""canvas"",) TagsAdd tags to your Streamlit apps. Created by @gagan3012.st_tags(label='# Enter Keywords:', text='Press enter to add more', value=['Zero', 'One', 'Two'], suggestions=['five', 'six', 'seven', 'eight', 'nine', 'three', 'eleven', 'ten', 'four'], maxtags = 4, key='1') NLUApply text mining on a dataframe. Created by @JohnSnowLabs.nlu.load('sentiment').predict('I love NLU! <3') Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.mention(label=""An awesome Streamlit App"", icon=""streamlit"", url=""https://extras.streamlit.app"",) Annotated textDisplay annotated text in Streamlit apps. Created by @tvst.annotated_text(""This "", (""is"", ""verb""), "" some "", (""annotated"", ""adj""), (""text"", ""noun""), "" for those of "", (""you"", ""pronoun""), "" who "", (""like"", ""verb""), "" this sort of "", (""thing"", ""noun""), ""."") Drawable CanvasProvides a sketching canvas using Fabric.js. Created by @andfanilo.st_canvas(fill_color=""rgba(255, 165, 0, 0.3)"", stroke_width=stroke_width, stroke_color=stroke_color, background_color=bg_color, background_image=Image.open(bg_image) if bg_image else None, update_streamlit=realtime_update, height=150, drawing_mode=drawing_mode, point_display_radius=point_display_radius if drawing_mode == 'point' else 0, key=""canvas"",) TagsAdd tags to your Streamlit apps. Created by @gagan3012.st_tags(label='# Enter Keywords:', text='Press enter to add more', value=['Zero', 'One', 'Two'], suggestions=['five', 'six', 'seven', 'eight', 'nine', 'three', 'eleven', 'ten', 'four'], maxtags = 4, key='1') NLUApply text mining on a dataframe. Created by @JohnSnowLabs.nlu.load('sentiment').predict('I love NLU! <3') Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.mention(label=""An awesome Streamlit App"", icon=""streamlit"", url=""https://extras.streamlit.app"",) Next Data elements DataframesDisplay a dataframe as an interactive table.st.dataframe(my_data_frame) Data editorDisplay a data editor widget.edited = st.data_editor(df, num_rows=""dynamic"") Column configurationConfigure the display and editing behavior of dataframes and data editors.st.column_config.NumberColumn(""Price (in USD)"", min_value=0, format=""$%d"") Static tablesDisplay a static table.st.table(my_data_frame) MetricsDisplay a metric in big bold font, with an optional indicator of how the metric changed.st.metric(""My metric"", 42, 2) Dicts and JSONDisplay object or string as a pretty-printed JSON string.st.json(my_dict) Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration! PreviousImage CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates value = streamlit_image_coordinates(""https://placekitten.com/200/300"") st.write(value) Plotly EventsMake Plotly charts interactive!. Created by @null-jones.from streamlit_plotly_events import plotly_events fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.metric_cards import style_metric_cards col3.metric(label=""No Change"", value=5000, delta=0) style_metric_cards() Streamlit AggridImplementation of Ag-Grid component for Streamlit. Created by @PablocFonseca.df = pd.DataFrame({'col1': [1, 2, 3], 'col2': [4, 5, 6]}) grid_return = AgGrid(df, editable=True) new_df = grid_return['data'] Streamlit FoliumStreamlit Component for rendering Folium maps. Created by @randyzwitch.m = folium.Map(location=[39.949610, -75.150282], zoom_start=16) folium.Marker([39.949610, -75.150282], popup=""Liberty Bell"", tooltip=""Liberty Bell"").add_to(m) st_data = st_folium(m, width=725) Pandas ProfilingPandas profiling component for Streamlit. Created by @okld.df = pd.read_csv(""https://storage.googleapis.com/tf-datasets/titanic/train.csv"") pr = df.profile_report() st_profile_report(pr) Image CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates value = streamlit_image_coordinates(""https://placekitten.com/200/300"") st.write(value) Plotly EventsMake Plotly charts interactive!. Created by @null-jones.from streamlit_plotly_events import plotly_events fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.metric_cards import style_metric_cards col3.metric(label=""No Change"", value=5000, delta=0) style_metric_cards() Streamlit AggridImplementation of Ag-Grid component for Streamlit. Created by @PablocFonseca.df = pd.DataFrame({'col1': [1, 2, 3], 'col2': [4, 5, 6]}) grid_return = AgGrid(df, editable=True) new_df = grid_return['data'] Streamlit FoliumStreamlit Component for rendering Folium maps. Created by @randyzwitch.m = folium.Map(location=[39.949610, -75.150282], zoom_start=16) folium.Marker([39.949610, -75.150282], popup=""Liberty Bell"", tooltip=""Liberty Bell"").add_to(m) st_data = st_folium(m, width=725) Pandas ProfilingPandas profiling component for Streamlit. Created by @okld.df = pd.read_csv(""https://storage.googleapis.com/tf-datasets/titanic/train.csv"") pr = df.profile_report() st_profile_report(pr) Image CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates value = streamlit_image_coordinates(""https://placekitten.com/200/300"") st.write(value) Plotly EventsMake Plotly charts interactive!. Created by @null-jones.from streamlit_plotly_events import plotly_events fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.metric_cards import style_metric_cards col3.metric(label=""No Change"", value=5000, delta=0) style_metric_cards() Next Chart elements Simple area chartsDisplay an area chart.st.area_chart(my_data_frame) Simple bar chartsDisplay a bar chart.st.bar_chart(my_data_frame) Simple line chartsDisplay a line chart.st.line_chart(my_data_frame) Simple scatter chartsDisplay a line chart.st.scatter_chart(my_data_frame) Scatterplots on mapsDisplay a map with points on it.st.map(my_data_frame) MatplotlibDisplay a matplotlib.pyplot figure.st.pyplot(my_mpl_figure) AltairDisplay a chart using the Altair library.st.altair_chart(my_altair_chart) Vega-LiteDisplay a chart using the Vega-Lite library.st.vega_lite_chart(my_vega_lite_chart) PlotlyDisplay an interactive Plotly chart.st.plotly_chart(my_plotly_chart) BokehDisplay an interactive Bokeh chart.st.bokeh_chart(my_bokeh_chart) PyDeckDisplay a chart using the PyDeck library.st.pydeck_chart(my_pydeck_chart) GraphVizDisplay a graph using the dagre-d3 library.st.graphviz_chart(my_graphviz_spec) Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration! PreviousStreamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl(""https://assets5.lottiefiles.com/packages/lf20_V9t630.json"") st_lottie(lottie_hello, key=""hello"") Plotly EventsMake Plotly charts interactive!. Created by @null-jones.fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.chart += get_annotations_chart(annotations=[(""Mar 01, 2008"", ""Pretty good day for GOOG""), (""Dec 01, 2007"", ""Something's going wrong for GOOG & AAPL""), (""Nov 01, 2008"", ""Market starts again thanks to...""), (""Dec 01, 2009"", ""Small crash for GOOG after...""),],) st.altair_chart(chart, use_container_width=True) PlostA deceptively simple plotting library for Streamlit. Created by @tvst.import plost plost.line_chart(my_dataframe, x='time', y='stock_value', color='stock_name',) HiPlotHigh dimensional Interactive Plotting. Created by @facebookresearch.data = [{'dropout':0.1, 'lr': 0.001, 'loss': 10.0, 'optimizer': 'SGD'}, {'dropout':0.15, 'lr': 0.01, 'loss': 3.5, 'optimizer': 'Adam'}, {'dropout':0.3, 'lr': 0.1, 'loss': 4.5, 'optimizer': 'Adam'}] hip.Experiment.from_iterable(data).display() EChartsHigh dimensional Interactive Plotting. Created by @andfanilo.from streamlit_echarts import st_echarts st_echarts(options=options) Streamlit FoliumStreamlit Component for rendering Folium maps. Created by @randyzwitch.m = folium.Map(location=[39.949610, -75.150282], zoom_start=16) st_data = st_folium(m, width=725) Spacy-StreamlitspaCy building blocks and visualizers for Streamlit apps. Created by @explosion.models = [""en_core_web_sm"", ""en_core_web_md""] spacy_streamlit.visualize(models, ""Sundar Pichai is the CEO of Google."") Streamlit AgraphA Streamlit Graph Vis, based on react-grah-vis. Created by @ChrisDelClea.from streamlit_agraph import agraph, Node, Edge, Config agraph(nodes=nodes, edges=edges, config=config) Streamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl(""https://assets5.lottiefiles.com/packages/lf20_V9t630.json"") st_lottie(lottie_hello, key=""hello"") Plotly EventsMake Plotly charts interactive!. Created by @null-jones.fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.chart += get_annotations_chart(annotations=[(""Mar 01, 2008"", ""Pretty good day for GOOG""), (""Dec 01, 2007"", ""Something's going wrong for GOOG & AAPL""), (""Nov 01, 2008"", ""Market starts again thanks to...""), (""Dec 01, 2009"", ""Small crash for GOOG after...""),],) st.altair_chart(chart, use_container_width=True) PlostA deceptively simple plotting library for Streamlit. Created by @tvst.import plost plost.line_chart(my_dataframe, x='time', y='stock_value', color='stock_name',) HiPlotHigh dimensional Interactive Plotting. Created by @facebookresearch.data = [{'dropout':0.1, 'lr': 0.001, 'loss': 10.0, 'optimizer': 'SGD'}, {'dropout':0.15, 'lr': 0.01, 'loss': 3.5, 'optimizer': 'Adam'}, {'dropout':0.3, 'lr': 0.1, 'loss': 4.5, 'optimizer': 'Adam'}] hip.Experiment.from_iterable(data).display() EChartsHigh dimensional Interactive Plotting. Created by @andfanilo.from streamlit_echarts import st_echarts st_echarts(options=options) Streamlit FoliumStreamlit Component for rendering Folium maps. Created by @randyzwitch.m = folium.Map(location=[39.949610, -75.150282], zoom_start=16) st_data = st_folium(m, width=725) Spacy-StreamlitspaCy building blocks and visualizers for Streamlit apps. Created by @explosion.models = [""en_core_web_sm"", ""en_core_web_md""] spacy_streamlit.visualize(models, ""Sundar Pichai is the CEO of Google."") Streamlit AgraphA Streamlit Graph Vis, based on react-grah-vis. Created by @ChrisDelClea.from streamlit_agraph import agraph, Node, Edge, Config agraph(nodes=nodes, edges=edges, config=config) Streamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl(""https://assets5.lottiefiles.com/packages/lf20_V9t630.json"") st_lottie(lottie_hello, key=""hello"") Plotly EventsMake Plotly charts interactive!. Created by @null-jones.fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.chart += get_annotations_chart(annotations=[(""Mar 01, 2008"", ""Pretty good day for GOOG""), (""Dec 01, 2007"", ""Something's going wrong for GOOG & AAPL""), (""Nov 01, 2008"", ""Market starts again thanks to...""), (""Dec 01, 2009"", ""Small crash for GOOG after...""),],) st.altair_chart(chart, use_container_width=True) Next Input widgets ButtonDisplay a button widget.clicked = st.button(""Click me"") Download buttonDisplay a download button widget.st.download_button(""Download file"", file) Form buttonDisplay a form submit button. For use with st.form.st.form_submit_button(""Sign up"") Link buttonDisplay a link button.st.link_button(""Go to gallery"", url) Page linkDisplay a link to another page in a multipage app.st.page_link(""app.py"", label=""Home"", icon=""🏠"") st.page_link(""pages/profile.py"", label=""My profile"") CheckboxDisplay a checkbox widget.selected = st.checkbox(""I agree"") Color pickerDisplay a color picker widget.color = st.color_picker(""Pick a color"") MultiselectDisplay a multiselect widget. The multiselect widget starts as empty.choices = st.multiselect(""Buy"", [""milk"", ""apples"", ""potatoes""]) RadioDisplay a radio button widget.choice = st.radio(""Pick one"", [""cats"", ""dogs""]) SelectboxDisplay a select widget.choice = st.selectbox(""Pick one"", [""cats"", ""dogs""]) Select-sliderDisplay a slider widget to select items from a list.size = st.select_slider(""Pick a size"", [""S"", ""M"", ""L""]) ToggleDisplay a toggle widget.activated = st.toggle(""Activate"") Number inputDisplay a numeric input widget.choice = st.number_input(""Pick a number"", 0, 10) SliderDisplay a slider widget.number = st.slider(""Pick a number"", 0, 100) Date inputDisplay a date input widget.date = st.date_input(""Your birthday"") Time inputDisplay a time input widget.time = st.time_input(""Meeting time"") Chat inputDisplay a chat input widget.prompt = st.chat_input(""Say something"") if prompt: st.write(f""The user has sent: {prompt}"") Text-areaDisplay a multi-line text input widget.text = st.text_area(""Text to translate"") Text inputDisplay a single-line text input widget.name = st.text_input(""First name"") Data editorDisplay a data editor widget.edited = st.experimental_data_editor(df, num_rows=""dynamic"") File UploaderDisplay a file uploader widget.data = st.file_uploader(""Upload a CSV"") Camera inputDisplay a widget that allows users to upload images directly from a camera.image = st.camera_input(""Take a picture"") Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration! PreviousStreamlit ChatStreamlit Component for a Chatbot UI. Created by @AI-Yash.from streamlit_chat import message message(""My message"") message(""Hello bot!"", is_user=True) # align's the message to the right Streamlit Option MenuSelect a single item from a list of options in a menu. Created by @victoryhb.from streamlit_option_menu import option_menu option_menu(""Main Menu"", [""Home"", 'Settings'], icons=['house', 'gear'], menu_icon=""cast"", default_index=1) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.stoggle import stoggle stoggle( ""Click me!"", """"""🥷 Surprise! Here's some additional content"""""",) Streamlit ElementsCreate a draggable and resizable dashboard in Streamlit. Created by @okls.from streamlit_elements import elements, mui, html with elements(""new_element""): mui.Typography(""Hello world"") TagsAdd tags to your Streamlit apps. Created by @gagan3012.from streamlit_tags import st_tags st_tags(label='# Enter Keywords:', text='Press enter to add more', value=['Zero', 'One', 'Two'], suggestions=['five', 'six', 'seven', 'eight', 'nine', 'three', 'eleven', 'ten', 'four'], maxtags = 4, key='1') StqdmThe simplest way to handle a progress bar in streamlit app. Created by @Wirg.from stqdm import stqdm for _ in stqdm(range(50)): sleep(0.5) TimelineDisplay a Timeline in Streamlit apps using TimelineJS. Created by @innerdoc.from streamlit_timeline import timeline with open('example.json', ""r"") as f: timeline(f.read(), height=800) Camera input liveAlternative for st.camera_input which returns the webcam images live. Created by @blackary.from camera_input_live import camera_input_live image = camera_input_live() st.image(value) Streamlit AceAce editor component for Streamlit. Created by @okld.from streamlit_ace import st_ace content = st_ace() content Streamlit ChatStreamlit Component for a Chatbot UI. Created by @AI-Yash.from streamlit_chat import message message(""My message"") message(""Hello bot!"", is_user=True) # align's the message to the right Streamlit Option MenuSelect a single item from a list of options in a menu. Created by @victoryhb.from streamlit_option_menu import option_menu option_menu(""Main Menu"", [""Home"", 'Settings'], icons=['house', 'gear'], menu_icon=""cast"", default_index=1) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.stoggle import stoggle stoggle( ""Click me!"", """"""🥷 Surprise! Here's some additional content"""""",) Streamlit ElementsCreate a draggable and resizable dashboard in Streamlit. Created by @okls.from streamlit_elements import elements, mui, html with elements(""new_element""): mui.Typography(""Hello world"") TagsAdd tags to your Streamlit apps. Created by @gagan3012.from streamlit_tags import st_tags st_tags(label='# Enter Keywords:', text='Press enter to add more', value=['Zero', 'One', 'Two'], suggestions=['five', 'six', 'seven', 'eight', 'nine', 'three', 'eleven', 'ten', 'four'], maxtags = 4, key='1') StqdmThe simplest way to handle a progress bar in streamlit app. Created by @Wirg.from stqdm import stqdm for _ in stqdm(range(50)): sleep(0.5) TimelineDisplay a Timeline in Streamlit apps using TimelineJS. Created by @innerdoc.from streamlit_timeline import timeline with open('example.json', ""r"") as f: timeline(f.read(), height=800) Camera input liveAlternative for st.camera_input which returns the webcam images live. Created by @blackary.from camera_input_live import camera_input_live image = camera_input_live() st.image(value) Streamlit AceAce editor component for Streamlit. Created by @okld.from streamlit_ace import st_ace content = st_ace() content Streamlit ChatStreamlit Component for a Chatbot UI. Created by @AI-Yash.from streamlit_chat import message message(""My message"") message(""Hello bot!"", is_user=True) # align's the message to the right Streamlit Option MenuSelect a single item from a list of options in a menu. Created by @victoryhb.from streamlit_option_menu import option_menu option_menu(""Main Menu"", [""Home"", 'Settings'], icons=['house', 'gear'], menu_icon=""cast"", default_index=1) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.stoggle import stoggle stoggle( ""Click me!"", """"""🥷 Surprise! Here's some additional content"""""",) Next Media elements ImageDisplay an image or list of images.st.image(numpy_array) st.image(image_bytes) st.image(file) st.image(""https://example.com/myimage.jpg"") AudioDisplay an audio player.st.audio(numpy_array) st.audio(audio_bytes) st.audio(file) st.audio(""https://example.com/myaudio.mp3"", format=""audio/mp3"") VideoDisplay a video player.st.video(numpy_array) st.video(video_bytes) st.video(file) st.video(""https://example.com/myvideo.mp4"", format=""video/mp4"") Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration! PreviousStreamlit CropperA simple image cropper for Streamlit. Created by @turner-anderson.from streamlit_cropper import st_cropper st_cropper(img, realtime_update=realtime_update, box_color=box_color, aspect_ratio=aspect_ratio) Image CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates streamlit_image_coordinates(""https://placekitten.com/200/300"") Streamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl(""https://assets5.lottiefiles.com/packages/lf20_V9t630.json"") st_lottie(lottie_hello, key=""hello"") Streamlit WebrtcHandling and transmitting real-time video/audio streams with Streamlit. Created by @whitphx.from streamlit_webrtc import webrtc_streamer webrtc_streamer(key=""sample"") Drawable CanvasProvides a sketching canvas using Fabric.js. Created by @andfanilo.from streamlit_drawable_canvas import st_canvas st_canvas(fill_color=""rgba(255, 165, 0, 0.3)"", stroke_width=stroke_width, stroke_color=stroke_color, background_color=bg_color, background_image=Image.open(bg_image) if bg_image else None, update_streamlit=realtime_update, height=150, drawing_mode=drawing_mode, point_display_radius=point_display_radius if drawing_mode == 'point' else 0, key=""canvas"",) Image ComparisonCompare images with a slider using JuxtaposeJS. Created by @fcakyon.from streamlit_image_comparison import image_comparison image_comparison(img1=""image1.jpg"", img2=""image2.jpg"",) Streamlit CropperA simple image cropper for Streamlit. Created by @turner-anderson.from streamlit_cropper import st_cropper st_cropper(img, realtime_update=realtime_update, box_color=box_color, aspect_ratio=aspect_ratio) Image CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates streamlit_image_coordinates(""https://placekitten.com/200/300"") Streamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl(""https://assets5.lottiefiles.com/packages/lf20_V9t630.json"") st_lottie(lottie_hello, key=""hello"") Streamlit WebrtcHandling and transmitting real-time video/audio streams with Streamlit. Created by @whitphx.from streamlit_webrtc import webrtc_streamer webrtc_streamer(key=""sample"") Drawable CanvasProvides a sketching canvas using Fabric.js. Created by @andfanilo.from streamlit_drawable_canvas import st_canvas st_canvas(fill_color=""rgba(255, 165, 0, 0.3)"", stroke_width=stroke_width, stroke_color=stroke_color, background_color=bg_color, background_image=Image.open(bg_image) if bg_image else None, update_streamlit=realtime_update, height=150, drawing_mode=drawing_mode, point_display_radius=point_display_radius if drawing_mode == 'point' else 0, key=""canvas"",) Image ComparisonCompare images with a slider using JuxtaposeJS. Created by @fcakyon.from streamlit_image_comparison import image_comparison image_comparison(img1=""image1.jpg"", img2=""image2.jpg"",) Streamlit CropperA simple image cropper for Streamlit. Created by @turner-anderson.from streamlit_cropper import st_cropper st_cropper(img, realtime_update=realtime_update, box_color=box_color, aspect_ratio=aspect_ratio) Image CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates streamlit_image_coordinates(""https://placekitten.com/200/300"") Streamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl(""https://assets5.lottiefiles.com/packages/lf20_V9t630.json"") st_lottie(lottie_hello, key=""hello"") Next Layouts and containers ColumnsInsert containers laid out as side-by-side columns.col1, col2 = st.columns(2) col1.write(""this is column 1"") col2.write(""this is column 2"") ContainerInsert a multi-element container.c = st.container() st.write(""This will show last"") c.write(""This will show first"") c.write(""This will show second"") Modal dialogsInsert a modal dialog that can rerun independently from the rest of the script.@st.experimental_dialog(""Sign up"") def email_form(): name = st.text_input(""Name"") email = st.text_input(""Email"") EmptyInsert a single-element container.c = st.empty() st.write(""This will show last"") c.write(""This will be replaced"") c.write(""This will show first"") ExpanderInsert a multi-element container that can be expanded/collapsed.with st.expander(""Open to see more""): st.write(""This is more content"") PopoverInsert a multi-element popover container that can be opened/closed.with st.popover(""Settings""): st.checkbox(""Show completed"") SidebarDisplay items in a sidebar.st.sidebar.write(""This lives in the sidebar"") st.sidebar.button(""Click me!"") TabsInsert containers separated into tabs.tab1, tab2 = st.tabs([""Tab 1"", ""Tab2""]) tab1.write(""this is tab 1"") tab2.write(""this is tab 2"") Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration!Streamlit ElementsCreate a draggable and resizable dashboard in Streamlit. Created by @okls.from streamlit_elements import elements, mui, html with elements(""new_element""): mui.Typography(""Hello world"") PydanticAuto-generate Streamlit UI from Pydantic Models and Dataclasses. Created by @lukasmasuch.import streamlit_pydantic as sp sp.pydantic_form(key=""my_form"", model=ExampleModel) Streamlit PagesAn experimental version of Streamlit Multi-Page Apps. Created by @blackary.from st_pages import Page, show_pages, add_page_title show_pages([ Page(""streamlit_app.py"", ""Home"", ""🏠""), Page(""other_pages/page2.py"", ""Page 2"", "":books:""), ]) Chat elements Streamlit provides a few commands to help you build conversational apps. These chat elements are designed to be used in conjunction with each other, but you can also use them separately. st.chat_message lets you insert a chat message container into the app so you can display messages from the user or the app. Chat containers can contain other Streamlit elements, including charts, tables, text, and more. st.chat_input lets you display a chat input widget so the user can type in a message. Chat inputDisplay a chat input widget.prompt = st.chat_input(""Say something"") if prompt: st.write(f""The user has sent: {prompt}"") Chat messageInsert a chat message container.import numpy as np with st.chat_message(""user""): st.write(""Hello 👋"") st.line_chart(np.random.randn(30, 3)) Status containerDisplay output of long-running tasks in a container.with st.status('Running'): do_something_slow() st.write_streamWrite generators or streams to the app with a typewriter effect.st.write_stream(my_generator) st.write_stream(my_llm_stream) Status elements Progress barDisplay a progress bar.for i in range(101): st.progress(i) do_something_slow() SpinnerTemporarily displays a message while executing a block of code.with st.spinner(""Please wait...""): do_something_slow() Status containerDisplay output of long-running tasks in a container.with st.status('Running'): do_something_slow() ToastBriefly displays a toast message in the bottom-right corner.st.toast('Butter!', icon='🧈') BalloonsDisplay celebratory balloons!do_something() # Celebrate when all done! st.balloons() SnowflakesDisplay celebratory snowflakes!do_something() # Celebrate when all done! st.snow() Success boxDisplay a success message.st.success(""Match found!"") Info boxDisplay an informational message.st.info(""Dataset is updated every day at midnight."") Warning boxDisplay warning message.st.warning(""Unable to fetch image. Skipping..."") Error boxDisplay error message.st.error(""We encountered an error"") Exception outputDisplay an exception.e = RuntimeError(""This is an exception of type RuntimeError"") st.exception(e) Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration!StqdmThe simplest way to handle a progress bar in streamlit app. Created by @Wirg.from stqdm import stqdm for _ in stqdm(range(50)): sleep(0.5) Custom notification boxA custom notification box with the ability to close it out. Created by @Socvest.from streamlit_custom_notification_box import custom_notification_box styles = {'material-icons':{'color': 'red'}, 'text-icon-link-close-container': {'box-shadow': '#3896de 0px 4px'}, 'notification-text': {'':''}, 'close-button':{'':''}, 'link':{'':''}} custom_notification_box(icon='info', textDisplay='We are almost done with your registration...', externalLink='more info', url='#', styles=styles, key=""foo"") Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.let_it_rain import rain rain(emoji=""🎈"", font_size=54, falling_speed=5, animation_length=""infinite"",) App logic and configuration Navigation and pages Switch pageProgrammatically navigates to a specified page.st.switch_page(""pages/my_page.py"") Page linkDisplay a link to another page in a multipage app.st.page_link(""app.py"", label=""Home"", icon=""🏠"") st.page_link(""pages/profile.py"", label=""My profile"") Execution flow Modal dialogsInsert a modal dialog that can rerun independently from the rest of the script.@st.experimental_dialog(""Sign up"") def email_form(): name = st.text_input(""Name"") email = st.text_input(""Email"") FormsCreate a form that batches elements together with a “Submit"" button.with st.form(key='my_form'): name = st.text_input(""Name"") email = st.text_input(""Email"") st.form_submit_button(""Sign up"") Partial rerunsDefine a fragment to rerun independently from the rest of the script.@st.experimental_fragment(run_every=""10s"") def fragment(): df = get_data() st.line_chart(df) Rerun scriptRerun the script immediately.st.rerun() Stop executionStops execution immediately.st.stop() Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration!AutorefreshForce a refresh without tying up a script. Created by @kmcgrady.from streamlit_autorefresh import st_autorefresh st_autorefresh(interval=2000, limit=100, key=""fizzbuzzcounter"") PydanticAuto-generate Streamlit UI from Pydantic Models and Dataclasses. Created by @lukasmasuch.import streamlit_pydantic as sp sp.pydantic_form(key=""my_form"", model=ExampleModel) Streamlit PagesAn experimental version of Streamlit Multi-Page Apps. Created by @blackary.from st_pages import Page, show_pages, add_page_title show_pages([ Page(""streamlit_app.py"", ""Home"", ""🏠""), Page(""other_pages/page2.py"", ""Page 2"", "":books:""), ]) Caching and state Cache dataFunction decorator to cache functions that return data (e.g. dataframe transforms, database queries, ML inference).@st.cache_data def long_function(param1, param2): # Perform expensive computation here or # fetch data from the web here return data Cache resourceFunction decorator to cache functions that return global resources (e.g. database connections, ML models).@st.cache_resource def init_model(): # Return a global resource here return pipeline( ""sentiment-analysis"", model=""distilbert-base-uncased-finetuned-sst-2-english"" ) Session stateSession state is a way to share variables between reruns, for each user session.st.session_state['key'] = value Query parametersGet, set, or clear the query parameters that are shown in the browser's URL bar.st.query_params[key] = value st.query_params.clear() Connections and databases Setup your connection Create a connectionConnect to a data source or APIconn = st.connection('pets_db', type='sql') pet_owners = conn.query('select * from pet_owners') st.dataframe(pet_owners) Built-in connections SnowflakeConnectionA connection to Snowflake.conn = st.connection('snowflake') SQLConnectionA connection to a SQL database using SQLAlchemy.conn = st.connection('sql') Build your own connections Connection base classBuild your own connection with BaseConnection.class MyConnection(BaseConnection[myconn.MyConnection]): def _connect(self, **kwargs) -> MyConnection: return myconn.connect(**self._secrets, **kwargs) def query(self, query): return self._instance.query(query) Secrets management Secrets singletonAccess secrets from a local TOML file.key = st.secrets[""OpenAI_key""] Secrets fileSave your secrets in a per-project or per-profile TOML file.OpenAI_key = """" Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration!AuthenticatorA secure authentication module to validate user credentials. Created by @mkhorasani.import streamlit_authenticator as stauth authenticator = stauth.Authenticate( config['credentials'], config['cookie']['name'], config['cookie']['key'], config['cookie']['expiry_days'], config['preauthorized']) WS localStorageA simple synchronous way of accessing localStorage from your app. Created by @gagangoku.from streamlit_ws_localstorage import injectWebsocketCode ret = conn.setLocalStorageVal(key='k1', val='v1') st.write('ret: ' + ret) Streamlit Auth0The fastest way to provide comprehensive login inside Streamlit. Created by @conradbez.from auth0_component import login_button user_info = login_button(clientId, domain = domain) st.write(user_info) Custom Components Declare a componentCreate and register a custom component.st.components.v1.declare_component( ""custom_slider"", ""/frontend"", ) HTMLDisplay an HTML string in an iframe.st.components.v1.html( ""

Foo bar.

"" ) iframeLoad a remote URL in an iframe.st.components.v1.iframe( ""docs.streamlit.io"" ) Utilities and user info User infost.experimental_user returns information about the logged-in user of private apps on Streamlit Community Cloud.if st.experimental_user.email == ""foo@corp.com"": st.write(""Welcome back, "", st.experimental_user.email) else: st.write(""You are not authorized to view this page."") Get helpDisplay object’s doc string, nicely formatted.st.help(st.write) st.help(pd.DataFrame) Render HTMLRenders HTML strings to your app.css = """""" """""" st.html(css) Configuration Configuration fileConfigures the default settings for your app.your-project/ ├── .streamlit/ │ └── config.toml └── your_app.py Set page title, favicon, and moreConfigures the default settings of the page.st.set_page_config( page_title=""My app"", page_icon="":shark:"", ) Developer tools App testing st.testing.v1.AppTestst.testing.v1.AppTest simulates a running Streamlit app for testing.from streamlit.testing.v1 import AppTest at = AppTest.from_file(""streamlit_app.py"") at.secrets[""WORD""] = ""Foobar"" at.run() assert not at.exception at.text_input(""word"").input(""Bazbat"").run() assert at.warning[0].value == ""Try again."" AppTest.from_filest.testing.v1.AppTest.from_file initializes a simulated app from a file.from streamlit.testing.v1 import AppTest at = AppTest.from_file(""streamlit_app.py"") at.run() AppTest.from_stringst.testing.v1.AppTest.from_string initializes a simulated app from a string.from streamlit.testing.v1 import AppTest at = AppTest.from_string(app_script_as_string) at.run() AppTest.from_functionst.testing.v1.AppTest.from_function initializes a simulated app from a function.from streamlit.testing.v1 import AppTest at = AppTest.from_function(app_script_as_callable) at.run() BlockA representation of container elements, including: st.chat_message st.columns st.sidebar st.tabs The main body of the app. # at.sidebar returns a Block at.sidebar.button[0].click().run() assert not at.exception ElementThe base class for representation of all elements, including: st.title st.header st.markdown st.dataframe # at.title returns a sequence of Title # Title inherits from Element assert at.title[0].value == ""My awesome app"" ButtonA representation of st.button and st.form_submit_button.at.button[0].click().run() ChatInputA representation of st.chat_input.at.chat_input[0].set_value(""What is Streamlit?"").run() CheckboxA representation of st.checkbox.at.checkbox[0].check().run() ColorPickerA representation of st.color_picker.at.color_picker[0].pick(""#FF4B4B"").run() DateInputA representation of st.date_input.release_date = datetime.date(2023, 10, 26) at.date_input[0].set_value(release_date).run() MultiselectA representation of st.multiselect.at.multiselect[0].select(""New York"").run() NumberInputA representation of st.number_input.at.number_input[0].increment().run() RadioA representation of st.radio.at.radio[0].set_value(""New York"").run() SelectSliderA representation of st.select_slider.at.select_slider[0].set_range(""A"",""C"").run() SelectboxA representation of st.selectbox.at.selectbox[0].select(""New York"").run() SliderA representation of st.slider.at.slider[0].set_range(2,5).run() TextAreaA representation of st.text_area.at.text_area[0].input(""Streamlit is awesome!"").run() TextInputA representation of st.text_input.at.text_input[0].input(""Streamlit"").run() TimeInputA representation of st.time_input.at.time_input[0].increment().run() ToggleA representation of st.toggle.at.toggle[0].set_value(""True"").run() Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration!Pandas ProfilingPandas profiling component for Streamlit. Created by @okld.df = pd.read_csv(""https://storage.googleapis.com/tf-datasets/titanic/train.csv"") pr = df.profile_report() st_profile_report(pr) Streamlit AceAce editor component for Streamlit. Created by @okld.from streamlit_ace import st_ace content = st_ace() content Streamlit AnalyticsTrack & visualize user interactions with your streamlit app. Created by @jrieke.import streamlit_analytics with streamlit_analytics.track(): st.text_input(""Write something"") Previous: ConceptsNext: Write and magicforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy" https://docs.streamlit.io/develop/api-reference/caching-and-state/st.cache_resource#stcache_resource,"DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceremovePAGE ELEMENTSWrite and magicaddText elementsaddData elementsaddChart elementsaddInput widgetsaddMedia elementsaddLayouts and containersaddChat elementsaddStatus elementsaddThird-party componentsopen_in_newAPPLICATION LOGICNavigation and pagesaddExecution flowaddCaching and stateremovest.cache_datast.cache_resourcest.cachedeletest.session_statest.query_paramsst.experimental_get_query_paramsdeletest.experimental_set_query_paramsdeleteConnections and secretsaddCustom componentsaddUtilitiesaddConfigurationaddTOOLSApp testingaddCommand lineaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Develop/API reference/Caching and state/st.cache_resourcestarTipThis page only contains information on the st.cache_resource API. For a deeper dive into caching and how to use it, check out Caching. st.cache_resourceStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeDecorator to cache functions that return global resources (e.g. database connections, ML models). Cached objects are shared across all users, sessions, and reruns. They must be thread-safe because they can be accessed from multiple threads concurrently. If thread safety is an issue, consider using st.session_state to store resources per session instead. You can clear a function's cache with func.clear() or clear the entire cache with st.cache_resource.clear(). To cache data, use st.cache_data instead. Learn more about caching at https://docs.streamlit.io/library/advanced-features/caching. Function signature[source] st.cache_resource(func, *, ttl, max_entries, show_spinner, validate, experimental_allow_widgets, hash_funcs=None) Parameters func (callable) The function that creates the cached resource. Streamlit hashes the function's source code. ttl (float, timedelta, str, or None) The maximum time to keep an entry in the cache. Can be one of: None if cache entries should never expire (default). A number specifying the time in seconds. A string specifying the time in a format supported by Pandas's Timedelta constructor, e.g. ""1d"", ""1.5 days"", or ""1h23s"". A timedelta object from Python's built-in datetime library, e.g. timedelta(days=1). max_entries (int or None) The maximum number of entries to keep in the cache, or None for an unbounded cache. When a new entry is added to a full cache, the oldest cached entry will be removed. Defaults to None. show_spinner (bool or str) Enable the spinner. Default is True to show a spinner when there is a ""cache miss"" and the cached resource is being created. If string, value of show_spinner param will be used for spinner text. validate (callable or None) An optional validation function for cached data. validate is called each time the cached value is accessed. It receives the cached value as its only parameter and it must return a boolean. If validate returns False, the current cached value is discarded, and the decorated function is called to compute a new value. This is useful e.g. to check the health of database connections. experimental_allow_widgets (bool) Allow widgets to be used in the cached function. Defaults to False. Support for widgets in cached functions is currently experimental. Setting this parameter to True may lead to excessive memory use since the widget value is treated as an additional input parameter to the cache. We may remove support for this option at any time without notice. hash_funcs (dict or None) Mapping of types or fully qualified names to hash functions. This is used to override the behavior of the hasher inside Streamlit's caching mechanism: when the hasher encounters an object, it will first check to see if its type matches a key in this dict and, if so, will use the provided function to generate a hash for it. See below for an example of how this can be used. Example import streamlit as st @st.cache_resource def get_database_session(url): # Create a database session object that points to the URL. return session s1 = get_database_session(SESSION_URL_1) # Actually executes the function, since this is the first time it was # encountered. s2 = get_database_session(SESSION_URL_1) # Does not execute the function. Instead, returns its previously computed # value. This means that now the connection object in s1 is the same as in s2. s3 = get_database_session(SESSION_URL_2) # This is a different URL, so the function executes. By default, all parameters to a cache_resource function must be hashable. Any parameter whose name begins with _ will not be hashed. You can use this as an ""escape hatch"" for parameters that are not hashable: import streamlit as st @st.cache_resource def get_database_session(_sessionmaker, url): # Create a database connection object that points to the URL. return connection s1 = get_database_session(create_sessionmaker(), DATA_URL_1) # Actually executes the function, since this is the first time it was # encountered. s2 = get_database_session(create_sessionmaker(), DATA_URL_1) # Does not execute the function. Instead, returns its previously computed # value - even though the _sessionmaker parameter was different # in both calls. A cache_resource function's cache can be procedurally cleared: import streamlit as st @st.cache_resource def get_database_session(_sessionmaker, url): # Create a database connection object that points to the URL. return connection fetch_and_clean_data.clear(_sessionmaker, ""https://streamlit.io/"") # Clear the cached entry for the arguments provided. get_database_session.clear() # Clear all cached entries for this function. To override the default hashing behavior, pass a custom hash function. You can do that by mapping a type (e.g. Person) to a hash function (str) like this: import streamlit as st from pydantic import BaseModel class Person(BaseModel): name: str @st.cache_resource(hash_funcs={Person: str}) def get_person_name(person: Person): return person.name Alternatively, you can map the type's fully-qualified name (e.g. ""__main__.Person"") to the hash function instead: import streamlit as st from pydantic import BaseModel class Person(BaseModel): name: str @st.cache_resource(hash_funcs={""__main__.Person"": str}) def get_person_name(person: Person): return person.name st.cache_resource.clearStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeClear all cache_resource caches. Function signature[source] st.cache_resource.clear() Example In the example below, pressing the ""Clear All"" button will clear all cache_resource caches. i.e. Clears cached global resources from all functions decorated with @st.cache_resource. import streamlit as st from transformers import BertModel @st.cache_resource def get_database_session(url): # Create a database session object that points to the URL. return session @st.cache_resource def get_model(model_type): # Create a model of the specified type. return BertModel.from_pretrained(model_type) if st.button(""Clear All""): # Clears all st.cache_resource caches: st.cache_resource.clear() CachedFunc.clearStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeClear the cached function's associated cache. If no arguments are passed, Streamlit will clear all values cached for the function. If arguments are passed, Streamlit will clear the cached value for these arguments only. Function signature[source] CachedFunc.clear(*args, **kwargs) Parameters *args (Any) Arguments of the cached functions. **kwargs (Any) Keyword arguments of the cached function. Example import streamlit as st import time @st.cache_data def foo(bar): time.sleep(2) st.write(f""Executed foo({bar})."") return bar if st.button(""Clear all cached values for `foo`"", on_click=foo.clear): foo.clear() if st.button(""Clear the cached value of `foo(1)`""): foo.clear(1) foo(1) foo(2) Using Streamlit commands in cached functions Static elements Since version 1.16.0, cached functions can contain Streamlit commands! For example, you can do this: from transformers import pipeline @st.cache_resource def load_model(): model = pipeline(""sentiment-analysis"") st.success(""Loaded NLP model from Hugging Face!"") # 👈 Show a success message return model As we know, Streamlit only runs this function if it hasn’t been cached before. On this first run, the st.success message will appear in the app. But what happens on subsequent runs? It still shows up! Streamlit realizes that there is an st. command inside the cached function, saves it during the first run, and replays it on subsequent runs. Replaying static elements works for both caching decorators. You can also use this functionality to cache entire parts of your UI: @st.cache_resource def load_model(): st.header(""Data analysis"") model = torchvision.models.resnet50(weights=ResNet50_Weights.DEFAULT) st.success(""Loaded model!"") st.write(""Turning on evaluation mode..."") model.eval() st.write(""Here's the model:"") return model Input widgets You can also use interactive input widgets like st.slider or st.text_input in cached functions. Widget replay is an experimental feature at the moment. To enable it, you need to set the experimental_allow_widgets parameter: @st.cache_resource(experimental_allow_widgets=True) # 👈 Set the parameter def load_model(): pretrained = st.checkbox(""Use pre-trained model:"") # 👈 Add a checkbox model = torchvision.models.resnet50(weights=ResNet50_Weights.DEFAULT, pretrained=pretrained) return model Streamlit treats the checkbox like an additional input parameter to the cached function. If you uncheck it, Streamlit will see if it has already cached the function for this checkbox state. If yes, it will return the cached value. If not, it will rerun the function using the new slider value. Using widgets in cached functions is extremely powerful because it lets you cache entire parts of your app. But it can be dangerous! Since Streamlit treats the widget value as an additional input parameter, it can easily lead to excessive memory usage. Imagine your cached function has five sliders and returns a 100 MB DataFrame. Then we’ll add 100 MB to the cache for every permutation of these five slider values – even if the sliders do not influence the returned data! These additions can make your cache explode very quickly. Please be aware of this limitation if you use widgets in cached functions. We recommend using this feature only for isolated parts of your UI where the widgets directly influence the cached return value. priority_highWarningSupport for widgets in cached functions is currently experimental. We may change or remove it anytime without warning. Please use it with care! push_pinNoteTwo widgets are currently not supported in cached functions: st.file_uploader and st.camera_input. We may support them in the future. Feel free to open a GitHub issue if you need them!Previous: st.cache_dataNext: st.cacheforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy" https://docs.streamlit.io/en/0.70.0/api.html#built-in-connections,"DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceremovePAGE ELEMENTSWrite and magicaddText elementsaddData elementsaddChart elementsaddInput widgetsaddMedia elementsaddLayouts and containersaddChat elementsaddStatus elementsaddThird-party componentsopen_in_newAPPLICATION LOGICNavigation and pagesaddExecution flowaddCaching and stateaddConnections and secretsaddCustom componentsaddUtilitiesaddConfigurationaddTOOLSApp testingaddCommand lineaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Develop/API referenceAPI reference Streamlit makes it easy for you to visualize, mutate, and share data. The API reference is organized by activity type, like displaying data or optimizing performance. Each section includes methods associated with the activity type, including examples. Browse our API below and click to learn more about any of our available commands! 🎈 Display almost anything Write and magic st.writeWrite arguments to the app.st.write(""Hello **world**!"") st.write(my_data_frame) st.write(my_mpl_figure) st.write_streamWrite generators or streams to the app with a typewriter effect.st.write_stream(my_generator) st.write_stream(my_llm_stream) MagicAny time Streamlit sees either a variable or literal value on its own line, it automatically writes that to your app using st.write""Hello **world**!"" my_data_frame my_mpl_figure Text elements MarkdownDisplay string formatted as Markdown.st.markdown(""Hello **world**!"") TitleDisplay text in title formatting.st.title(""The app title"") HeaderDisplay text in header formatting.st.header(""This is a header"") SubheaderDisplay text in subheader formatting.st.subheader(""This is a subheader"") CaptionDisplay text in small font.st.caption(""This is written small caption text"") Code blockDisplay a code block with optional syntax highlighting.st.code(""a = 1234"") EchoDisplay some code in the app, then execute it. Useful for tutorials.with st.echo(): st.write('This code will be printed') LaTeXDisplay mathematical expressions formatted as LaTeX.st.latex(""\int a x^2 \,dx"") Preformatted textWrite fixed-width and preformatted text.st.text(""Hello world"") DividerDisplay a horizontal rule.st.divider() Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration! PreviousTagsAdd tags to your Streamlit apps. Created by @gagan3012.st_tags(label='# Enter Keywords:', text='Press enter to add more', value=['Zero', 'One', 'Two'], suggestions=['five', 'six', 'seven', 'eight', 'nine', 'three', 'eleven', 'ten', 'four'], maxtags = 4, key='1') NLUApply text mining on a dataframe. Created by @JohnSnowLabs.nlu.load('sentiment').predict('I love NLU! <3') Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.mention(label=""An awesome Streamlit App"", icon=""streamlit"", url=""https://extras.streamlit.app"",) Annotated textDisplay annotated text in Streamlit apps. Created by @tvst.annotated_text(""This "", (""is"", ""verb""), "" some "", (""annotated"", ""adj""), (""text"", ""noun""), "" for those of "", (""you"", ""pronoun""), "" who "", (""like"", ""verb""), "" this sort of "", (""thing"", ""noun""), ""."") Drawable CanvasProvides a sketching canvas using Fabric.js. Created by @andfanilo.st_canvas(fill_color=""rgba(255, 165, 0, 0.3)"", stroke_width=stroke_width, stroke_color=stroke_color, background_color=bg_color, background_image=Image.open(bg_image) if bg_image else None, update_streamlit=realtime_update, height=150, drawing_mode=drawing_mode, point_display_radius=point_display_radius if drawing_mode == 'point' else 0, key=""canvas"",) TagsAdd tags to your Streamlit apps. Created by @gagan3012.st_tags(label='# Enter Keywords:', text='Press enter to add more', value=['Zero', 'One', 'Two'], suggestions=['five', 'six', 'seven', 'eight', 'nine', 'three', 'eleven', 'ten', 'four'], maxtags = 4, key='1') NLUApply text mining on a dataframe. Created by @JohnSnowLabs.nlu.load('sentiment').predict('I love NLU! <3') Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.mention(label=""An awesome Streamlit App"", icon=""streamlit"", url=""https://extras.streamlit.app"",) Annotated textDisplay annotated text in Streamlit apps. Created by @tvst.annotated_text(""This "", (""is"", ""verb""), "" some "", (""annotated"", ""adj""), (""text"", ""noun""), "" for those of "", (""you"", ""pronoun""), "" who "", (""like"", ""verb""), "" this sort of "", (""thing"", ""noun""), ""."") Drawable CanvasProvides a sketching canvas using Fabric.js. Created by @andfanilo.st_canvas(fill_color=""rgba(255, 165, 0, 0.3)"", stroke_width=stroke_width, stroke_color=stroke_color, background_color=bg_color, background_image=Image.open(bg_image) if bg_image else None, update_streamlit=realtime_update, height=150, drawing_mode=drawing_mode, point_display_radius=point_display_radius if drawing_mode == 'point' else 0, key=""canvas"",) TagsAdd tags to your Streamlit apps. Created by @gagan3012.st_tags(label='# Enter Keywords:', text='Press enter to add more', value=['Zero', 'One', 'Two'], suggestions=['five', 'six', 'seven', 'eight', 'nine', 'three', 'eleven', 'ten', 'four'], maxtags = 4, key='1') NLUApply text mining on a dataframe. Created by @JohnSnowLabs.nlu.load('sentiment').predict('I love NLU! <3') Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.mention(label=""An awesome Streamlit App"", icon=""streamlit"", url=""https://extras.streamlit.app"",) Next Data elements DataframesDisplay a dataframe as an interactive table.st.dataframe(my_data_frame) Data editorDisplay a data editor widget.edited = st.data_editor(df, num_rows=""dynamic"") Column configurationConfigure the display and editing behavior of dataframes and data editors.st.column_config.NumberColumn(""Price (in USD)"", min_value=0, format=""$%d"") Static tablesDisplay a static table.st.table(my_data_frame) MetricsDisplay a metric in big bold font, with an optional indicator of how the metric changed.st.metric(""My metric"", 42, 2) Dicts and JSONDisplay object or string as a pretty-printed JSON string.st.json(my_dict) Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration! PreviousImage CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates value = streamlit_image_coordinates(""https://placekitten.com/200/300"") st.write(value) Plotly EventsMake Plotly charts interactive!. Created by @null-jones.from streamlit_plotly_events import plotly_events fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.metric_cards import style_metric_cards col3.metric(label=""No Change"", value=5000, delta=0) style_metric_cards() Streamlit AggridImplementation of Ag-Grid component for Streamlit. Created by @PablocFonseca.df = pd.DataFrame({'col1': [1, 2, 3], 'col2': [4, 5, 6]}) grid_return = AgGrid(df, editable=True) new_df = grid_return['data'] Streamlit FoliumStreamlit Component for rendering Folium maps. Created by @randyzwitch.m = folium.Map(location=[39.949610, -75.150282], zoom_start=16) folium.Marker([39.949610, -75.150282], popup=""Liberty Bell"", tooltip=""Liberty Bell"").add_to(m) st_data = st_folium(m, width=725) Pandas ProfilingPandas profiling component for Streamlit. Created by @okld.df = pd.read_csv(""https://storage.googleapis.com/tf-datasets/titanic/train.csv"") pr = df.profile_report() st_profile_report(pr) Image CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates value = streamlit_image_coordinates(""https://placekitten.com/200/300"") st.write(value) Plotly EventsMake Plotly charts interactive!. Created by @null-jones.from streamlit_plotly_events import plotly_events fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.metric_cards import style_metric_cards col3.metric(label=""No Change"", value=5000, delta=0) style_metric_cards() Streamlit AggridImplementation of Ag-Grid component for Streamlit. Created by @PablocFonseca.df = pd.DataFrame({'col1': [1, 2, 3], 'col2': [4, 5, 6]}) grid_return = AgGrid(df, editable=True) new_df = grid_return['data'] Streamlit FoliumStreamlit Component for rendering Folium maps. Created by @randyzwitch.m = folium.Map(location=[39.949610, -75.150282], zoom_start=16) folium.Marker([39.949610, -75.150282], popup=""Liberty Bell"", tooltip=""Liberty Bell"").add_to(m) st_data = st_folium(m, width=725) Pandas ProfilingPandas profiling component for Streamlit. Created by @okld.df = pd.read_csv(""https://storage.googleapis.com/tf-datasets/titanic/train.csv"") pr = df.profile_report() st_profile_report(pr) Image CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates value = streamlit_image_coordinates(""https://placekitten.com/200/300"") st.write(value) Plotly EventsMake Plotly charts interactive!. Created by @null-jones.from streamlit_plotly_events import plotly_events fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.metric_cards import style_metric_cards col3.metric(label=""No Change"", value=5000, delta=0) style_metric_cards() Next Chart elements Simple area chartsDisplay an area chart.st.area_chart(my_data_frame) Simple bar chartsDisplay a bar chart.st.bar_chart(my_data_frame) Simple line chartsDisplay a line chart.st.line_chart(my_data_frame) Simple scatter chartsDisplay a line chart.st.scatter_chart(my_data_frame) Scatterplots on mapsDisplay a map with points on it.st.map(my_data_frame) MatplotlibDisplay a matplotlib.pyplot figure.st.pyplot(my_mpl_figure) AltairDisplay a chart using the Altair library.st.altair_chart(my_altair_chart) Vega-LiteDisplay a chart using the Vega-Lite library.st.vega_lite_chart(my_vega_lite_chart) PlotlyDisplay an interactive Plotly chart.st.plotly_chart(my_plotly_chart) BokehDisplay an interactive Bokeh chart.st.bokeh_chart(my_bokeh_chart) PyDeckDisplay a chart using the PyDeck library.st.pydeck_chart(my_pydeck_chart) GraphVizDisplay a graph using the dagre-d3 library.st.graphviz_chart(my_graphviz_spec) Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration! PreviousStreamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl(""https://assets5.lottiefiles.com/packages/lf20_V9t630.json"") st_lottie(lottie_hello, key=""hello"") Plotly EventsMake Plotly charts interactive!. Created by @null-jones.fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.chart += get_annotations_chart(annotations=[(""Mar 01, 2008"", ""Pretty good day for GOOG""), (""Dec 01, 2007"", ""Something's going wrong for GOOG & AAPL""), (""Nov 01, 2008"", ""Market starts again thanks to...""), (""Dec 01, 2009"", ""Small crash for GOOG after...""),],) st.altair_chart(chart, use_container_width=True) PlostA deceptively simple plotting library for Streamlit. Created by @tvst.import plost plost.line_chart(my_dataframe, x='time', y='stock_value', color='stock_name',) HiPlotHigh dimensional Interactive Plotting. Created by @facebookresearch.data = [{'dropout':0.1, 'lr': 0.001, 'loss': 10.0, 'optimizer': 'SGD'}, {'dropout':0.15, 'lr': 0.01, 'loss': 3.5, 'optimizer': 'Adam'}, {'dropout':0.3, 'lr': 0.1, 'loss': 4.5, 'optimizer': 'Adam'}] hip.Experiment.from_iterable(data).display() EChartsHigh dimensional Interactive Plotting. Created by @andfanilo.from streamlit_echarts import st_echarts st_echarts(options=options) Streamlit FoliumStreamlit Component for rendering Folium maps. Created by @randyzwitch.m = folium.Map(location=[39.949610, -75.150282], zoom_start=16) st_data = st_folium(m, width=725) Spacy-StreamlitspaCy building blocks and visualizers for Streamlit apps. Created by @explosion.models = [""en_core_web_sm"", ""en_core_web_md""] spacy_streamlit.visualize(models, ""Sundar Pichai is the CEO of Google."") Streamlit AgraphA Streamlit Graph Vis, based on react-grah-vis. Created by @ChrisDelClea.from streamlit_agraph import agraph, Node, Edge, Config agraph(nodes=nodes, edges=edges, config=config) Streamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl(""https://assets5.lottiefiles.com/packages/lf20_V9t630.json"") st_lottie(lottie_hello, key=""hello"") Plotly EventsMake Plotly charts interactive!. Created by @null-jones.fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.chart += get_annotations_chart(annotations=[(""Mar 01, 2008"", ""Pretty good day for GOOG""), (""Dec 01, 2007"", ""Something's going wrong for GOOG & AAPL""), (""Nov 01, 2008"", ""Market starts again thanks to...""), (""Dec 01, 2009"", ""Small crash for GOOG after...""),],) st.altair_chart(chart, use_container_width=True) PlostA deceptively simple plotting library for Streamlit. Created by @tvst.import plost plost.line_chart(my_dataframe, x='time', y='stock_value', color='stock_name',) HiPlotHigh dimensional Interactive Plotting. Created by @facebookresearch.data = [{'dropout':0.1, 'lr': 0.001, 'loss': 10.0, 'optimizer': 'SGD'}, {'dropout':0.15, 'lr': 0.01, 'loss': 3.5, 'optimizer': 'Adam'}, {'dropout':0.3, 'lr': 0.1, 'loss': 4.5, 'optimizer': 'Adam'}] hip.Experiment.from_iterable(data).display() EChartsHigh dimensional Interactive Plotting. Created by @andfanilo.from streamlit_echarts import st_echarts st_echarts(options=options) Streamlit FoliumStreamlit Component for rendering Folium maps. Created by @randyzwitch.m = folium.Map(location=[39.949610, -75.150282], zoom_start=16) st_data = st_folium(m, width=725) Spacy-StreamlitspaCy building blocks and visualizers for Streamlit apps. Created by @explosion.models = [""en_core_web_sm"", ""en_core_web_md""] spacy_streamlit.visualize(models, ""Sundar Pichai is the CEO of Google."") Streamlit AgraphA Streamlit Graph Vis, based on react-grah-vis. Created by @ChrisDelClea.from streamlit_agraph import agraph, Node, Edge, Config agraph(nodes=nodes, edges=edges, config=config) Streamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl(""https://assets5.lottiefiles.com/packages/lf20_V9t630.json"") st_lottie(lottie_hello, key=""hello"") Plotly EventsMake Plotly charts interactive!. Created by @null-jones.fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.chart += get_annotations_chart(annotations=[(""Mar 01, 2008"", ""Pretty good day for GOOG""), (""Dec 01, 2007"", ""Something's going wrong for GOOG & AAPL""), (""Nov 01, 2008"", ""Market starts again thanks to...""), (""Dec 01, 2009"", ""Small crash for GOOG after...""),],) st.altair_chart(chart, use_container_width=True) Next Input widgets ButtonDisplay a button widget.clicked = st.button(""Click me"") Download buttonDisplay a download button widget.st.download_button(""Download file"", file) Form buttonDisplay a form submit button. For use with st.form.st.form_submit_button(""Sign up"") Link buttonDisplay a link button.st.link_button(""Go to gallery"", url) Page linkDisplay a link to another page in a multipage app.st.page_link(""app.py"", label=""Home"", icon=""🏠"") st.page_link(""pages/profile.py"", label=""My profile"") CheckboxDisplay a checkbox widget.selected = st.checkbox(""I agree"") Color pickerDisplay a color picker widget.color = st.color_picker(""Pick a color"") MultiselectDisplay a multiselect widget. The multiselect widget starts as empty.choices = st.multiselect(""Buy"", [""milk"", ""apples"", ""potatoes""]) RadioDisplay a radio button widget.choice = st.radio(""Pick one"", [""cats"", ""dogs""]) SelectboxDisplay a select widget.choice = st.selectbox(""Pick one"", [""cats"", ""dogs""]) Select-sliderDisplay a slider widget to select items from a list.size = st.select_slider(""Pick a size"", [""S"", ""M"", ""L""]) ToggleDisplay a toggle widget.activated = st.toggle(""Activate"") Number inputDisplay a numeric input widget.choice = st.number_input(""Pick a number"", 0, 10) SliderDisplay a slider widget.number = st.slider(""Pick a number"", 0, 100) Date inputDisplay a date input widget.date = st.date_input(""Your birthday"") Time inputDisplay a time input widget.time = st.time_input(""Meeting time"") Chat inputDisplay a chat input widget.prompt = st.chat_input(""Say something"") if prompt: st.write(f""The user has sent: {prompt}"") Text-areaDisplay a multi-line text input widget.text = st.text_area(""Text to translate"") Text inputDisplay a single-line text input widget.name = st.text_input(""First name"") Data editorDisplay a data editor widget.edited = st.experimental_data_editor(df, num_rows=""dynamic"") File UploaderDisplay a file uploader widget.data = st.file_uploader(""Upload a CSV"") Camera inputDisplay a widget that allows users to upload images directly from a camera.image = st.camera_input(""Take a picture"") Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration! PreviousStreamlit ChatStreamlit Component for a Chatbot UI. Created by @AI-Yash.from streamlit_chat import message message(""My message"") message(""Hello bot!"", is_user=True) # align's the message to the right Streamlit Option MenuSelect a single item from a list of options in a menu. Created by @victoryhb.from streamlit_option_menu import option_menu option_menu(""Main Menu"", [""Home"", 'Settings'], icons=['house', 'gear'], menu_icon=""cast"", default_index=1) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.stoggle import stoggle stoggle( ""Click me!"", """"""🥷 Surprise! Here's some additional content"""""",) Streamlit ElementsCreate a draggable and resizable dashboard in Streamlit. Created by @okls.from streamlit_elements import elements, mui, html with elements(""new_element""): mui.Typography(""Hello world"") TagsAdd tags to your Streamlit apps. Created by @gagan3012.from streamlit_tags import st_tags st_tags(label='# Enter Keywords:', text='Press enter to add more', value=['Zero', 'One', 'Two'], suggestions=['five', 'six', 'seven', 'eight', 'nine', 'three', 'eleven', 'ten', 'four'], maxtags = 4, key='1') StqdmThe simplest way to handle a progress bar in streamlit app. Created by @Wirg.from stqdm import stqdm for _ in stqdm(range(50)): sleep(0.5) TimelineDisplay a Timeline in Streamlit apps using TimelineJS. Created by @innerdoc.from streamlit_timeline import timeline with open('example.json', ""r"") as f: timeline(f.read(), height=800) Camera input liveAlternative for st.camera_input which returns the webcam images live. Created by @blackary.from camera_input_live import camera_input_live image = camera_input_live() st.image(value) Streamlit AceAce editor component for Streamlit. Created by @okld.from streamlit_ace import st_ace content = st_ace() content Streamlit ChatStreamlit Component for a Chatbot UI. Created by @AI-Yash.from streamlit_chat import message message(""My message"") message(""Hello bot!"", is_user=True) # align's the message to the right Streamlit Option MenuSelect a single item from a list of options in a menu. Created by @victoryhb.from streamlit_option_menu import option_menu option_menu(""Main Menu"", [""Home"", 'Settings'], icons=['house', 'gear'], menu_icon=""cast"", default_index=1) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.stoggle import stoggle stoggle( ""Click me!"", """"""🥷 Surprise! Here's some additional content"""""",) Streamlit ElementsCreate a draggable and resizable dashboard in Streamlit. Created by @okls.from streamlit_elements import elements, mui, html with elements(""new_element""): mui.Typography(""Hello world"") TagsAdd tags to your Streamlit apps. Created by @gagan3012.from streamlit_tags import st_tags st_tags(label='# Enter Keywords:', text='Press enter to add more', value=['Zero', 'One', 'Two'], suggestions=['five', 'six', 'seven', 'eight', 'nine', 'three', 'eleven', 'ten', 'four'], maxtags = 4, key='1') StqdmThe simplest way to handle a progress bar in streamlit app. Created by @Wirg.from stqdm import stqdm for _ in stqdm(range(50)): sleep(0.5) TimelineDisplay a Timeline in Streamlit apps using TimelineJS. Created by @innerdoc.from streamlit_timeline import timeline with open('example.json', ""r"") as f: timeline(f.read(), height=800) Camera input liveAlternative for st.camera_input which returns the webcam images live. Created by @blackary.from camera_input_live import camera_input_live image = camera_input_live() st.image(value) Streamlit AceAce editor component for Streamlit. Created by @okld.from streamlit_ace import st_ace content = st_ace() content Streamlit ChatStreamlit Component for a Chatbot UI. Created by @AI-Yash.from streamlit_chat import message message(""My message"") message(""Hello bot!"", is_user=True) # align's the message to the right Streamlit Option MenuSelect a single item from a list of options in a menu. Created by @victoryhb.from streamlit_option_menu import option_menu option_menu(""Main Menu"", [""Home"", 'Settings'], icons=['house', 'gear'], menu_icon=""cast"", default_index=1) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.stoggle import stoggle stoggle( ""Click me!"", """"""🥷 Surprise! Here's some additional content"""""",) Next Media elements ImageDisplay an image or list of images.st.image(numpy_array) st.image(image_bytes) st.image(file) st.image(""https://example.com/myimage.jpg"") AudioDisplay an audio player.st.audio(numpy_array) st.audio(audio_bytes) st.audio(file) st.audio(""https://example.com/myaudio.mp3"", format=""audio/mp3"") VideoDisplay a video player.st.video(numpy_array) st.video(video_bytes) st.video(file) st.video(""https://example.com/myvideo.mp4"", format=""video/mp4"") Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration! PreviousStreamlit CropperA simple image cropper for Streamlit. Created by @turner-anderson.from streamlit_cropper import st_cropper st_cropper(img, realtime_update=realtime_update, box_color=box_color, aspect_ratio=aspect_ratio) Image CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates streamlit_image_coordinates(""https://placekitten.com/200/300"") Streamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl(""https://assets5.lottiefiles.com/packages/lf20_V9t630.json"") st_lottie(lottie_hello, key=""hello"") Streamlit WebrtcHandling and transmitting real-time video/audio streams with Streamlit. Created by @whitphx.from streamlit_webrtc import webrtc_streamer webrtc_streamer(key=""sample"") Drawable CanvasProvides a sketching canvas using Fabric.js. Created by @andfanilo.from streamlit_drawable_canvas import st_canvas st_canvas(fill_color=""rgba(255, 165, 0, 0.3)"", stroke_width=stroke_width, stroke_color=stroke_color, background_color=bg_color, background_image=Image.open(bg_image) if bg_image else None, update_streamlit=realtime_update, height=150, drawing_mode=drawing_mode, point_display_radius=point_display_radius if drawing_mode == 'point' else 0, key=""canvas"",) Image ComparisonCompare images with a slider using JuxtaposeJS. Created by @fcakyon.from streamlit_image_comparison import image_comparison image_comparison(img1=""image1.jpg"", img2=""image2.jpg"",) Streamlit CropperA simple image cropper for Streamlit. Created by @turner-anderson.from streamlit_cropper import st_cropper st_cropper(img, realtime_update=realtime_update, box_color=box_color, aspect_ratio=aspect_ratio) Image CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates streamlit_image_coordinates(""https://placekitten.com/200/300"") Streamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl(""https://assets5.lottiefiles.com/packages/lf20_V9t630.json"") st_lottie(lottie_hello, key=""hello"") Streamlit WebrtcHandling and transmitting real-time video/audio streams with Streamlit. Created by @whitphx.from streamlit_webrtc import webrtc_streamer webrtc_streamer(key=""sample"") Drawable CanvasProvides a sketching canvas using Fabric.js. Created by @andfanilo.from streamlit_drawable_canvas import st_canvas st_canvas(fill_color=""rgba(255, 165, 0, 0.3)"", stroke_width=stroke_width, stroke_color=stroke_color, background_color=bg_color, background_image=Image.open(bg_image) if bg_image else None, update_streamlit=realtime_update, height=150, drawing_mode=drawing_mode, point_display_radius=point_display_radius if drawing_mode == 'point' else 0, key=""canvas"",) Image ComparisonCompare images with a slider using JuxtaposeJS. Created by @fcakyon.from streamlit_image_comparison import image_comparison image_comparison(img1=""image1.jpg"", img2=""image2.jpg"",) Streamlit CropperA simple image cropper for Streamlit. Created by @turner-anderson.from streamlit_cropper import st_cropper st_cropper(img, realtime_update=realtime_update, box_color=box_color, aspect_ratio=aspect_ratio) Image CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates streamlit_image_coordinates(""https://placekitten.com/200/300"") Streamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl(""https://assets5.lottiefiles.com/packages/lf20_V9t630.json"") st_lottie(lottie_hello, key=""hello"") Next Layouts and containers ColumnsInsert containers laid out as side-by-side columns.col1, col2 = st.columns(2) col1.write(""this is column 1"") col2.write(""this is column 2"") ContainerInsert a multi-element container.c = st.container() st.write(""This will show last"") c.write(""This will show first"") c.write(""This will show second"") Modal dialogsInsert a modal dialog that can rerun independently from the rest of the script.@st.experimental_dialog(""Sign up"") def email_form(): name = st.text_input(""Name"") email = st.text_input(""Email"") EmptyInsert a single-element container.c = st.empty() st.write(""This will show last"") c.write(""This will be replaced"") c.write(""This will show first"") ExpanderInsert a multi-element container that can be expanded/collapsed.with st.expander(""Open to see more""): st.write(""This is more content"") PopoverInsert a multi-element popover container that can be opened/closed.with st.popover(""Settings""): st.checkbox(""Show completed"") SidebarDisplay items in a sidebar.st.sidebar.write(""This lives in the sidebar"") st.sidebar.button(""Click me!"") TabsInsert containers separated into tabs.tab1, tab2 = st.tabs([""Tab 1"", ""Tab2""]) tab1.write(""this is tab 1"") tab2.write(""this is tab 2"") Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration!Streamlit ElementsCreate a draggable and resizable dashboard in Streamlit. Created by @okls.from streamlit_elements import elements, mui, html with elements(""new_element""): mui.Typography(""Hello world"") PydanticAuto-generate Streamlit UI from Pydantic Models and Dataclasses. Created by @lukasmasuch.import streamlit_pydantic as sp sp.pydantic_form(key=""my_form"", model=ExampleModel) Streamlit PagesAn experimental version of Streamlit Multi-Page Apps. Created by @blackary.from st_pages import Page, show_pages, add_page_title show_pages([ Page(""streamlit_app.py"", ""Home"", ""🏠""), Page(""other_pages/page2.py"", ""Page 2"", "":books:""), ]) Chat elements Streamlit provides a few commands to help you build conversational apps. These chat elements are designed to be used in conjunction with each other, but you can also use them separately. st.chat_message lets you insert a chat message container into the app so you can display messages from the user or the app. Chat containers can contain other Streamlit elements, including charts, tables, text, and more. st.chat_input lets you display a chat input widget so the user can type in a message. Chat inputDisplay a chat input widget.prompt = st.chat_input(""Say something"") if prompt: st.write(f""The user has sent: {prompt}"") Chat messageInsert a chat message container.import numpy as np with st.chat_message(""user""): st.write(""Hello 👋"") st.line_chart(np.random.randn(30, 3)) Status containerDisplay output of long-running tasks in a container.with st.status('Running'): do_something_slow() st.write_streamWrite generators or streams to the app with a typewriter effect.st.write_stream(my_generator) st.write_stream(my_llm_stream) Status elements Progress barDisplay a progress bar.for i in range(101): st.progress(i) do_something_slow() SpinnerTemporarily displays a message while executing a block of code.with st.spinner(""Please wait...""): do_something_slow() Status containerDisplay output of long-running tasks in a container.with st.status('Running'): do_something_slow() ToastBriefly displays a toast message in the bottom-right corner.st.toast('Butter!', icon='🧈') BalloonsDisplay celebratory balloons!do_something() # Celebrate when all done! st.balloons() SnowflakesDisplay celebratory snowflakes!do_something() # Celebrate when all done! st.snow() Success boxDisplay a success message.st.success(""Match found!"") Info boxDisplay an informational message.st.info(""Dataset is updated every day at midnight."") Warning boxDisplay warning message.st.warning(""Unable to fetch image. Skipping..."") Error boxDisplay error message.st.error(""We encountered an error"") Exception outputDisplay an exception.e = RuntimeError(""This is an exception of type RuntimeError"") st.exception(e) Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration!StqdmThe simplest way to handle a progress bar in streamlit app. Created by @Wirg.from stqdm import stqdm for _ in stqdm(range(50)): sleep(0.5) Custom notification boxA custom notification box with the ability to close it out. Created by @Socvest.from streamlit_custom_notification_box import custom_notification_box styles = {'material-icons':{'color': 'red'}, 'text-icon-link-close-container': {'box-shadow': '#3896de 0px 4px'}, 'notification-text': {'':''}, 'close-button':{'':''}, 'link':{'':''}} custom_notification_box(icon='info', textDisplay='We are almost done with your registration...', externalLink='more info', url='#', styles=styles, key=""foo"") Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.let_it_rain import rain rain(emoji=""🎈"", font_size=54, falling_speed=5, animation_length=""infinite"",) App logic and configuration Navigation and pages Switch pageProgrammatically navigates to a specified page.st.switch_page(""pages/my_page.py"") Page linkDisplay a link to another page in a multipage app.st.page_link(""app.py"", label=""Home"", icon=""🏠"") st.page_link(""pages/profile.py"", label=""My profile"") Execution flow Modal dialogsInsert a modal dialog that can rerun independently from the rest of the script.@st.experimental_dialog(""Sign up"") def email_form(): name = st.text_input(""Name"") email = st.text_input(""Email"") FormsCreate a form that batches elements together with a “Submit"" button.with st.form(key='my_form'): name = st.text_input(""Name"") email = st.text_input(""Email"") st.form_submit_button(""Sign up"") Partial rerunsDefine a fragment to rerun independently from the rest of the script.@st.experimental_fragment(run_every=""10s"") def fragment(): df = get_data() st.line_chart(df) Rerun scriptRerun the script immediately.st.rerun() Stop executionStops execution immediately.st.stop() Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration!AutorefreshForce a refresh without tying up a script. Created by @kmcgrady.from streamlit_autorefresh import st_autorefresh st_autorefresh(interval=2000, limit=100, key=""fizzbuzzcounter"") PydanticAuto-generate Streamlit UI from Pydantic Models and Dataclasses. Created by @lukasmasuch.import streamlit_pydantic as sp sp.pydantic_form(key=""my_form"", model=ExampleModel) Streamlit PagesAn experimental version of Streamlit Multi-Page Apps. Created by @blackary.from st_pages import Page, show_pages, add_page_title show_pages([ Page(""streamlit_app.py"", ""Home"", ""🏠""), Page(""other_pages/page2.py"", ""Page 2"", "":books:""), ]) Caching and state Cache dataFunction decorator to cache functions that return data (e.g. dataframe transforms, database queries, ML inference).@st.cache_data def long_function(param1, param2): # Perform expensive computation here or # fetch data from the web here return data Cache resourceFunction decorator to cache functions that return global resources (e.g. database connections, ML models).@st.cache_resource def init_model(): # Return a global resource here return pipeline( ""sentiment-analysis"", model=""distilbert-base-uncased-finetuned-sst-2-english"" ) Session stateSession state is a way to share variables between reruns, for each user session.st.session_state['key'] = value Query parametersGet, set, or clear the query parameters that are shown in the browser's URL bar.st.query_params[key] = value st.query_params.clear() Connections and databases Setup your connection Create a connectionConnect to a data source or APIconn = st.connection('pets_db', type='sql') pet_owners = conn.query('select * from pet_owners') st.dataframe(pet_owners) Built-in connections SnowflakeConnectionA connection to Snowflake.conn = st.connection('snowflake') SQLConnectionA connection to a SQL database using SQLAlchemy.conn = st.connection('sql') Build your own connections Connection base classBuild your own connection with BaseConnection.class MyConnection(BaseConnection[myconn.MyConnection]): def _connect(self, **kwargs) -> MyConnection: return myconn.connect(**self._secrets, **kwargs) def query(self, query): return self._instance.query(query) Secrets management Secrets singletonAccess secrets from a local TOML file.key = st.secrets[""OpenAI_key""] Secrets fileSave your secrets in a per-project or per-profile TOML file.OpenAI_key = """" Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration!AuthenticatorA secure authentication module to validate user credentials. Created by @mkhorasani.import streamlit_authenticator as stauth authenticator = stauth.Authenticate( config['credentials'], config['cookie']['name'], config['cookie']['key'], config['cookie']['expiry_days'], config['preauthorized']) WS localStorageA simple synchronous way of accessing localStorage from your app. Created by @gagangoku.from streamlit_ws_localstorage import injectWebsocketCode ret = conn.setLocalStorageVal(key='k1', val='v1') st.write('ret: ' + ret) Streamlit Auth0The fastest way to provide comprehensive login inside Streamlit. Created by @conradbez.from auth0_component import login_button user_info = login_button(clientId, domain = domain) st.write(user_info) Custom Components Declare a componentCreate and register a custom component.st.components.v1.declare_component( ""custom_slider"", ""/frontend"", ) HTMLDisplay an HTML string in an iframe.st.components.v1.html( ""

Foo bar.

"" ) iframeLoad a remote URL in an iframe.st.components.v1.iframe( ""docs.streamlit.io"" ) Utilities and user info User infost.experimental_user returns information about the logged-in user of private apps on Streamlit Community Cloud.if st.experimental_user.email == ""foo@corp.com"": st.write(""Welcome back, "", st.experimental_user.email) else: st.write(""You are not authorized to view this page."") Get helpDisplay object’s doc string, nicely formatted.st.help(st.write) st.help(pd.DataFrame) Render HTMLRenders HTML strings to your app.css = """""" """""" st.html(css) Configuration Configuration fileConfigures the default settings for your app.your-project/ ├── .streamlit/ │ └── config.toml └── your_app.py Set page title, favicon, and moreConfigures the default settings of the page.st.set_page_config( page_title=""My app"", page_icon="":shark:"", ) Developer tools App testing st.testing.v1.AppTestst.testing.v1.AppTest simulates a running Streamlit app for testing.from streamlit.testing.v1 import AppTest at = AppTest.from_file(""streamlit_app.py"") at.secrets[""WORD""] = ""Foobar"" at.run() assert not at.exception at.text_input(""word"").input(""Bazbat"").run() assert at.warning[0].value == ""Try again."" AppTest.from_filest.testing.v1.AppTest.from_file initializes a simulated app from a file.from streamlit.testing.v1 import AppTest at = AppTest.from_file(""streamlit_app.py"") at.run() AppTest.from_stringst.testing.v1.AppTest.from_string initializes a simulated app from a string.from streamlit.testing.v1 import AppTest at = AppTest.from_string(app_script_as_string) at.run() AppTest.from_functionst.testing.v1.AppTest.from_function initializes a simulated app from a function.from streamlit.testing.v1 import AppTest at = AppTest.from_function(app_script_as_callable) at.run() BlockA representation of container elements, including: st.chat_message st.columns st.sidebar st.tabs The main body of the app. # at.sidebar returns a Block at.sidebar.button[0].click().run() assert not at.exception ElementThe base class for representation of all elements, including: st.title st.header st.markdown st.dataframe # at.title returns a sequence of Title # Title inherits from Element assert at.title[0].value == ""My awesome app"" ButtonA representation of st.button and st.form_submit_button.at.button[0].click().run() ChatInputA representation of st.chat_input.at.chat_input[0].set_value(""What is Streamlit?"").run() CheckboxA representation of st.checkbox.at.checkbox[0].check().run() ColorPickerA representation of st.color_picker.at.color_picker[0].pick(""#FF4B4B"").run() DateInputA representation of st.date_input.release_date = datetime.date(2023, 10, 26) at.date_input[0].set_value(release_date).run() MultiselectA representation of st.multiselect.at.multiselect[0].select(""New York"").run() NumberInputA representation of st.number_input.at.number_input[0].increment().run() RadioA representation of st.radio.at.radio[0].set_value(""New York"").run() SelectSliderA representation of st.select_slider.at.select_slider[0].set_range(""A"",""C"").run() SelectboxA representation of st.selectbox.at.selectbox[0].select(""New York"").run() SliderA representation of st.slider.at.slider[0].set_range(2,5).run() TextAreaA representation of st.text_area.at.text_area[0].input(""Streamlit is awesome!"").run() TextInputA representation of st.text_input.at.text_input[0].input(""Streamlit"").run() TimeInputA representation of st.time_input.at.time_input[0].increment().run() ToggleA representation of st.toggle.at.toggle[0].set_value(""True"").run() Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration!Pandas ProfilingPandas profiling component for Streamlit. Created by @okld.df = pd.read_csv(""https://storage.googleapis.com/tf-datasets/titanic/train.csv"") pr = df.profile_report() st_profile_report(pr) Streamlit AceAce editor component for Streamlit. Created by @okld.from streamlit_ace import st_ace content = st_ace() content Streamlit AnalyticsTrack & visualize user interactions with your streamlit app. Created by @jrieke.import streamlit_analytics with streamlit_analytics.track(): st.text_input(""Write something"") Previous: ConceptsNext: Write and magicforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy" https://docs.streamlit.io/get-started/fundamentals/advanced-concepts#examples-of-using-session-state,"DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsremoveBasic conceptsAdvanced conceptsAdditional featuresSummaryFirst stepsaddcodeDevelopConceptsaddAPI referenceaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Get started/Fundamentals/Advanced conceptsAdvanced concepts of Streamlit Now that you know how a Streamlit app runs and handles data, let's talk about being efficient. Caching allows you to save the output of a function so you can skip over it on rerun. Session State lets you save information for each user that is preserved between reruns. This not only allows you to avoid unecessary recalculation, but also allows you to create dynamic pages and handle progressive processes. Caching Caching allows your app to stay performant even when loading data from the web, manipulating large datasets, or performing expensive computations. The basic idea behind caching is to store the results of expensive function calls and return the cached result when the same inputs occur again. This avoids repeated execution of a function with the same input values. To cache a function in Streamlit, you need to apply a caching decorator to it. You have two choices: st.cache_data is the recommended way to cache computations that return data. Use st.cache_data when you use a function that returns a serializable data object (e.g. str, int, float, DataFrame, dict, list). It creates a new copy of the data at each function call, making it safe against mutations and race conditions. The behavior of st.cache_data is what you want in most cases – so if you're unsure, start with st.cache_data and see if it works! st.cache_resource is the recommended way to cache global resources like ML models or database connections. Use st.cache_resource when your function returns unserializable objects that you don’t want to load multiple times. It returns the cached object itself, which is shared across all reruns and sessions without copying or duplication. If you mutate an object that is cached using st.cache_resource, that mutation will exist across all reruns and sessions. Example: @st.cache_data def long_running_function(param1, param2): return … In the above example, long_running_function is decorated with @st.cache_data. As a result, Streamlit notes the following: The name of the function (""long_running_function""). The value of the inputs (param1, param2). The code within the function. Before running the code within long_running_function, Streamlit checks its cache for a previously saved result. If it finds a cached result for the given function and input values, it will return that cached result and not rerun function's code. Otherwise, Streamlit executes the function, saves the result in its cache, and proceeds with the script run. During development, the cache updates automatically as the function code changes, ensuring that the latest changes are reflected in the cache. Streamlit's two caching decorators and their use cases. For more information about the Streamlit caching decorators, their configuration parameters, and their limitations, see Caching. Session State Session State provides a dictionary-like interface where you can save information that is preserved between script reruns. Use st.session_state with key or attribute notation to store and recall values. For example, st.session_state[""my_key""] or st.session_state.my_key. Remember that widgets handle their statefulness all by themselves, so you won't always need to use Session State! What is a session? A session is a single instance of viewing an app. If you view an app from two different tabs in your browser, each tab will have its own session. So each viewer of an app will have a Session State tied to their specific view. Streamlit maintains this session as the user interacts with the app. If the user refreshes their browser page or reloads the URL to the app, their Session State resets and they begin again with a new session. Examples of using Session State Here's a simple app that counts the number of times the page has been run. Every time you click the button, the script will rerun. import streamlit as st if ""counter"" not in st.session_state: st.session_state.counter = 0 st.session_state.counter += 1 st.header(f""This page has run {st.session_state.counter} times."") st.button(""Run it again"") First run: The first time the app runs for each user, Session State is empty. Therefore, a key-value pair is created (""counter"":0). As the script continues, the counter is immediately incremented (""counter"":1) and the result is displayed: ""This page has run 1 times."" When the page has fully rendered, the script has finished and the Streamlit server waits for the user to do something. When that user clicks the button, a rerun begins. Second run: Since ""counter"" is already a key in Session State, it is not reinitialized. As the script continues, the counter is incremented (""counter"":2) and the result is displayed: ""This page has run 2 times."" There are a few common scenarios where Session State is helpful. As demonstrated above, Session State is used when you have a progressive process that you want to build upon from one rerun to the next. Session State can also be used to prevent recalculation, similar to caching. However, the differences are important: Caching associates stored values to specific functions and inputs. Cached values are accessible to all users across all sessions. Session State associates stored values to keys (strings). Values in session state are only available in the single session where it was saved. If you have random number generation in your app, you'd likely use Session State. Here's an example where data is generated randomly at the beginning of each session. By saving this random information in Session State, each user gets different random data when they open the app but it won't keep changing on them as they interact with it. If you select different colors with the picker you'll see that the data does not get re-randomized with each rerun. (If you open the app in a new tab to start a new session, you'll see different data!) import streamlit as st import pandas as pd import numpy as np if ""df"" not in st.session_state: st.session_state.df = pd.DataFrame(np.random.randn(20, 2), columns=[""x"", ""y""]) st.header(""Choose a datapoint color"") color = st.color_picker(""Color"", ""#FF0000"") st.divider() st.scatter_chart(st.session_state.df, x=""x"", y=""y"", color=color) If you are pulling the same data for all users, you'd likely cache a function that retrieves that data. On the other hand, if you pull data specific to a user, such as querying their personal information, you may want to save that in Session State. That way, the queried data is only available in that one session. As mentioned in Basic concepts, Session State is also related to widgets. Widgets are magical and handle statefulness quietly on their own. As an advanced feature however, you can manipulate the value of widgets within your code by assigning keys to them. Any key assigned to a widget becomes a key in Session State tied to the value of the widget. This can be used to manipulate the widget. After you finish understanding the basics of Streamlit, check out our guide on Widget behavior to dig in the details if you're interested. Connections As hinted above, you can use @st.cache_resource to cache connections. This is the most general solution which allows you to use almost any connection from any Python library. However, Streamlit also offers a convenient way to handle some of the most popular connections, like SQL! st.connection takes care of the caching for you so you can enjoy fewer lines of code. Getting data from your database can be as easy as: import streamlit as st conn = st.connection(""my_database"") df = conn.query(""select * from my_table"") st.dataframe(df) Of course, you may be wondering where your username and password go. Streamlit has a convenient mechanism for Secrets management. For now, let's just see how st.connection works very nicely with secrets. In your local project directory, you can save a .streamlit/secrets.toml file. You save your secrets in the toml file and st.connection just uses them! For example, if you have an app file streamlit_app.py your project directory may look like this: your-LOCAL-repository/ ├── .streamlit/ │ └── secrets.toml # Make sure to gitignore this! └── streamlit_app.py For the above SQL example, your secrets.toml file might look like the following: [connections.my_database] type=""sql"" dialect=""mysql"" username=""xxx"" password=""xxx"" host=""example.com"" # IP or URL port=3306 # Port number database=""mydb"" # Database name Since you don't want to commit your secrets.toml file to your repository, you'll need to learn how your host handles secrets when you're ready to publish your app. Each host platform may have a different way for you to pass your secrets. If you use Streamlit Community Cloud for example, each deployed app has a settings menu where you can load your secrets. After you've written an app and are ready to deploy, you can read all about how to Deploy your app on Community Cloud.Previous: Basic conceptsNext: Additional featuresforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy" https://docs.streamlit.io/develop/api-reference/widgets/st.multiselect#stmultiselect,"DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceremovePAGE ELEMENTSWrite and magicaddText elementsaddData elementsaddChart elementsaddInput widgetsremoveBUTTONSst.buttonst.download_buttonst.form_submit_buttonlinkst.link_buttonst.page_linkSELECTIONSst.checkboxst.color_pickerst.multiselectst.radiost.selectboxst.select_sliderst.toggleNUMERICst.number_inputst.sliderDATE & TIMEst.date_inputst.time_inputTEXTst.chat_inputlinkst.text_areast.text_inputMEDIA & FILESst.camera_inputst.data_editorlinkst.file_uploaderMedia elementsaddLayouts and containersaddChat elementsaddStatus elementsaddThird-party componentsopen_in_newAPPLICATION LOGICNavigation and pagesaddExecution flowaddCaching and stateaddConnections and secretsaddCustom componentsaddUtilitiesaddConfigurationaddTOOLSApp testingaddCommand lineaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Develop/API reference/Input widgets/st.multiselectst.multiselectStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeDisplay a multiselect widget. The multiselect widget starts as empty. Function signature[source] st.multiselect(label, options, default=None, format_func=special_internal_function, key=None, help=None, on_change=None, args=None, kwargs=None, *, max_selections=None, placeholder=""Choose an option"", disabled=False, label_visibility=""visible"") Parameters label (str) A short label explaining to the user what this select widget is for. The label can optionally contain Markdown and supports the following elements: Bold, Italics, Strikethroughs, Inline Code, Emojis, and Links. This also supports: Emoji shortcodes, such as :+1: and :sunglasses:. For a list of all supported codes, see https://share.streamlit.io/streamlit/emoji-shortcodes. LaTeX expressions, by wrapping them in ""$"" or ""$$"" (the ""$$"" must be on their own lines). Supported LaTeX functions are listed at https://katex.org/docs/supported.html. Colored text and background colors for text, using the syntax :color[text to be colored] and :color-background[text to be colored], respectively. color must be replaced with any of the following supported colors: blue, green, orange, red, violet, gray/grey, rainbow. For example, you can use :orange[your text here] or :blue-background[your text here]. Unsupported elements are unwrapped so only their children (text contents) render. Display unsupported elements as literal characters by backslash-escaping them. E.g. 1\. Not an ordered list. For accessibility reasons, you should never set an empty label (label="""") but hide it with label_visibility if needed. In the future, we may disallow empty labels by raising an exception. options (Iterable) Labels for the select options in an Iterable. For example, this can be a list, numpy.ndarray, pandas.Series, pandas.DataFrame, or pandas.Index. For pandas.DataFrame, the first column is used. Each label will be cast to str internally by default. default (Iterable of V, V, or None) List of default values. Can also be a single value. format_func (function) Function to modify the display of selectbox options. It receives the raw option as an argument and should output the label to be shown for that option. This has no impact on the return value of the multiselect. key (str or int) An optional string or integer to use as the unique key for the widget. If this is omitted, a key will be generated for the widget based on its content. Multiple widgets of the same type may not share the same key. help (str) An optional tooltip that gets displayed next to the multiselect. on_change (callable) An optional callback invoked when this multiselect's value changes. args (tuple) An optional tuple of args to pass to the callback. kwargs (dict) An optional dict of kwargs to pass to the callback. max_selections (int) The max selections that can be selected at a time. placeholder (str) A string to display when no options are selected. Defaults to 'Choose an option'. disabled (bool) An optional boolean, which disables the multiselect widget if set to True. The default is False. This argument can only be supplied by keyword. label_visibility (""visible"", ""hidden"", or ""collapsed"") The visibility of the label. If ""hidden"", the label doesn't show but there is still empty space for it above the widget (equivalent to label=""""). If ""collapsed"", both the label and the space are removed. Default is ""visible"". Returns(list) A list with the selected options Example import streamlit as st options = st.multiselect( ""What are your favorite colors"", [""Green"", ""Yellow"", ""Red"", ""Blue""], [""Yellow"", ""Red""]) st.write(""You selected:"", options) Built with Streamlit 🎈Fullscreen open_in_new Previous: st.color_pickerNext: st.radioforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy" https://docs.streamlit.io/develop/tutorials/databases/bigquery#create-a-bigquery-database,"DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceaddTutorialsremoveExecution flowaddConnect to data sourcesremoveAWS S3BigQueryDeta BaseFirestoreopen_in_newGoogle Cloud StorageMicrosoft SQL ServerMongoDBMySQLNeonPostgreSQLPrivate Google SheetPublic Google SheetSnowflakeSupabaseTableauTiDBTigerGraphMultipage appsaddWork with LLMsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Develop/Tutorials/Connect to data sources/BigQueryConnect Streamlit to Google BigQuery Introduction This guide explains how to securely access a BigQuery database from Streamlit Community Cloud. It uses the google-cloud-bigquery library and Streamlit's Secrets management. Create a BigQuery database push_pinNoteIf you already have a database that you want to use, feel free to skip to the next step. For this example, we will use one of the sample datasets from BigQuery (namely the shakespeare table). If you want to create a new dataset instead, follow Google's quickstart guide. Enable the BigQuery API Programmatic access to BigQuery is controlled through Google Cloud Platform. Create an account or sign in and head over to the APIs & Services dashboard (select or create a project if asked). As shown below, search for the BigQuery API and enable it: Create a service account & key file To use the BigQuery API from Streamlit Community Cloud, you need a Google Cloud Platform service account (a special account type for programmatic data access). Go to the Service Accounts page and create an account with the Viewer permission (this will let the account access data but not change it): push_pinNoteIf the button CREATE SERVICE ACCOUNT is gray, you don't have the correct permissions. Ask the admin of your Google Cloud project for help. After clicking DONE, you should be back on the service accounts overview. Create a JSON key file for the new account and download it: Add the key file to your local app secrets Your local Streamlit app will read secrets from a file .streamlit/secrets.toml in your app's root directory. Create this file if it doesn't exist yet and add the content of the key file you just downloaded to it as shown below: # .streamlit/secrets.toml [gcp_service_account] type = ""service_account"" project_id = ""xxx"" private_key_id = ""xxx"" private_key = ""xxx"" client_email = ""xxx"" client_id = ""xxx"" auth_uri = ""https://accounts.google.com/o/oauth2/auth"" token_uri = ""https://oauth2.googleapis.com/token"" auth_provider_x509_cert_url = ""https://www.googleapis.com/oauth2/v1/certs"" client_x509_cert_url = ""xxx"" priority_highImportantAdd this file to .gitignore and don't commit it to your GitHub repo! Copy your app secrets to the cloud As the secrets.toml file above is not committed to GitHub, you need to pass its content to your deployed app (on Streamlit Community Cloud) separately. Go to the app dashboard and in the app's dropdown menu, click on Edit Secrets. Copy the content of secrets.toml into the text area. More information is available at Secrets management. Add google-cloud-bigquery to your requirements file Add the google-cloud-bigquery package to your requirements.txt file, preferably pinning its version (replace x.x.x with the version want installed): # requirements.txt google-cloud-bigquery==x.x.x Write your Streamlit app Copy the code below to your Streamlit app and run it. Make sure to adapt the query if you don't use the sample table. # streamlit_app.py import streamlit as st from google.oauth2 import service_account from google.cloud import bigquery # Create API client. credentials = service_account.Credentials.from_service_account_info( st.secrets[""gcp_service_account""] ) client = bigquery.Client(credentials=credentials) # Perform query. # Uses st.cache_data to only rerun when the query changes or after 10 min. @st.cache_data(ttl=600) def run_query(query): query_job = client.query(query) rows_raw = query_job.result() # Convert to list of dicts. Required for st.cache_data to hash the return value. rows = [dict(row) for row in rows_raw] return rows rows = run_query(""SELECT word FROM `bigquery-public-data.samples.shakespeare` LIMIT 10"") # Print results. st.write(""Some wise words from Shakespeare:"") for row in rows: st.write(""✍️ "" + row['word']) See st.cache_data above? Without it, Streamlit would run the query every time the app reruns (e.g. on a widget interaction). With st.cache_data, it only runs when the query changes or after 10 minutes (that's what ttl is for). Watch out: If your database updates more frequently, you should adapt ttl or remove caching so viewers always see the latest data. Learn more in Caching. Alternatively, you can use pandas to read from BigQuery right into a dataframe! Follow all the above steps, install the pandas-gbq library (don't forget to add it to requirements.txt!), and call pandas.read_gbq(query, credentials=credentials). More info in the pandas docs. If everything worked out (and you used the sample table), your app should look like this: Previous: AWS S3Next: Deta BaseforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy" https://docs.streamlit.io/develop/api-reference/caching-and-state/st.query_params#stquery_paramsclear,"DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceremovePAGE ELEMENTSWrite and magicaddText elementsaddData elementsaddChart elementsaddInput widgetsaddMedia elementsaddLayouts and containersaddChat elementsaddStatus elementsaddThird-party componentsopen_in_newAPPLICATION LOGICNavigation and pagesaddExecution flowaddCaching and stateremovest.cache_datast.cache_resourcest.cachedeletest.session_statest.query_paramsst.experimental_get_query_paramsdeletest.experimental_set_query_paramsdeleteConnections and secretsaddCustom componentsaddUtilitiesaddConfigurationaddTOOLSApp testingaddCommand lineaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Develop/API reference/Caching and state/st.query_paramsst.query_params st.query_params provides a dictionary-like interface to access query parameters in your app's URL and is available as of Streamlit 1.30.0. It behaves similarly to st.session_state with the notable exception that keys may be repeated in an app's URL. Handling of repeated keys requires special consideration as explained below. st.query_params can be used with both key and attribute notation. For example, st.query_params.my_key and st.query_params[""my_key""]. All keys and values will be set and returned as strings. When you write to st.query_params, key-value pair prefixed with ? is added to the end of your app's URL. Each additional pair is prefixed with & instead of ?. Query parameters are cleared when navigating between pages in a multipage app. For example, consider the following URL: https://your_app.streamlit.app/?first_key=1&second_key=two&third_key=true The parameters in the URL above will be accessible in st.query_params as: { ""first_key"" : ""1"", ""second_key"" : ""two"", ""third_key"" : ""true"" } This means you can use those parameters in your app like this: # You can read query params using key notation if st.query_params[""first_key""] == ""1"": do_something() # ...or using attribute notation if st.query_params.second_key == ""two"": do_something_else() # And you can change a param by just writing to it st.query_params.first_key = 2 # This gets converted to str automatically Repeated keys When a key is repeated in your app's URL (?a=1&a=2&a=3), dict-like methods will return only the last value. In this example, st.query_params[""a""] returns ""3"". To get all keys as a list, use the .get_all() method shown below. To set the value of a repeated key, assign the values as a list. For example, st.query_params.a = [""1"", ""2"", ""3""] produces the repeated key given at the beginning of this paragraph. Limitation st.query_params can't get or set embedding settings as described in Embed your app. st.query_params.embed and st.query_params.embed_options will raise an AttributeError or StreamlitAPIException when trying to get or set their values, respectively. st.query_params.clearStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeClear all query parameters from the URL of the app. Function signature[source] st.query_params.clear() Returns(None) No description st.query_params.from_dictStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSet all of the query parameters from a dictionary or dictionary-like object. This method primarily exists for advanced users who want to control multiple query parameters in a single update. To set individual query parameters, use key or attribute notation instead. This method inherits limitations from st.query_params and can't be used to set embedding options as described in Embed your app. To handle repeated keys, the value in a key-value pair should be a list. Note .from_dict() is not a direct inverse of .to_dict() if you are working with repeated keys. A true inverse operation is {key: st.query_params.get_all(key) for key st.query_params}. Function signature[source] st.query_params.from_dict(params) Parameters params (dict) A dictionary used to replace the current query parameters. Example import streamlit as st st.query_params.from_dict({""foo"": ""bar"", ""baz"": [1, ""two""]}) st.query_params.get_allStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeGet a list of all query parameter values associated to a given key. When a key is repeated as a query parameter within the URL, this method allows all values to be obtained. In contrast, dict-like methods only retrieve the last value when a key is repeated in the URL. Function signature[source] st.query_params.get_all(key) Parameters key (str) The label of the query parameter in the URL. Returns(List[str]) A list of values associated to the given key. May return zero, one, or multiple values. st.query_params.to_dictStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeGet all query parameters as a dictionary. This method primarily exists for internal use and is not needed for most cases. st.query_params returns an object that inherits from dict by default. When a key is repeated as a query parameter within the URL, this method will return only the last value of each unique key. Function signature[source] st.query_params.to_dict() Returns(Dict[str,str]) A dictionary of the current query paramters in the app's URL. Previous: st.session_stateNext: st.experimental_get_query_paramsforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy" https://docs.streamlit.io/develop/api-reference/data,"DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceremovePAGE ELEMENTSWrite and magicaddText elementsaddData elementsremovest.dataframest.data_editorst.column_configaddst.tablest.metricst.jsonChart elementsaddInput widgetsaddMedia elementsaddLayouts and containersaddChat elementsaddStatus elementsaddThird-party componentsopen_in_newAPPLICATION LOGICNavigation and pagesaddExecution flowaddCaching and stateaddConnections and secretsaddCustom componentsaddUtilitiesaddConfigurationaddTOOLSApp testingaddCommand lineaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Develop/API reference/Data elementsData elements When you're working with data, it is extremely valuable to visualize that data quickly, interactively, and from multiple different angles. That's what Streamlit is actually built and optimized for. You can display data via charts, and you can display it in raw form. These are the Streamlit commands you can use to display and interact with raw data. DataframesDisplay a dataframe as an interactive table.st.dataframe(my_data_frame) Data editorDisplay a data editor widget.edited = st.data_editor(df, num_rows=""dynamic"") Column configurationConfigure the display and editing behavior of dataframes and data editors.st.column_config.NumberColumn(""Price (in USD)"", min_value=0, format=""$%d"") Static tablesDisplay a static table.st.table(my_data_frame) MetricsDisplay a metric in big bold font, with an optional indicator of how the metric changed.st.metric(""My metric"", 42, 2) Dicts and JSONDisplay object or string as a pretty-printed JSON string.st.json(my_dict) Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration! PreviousImage CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates value = streamlit_image_coordinates(""https://placekitten.com/200/300"") st.write(value) Plotly EventsMake Plotly charts interactive!. Created by @null-jones.from streamlit_plotly_events import plotly_events fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.metric_cards import style_metric_cards col3.metric(label=""No Change"", value=5000, delta=0) style_metric_cards() Streamlit AggridImplementation of Ag-Grid component for Streamlit. Created by @PablocFonseca.df = pd.DataFrame({'col1': [1, 2, 3], 'col2': [4, 5, 6]}) grid_return = AgGrid(df, editable=True) new_df = grid_return['data'] Streamlit FoliumStreamlit Component for rendering Folium maps. Created by @randyzwitch.m = folium.Map(location=[39.949610, -75.150282], zoom_start=16) folium.Marker([39.949610, -75.150282], popup=""Liberty Bell"", tooltip=""Liberty Bell"").add_to(m) st_data = st_folium(m, width=725) Pandas ProfilingPandas profiling component for Streamlit. Created by @okld.df = pd.read_csv(""https://storage.googleapis.com/tf-datasets/titanic/train.csv"") pr = df.profile_report() st_profile_report(pr) Image CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates value = streamlit_image_coordinates(""https://placekitten.com/200/300"") st.write(value) Plotly EventsMake Plotly charts interactive!. Created by @null-jones.from streamlit_plotly_events import plotly_events fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.metric_cards import style_metric_cards col3.metric(label=""No Change"", value=5000, delta=0) style_metric_cards() Streamlit AggridImplementation of Ag-Grid component for Streamlit. Created by @PablocFonseca.df = pd.DataFrame({'col1': [1, 2, 3], 'col2': [4, 5, 6]}) grid_return = AgGrid(df, editable=True) new_df = grid_return['data'] Streamlit FoliumStreamlit Component for rendering Folium maps. Created by @randyzwitch.m = folium.Map(location=[39.949610, -75.150282], zoom_start=16) folium.Marker([39.949610, -75.150282], popup=""Liberty Bell"", tooltip=""Liberty Bell"").add_to(m) st_data = st_folium(m, width=725) Pandas ProfilingPandas profiling component for Streamlit. Created by @okld.df = pd.read_csv(""https://storage.googleapis.com/tf-datasets/titanic/train.csv"") pr = df.profile_report() st_profile_report(pr) Image CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates value = streamlit_image_coordinates(""https://placekitten.com/200/300"") st.write(value) Plotly EventsMake Plotly charts interactive!. Created by @null-jones.from streamlit_plotly_events import plotly_events fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.metric_cards import style_metric_cards col3.metric(label=""No Change"", value=5000, delta=0) style_metric_cards() NextPrevious: Text elementsNext: st.dataframeforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy" https://docs.streamlit.io/develop/api-reference#chat-elements,"DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceremovePAGE ELEMENTSWrite and magicaddText elementsaddData elementsaddChart elementsaddInput widgetsaddMedia elementsaddLayouts and containersaddChat elementsaddStatus elementsaddThird-party componentsopen_in_newAPPLICATION LOGICNavigation and pagesaddExecution flowaddCaching and stateaddConnections and secretsaddCustom componentsaddUtilitiesaddConfigurationaddTOOLSApp testingaddCommand lineaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Develop/API referenceAPI reference Streamlit makes it easy for you to visualize, mutate, and share data. The API reference is organized by activity type, like displaying data or optimizing performance. Each section includes methods associated with the activity type, including examples. Browse our API below and click to learn more about any of our available commands! 🎈 Display almost anything Write and magic st.writeWrite arguments to the app.st.write(""Hello **world**!"") st.write(my_data_frame) st.write(my_mpl_figure) st.write_streamWrite generators or streams to the app with a typewriter effect.st.write_stream(my_generator) st.write_stream(my_llm_stream) MagicAny time Streamlit sees either a variable or literal value on its own line, it automatically writes that to your app using st.write""Hello **world**!"" my_data_frame my_mpl_figure Text elements MarkdownDisplay string formatted as Markdown.st.markdown(""Hello **world**!"") TitleDisplay text in title formatting.st.title(""The app title"") HeaderDisplay text in header formatting.st.header(""This is a header"") SubheaderDisplay text in subheader formatting.st.subheader(""This is a subheader"") CaptionDisplay text in small font.st.caption(""This is written small caption text"") Code blockDisplay a code block with optional syntax highlighting.st.code(""a = 1234"") EchoDisplay some code in the app, then execute it. Useful for tutorials.with st.echo(): st.write('This code will be printed') LaTeXDisplay mathematical expressions formatted as LaTeX.st.latex(""\int a x^2 \,dx"") Preformatted textWrite fixed-width and preformatted text.st.text(""Hello world"") DividerDisplay a horizontal rule.st.divider() Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration! PreviousTagsAdd tags to your Streamlit apps. Created by @gagan3012.st_tags(label='# Enter Keywords:', text='Press enter to add more', value=['Zero', 'One', 'Two'], suggestions=['five', 'six', 'seven', 'eight', 'nine', 'three', 'eleven', 'ten', 'four'], maxtags = 4, key='1') NLUApply text mining on a dataframe. Created by @JohnSnowLabs.nlu.load('sentiment').predict('I love NLU! <3') Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.mention(label=""An awesome Streamlit App"", icon=""streamlit"", url=""https://extras.streamlit.app"",) Annotated textDisplay annotated text in Streamlit apps. Created by @tvst.annotated_text(""This "", (""is"", ""verb""), "" some "", (""annotated"", ""adj""), (""text"", ""noun""), "" for those of "", (""you"", ""pronoun""), "" who "", (""like"", ""verb""), "" this sort of "", (""thing"", ""noun""), ""."") Drawable CanvasProvides a sketching canvas using Fabric.js. Created by @andfanilo.st_canvas(fill_color=""rgba(255, 165, 0, 0.3)"", stroke_width=stroke_width, stroke_color=stroke_color, background_color=bg_color, background_image=Image.open(bg_image) if bg_image else None, update_streamlit=realtime_update, height=150, drawing_mode=drawing_mode, point_display_radius=point_display_radius if drawing_mode == 'point' else 0, key=""canvas"",) TagsAdd tags to your Streamlit apps. Created by @gagan3012.st_tags(label='# Enter Keywords:', text='Press enter to add more', value=['Zero', 'One', 'Two'], suggestions=['five', 'six', 'seven', 'eight', 'nine', 'three', 'eleven', 'ten', 'four'], maxtags = 4, key='1') NLUApply text mining on a dataframe. Created by @JohnSnowLabs.nlu.load('sentiment').predict('I love NLU! <3') Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.mention(label=""An awesome Streamlit App"", icon=""streamlit"", url=""https://extras.streamlit.app"",) Annotated textDisplay annotated text in Streamlit apps. Created by @tvst.annotated_text(""This "", (""is"", ""verb""), "" some "", (""annotated"", ""adj""), (""text"", ""noun""), "" for those of "", (""you"", ""pronoun""), "" who "", (""like"", ""verb""), "" this sort of "", (""thing"", ""noun""), ""."") Drawable CanvasProvides a sketching canvas using Fabric.js. Created by @andfanilo.st_canvas(fill_color=""rgba(255, 165, 0, 0.3)"", stroke_width=stroke_width, stroke_color=stroke_color, background_color=bg_color, background_image=Image.open(bg_image) if bg_image else None, update_streamlit=realtime_update, height=150, drawing_mode=drawing_mode, point_display_radius=point_display_radius if drawing_mode == 'point' else 0, key=""canvas"",) TagsAdd tags to your Streamlit apps. Created by @gagan3012.st_tags(label='# Enter Keywords:', text='Press enter to add more', value=['Zero', 'One', 'Two'], suggestions=['five', 'six', 'seven', 'eight', 'nine', 'three', 'eleven', 'ten', 'four'], maxtags = 4, key='1') NLUApply text mining on a dataframe. Created by @JohnSnowLabs.nlu.load('sentiment').predict('I love NLU! <3') Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.mention(label=""An awesome Streamlit App"", icon=""streamlit"", url=""https://extras.streamlit.app"",) Next Data elements DataframesDisplay a dataframe as an interactive table.st.dataframe(my_data_frame) Data editorDisplay a data editor widget.edited = st.data_editor(df, num_rows=""dynamic"") Column configurationConfigure the display and editing behavior of dataframes and data editors.st.column_config.NumberColumn(""Price (in USD)"", min_value=0, format=""$%d"") Static tablesDisplay a static table.st.table(my_data_frame) MetricsDisplay a metric in big bold font, with an optional indicator of how the metric changed.st.metric(""My metric"", 42, 2) Dicts and JSONDisplay object or string as a pretty-printed JSON string.st.json(my_dict) Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration! PreviousImage CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates value = streamlit_image_coordinates(""https://placekitten.com/200/300"") st.write(value) Plotly EventsMake Plotly charts interactive!. Created by @null-jones.from streamlit_plotly_events import plotly_events fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.metric_cards import style_metric_cards col3.metric(label=""No Change"", value=5000, delta=0) style_metric_cards() Streamlit AggridImplementation of Ag-Grid component for Streamlit. Created by @PablocFonseca.df = pd.DataFrame({'col1': [1, 2, 3], 'col2': [4, 5, 6]}) grid_return = AgGrid(df, editable=True) new_df = grid_return['data'] Streamlit FoliumStreamlit Component for rendering Folium maps. Created by @randyzwitch.m = folium.Map(location=[39.949610, -75.150282], zoom_start=16) folium.Marker([39.949610, -75.150282], popup=""Liberty Bell"", tooltip=""Liberty Bell"").add_to(m) st_data = st_folium(m, width=725) Pandas ProfilingPandas profiling component for Streamlit. Created by @okld.df = pd.read_csv(""https://storage.googleapis.com/tf-datasets/titanic/train.csv"") pr = df.profile_report() st_profile_report(pr) Image CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates value = streamlit_image_coordinates(""https://placekitten.com/200/300"") st.write(value) Plotly EventsMake Plotly charts interactive!. Created by @null-jones.from streamlit_plotly_events import plotly_events fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.metric_cards import style_metric_cards col3.metric(label=""No Change"", value=5000, delta=0) style_metric_cards() Streamlit AggridImplementation of Ag-Grid component for Streamlit. Created by @PablocFonseca.df = pd.DataFrame({'col1': [1, 2, 3], 'col2': [4, 5, 6]}) grid_return = AgGrid(df, editable=True) new_df = grid_return['data'] Streamlit FoliumStreamlit Component for rendering Folium maps. Created by @randyzwitch.m = folium.Map(location=[39.949610, -75.150282], zoom_start=16) folium.Marker([39.949610, -75.150282], popup=""Liberty Bell"", tooltip=""Liberty Bell"").add_to(m) st_data = st_folium(m, width=725) Pandas ProfilingPandas profiling component for Streamlit. Created by @okld.df = pd.read_csv(""https://storage.googleapis.com/tf-datasets/titanic/train.csv"") pr = df.profile_report() st_profile_report(pr) Image CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates value = streamlit_image_coordinates(""https://placekitten.com/200/300"") st.write(value) Plotly EventsMake Plotly charts interactive!. Created by @null-jones.from streamlit_plotly_events import plotly_events fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.metric_cards import style_metric_cards col3.metric(label=""No Change"", value=5000, delta=0) style_metric_cards() Next Chart elements Simple area chartsDisplay an area chart.st.area_chart(my_data_frame) Simple bar chartsDisplay a bar chart.st.bar_chart(my_data_frame) Simple line chartsDisplay a line chart.st.line_chart(my_data_frame) Simple scatter chartsDisplay a line chart.st.scatter_chart(my_data_frame) Scatterplots on mapsDisplay a map with points on it.st.map(my_data_frame) MatplotlibDisplay a matplotlib.pyplot figure.st.pyplot(my_mpl_figure) AltairDisplay a chart using the Altair library.st.altair_chart(my_altair_chart) Vega-LiteDisplay a chart using the Vega-Lite library.st.vega_lite_chart(my_vega_lite_chart) PlotlyDisplay an interactive Plotly chart.st.plotly_chart(my_plotly_chart) BokehDisplay an interactive Bokeh chart.st.bokeh_chart(my_bokeh_chart) PyDeckDisplay a chart using the PyDeck library.st.pydeck_chart(my_pydeck_chart) GraphVizDisplay a graph using the dagre-d3 library.st.graphviz_chart(my_graphviz_spec) Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration! PreviousStreamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl(""https://assets5.lottiefiles.com/packages/lf20_V9t630.json"") st_lottie(lottie_hello, key=""hello"") Plotly EventsMake Plotly charts interactive!. Created by @null-jones.fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.chart += get_annotations_chart(annotations=[(""Mar 01, 2008"", ""Pretty good day for GOOG""), (""Dec 01, 2007"", ""Something's going wrong for GOOG & AAPL""), (""Nov 01, 2008"", ""Market starts again thanks to...""), (""Dec 01, 2009"", ""Small crash for GOOG after...""),],) st.altair_chart(chart, use_container_width=True) PlostA deceptively simple plotting library for Streamlit. Created by @tvst.import plost plost.line_chart(my_dataframe, x='time', y='stock_value', color='stock_name',) HiPlotHigh dimensional Interactive Plotting. Created by @facebookresearch.data = [{'dropout':0.1, 'lr': 0.001, 'loss': 10.0, 'optimizer': 'SGD'}, {'dropout':0.15, 'lr': 0.01, 'loss': 3.5, 'optimizer': 'Adam'}, {'dropout':0.3, 'lr': 0.1, 'loss': 4.5, 'optimizer': 'Adam'}] hip.Experiment.from_iterable(data).display() EChartsHigh dimensional Interactive Plotting. Created by @andfanilo.from streamlit_echarts import st_echarts st_echarts(options=options) Streamlit FoliumStreamlit Component for rendering Folium maps. Created by @randyzwitch.m = folium.Map(location=[39.949610, -75.150282], zoom_start=16) st_data = st_folium(m, width=725) Spacy-StreamlitspaCy building blocks and visualizers for Streamlit apps. Created by @explosion.models = [""en_core_web_sm"", ""en_core_web_md""] spacy_streamlit.visualize(models, ""Sundar Pichai is the CEO of Google."") Streamlit AgraphA Streamlit Graph Vis, based on react-grah-vis. Created by @ChrisDelClea.from streamlit_agraph import agraph, Node, Edge, Config agraph(nodes=nodes, edges=edges, config=config) Streamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl(""https://assets5.lottiefiles.com/packages/lf20_V9t630.json"") st_lottie(lottie_hello, key=""hello"") Plotly EventsMake Plotly charts interactive!. Created by @null-jones.fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.chart += get_annotations_chart(annotations=[(""Mar 01, 2008"", ""Pretty good day for GOOG""), (""Dec 01, 2007"", ""Something's going wrong for GOOG & AAPL""), (""Nov 01, 2008"", ""Market starts again thanks to...""), (""Dec 01, 2009"", ""Small crash for GOOG after...""),],) st.altair_chart(chart, use_container_width=True) PlostA deceptively simple plotting library for Streamlit. Created by @tvst.import plost plost.line_chart(my_dataframe, x='time', y='stock_value', color='stock_name',) HiPlotHigh dimensional Interactive Plotting. Created by @facebookresearch.data = [{'dropout':0.1, 'lr': 0.001, 'loss': 10.0, 'optimizer': 'SGD'}, {'dropout':0.15, 'lr': 0.01, 'loss': 3.5, 'optimizer': 'Adam'}, {'dropout':0.3, 'lr': 0.1, 'loss': 4.5, 'optimizer': 'Adam'}] hip.Experiment.from_iterable(data).display() EChartsHigh dimensional Interactive Plotting. Created by @andfanilo.from streamlit_echarts import st_echarts st_echarts(options=options) Streamlit FoliumStreamlit Component for rendering Folium maps. Created by @randyzwitch.m = folium.Map(location=[39.949610, -75.150282], zoom_start=16) st_data = st_folium(m, width=725) Spacy-StreamlitspaCy building blocks and visualizers for Streamlit apps. Created by @explosion.models = [""en_core_web_sm"", ""en_core_web_md""] spacy_streamlit.visualize(models, ""Sundar Pichai is the CEO of Google."") Streamlit AgraphA Streamlit Graph Vis, based on react-grah-vis. Created by @ChrisDelClea.from streamlit_agraph import agraph, Node, Edge, Config agraph(nodes=nodes, edges=edges, config=config) Streamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl(""https://assets5.lottiefiles.com/packages/lf20_V9t630.json"") st_lottie(lottie_hello, key=""hello"") Plotly EventsMake Plotly charts interactive!. Created by @null-jones.fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.chart += get_annotations_chart(annotations=[(""Mar 01, 2008"", ""Pretty good day for GOOG""), (""Dec 01, 2007"", ""Something's going wrong for GOOG & AAPL""), (""Nov 01, 2008"", ""Market starts again thanks to...""), (""Dec 01, 2009"", ""Small crash for GOOG after...""),],) st.altair_chart(chart, use_container_width=True) Next Input widgets ButtonDisplay a button widget.clicked = st.button(""Click me"") Download buttonDisplay a download button widget.st.download_button(""Download file"", file) Form buttonDisplay a form submit button. For use with st.form.st.form_submit_button(""Sign up"") Link buttonDisplay a link button.st.link_button(""Go to gallery"", url) Page linkDisplay a link to another page in a multipage app.st.page_link(""app.py"", label=""Home"", icon=""🏠"") st.page_link(""pages/profile.py"", label=""My profile"") CheckboxDisplay a checkbox widget.selected = st.checkbox(""I agree"") Color pickerDisplay a color picker widget.color = st.color_picker(""Pick a color"") MultiselectDisplay a multiselect widget. The multiselect widget starts as empty.choices = st.multiselect(""Buy"", [""milk"", ""apples"", ""potatoes""]) RadioDisplay a radio button widget.choice = st.radio(""Pick one"", [""cats"", ""dogs""]) SelectboxDisplay a select widget.choice = st.selectbox(""Pick one"", [""cats"", ""dogs""]) Select-sliderDisplay a slider widget to select items from a list.size = st.select_slider(""Pick a size"", [""S"", ""M"", ""L""]) ToggleDisplay a toggle widget.activated = st.toggle(""Activate"") Number inputDisplay a numeric input widget.choice = st.number_input(""Pick a number"", 0, 10) SliderDisplay a slider widget.number = st.slider(""Pick a number"", 0, 100) Date inputDisplay a date input widget.date = st.date_input(""Your birthday"") Time inputDisplay a time input widget.time = st.time_input(""Meeting time"") Chat inputDisplay a chat input widget.prompt = st.chat_input(""Say something"") if prompt: st.write(f""The user has sent: {prompt}"") Text-areaDisplay a multi-line text input widget.text = st.text_area(""Text to translate"") Text inputDisplay a single-line text input widget.name = st.text_input(""First name"") Data editorDisplay a data editor widget.edited = st.experimental_data_editor(df, num_rows=""dynamic"") File UploaderDisplay a file uploader widget.data = st.file_uploader(""Upload a CSV"") Camera inputDisplay a widget that allows users to upload images directly from a camera.image = st.camera_input(""Take a picture"") Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration! PreviousStreamlit ChatStreamlit Component for a Chatbot UI. Created by @AI-Yash.from streamlit_chat import message message(""My message"") message(""Hello bot!"", is_user=True) # align's the message to the right Streamlit Option MenuSelect a single item from a list of options in a menu. Created by @victoryhb.from streamlit_option_menu import option_menu option_menu(""Main Menu"", [""Home"", 'Settings'], icons=['house', 'gear'], menu_icon=""cast"", default_index=1) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.stoggle import stoggle stoggle( ""Click me!"", """"""🥷 Surprise! Here's some additional content"""""",) Streamlit ElementsCreate a draggable and resizable dashboard in Streamlit. Created by @okls.from streamlit_elements import elements, mui, html with elements(""new_element""): mui.Typography(""Hello world"") TagsAdd tags to your Streamlit apps. Created by @gagan3012.from streamlit_tags import st_tags st_tags(label='# Enter Keywords:', text='Press enter to add more', value=['Zero', 'One', 'Two'], suggestions=['five', 'six', 'seven', 'eight', 'nine', 'three', 'eleven', 'ten', 'four'], maxtags = 4, key='1') StqdmThe simplest way to handle a progress bar in streamlit app. Created by @Wirg.from stqdm import stqdm for _ in stqdm(range(50)): sleep(0.5) TimelineDisplay a Timeline in Streamlit apps using TimelineJS. Created by @innerdoc.from streamlit_timeline import timeline with open('example.json', ""r"") as f: timeline(f.read(), height=800) Camera input liveAlternative for st.camera_input which returns the webcam images live. Created by @blackary.from camera_input_live import camera_input_live image = camera_input_live() st.image(value) Streamlit AceAce editor component for Streamlit. Created by @okld.from streamlit_ace import st_ace content = st_ace() content Streamlit ChatStreamlit Component for a Chatbot UI. Created by @AI-Yash.from streamlit_chat import message message(""My message"") message(""Hello bot!"", is_user=True) # align's the message to the right Streamlit Option MenuSelect a single item from a list of options in a menu. Created by @victoryhb.from streamlit_option_menu import option_menu option_menu(""Main Menu"", [""Home"", 'Settings'], icons=['house', 'gear'], menu_icon=""cast"", default_index=1) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.stoggle import stoggle stoggle( ""Click me!"", """"""🥷 Surprise! Here's some additional content"""""",) Streamlit ElementsCreate a draggable and resizable dashboard in Streamlit. Created by @okls.from streamlit_elements import elements, mui, html with elements(""new_element""): mui.Typography(""Hello world"") TagsAdd tags to your Streamlit apps. Created by @gagan3012.from streamlit_tags import st_tags st_tags(label='# Enter Keywords:', text='Press enter to add more', value=['Zero', 'One', 'Two'], suggestions=['five', 'six', 'seven', 'eight', 'nine', 'three', 'eleven', 'ten', 'four'], maxtags = 4, key='1') StqdmThe simplest way to handle a progress bar in streamlit app. Created by @Wirg.from stqdm import stqdm for _ in stqdm(range(50)): sleep(0.5) TimelineDisplay a Timeline in Streamlit apps using TimelineJS. Created by @innerdoc.from streamlit_timeline import timeline with open('example.json', ""r"") as f: timeline(f.read(), height=800) Camera input liveAlternative for st.camera_input which returns the webcam images live. Created by @blackary.from camera_input_live import camera_input_live image = camera_input_live() st.image(value) Streamlit AceAce editor component for Streamlit. Created by @okld.from streamlit_ace import st_ace content = st_ace() content Streamlit ChatStreamlit Component for a Chatbot UI. Created by @AI-Yash.from streamlit_chat import message message(""My message"") message(""Hello bot!"", is_user=True) # align's the message to the right Streamlit Option MenuSelect a single item from a list of options in a menu. Created by @victoryhb.from streamlit_option_menu import option_menu option_menu(""Main Menu"", [""Home"", 'Settings'], icons=['house', 'gear'], menu_icon=""cast"", default_index=1) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.stoggle import stoggle stoggle( ""Click me!"", """"""🥷 Surprise! Here's some additional content"""""",) Next Media elements ImageDisplay an image or list of images.st.image(numpy_array) st.image(image_bytes) st.image(file) st.image(""https://example.com/myimage.jpg"") AudioDisplay an audio player.st.audio(numpy_array) st.audio(audio_bytes) st.audio(file) st.audio(""https://example.com/myaudio.mp3"", format=""audio/mp3"") VideoDisplay a video player.st.video(numpy_array) st.video(video_bytes) st.video(file) st.video(""https://example.com/myvideo.mp4"", format=""video/mp4"") Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration! PreviousStreamlit CropperA simple image cropper for Streamlit. Created by @turner-anderson.from streamlit_cropper import st_cropper st_cropper(img, realtime_update=realtime_update, box_color=box_color, aspect_ratio=aspect_ratio) Image CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates streamlit_image_coordinates(""https://placekitten.com/200/300"") Streamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl(""https://assets5.lottiefiles.com/packages/lf20_V9t630.json"") st_lottie(lottie_hello, key=""hello"") Streamlit WebrtcHandling and transmitting real-time video/audio streams with Streamlit. Created by @whitphx.from streamlit_webrtc import webrtc_streamer webrtc_streamer(key=""sample"") Drawable CanvasProvides a sketching canvas using Fabric.js. Created by @andfanilo.from streamlit_drawable_canvas import st_canvas st_canvas(fill_color=""rgba(255, 165, 0, 0.3)"", stroke_width=stroke_width, stroke_color=stroke_color, background_color=bg_color, background_image=Image.open(bg_image) if bg_image else None, update_streamlit=realtime_update, height=150, drawing_mode=drawing_mode, point_display_radius=point_display_radius if drawing_mode == 'point' else 0, key=""canvas"",) Image ComparisonCompare images with a slider using JuxtaposeJS. Created by @fcakyon.from streamlit_image_comparison import image_comparison image_comparison(img1=""image1.jpg"", img2=""image2.jpg"",) Streamlit CropperA simple image cropper for Streamlit. Created by @turner-anderson.from streamlit_cropper import st_cropper st_cropper(img, realtime_update=realtime_update, box_color=box_color, aspect_ratio=aspect_ratio) Image CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates streamlit_image_coordinates(""https://placekitten.com/200/300"") Streamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl(""https://assets5.lottiefiles.com/packages/lf20_V9t630.json"") st_lottie(lottie_hello, key=""hello"") Streamlit WebrtcHandling and transmitting real-time video/audio streams with Streamlit. Created by @whitphx.from streamlit_webrtc import webrtc_streamer webrtc_streamer(key=""sample"") Drawable CanvasProvides a sketching canvas using Fabric.js. Created by @andfanilo.from streamlit_drawable_canvas import st_canvas st_canvas(fill_color=""rgba(255, 165, 0, 0.3)"", stroke_width=stroke_width, stroke_color=stroke_color, background_color=bg_color, background_image=Image.open(bg_image) if bg_image else None, update_streamlit=realtime_update, height=150, drawing_mode=drawing_mode, point_display_radius=point_display_radius if drawing_mode == 'point' else 0, key=""canvas"",) Image ComparisonCompare images with a slider using JuxtaposeJS. Created by @fcakyon.from streamlit_image_comparison import image_comparison image_comparison(img1=""image1.jpg"", img2=""image2.jpg"",) Streamlit CropperA simple image cropper for Streamlit. Created by @turner-anderson.from streamlit_cropper import st_cropper st_cropper(img, realtime_update=realtime_update, box_color=box_color, aspect_ratio=aspect_ratio) Image CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates streamlit_image_coordinates(""https://placekitten.com/200/300"") Streamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl(""https://assets5.lottiefiles.com/packages/lf20_V9t630.json"") st_lottie(lottie_hello, key=""hello"") Next Layouts and containers ColumnsInsert containers laid out as side-by-side columns.col1, col2 = st.columns(2) col1.write(""this is column 1"") col2.write(""this is column 2"") ContainerInsert a multi-element container.c = st.container() st.write(""This will show last"") c.write(""This will show first"") c.write(""This will show second"") Modal dialogsInsert a modal dialog that can rerun independently from the rest of the script.@st.experimental_dialog(""Sign up"") def email_form(): name = st.text_input(""Name"") email = st.text_input(""Email"") EmptyInsert a single-element container.c = st.empty() st.write(""This will show last"") c.write(""This will be replaced"") c.write(""This will show first"") ExpanderInsert a multi-element container that can be expanded/collapsed.with st.expander(""Open to see more""): st.write(""This is more content"") PopoverInsert a multi-element popover container that can be opened/closed.with st.popover(""Settings""): st.checkbox(""Show completed"") SidebarDisplay items in a sidebar.st.sidebar.write(""This lives in the sidebar"") st.sidebar.button(""Click me!"") TabsInsert containers separated into tabs.tab1, tab2 = st.tabs([""Tab 1"", ""Tab2""]) tab1.write(""this is tab 1"") tab2.write(""this is tab 2"") Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration!Streamlit ElementsCreate a draggable and resizable dashboard in Streamlit. Created by @okls.from streamlit_elements import elements, mui, html with elements(""new_element""): mui.Typography(""Hello world"") PydanticAuto-generate Streamlit UI from Pydantic Models and Dataclasses. Created by @lukasmasuch.import streamlit_pydantic as sp sp.pydantic_form(key=""my_form"", model=ExampleModel) Streamlit PagesAn experimental version of Streamlit Multi-Page Apps. Created by @blackary.from st_pages import Page, show_pages, add_page_title show_pages([ Page(""streamlit_app.py"", ""Home"", ""🏠""), Page(""other_pages/page2.py"", ""Page 2"", "":books:""), ]) Chat elements Streamlit provides a few commands to help you build conversational apps. These chat elements are designed to be used in conjunction with each other, but you can also use them separately. st.chat_message lets you insert a chat message container into the app so you can display messages from the user or the app. Chat containers can contain other Streamlit elements, including charts, tables, text, and more. st.chat_input lets you display a chat input widget so the user can type in a message. Chat inputDisplay a chat input widget.prompt = st.chat_input(""Say something"") if prompt: st.write(f""The user has sent: {prompt}"") Chat messageInsert a chat message container.import numpy as np with st.chat_message(""user""): st.write(""Hello 👋"") st.line_chart(np.random.randn(30, 3)) Status containerDisplay output of long-running tasks in a container.with st.status('Running'): do_something_slow() st.write_streamWrite generators or streams to the app with a typewriter effect.st.write_stream(my_generator) st.write_stream(my_llm_stream) Status elements Progress barDisplay a progress bar.for i in range(101): st.progress(i) do_something_slow() SpinnerTemporarily displays a message while executing a block of code.with st.spinner(""Please wait...""): do_something_slow() Status containerDisplay output of long-running tasks in a container.with st.status('Running'): do_something_slow() ToastBriefly displays a toast message in the bottom-right corner.st.toast('Butter!', icon='🧈') BalloonsDisplay celebratory balloons!do_something() # Celebrate when all done! st.balloons() SnowflakesDisplay celebratory snowflakes!do_something() # Celebrate when all done! st.snow() Success boxDisplay a success message.st.success(""Match found!"") Info boxDisplay an informational message.st.info(""Dataset is updated every day at midnight."") Warning boxDisplay warning message.st.warning(""Unable to fetch image. Skipping..."") Error boxDisplay error message.st.error(""We encountered an error"") Exception outputDisplay an exception.e = RuntimeError(""This is an exception of type RuntimeError"") st.exception(e) Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration!StqdmThe simplest way to handle a progress bar in streamlit app. Created by @Wirg.from stqdm import stqdm for _ in stqdm(range(50)): sleep(0.5) Custom notification boxA custom notification box with the ability to close it out. Created by @Socvest.from streamlit_custom_notification_box import custom_notification_box styles = {'material-icons':{'color': 'red'}, 'text-icon-link-close-container': {'box-shadow': '#3896de 0px 4px'}, 'notification-text': {'':''}, 'close-button':{'':''}, 'link':{'':''}} custom_notification_box(icon='info', textDisplay='We are almost done with your registration...', externalLink='more info', url='#', styles=styles, key=""foo"") Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.let_it_rain import rain rain(emoji=""🎈"", font_size=54, falling_speed=5, animation_length=""infinite"",) App logic and configuration Navigation and pages Switch pageProgrammatically navigates to a specified page.st.switch_page(""pages/my_page.py"") Page linkDisplay a link to another page in a multipage app.st.page_link(""app.py"", label=""Home"", icon=""🏠"") st.page_link(""pages/profile.py"", label=""My profile"") Execution flow Modal dialogsInsert a modal dialog that can rerun independently from the rest of the script.@st.experimental_dialog(""Sign up"") def email_form(): name = st.text_input(""Name"") email = st.text_input(""Email"") FormsCreate a form that batches elements together with a “Submit"" button.with st.form(key='my_form'): name = st.text_input(""Name"") email = st.text_input(""Email"") st.form_submit_button(""Sign up"") Partial rerunsDefine a fragment to rerun independently from the rest of the script.@st.experimental_fragment(run_every=""10s"") def fragment(): df = get_data() st.line_chart(df) Rerun scriptRerun the script immediately.st.rerun() Stop executionStops execution immediately.st.stop() Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration!AutorefreshForce a refresh without tying up a script. Created by @kmcgrady.from streamlit_autorefresh import st_autorefresh st_autorefresh(interval=2000, limit=100, key=""fizzbuzzcounter"") PydanticAuto-generate Streamlit UI from Pydantic Models and Dataclasses. Created by @lukasmasuch.import streamlit_pydantic as sp sp.pydantic_form(key=""my_form"", model=ExampleModel) Streamlit PagesAn experimental version of Streamlit Multi-Page Apps. Created by @blackary.from st_pages import Page, show_pages, add_page_title show_pages([ Page(""streamlit_app.py"", ""Home"", ""🏠""), Page(""other_pages/page2.py"", ""Page 2"", "":books:""), ]) Caching and state Cache dataFunction decorator to cache functions that return data (e.g. dataframe transforms, database queries, ML inference).@st.cache_data def long_function(param1, param2): # Perform expensive computation here or # fetch data from the web here return data Cache resourceFunction decorator to cache functions that return global resources (e.g. database connections, ML models).@st.cache_resource def init_model(): # Return a global resource here return pipeline( ""sentiment-analysis"", model=""distilbert-base-uncased-finetuned-sst-2-english"" ) Session stateSession state is a way to share variables between reruns, for each user session.st.session_state['key'] = value Query parametersGet, set, or clear the query parameters that are shown in the browser's URL bar.st.query_params[key] = value st.query_params.clear() Connections and databases Setup your connection Create a connectionConnect to a data source or APIconn = st.connection('pets_db', type='sql') pet_owners = conn.query('select * from pet_owners') st.dataframe(pet_owners) Built-in connections SnowflakeConnectionA connection to Snowflake.conn = st.connection('snowflake') SQLConnectionA connection to a SQL database using SQLAlchemy.conn = st.connection('sql') Build your own connections Connection base classBuild your own connection with BaseConnection.class MyConnection(BaseConnection[myconn.MyConnection]): def _connect(self, **kwargs) -> MyConnection: return myconn.connect(**self._secrets, **kwargs) def query(self, query): return self._instance.query(query) Secrets management Secrets singletonAccess secrets from a local TOML file.key = st.secrets[""OpenAI_key""] Secrets fileSave your secrets in a per-project or per-profile TOML file.OpenAI_key = """" Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration!AuthenticatorA secure authentication module to validate user credentials. Created by @mkhorasani.import streamlit_authenticator as stauth authenticator = stauth.Authenticate( config['credentials'], config['cookie']['name'], config['cookie']['key'], config['cookie']['expiry_days'], config['preauthorized']) WS localStorageA simple synchronous way of accessing localStorage from your app. Created by @gagangoku.from streamlit_ws_localstorage import injectWebsocketCode ret = conn.setLocalStorageVal(key='k1', val='v1') st.write('ret: ' + ret) Streamlit Auth0The fastest way to provide comprehensive login inside Streamlit. Created by @conradbez.from auth0_component import login_button user_info = login_button(clientId, domain = domain) st.write(user_info) Custom Components Declare a componentCreate and register a custom component.st.components.v1.declare_component( ""custom_slider"", ""/frontend"", ) HTMLDisplay an HTML string in an iframe.st.components.v1.html( ""

Foo bar.

"" ) iframeLoad a remote URL in an iframe.st.components.v1.iframe( ""docs.streamlit.io"" ) Utilities and user info User infost.experimental_user returns information about the logged-in user of private apps on Streamlit Community Cloud.if st.experimental_user.email == ""foo@corp.com"": st.write(""Welcome back, "", st.experimental_user.email) else: st.write(""You are not authorized to view this page."") Get helpDisplay object’s doc string, nicely formatted.st.help(st.write) st.help(pd.DataFrame) Render HTMLRenders HTML strings to your app.css = """""" """""" st.html(css) Configuration Configuration fileConfigures the default settings for your app.your-project/ ├── .streamlit/ │ └── config.toml └── your_app.py Set page title, favicon, and moreConfigures the default settings of the page.st.set_page_config( page_title=""My app"", page_icon="":shark:"", ) Developer tools App testing st.testing.v1.AppTestst.testing.v1.AppTest simulates a running Streamlit app for testing.from streamlit.testing.v1 import AppTest at = AppTest.from_file(""streamlit_app.py"") at.secrets[""WORD""] = ""Foobar"" at.run() assert not at.exception at.text_input(""word"").input(""Bazbat"").run() assert at.warning[0].value == ""Try again."" AppTest.from_filest.testing.v1.AppTest.from_file initializes a simulated app from a file.from streamlit.testing.v1 import AppTest at = AppTest.from_file(""streamlit_app.py"") at.run() AppTest.from_stringst.testing.v1.AppTest.from_string initializes a simulated app from a string.from streamlit.testing.v1 import AppTest at = AppTest.from_string(app_script_as_string) at.run() AppTest.from_functionst.testing.v1.AppTest.from_function initializes a simulated app from a function.from streamlit.testing.v1 import AppTest at = AppTest.from_function(app_script_as_callable) at.run() BlockA representation of container elements, including: st.chat_message st.columns st.sidebar st.tabs The main body of the app. # at.sidebar returns a Block at.sidebar.button[0].click().run() assert not at.exception ElementThe base class for representation of all elements, including: st.title st.header st.markdown st.dataframe # at.title returns a sequence of Title # Title inherits from Element assert at.title[0].value == ""My awesome app"" ButtonA representation of st.button and st.form_submit_button.at.button[0].click().run() ChatInputA representation of st.chat_input.at.chat_input[0].set_value(""What is Streamlit?"").run() CheckboxA representation of st.checkbox.at.checkbox[0].check().run() ColorPickerA representation of st.color_picker.at.color_picker[0].pick(""#FF4B4B"").run() DateInputA representation of st.date_input.release_date = datetime.date(2023, 10, 26) at.date_input[0].set_value(release_date).run() MultiselectA representation of st.multiselect.at.multiselect[0].select(""New York"").run() NumberInputA representation of st.number_input.at.number_input[0].increment().run() RadioA representation of st.radio.at.radio[0].set_value(""New York"").run() SelectSliderA representation of st.select_slider.at.select_slider[0].set_range(""A"",""C"").run() SelectboxA representation of st.selectbox.at.selectbox[0].select(""New York"").run() SliderA representation of st.slider.at.slider[0].set_range(2,5).run() TextAreaA representation of st.text_area.at.text_area[0].input(""Streamlit is awesome!"").run() TextInputA representation of st.text_input.at.text_input[0].input(""Streamlit"").run() TimeInputA representation of st.time_input.at.time_input[0].increment().run() ToggleA representation of st.toggle.at.toggle[0].set_value(""True"").run() Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration!Pandas ProfilingPandas profiling component for Streamlit. Created by @okld.df = pd.read_csv(""https://storage.googleapis.com/tf-datasets/titanic/train.csv"") pr = df.profile_report() st_profile_report(pr) Streamlit AceAce editor component for Streamlit. Created by @okld.from streamlit_ace import st_ace content = st_ace() content Streamlit AnalyticsTrack & visualize user interactions with your streamlit app. Created by @jrieke.import streamlit_analytics with streamlit_analytics.track(): st.text_input(""Write something"") Previous: ConceptsNext: Write and magicforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy" https://docs.streamlit.io/develop/api-reference/execution-flow#change-execution,"DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceremovePAGE ELEMENTSWrite and magicaddText elementsaddData elementsaddChart elementsaddInput widgetsaddMedia elementsaddLayouts and containersaddChat elementsaddStatus elementsaddThird-party componentsopen_in_newAPPLICATION LOGICNavigation and pagesaddExecution flowremovest.dialogst.formst.form_submit_buttonst.fragmentst.rerunst.stopCaching and stateaddConnections and secretsaddCustom componentsaddUtilitiesaddConfigurationaddTOOLSApp testingaddCommand lineaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Develop/API reference/Execution flowExecution flow Change execution By default, Streamlit apps execute the script entirely, but we allow some functionality to handle control flow in your applications. Modal dialogsInsert a modal dialog that can rerun independently from the rest of the script.@st.experimental_dialog(""Sign up"") def email_form(): name = st.text_input(""Name"") email = st.text_input(""Email"") Partial rerunsDefine a fragment to rerun independently from the rest of the script.@st.experimental_fragment(run_every=""10s"") def fragment(): df = get_data() st.line_chart(df) Rerun scriptRerun the script immediately.st.rerun() Stop executionStops execution immediately.st.stop() Group multiple widgets By default, Streamlit reruns your script everytime a user interacts with your app. However, sometimes it's a better user experience to wait until a group of related widgets is filled before actually rerunning the script. That's what st.form is for! FormsCreate a form that batches elements together with a “Submit"" button.with st.form(key='my_form'): name = st.text_input(""Name"") email = st.text_input(""Email"") st.form_submit_button(""Sign up"") Form submit buttonDisplay a form submit button.with st.form(key='my_form'): name = st.text_input(""Name"") email = st.text_input(""Email"") st.form_submit_button(""Sign up"") Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration!AutorefreshForce a refresh without tying up a script. Created by @kmcgrady.from streamlit_autorefresh import st_autorefresh st_autorefresh(interval=2000, limit=100, key=""fizzbuzzcounter"") PydanticAuto-generate Streamlit UI from Pydantic Models and Dataclasses. Created by @lukasmasuch.import streamlit_pydantic as sp sp.pydantic_form(key=""my_form"", model=ExampleModel) Streamlit PagesAn experimental version of Streamlit Multi-Page Apps. Created by @blackary.from st_pages import Page, show_pages, add_page_title show_pages([ Page(""streamlit_app.py"", ""Home"", ""🏠""), Page(""other_pages/page2.py"", ""Page 2"", "":books:""), ]) Previous: Navigation and pagesNext: st.dialogforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy" https://docs.streamlit.io/knowledge-base/deploy/custom-subdomains#custom-subdomains,"DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudremoveGet startedaddDeploy your appremoveApp dependenciesSecrets managementManage your appaddShare your appaddManage your accountaddTroubleshootingStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Deploy/Streamlit Community Cloud/Deploy your appDeploy your app Streamlit Community Cloud lets you deploy your apps in just one click, and most apps will deploy in only a few minutes. If you don't have an app ready to deploy, fork or clone one from our App gallery — you can find apps for machine learning, data visualization, data exploration, A/B testing and more. You can also fork and deploy samples straight from the New app button. Once you've deployed your app, check out how you can Edit your app with GitHub Codespaces. push_pinNoteIf you want to deploy your app on a different cloud service, check out the Deploy Streamlit apps article in our Knowledge Base. Add your app to GitHub Streamlit Community Cloud launches apps directly from your GitHub repo, so your app code and dependencies need to be on GitHub before you try to deploy your app. For more information on how to specify dependencies, see App dependencies. Your directory structure should look similar to this: your-repository/ ├── your_app.py └── requirements.txt If you are including any custom Configuration or Theming, make sure your config file is saved relative to the root of your repo. Within your repo, your config file should be named .streamlit/config.toml. your-repository/ ├── .streamlit/ │ └── config.toml ├── your_app.py └── requirements.txt priority_highImportantAlthough you can deploy multiple apps from the same repository, there can be only one configuration file. Deploy your app From your workspace at share.streamlit.io, click ""New app"" from the upper-right corner of your workspace. Fill in your repo, branch, and file path. As a shortcut, you can also click ""Paste GitHub URL"" to paste a link directly to your_app.py on GitHub. An app URL with a random hash is prefilled but you can change this to a custom subdomain instead. In the example below, the app would be deployed to https://red-balloon.streamlit.app/. You can always change your subdomain later. See more about Custom subdomains at the end of this page. Advanced settings for deployment push_pinNoteStreamlit Community Cloud supports all released versions of Python that are still receiving security updates. Streamlit Community Cloud defaults to version 3.9. You can select a version of your choice from the ""Python version"" dropdown in the ""Advanced settings"" modal. If an app is running a version of Python that becomes unsupported, it will be forcibly upgraded to the oldest, supported version of Python and may break. (Optional) If you are connecting to a data source or want to specify the Python version for your app, you can do that by clicking ""Advanced settings"" before you deploy the app. Learn more about Secrets management. Watch your app launch Your app is now deploying and you can watch while it launches. Most apps take only a couple of minutes to deploy, but if your app has a lot of dependencies it may take longer to deploy the first time. After the initial deployment, any change that does not touch your dependencies should show up immediately. push_pinNoteThe Streamlit Community Cloud logs on the right hand side of your app are only viewable to users with developer access to your repository. These logs help you debug any issues with the app. Learn more about Streamlit Community Cloud logs. Your app URL That's it — you're done! Your app now has a unique subdomain URL that you can share with others. Read more about how to Share your app with viewers. Unique subdomains If the ""Custom subdomain (optional)"" field is blank when you deploy your app, a URL is assigned following a structure based on your GitHub repo. The URL begins with your GitHub username or organization owning your repo, followed by your repo name, app path, and a short hash. If you deploy from a branch other than main or master, the URL also includes the branch name. https://[GitHub username or organization]-[repo name]-[app path]-[branch name]-[short hash].streamlit.app For example, this is an app deployed from the streamlit organization. The repo is demo-self-driving and the app name is streamlit_app.py in the root directory. The branch name is master and therefore not included. https://streamlit-demo-self-driving-streamlit-app-8jya0g.streamlit.app Custom subdomains Setting a custom subdomain makes it much easier to share your app since you can choose something memorable. Whether you set a custom subdomain during deployment or later, your app's URL will appear as: https://.streamlit.app To view or customize your app subdomain from the dashboard: Click the overflow icon (more_vert) to the app's right and select ""Settings"". View the ""General"" tab in the App settings modal. Your app's unique subdomain will appear here. Pick a custom subdomain between 6 and 63 characters in length for your app's URL and hit ""Save"". It's that simple! You can then access your app by visiting your customized URL 🎉. If a custom subdomain is not available (e.g. because it's already taken), you'll see an error message like this: Previous: Get startedNext: App dependenciesforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy" https://docs.streamlit.io/deploy/concepts/dependencies#pip-and-requirementstxt,"DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceaddTutorialsaddQuick referenceaddweb_assetDeployConceptsremoveDependenciesSecretsStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Deploy/Concepts/DependenciesManaging dependencies when deploying your app Before you began developing your app, you set up and configured your development environment by installing Python and Streamlit. When you deploy your app, you need to set up and configure your deployment environment in the same way. When you deploy your app to a cloud service, your app's Python server will be running on a remote machine. This remote machine will not have access all the files and programs on your personal computer. All Streamlit apps have at least two dependencies: Python and Streamlit. Your app may have additional dependencies in the form of Python packages or software that must be installed to properly execute your script. If you are using a service like Streamlit Community Cloud which is designed for Streamlit apps, we'll take care of Python and Streamlit for you! Install Python and other software If you are using Streamlit Community Cloud, Python is already installed. You can just pick the version in the deployment dialog. If you need to install Python yourself or you have other non-Python software to install, follow your platform's instructions to install additional software. You will commonly use a package management tool to do this. For example, Streamlit Community Cloud uses Advanced Package Tool (apt) for Debian-based Linux systems. For more information about installing non-Python depencies on Streamlit Community Cloud, see apt-get dependencies. Install Python packages Once you have Python installed in your deployment environment, you'll need to install all the necessary Python packages, including Streamlit! With each import of an installed package, you add a Python dependency to your script. You need to install those dependencies in your deployment environment through a Python package manager. If you are using Streamlit Community Cloud, you'll have the latest version of Streamlit and all of its dependencies installed by default. So, if you're making a simple app and don't need additional dependencies, you won't have to do anything at all! pip and requirements.txt Since pip comes by default with Python, the most common way to configure your Python environment is with a requirements.txt file. Each line of a requirements.txt file is a package to pip install. You should not include built-in Python libraries like math or random in your requirements.txt file. These are a part of Python and aren't installed separately. If you have a script like the following, you would only need to install Streamlit. No extra dependencies would be needed since pandas and numpy are installed as direct dependencies of streamlit. Similarly, math and random are built into Python. import streamlit as st import pandas as pd import numpy as np import math import random st.write('Hi!') However, it's a best practice accurately record packages you use, so the recommended requirements.txt file would be: streamlit pandas numpy If you needed to specify certain versions, another valid example would be: streamlit==1.24.1 pandas>2.0 numpy<=1.25.1 A requirements.txt file is commonly saved in the root of your repository or file directory. If you are using Streamlit Community Cloud, see Add Python dependencies for more information. Otherwise, check your platform's documentation.Previous: ConceptsNext: SecretsforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy" https://docs.streamlit.io/develop/api-reference/app-testing/st.testing.v1.apptest#apptestmain,"DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceremovePAGE ELEMENTSWrite and magicaddText elementsaddData elementsaddChart elementsaddInput widgetsaddMedia elementsaddLayouts and containersaddChat elementsaddStatus elementsaddThird-party componentsopen_in_newAPPLICATION LOGICNavigation and pagesaddExecution flowaddCaching and stateaddConnections and secretsaddCustom componentsaddUtilitiesaddConfigurationaddTOOLSApp testingremovest.testing.v1.AppTestTesting element classesCommand lineaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Develop/API reference/App testing/st.testing.v1.AppTest The AppTest class st.testing.v1.AppTestStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA simulated Streamlit app to check the correctness of displayed elements and outputs. An instance of AppTest simulates a running Streamlit app. This class provides methods to set up, manipulate, and inspect the app contents via API instead of a browser UI. It can be used to write automated tests of an app in various scenarios. These can then be run using a tool like pytest. AppTest can be initialized by one of three class methods: st.testing.v1.AppTest.from_file (recommended) st.testing.v1.AppTest.from_string st.testing.v1.AppTest.from_function Once initialized, Session State and widget values can be updated and the script can be run. Unlike an actual live-running Streamlit app, you need to call AppTest.run() explicitly to re-run the app after changing a widget value. Switching pages also requires an explicit, follow-up call to AppTest.run(). AppTest enables developers to build tests on their app as-is, in the familiar python test format, without major refactoring or abstracting out logic to be tested separately from the UI. Tests can run quickly with very low overhead. A typical pattern is to build a suite of tests for an app that ensure consistent functionality as the app evolves, and run the tests locally and/or in a CI environment like Github Actions. Note AppTest only supports testing a single page of an app per instance. For multipage apps, each page will need to be tested separately. No methods exist to programatically switch pages within AppTest. Class description[source] st.testing.v1.AppTest(script_path, *, default_timeout, args=None, kwargs=None) Methods get(element_type) Get elements or widgets of the specified type. run(*, timeout=None) Run the script from the current state. switch_page(page_path) Switch to another page of the app. Attributes secrets (dict[str, Any]) Dictionary of secrets to be used the simulated app. Use dict-like syntax to set secret values for the simulated app. session_state (SafeSessionState) Session State for the simulated app. SafeSessionState object supports read and write operations as usual for Streamlit apps. query_params (dict[str, Any]) Dictionary of query parameters to be used by the simluated app. Use dict-like syntax to set query_params values for the simulated app. button Sequence of all st.button and st.form_submit_button widgets. caption Sequence of all st.caption elements. chat_input Sequence of all st.chat_input widgets. chat_message Sequence of all st.chat_message elements. checkbox Sequence of all st.checkbox widgets. code Sequence of all st.code elements. color_picker Sequence of all st.color_picker widgets. columns Sequence of all columns within st.columns elements. dataframe Sequence of all st.dataframe elements. date_input Sequence of all st.date_input widgets. divider Sequence of all st.divider elements. error Sequence of all st.error elements. exception Sequence of all st.exception elements. expander Sequence of all st.expander elements. header Sequence of all st.header elements. info Sequence of all st.info elements. json Sequence of all st.json elements. latex Sequence of all st.latex elements. main Sequence of elements within the main body of the app. markdown Sequence of all st.markdown elements. metric Sequence of all st.metric elements. multiselect Sequence of all st.multiselect widgets. number_input Sequence of all st.number_input widgets. radio Sequence of all st.radio widgets. select_slider Sequence of all st.select_slider widgets. selectbox Sequence of all st.selectbox widgets. sidebar Sequence of all elements within st.sidebar. slider Sequence of all st.slider widgets. status Sequence of all st.status elements. subheader Sequence of all st.subheader elements. success Sequence of all st.success elements. table Sequence of all st.table elements. tabs Sequence of all tabs within st.tabs elements. text Sequence of all st.text elements. text_area Sequence of all st.text_area widgets. text_input Sequence of all st.text_input widgets. time_input Sequence of all st.time_input widgets. title Sequence of all st.title elements. toast Sequence of all st.toast elements. toggle Sequence of all st.toggle widgets. warning Sequence of all st.warning elements. Initialize a simulated app using AppTest AppTest.from_fileStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeCreate an instance of AppTest to simulate an app page defined within a file. This option is most convenient for CI workflows and testing of published apps. The script must be executable on its own and so must contain all necessary imports. Function signature[source] AppTest.from_file(cls, script_path, *, default_timeout=3) Parameters script_path (str) Path to a script file. The path should be absolute or relative to the file calling .from_file. default_timeout (float) Default time in seconds before a script run is timed out. Can be overridden for individual .run() calls. Returns(AppTest) A simulated Streamlit app for testing. The simulated app can be executed via .run(). AppTest.from_stringStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeCreate an instance of AppTest to simulate an app page defined within a string. This is useful for testing short scripts that fit comfortably as an inline string in the test itself, without having to create a separate file for it. The script must be executable on its own and so must contain all necessary imports. Function signature[source] AppTest.from_string(cls, script, *, default_timeout=3) Parameters script (str) The string contents of the script to be run. default_timeout (float) Default time in seconds before a script run is timed out. Can be overridden for individual .run() calls. Returns(AppTest) A simulated Streamlit app for testing. The simulated app can be executed via .run(). AppTest.from_functionStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeCreate an instance of AppTest to simulate an app page defined within a function. This is similar to AppTest.from_string(), but more convenient to write with IDE assistance. The script must be executable on its own and so must contain all necessary imports. Function signature[source] AppTest.from_function(cls, script, *, default_timeout=3, args=None, kwargs=None) Parameters script (Callable) A function whose body will be used as a script. Must be runnable in isolation, so it must include any necessary imports. default_timeout (float) Default time in seconds before a script run is timed out. Can be overridden for individual .run() calls. args (tuple) An optional tuple of args to pass to the script function. kwargs (dict) An optional dict of kwargs to pass to the script function. Returns(AppTest) A simulated Streamlit app for testing. The simulated app can be executed via .run(). Run an AppTest script AppTest.runStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeRun the script from the current state. This is equivalent to manually rerunning the app or the rerun that occurs upon user interaction. AppTest.run() must be manually called after updating a widget value or switching pages as script reruns do not occur automatically as they do for live-running Streamlit apps. Function signature[source] AppTest.run(*, timeout=None) Parameters timeout (null) The maximum number of seconds to run the script. None means use the default timeout set for the instance of AppTest. Returns(AppTest) self AppTest.switch_pageStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSwitch to another page of the app. This method does not automatically rerun the app. Use a follow-up call to AppTest.run() to obtain the elements on the selected page. Function signature[source] AppTest.switch_page(page_path) Parameters page_path (str) Path of the page to switch to. The path must be relative to the main script's location (e.g. ""pages/my_page.py""). Returns(AppTest) self Get AppTest script elements The main value of AppTest is providing an API to programmatically inspect and interact with the elements and widgets produced by a running Streamlit app. Using the AppTest. properties or AppTest.get() method returns a collection of all the elements or widgets of the specified type that would have been displayed by running the app. Note that you can also retrieve elements within a specific container in the same way - first retrieve the container, then retrieve the elements just in that container. AppTest.getStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeGet elements or widgets of the specified type. This method returns the collection of all elements or widgets of the specified type on the current page. Retrieve a specific element by using its index (order on page) or key lookup. Function signature[source] AppTest.get(element_type) Parameters element_type (str) An element attribute of AppTest. For example, ""button"", ""caption"", or ""chat_input"". Returns(Sequence of Elements) Sequence of elements of the given type. Individual elements can be accessed from a Sequence by index (order on the page). When getting and element_type that is a widget, individual widgets can be accessed by key. For example, at.get(""text"")[0] for the first st.text element or at.get(""slider"")(key=""my_key"") for the st.slider widget with a given key. AppTest.buttonStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.button and st.form_submit_button widgets. Function signature[source] AppTest.button Returns(WidgetList of Button) Sequence of all st.button and st.form_submit_button widgets. Individual widgets can be accessed from a WidgetList by index (order on the page) or key. For example, at.button[0] for the first widget or at.button(key=""my_key"") for a widget with a given key. AppTest.captionStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.caption elements. Function signature[source] AppTest.caption Returns(ElementList of Caption) Sequence of all st.caption elements. Individual elements can be accessed from an ElementList by index (order on the page). For example, at.caption[0] for the first element. Caption is an extension of the Element class. AppTest.chat_inputStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.chat_input widgets. Function signature[source] AppTest.chat_input Returns(WidgetList of ChatInput) Sequence of all st.chat_input widgets. Individual widgets can be accessed from a WidgetList by index (order on the page) or key. For example, at.chat_input[0] for the first widget or at.chat_input(key=""my_key"") for a widget with a given key. AppTest.chat_messageStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.chat_message elements. Function signature[source] AppTest.chat_message Returns(Sequence of ChatMessage) Sequence of all st.chat_message elements. Individual elements can be accessed from an ElementList by index (order on the page). For example, at.chat_message[0] for the first element. ChatMessage is an extension of the Block class. AppTest.checkboxStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.checkbox widgets. Function signature[source] AppTest.checkbox Returns(WidgetList of Checkbox) Sequence of all st.checkbox widgets. Individual widgets can be accessed from a WidgetList by index (order on the page) or key. For example, at.checkbox[0] for the first widget or at.checkbox(key=""my_key"") for a widget with a given key. AppTest.codeStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.code elements. Function signature[source] AppTest.code Returns(ElementList of Code) Sequence of all st.code elements. Individual elements can be accessed from an ElementList by index (order on the page). For example, at.code[0] for the first element. Code is an extension of the Element class. AppTest.color_pickerStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.color_picker widgets. Function signature[source] AppTest.color_picker Returns(WidgetList of ColorPicker) Sequence of all st.color_picker widgets. Individual widgets can be accessed from a WidgetList by index (order on the page) or key. For example, at.color_picker[0] for the first widget or at.color_picker(key=""my_key"") for a widget with a given key. AppTest.columnsStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all columns within st.columns elements. Each column within a single st.columns will be returned as a separate Column in the Sequence. Function signature[source] AppTest.columns Returns(Sequence of Column) Sequence of all columns within st.columns elements. Individual columns can be accessed from an ElementList by index (order on the page). For example, at.columns[0] for the first column. Column is an extension of the Block class. AppTest.dataframeStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.dataframe elements. Function signature[source] AppTest.dataframe Returns(ElementList of Dataframe) Sequence of all st.dataframe elements. Individual elements can be accessed from an ElementList by index (order on the page). For example, at.dataframe[0] for the first element. Dataframe is an extension of the Element class. AppTest.date_inputStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.date_input widgets. Function signature[source] AppTest.date_input Returns(WidgetList of DateInput) Sequence of all st.date_input widgets. Individual widgets can be accessed from a WidgetList by index (order on the page) or key. For example, at.date_input[0] for the first widget or at.date_input(key=""my_key"") for a widget with a given key. AppTest.dividerStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.divider elements. Function signature[source] AppTest.divider Returns(ElementList of Divider) Sequence of all st.divider elements. Individual elements can be accessed from an ElementList by index (order on the page). For example, at.divider[0] for the first element. Divider is an extension of the Element class. AppTest.errorStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.error elements. Function signature[source] AppTest.error Returns(ElementList of Error) Sequence of all st.error elements. Individual elements can be accessed from an ElementList by index (order on the page). For example, at.error[0] for the first element. Error is an extension of the Element class. AppTest.exceptionStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.exception elements. Function signature[source] AppTest.exception Returns(ElementList of Exception) Sequence of all st.exception elements. Individual elements can be accessed from an ElementList by index (order on the page). For example, at.exception[0] for the first element. Exception is an extension of the Element class. AppTest.expanderStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.expander elements. Function signature[source] AppTest.expander Returns(Sequence of Expandable) Sequence of all st.expander elements. Individual elements can be accessed from a Sequence by index (order on the page). For example, at.expander[0] for the first element. Expandable is an extension of the Block class. AppTest.headerStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.header elements. Function signature[source] AppTest.header Returns(ElementList of Header) Sequence of all st.header elements. Individual elements can be accessed from an ElementList by index (order on the page). For example, at.header[0] for the first element. Header is an extension of the Element class. AppTest.infoStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.info elements. Function signature[source] AppTest.info Returns(ElementList of Info) Sequence of all st.info elements. Individual elements can be accessed from an ElementList by index (order on the page). For example, at.info[0] for the first element. Info is an extension of the Element class. AppTest.jsonStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.json elements. Function signature[source] AppTest.json Returns(ElementList of Json) Sequence of all st.json elements. Individual elements can be accessed from an ElementList by index (order on the page). For example, at.json[0] for the first element. Json is an extension of the Element class. AppTest.latexStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.latex elements. Function signature[source] AppTest.latex Returns(ElementList of Latex) Sequence of all st.latex elements. Individual elements can be accessed from an ElementList by index (order on the page). For example, at.latex[0] for the first element. Latex is an extension of the Element class. AppTest.mainStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of elements within the main body of the app. Function signature[source] AppTest.main Returns(Block) A container of elements. Block can be queried for elements in the same manner as AppTest. For example, Block.checkbox will return all st.checkbox within the associated container. AppTest.markdownStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.markdown elements. Function signature[source] AppTest.markdown Returns(ElementList of Markdown) Sequence of all st.markdown elements. Individual elements can be accessed from an ElementList by index (order on the page). For example, at.markdown[0] for the first element. Markdown is an extension of the Element class. AppTest.metricStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.metric elements. Function signature[source] AppTest.metric Returns(ElementList of Metric) Sequence of all st.metric elements. Individual elements can be accessed from an ElementList by index (order on the page). For example, at.metric[0] for the first element. Metric is an extension of the Element class. AppTest.multiselectStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.multiselect widgets. Function signature[source] AppTest.multiselect Returns(WidgetList of Multiselect) Sequence of all st.multiselect widgets. Individual widgets can be accessed from a WidgetList by index (order on the page) or key. For example, at.multiselect[0] for the first widget or at.multiselect(key=""my_key"") for a widget with a given key. AppTest.number_inputStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.number_input widgets. Function signature[source] AppTest.number_input Returns(WidgetList of NumberInput) Sequence of all st.number_input widgets. Individual widgets can be accessed from a WidgetList by index (order on the page) or key. For example, at.number_input[0] for the first widget or at.number_input(key=""my_key"") for a widget with a given key. AppTest.radioStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.radio widgets. Function signature[source] AppTest.radio Returns(WidgetList of Radio) Sequence of all st.radio widgets. Individual widgets can be accessed from a WidgetList by index (order on the page) or key. For example, at.radio[0] for the first widget or at.radio(key=""my_key"") for a widget with a given key. AppTest.select_sliderStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.select_slider widgets. Function signature[source] AppTest.select_slider Returns(WidgetList of SelectSlider) Sequence of all st.select_slider widgets. Individual widgets can be accessed from a WidgetList by index (order on the page) or key. For example, at.select_slider[0] for the first widget or at.select_slider(key=""my_key"") for a widget with a given key. AppTest.selectboxStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.selectbox widgets. Function signature[source] AppTest.selectbox Returns(WidgetList of Selectbox) Sequence of all st.selectbox widgets. Individual widgets can be accessed from a WidgetList by index (order on the page) or key. For example, at.selectbox[0] for the first widget or at.selectbox(key=""my_key"") for a widget with a given key. AppTest.sidebarStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all elements within st.sidebar. Function signature[source] AppTest.sidebar Returns(Block) A container of elements. Block can be queried for elements in the same manner as AppTest. For example, Block.checkbox will return all st.checkbox within the associated container. AppTest.sliderStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.slider widgets. Function signature[source] AppTest.slider Returns(WidgetList of Slider) Sequence of all st.slider widgets. Individual widgets can be accessed from a WidgetList by index (order on the page) or key. For example, at.slider[0] for the first widget or at.slider(key=""my_key"") for a widget with a given key. AppTest.subheaderStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.subheader elements. Function signature[source] AppTest.subheader Returns(ElementList of Subheader) Sequence of all st.subheader elements. Individual elements can be accessed from an ElementList by index (order on the page). For example, at.subheader[0] for the first element. Subheader is an extension of the Element class. AppTest.successStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.success elements. Function signature[source] AppTest.success Returns(ElementList of Success) Sequence of all st.success elements. Individual elements can be accessed from an ElementList by index (order on the page). For example, at.success[0] for the first element. Success is an extension of the Element class. AppTest.statusStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.status elements. Function signature[source] AppTest.status Returns(Sequence of Status) Sequence of all st.status elements. Individual elements can be accessed from a Sequence by index (order on the page). For example, at.status[0] for the first element. Status is an extension of the Block class. AppTest.tableStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.table elements. Function signature[source] AppTest.table Returns(ElementList of Table) Sequence of all st.table elements. Individual elements can be accessed from an ElementList by index (order on the page). For example, at.table[0] for the first element. Table is an extension of the Element class. AppTest.tabsStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all tabs within st.tabs elements. Each tab within a single st.tabs will be returned as a separate Tab in the Sequence. Additionally, the tab labels are forwarded to each Tab element as a property. For example, st.tabs(""A"",""B"") will yield two Tab objects, with Tab.label returning ""A"" and ""B"", respectively. Function signature[source] AppTest.tabs Returns(Sequence of Tab) Sequence of all tabs within st.tabs elements. Individual tabs can be accessed from an ElementList by index (order on the page). For example, at.tabs[0] for the first tab. Tab is an extension of the Block class. AppTest.textStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.text elements. Function signature[source] AppTest.text Returns(ElementList of Text) Sequence of all st.text elements. Individual elements can be accessed from an ElementList by index (order on the page). For example, at.text[0] for the first element. Text is an extension of the Element class. AppTest.text_areaStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.text_area widgets. Function signature[source] AppTest.text_area Returns(WidgetList of TextArea) Sequence of all st.text_area widgets. Individual widgets can be accessed from a WidgetList by index (order on the page) or key. For example, at.text_area[0] for the first widget or at.text_area(key=""my_key"") for a widget with a given key. AppTest.text_inputStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.text_input widgets. Function signature[source] AppTest.text_input Returns(WidgetList of TextInput) Sequence of all st.text_input widgets. Individual widgets can be accessed from a WidgetList by index (order on the page) or key. For example, at.text_input[0] for the first widget or at.text_input(key=""my_key"") for a widget with a given key. AppTest.time_inputStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.time_input widgets. Function signature[source] AppTest.time_input Returns(WidgetList of TimeInput) Sequence of all st.time_input widgets. Individual widgets can be accessed from a WidgetList by index (order on the page) or key. For example, at.time_input[0] for the first widget or at.time_input(key=""my_key"") for a widget with a given key. AppTest.titleStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.title elements. Function signature[source] AppTest.title Returns(ElementList of Title) Sequence of all st.title elements. Individual elements can be accessed from an ElementList by index (order on the page). For example, at.title[0] for the first element. Title is an extension of the Element class. AppTest.toastStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.toast elements. Function signature[source] AppTest.toast Returns(ElementList of Toast) Sequence of all st.toast elements. Individual elements can be accessed from an ElementList by index (order on the page). For example, at.toast[0] for the first element. Toast is an extension of the Element class. AppTest.toggleStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.toggle widgets. Function signature[source] AppTest.toggle Returns(WidgetList of Toggle) Sequence of all st.toggle widgets. Individual widgets can be accessed from a WidgetList by index (order on the page) or key. For example, at.toggle[0] for the first widget or at.toggle(key=""my_key"") for a widget with a given key. AppTest.warningStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.warning elements. Function signature[source] AppTest.warning Returns(ElementList of Warning) Sequence of all st.warning elements. Individual elements can be accessed from an ElementList by index (order on the page). For example, at.warning[0] for the first element. Warning is an extension of the Element class. Previous: App testingNext: Testing element classesforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy" https://docs.streamlit.io/develop/api-reference/app-testing/st.testing.v1.apptest#apptestwarning,"DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceremovePAGE ELEMENTSWrite and magicaddText elementsaddData elementsaddChart elementsaddInput widgetsaddMedia elementsaddLayouts and containersaddChat elementsaddStatus elementsaddThird-party componentsopen_in_newAPPLICATION LOGICNavigation and pagesaddExecution flowaddCaching and stateaddConnections and secretsaddCustom componentsaddUtilitiesaddConfigurationaddTOOLSApp testingremovest.testing.v1.AppTestTesting element classesCommand lineaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Develop/API reference/App testing/st.testing.v1.AppTest The AppTest class st.testing.v1.AppTestStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA simulated Streamlit app to check the correctness of displayed elements and outputs. An instance of AppTest simulates a running Streamlit app. This class provides methods to set up, manipulate, and inspect the app contents via API instead of a browser UI. It can be used to write automated tests of an app in various scenarios. These can then be run using a tool like pytest. AppTest can be initialized by one of three class methods: st.testing.v1.AppTest.from_file (recommended) st.testing.v1.AppTest.from_string st.testing.v1.AppTest.from_function Once initialized, Session State and widget values can be updated and the script can be run. Unlike an actual live-running Streamlit app, you need to call AppTest.run() explicitly to re-run the app after changing a widget value. Switching pages also requires an explicit, follow-up call to AppTest.run(). AppTest enables developers to build tests on their app as-is, in the familiar python test format, without major refactoring or abstracting out logic to be tested separately from the UI. Tests can run quickly with very low overhead. A typical pattern is to build a suite of tests for an app that ensure consistent functionality as the app evolves, and run the tests locally and/or in a CI environment like Github Actions. Note AppTest only supports testing a single page of an app per instance. For multipage apps, each page will need to be tested separately. No methods exist to programatically switch pages within AppTest. Class description[source] st.testing.v1.AppTest(script_path, *, default_timeout, args=None, kwargs=None) Methods get(element_type) Get elements or widgets of the specified type. run(*, timeout=None) Run the script from the current state. switch_page(page_path) Switch to another page of the app. Attributes secrets (dict[str, Any]) Dictionary of secrets to be used the simulated app. Use dict-like syntax to set secret values for the simulated app. session_state (SafeSessionState) Session State for the simulated app. SafeSessionState object supports read and write operations as usual for Streamlit apps. query_params (dict[str, Any]) Dictionary of query parameters to be used by the simluated app. Use dict-like syntax to set query_params values for the simulated app. button Sequence of all st.button and st.form_submit_button widgets. caption Sequence of all st.caption elements. chat_input Sequence of all st.chat_input widgets. chat_message Sequence of all st.chat_message elements. checkbox Sequence of all st.checkbox widgets. code Sequence of all st.code elements. color_picker Sequence of all st.color_picker widgets. columns Sequence of all columns within st.columns elements. dataframe Sequence of all st.dataframe elements. date_input Sequence of all st.date_input widgets. divider Sequence of all st.divider elements. error Sequence of all st.error elements. exception Sequence of all st.exception elements. expander Sequence of all st.expander elements. header Sequence of all st.header elements. info Sequence of all st.info elements. json Sequence of all st.json elements. latex Sequence of all st.latex elements. main Sequence of elements within the main body of the app. markdown Sequence of all st.markdown elements. metric Sequence of all st.metric elements. multiselect Sequence of all st.multiselect widgets. number_input Sequence of all st.number_input widgets. radio Sequence of all st.radio widgets. select_slider Sequence of all st.select_slider widgets. selectbox Sequence of all st.selectbox widgets. sidebar Sequence of all elements within st.sidebar. slider Sequence of all st.slider widgets. status Sequence of all st.status elements. subheader Sequence of all st.subheader elements. success Sequence of all st.success elements. table Sequence of all st.table elements. tabs Sequence of all tabs within st.tabs elements. text Sequence of all st.text elements. text_area Sequence of all st.text_area widgets. text_input Sequence of all st.text_input widgets. time_input Sequence of all st.time_input widgets. title Sequence of all st.title elements. toast Sequence of all st.toast elements. toggle Sequence of all st.toggle widgets. warning Sequence of all st.warning elements. Initialize a simulated app using AppTest AppTest.from_fileStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeCreate an instance of AppTest to simulate an app page defined within a file. This option is most convenient for CI workflows and testing of published apps. The script must be executable on its own and so must contain all necessary imports. Function signature[source] AppTest.from_file(cls, script_path, *, default_timeout=3) Parameters script_path (str) Path to a script file. The path should be absolute or relative to the file calling .from_file. default_timeout (float) Default time in seconds before a script run is timed out. Can be overridden for individual .run() calls. Returns(AppTest) A simulated Streamlit app for testing. The simulated app can be executed via .run(). AppTest.from_stringStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeCreate an instance of AppTest to simulate an app page defined within a string. This is useful for testing short scripts that fit comfortably as an inline string in the test itself, without having to create a separate file for it. The script must be executable on its own and so must contain all necessary imports. Function signature[source] AppTest.from_string(cls, script, *, default_timeout=3) Parameters script (str) The string contents of the script to be run. default_timeout (float) Default time in seconds before a script run is timed out. Can be overridden for individual .run() calls. Returns(AppTest) A simulated Streamlit app for testing. The simulated app can be executed via .run(). AppTest.from_functionStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeCreate an instance of AppTest to simulate an app page defined within a function. This is similar to AppTest.from_string(), but more convenient to write with IDE assistance. The script must be executable on its own and so must contain all necessary imports. Function signature[source] AppTest.from_function(cls, script, *, default_timeout=3, args=None, kwargs=None) Parameters script (Callable) A function whose body will be used as a script. Must be runnable in isolation, so it must include any necessary imports. default_timeout (float) Default time in seconds before a script run is timed out. Can be overridden for individual .run() calls. args (tuple) An optional tuple of args to pass to the script function. kwargs (dict) An optional dict of kwargs to pass to the script function. Returns(AppTest) A simulated Streamlit app for testing. The simulated app can be executed via .run(). Run an AppTest script AppTest.runStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeRun the script from the current state. This is equivalent to manually rerunning the app or the rerun that occurs upon user interaction. AppTest.run() must be manually called after updating a widget value or switching pages as script reruns do not occur automatically as they do for live-running Streamlit apps. Function signature[source] AppTest.run(*, timeout=None) Parameters timeout (null) The maximum number of seconds to run the script. None means use the default timeout set for the instance of AppTest. Returns(AppTest) self AppTest.switch_pageStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSwitch to another page of the app. This method does not automatically rerun the app. Use a follow-up call to AppTest.run() to obtain the elements on the selected page. Function signature[source] AppTest.switch_page(page_path) Parameters page_path (str) Path of the page to switch to. The path must be relative to the main script's location (e.g. ""pages/my_page.py""). Returns(AppTest) self Get AppTest script elements The main value of AppTest is providing an API to programmatically inspect and interact with the elements and widgets produced by a running Streamlit app. Using the AppTest. properties or AppTest.get() method returns a collection of all the elements or widgets of the specified type that would have been displayed by running the app. Note that you can also retrieve elements within a specific container in the same way - first retrieve the container, then retrieve the elements just in that container. AppTest.getStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeGet elements or widgets of the specified type. This method returns the collection of all elements or widgets of the specified type on the current page. Retrieve a specific element by using its index (order on page) or key lookup. Function signature[source] AppTest.get(element_type) Parameters element_type (str) An element attribute of AppTest. For example, ""button"", ""caption"", or ""chat_input"". Returns(Sequence of Elements) Sequence of elements of the given type. Individual elements can be accessed from a Sequence by index (order on the page). When getting and element_type that is a widget, individual widgets can be accessed by key. For example, at.get(""text"")[0] for the first st.text element or at.get(""slider"")(key=""my_key"") for the st.slider widget with a given key. AppTest.buttonStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.button and st.form_submit_button widgets. Function signature[source] AppTest.button Returns(WidgetList of Button) Sequence of all st.button and st.form_submit_button widgets. Individual widgets can be accessed from a WidgetList by index (order on the page) or key. For example, at.button[0] for the first widget or at.button(key=""my_key"") for a widget with a given key. AppTest.captionStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.caption elements. Function signature[source] AppTest.caption Returns(ElementList of Caption) Sequence of all st.caption elements. Individual elements can be accessed from an ElementList by index (order on the page). For example, at.caption[0] for the first element. Caption is an extension of the Element class. AppTest.chat_inputStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.chat_input widgets. Function signature[source] AppTest.chat_input Returns(WidgetList of ChatInput) Sequence of all st.chat_input widgets. Individual widgets can be accessed from a WidgetList by index (order on the page) or key. For example, at.chat_input[0] for the first widget or at.chat_input(key=""my_key"") for a widget with a given key. AppTest.chat_messageStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.chat_message elements. Function signature[source] AppTest.chat_message Returns(Sequence of ChatMessage) Sequence of all st.chat_message elements. Individual elements can be accessed from an ElementList by index (order on the page). For example, at.chat_message[0] for the first element. ChatMessage is an extension of the Block class. AppTest.checkboxStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.checkbox widgets. Function signature[source] AppTest.checkbox Returns(WidgetList of Checkbox) Sequence of all st.checkbox widgets. Individual widgets can be accessed from a WidgetList by index (order on the page) or key. For example, at.checkbox[0] for the first widget or at.checkbox(key=""my_key"") for a widget with a given key. AppTest.codeStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.code elements. Function signature[source] AppTest.code Returns(ElementList of Code) Sequence of all st.code elements. Individual elements can be accessed from an ElementList by index (order on the page). For example, at.code[0] for the first element. Code is an extension of the Element class. AppTest.color_pickerStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.color_picker widgets. Function signature[source] AppTest.color_picker Returns(WidgetList of ColorPicker) Sequence of all st.color_picker widgets. Individual widgets can be accessed from a WidgetList by index (order on the page) or key. For example, at.color_picker[0] for the first widget or at.color_picker(key=""my_key"") for a widget with a given key. AppTest.columnsStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all columns within st.columns elements. Each column within a single st.columns will be returned as a separate Column in the Sequence. Function signature[source] AppTest.columns Returns(Sequence of Column) Sequence of all columns within st.columns elements. Individual columns can be accessed from an ElementList by index (order on the page). For example, at.columns[0] for the first column. Column is an extension of the Block class. AppTest.dataframeStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.dataframe elements. Function signature[source] AppTest.dataframe Returns(ElementList of Dataframe) Sequence of all st.dataframe elements. Individual elements can be accessed from an ElementList by index (order on the page). For example, at.dataframe[0] for the first element. Dataframe is an extension of the Element class. AppTest.date_inputStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.date_input widgets. Function signature[source] AppTest.date_input Returns(WidgetList of DateInput) Sequence of all st.date_input widgets. Individual widgets can be accessed from a WidgetList by index (order on the page) or key. For example, at.date_input[0] for the first widget or at.date_input(key=""my_key"") for a widget with a given key. AppTest.dividerStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.divider elements. Function signature[source] AppTest.divider Returns(ElementList of Divider) Sequence of all st.divider elements. Individual elements can be accessed from an ElementList by index (order on the page). For example, at.divider[0] for the first element. Divider is an extension of the Element class. AppTest.errorStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.error elements. Function signature[source] AppTest.error Returns(ElementList of Error) Sequence of all st.error elements. Individual elements can be accessed from an ElementList by index (order on the page). For example, at.error[0] for the first element. Error is an extension of the Element class. AppTest.exceptionStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.exception elements. Function signature[source] AppTest.exception Returns(ElementList of Exception) Sequence of all st.exception elements. Individual elements can be accessed from an ElementList by index (order on the page). For example, at.exception[0] for the first element. Exception is an extension of the Element class. AppTest.expanderStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.expander elements. Function signature[source] AppTest.expander Returns(Sequence of Expandable) Sequence of all st.expander elements. Individual elements can be accessed from a Sequence by index (order on the page). For example, at.expander[0] for the first element. Expandable is an extension of the Block class. AppTest.headerStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.header elements. Function signature[source] AppTest.header Returns(ElementList of Header) Sequence of all st.header elements. Individual elements can be accessed from an ElementList by index (order on the page). For example, at.header[0] for the first element. Header is an extension of the Element class. AppTest.infoStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.info elements. Function signature[source] AppTest.info Returns(ElementList of Info) Sequence of all st.info elements. Individual elements can be accessed from an ElementList by index (order on the page). For example, at.info[0] for the first element. Info is an extension of the Element class. AppTest.jsonStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.json elements. Function signature[source] AppTest.json Returns(ElementList of Json) Sequence of all st.json elements. Individual elements can be accessed from an ElementList by index (order on the page). For example, at.json[0] for the first element. Json is an extension of the Element class. AppTest.latexStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.latex elements. Function signature[source] AppTest.latex Returns(ElementList of Latex) Sequence of all st.latex elements. Individual elements can be accessed from an ElementList by index (order on the page). For example, at.latex[0] for the first element. Latex is an extension of the Element class. AppTest.mainStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of elements within the main body of the app. Function signature[source] AppTest.main Returns(Block) A container of elements. Block can be queried for elements in the same manner as AppTest. For example, Block.checkbox will return all st.checkbox within the associated container. AppTest.markdownStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.markdown elements. Function signature[source] AppTest.markdown Returns(ElementList of Markdown) Sequence of all st.markdown elements. Individual elements can be accessed from an ElementList by index (order on the page). For example, at.markdown[0] for the first element. Markdown is an extension of the Element class. AppTest.metricStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.metric elements. Function signature[source] AppTest.metric Returns(ElementList of Metric) Sequence of all st.metric elements. Individual elements can be accessed from an ElementList by index (order on the page). For example, at.metric[0] for the first element. Metric is an extension of the Element class. AppTest.multiselectStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.multiselect widgets. Function signature[source] AppTest.multiselect Returns(WidgetList of Multiselect) Sequence of all st.multiselect widgets. Individual widgets can be accessed from a WidgetList by index (order on the page) or key. For example, at.multiselect[0] for the first widget or at.multiselect(key=""my_key"") for a widget with a given key. AppTest.number_inputStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.number_input widgets. Function signature[source] AppTest.number_input Returns(WidgetList of NumberInput) Sequence of all st.number_input widgets. Individual widgets can be accessed from a WidgetList by index (order on the page) or key. For example, at.number_input[0] for the first widget or at.number_input(key=""my_key"") for a widget with a given key. AppTest.radioStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.radio widgets. Function signature[source] AppTest.radio Returns(WidgetList of Radio) Sequence of all st.radio widgets. Individual widgets can be accessed from a WidgetList by index (order on the page) or key. For example, at.radio[0] for the first widget or at.radio(key=""my_key"") for a widget with a given key. AppTest.select_sliderStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.select_slider widgets. Function signature[source] AppTest.select_slider Returns(WidgetList of SelectSlider) Sequence of all st.select_slider widgets. Individual widgets can be accessed from a WidgetList by index (order on the page) or key. For example, at.select_slider[0] for the first widget or at.select_slider(key=""my_key"") for a widget with a given key. AppTest.selectboxStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.selectbox widgets. Function signature[source] AppTest.selectbox Returns(WidgetList of Selectbox) Sequence of all st.selectbox widgets. Individual widgets can be accessed from a WidgetList by index (order on the page) or key. For example, at.selectbox[0] for the first widget or at.selectbox(key=""my_key"") for a widget with a given key. AppTest.sidebarStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all elements within st.sidebar. Function signature[source] AppTest.sidebar Returns(Block) A container of elements. Block can be queried for elements in the same manner as AppTest. For example, Block.checkbox will return all st.checkbox within the associated container. AppTest.sliderStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.slider widgets. Function signature[source] AppTest.slider Returns(WidgetList of Slider) Sequence of all st.slider widgets. Individual widgets can be accessed from a WidgetList by index (order on the page) or key. For example, at.slider[0] for the first widget or at.slider(key=""my_key"") for a widget with a given key. AppTest.subheaderStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.subheader elements. Function signature[source] AppTest.subheader Returns(ElementList of Subheader) Sequence of all st.subheader elements. Individual elements can be accessed from an ElementList by index (order on the page). For example, at.subheader[0] for the first element. Subheader is an extension of the Element class. AppTest.successStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.success elements. Function signature[source] AppTest.success Returns(ElementList of Success) Sequence of all st.success elements. Individual elements can be accessed from an ElementList by index (order on the page). For example, at.success[0] for the first element. Success is an extension of the Element class. AppTest.statusStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.status elements. Function signature[source] AppTest.status Returns(Sequence of Status) Sequence of all st.status elements. Individual elements can be accessed from a Sequence by index (order on the page). For example, at.status[0] for the first element. Status is an extension of the Block class. AppTest.tableStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.table elements. Function signature[source] AppTest.table Returns(ElementList of Table) Sequence of all st.table elements. Individual elements can be accessed from an ElementList by index (order on the page). For example, at.table[0] for the first element. Table is an extension of the Element class. AppTest.tabsStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all tabs within st.tabs elements. Each tab within a single st.tabs will be returned as a separate Tab in the Sequence. Additionally, the tab labels are forwarded to each Tab element as a property. For example, st.tabs(""A"",""B"") will yield two Tab objects, with Tab.label returning ""A"" and ""B"", respectively. Function signature[source] AppTest.tabs Returns(Sequence of Tab) Sequence of all tabs within st.tabs elements. Individual tabs can be accessed from an ElementList by index (order on the page). For example, at.tabs[0] for the first tab. Tab is an extension of the Block class. AppTest.textStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.text elements. Function signature[source] AppTest.text Returns(ElementList of Text) Sequence of all st.text elements. Individual elements can be accessed from an ElementList by index (order on the page). For example, at.text[0] for the first element. Text is an extension of the Element class. AppTest.text_areaStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.text_area widgets. Function signature[source] AppTest.text_area Returns(WidgetList of TextArea) Sequence of all st.text_area widgets. Individual widgets can be accessed from a WidgetList by index (order on the page) or key. For example, at.text_area[0] for the first widget or at.text_area(key=""my_key"") for a widget with a given key. AppTest.text_inputStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.text_input widgets. Function signature[source] AppTest.text_input Returns(WidgetList of TextInput) Sequence of all st.text_input widgets. Individual widgets can be accessed from a WidgetList by index (order on the page) or key. For example, at.text_input[0] for the first widget or at.text_input(key=""my_key"") for a widget with a given key. AppTest.time_inputStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.time_input widgets. Function signature[source] AppTest.time_input Returns(WidgetList of TimeInput) Sequence of all st.time_input widgets. Individual widgets can be accessed from a WidgetList by index (order on the page) or key. For example, at.time_input[0] for the first widget or at.time_input(key=""my_key"") for a widget with a given key. AppTest.titleStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.title elements. Function signature[source] AppTest.title Returns(ElementList of Title) Sequence of all st.title elements. Individual elements can be accessed from an ElementList by index (order on the page). For example, at.title[0] for the first element. Title is an extension of the Element class. AppTest.toastStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.toast elements. Function signature[source] AppTest.toast Returns(ElementList of Toast) Sequence of all st.toast elements. Individual elements can be accessed from an ElementList by index (order on the page). For example, at.toast[0] for the first element. Toast is an extension of the Element class. AppTest.toggleStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.toggle widgets. Function signature[source] AppTest.toggle Returns(WidgetList of Toggle) Sequence of all st.toggle widgets. Individual widgets can be accessed from a WidgetList by index (order on the page) or key. For example, at.toggle[0] for the first widget or at.toggle(key=""my_key"") for a widget with a given key. AppTest.warningStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.warning elements. Function signature[source] AppTest.warning Returns(ElementList of Warning) Sequence of all st.warning elements. Individual elements can be accessed from an ElementList by index (order on the page). For example, at.warning[0] for the first element. Warning is an extension of the Element class. Previous: App testingNext: Testing element classesforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy" https://docs.streamlit.io/develop/api-reference/data#display-charts,"DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceremovePAGE ELEMENTSWrite and magicaddText elementsaddData elementsremovest.dataframest.data_editorst.column_configaddst.tablest.metricst.jsonChart elementsaddInput widgetsaddMedia elementsaddLayouts and containersaddChat elementsaddStatus elementsaddThird-party componentsopen_in_newAPPLICATION LOGICNavigation and pagesaddExecution flowaddCaching and stateaddConnections and secretsaddCustom componentsaddUtilitiesaddConfigurationaddTOOLSApp testingaddCommand lineaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Develop/API reference/Data elementsData elements When you're working with data, it is extremely valuable to visualize that data quickly, interactively, and from multiple different angles. That's what Streamlit is actually built and optimized for. You can display data via charts, and you can display it in raw form. These are the Streamlit commands you can use to display and interact with raw data. DataframesDisplay a dataframe as an interactive table.st.dataframe(my_data_frame) Data editorDisplay a data editor widget.edited = st.data_editor(df, num_rows=""dynamic"") Column configurationConfigure the display and editing behavior of dataframes and data editors.st.column_config.NumberColumn(""Price (in USD)"", min_value=0, format=""$%d"") Static tablesDisplay a static table.st.table(my_data_frame) MetricsDisplay a metric in big bold font, with an optional indicator of how the metric changed.st.metric(""My metric"", 42, 2) Dicts and JSONDisplay object or string as a pretty-printed JSON string.st.json(my_dict) Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration! PreviousImage CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates value = streamlit_image_coordinates(""https://placekitten.com/200/300"") st.write(value) Plotly EventsMake Plotly charts interactive!. Created by @null-jones.from streamlit_plotly_events import plotly_events fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.metric_cards import style_metric_cards col3.metric(label=""No Change"", value=5000, delta=0) style_metric_cards() Streamlit AggridImplementation of Ag-Grid component for Streamlit. Created by @PablocFonseca.df = pd.DataFrame({'col1': [1, 2, 3], 'col2': [4, 5, 6]}) grid_return = AgGrid(df, editable=True) new_df = grid_return['data'] Streamlit FoliumStreamlit Component for rendering Folium maps. Created by @randyzwitch.m = folium.Map(location=[39.949610, -75.150282], zoom_start=16) folium.Marker([39.949610, -75.150282], popup=""Liberty Bell"", tooltip=""Liberty Bell"").add_to(m) st_data = st_folium(m, width=725) Pandas ProfilingPandas profiling component for Streamlit. Created by @okld.df = pd.read_csv(""https://storage.googleapis.com/tf-datasets/titanic/train.csv"") pr = df.profile_report() st_profile_report(pr) Image CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates value = streamlit_image_coordinates(""https://placekitten.com/200/300"") st.write(value) Plotly EventsMake Plotly charts interactive!. Created by @null-jones.from streamlit_plotly_events import plotly_events fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.metric_cards import style_metric_cards col3.metric(label=""No Change"", value=5000, delta=0) style_metric_cards() Streamlit AggridImplementation of Ag-Grid component for Streamlit. Created by @PablocFonseca.df = pd.DataFrame({'col1': [1, 2, 3], 'col2': [4, 5, 6]}) grid_return = AgGrid(df, editable=True) new_df = grid_return['data'] Streamlit FoliumStreamlit Component for rendering Folium maps. Created by @randyzwitch.m = folium.Map(location=[39.949610, -75.150282], zoom_start=16) folium.Marker([39.949610, -75.150282], popup=""Liberty Bell"", tooltip=""Liberty Bell"").add_to(m) st_data = st_folium(m, width=725) Pandas ProfilingPandas profiling component for Streamlit. Created by @okld.df = pd.read_csv(""https://storage.googleapis.com/tf-datasets/titanic/train.csv"") pr = df.profile_report() st_profile_report(pr) Image CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates value = streamlit_image_coordinates(""https://placekitten.com/200/300"") st.write(value) Plotly EventsMake Plotly charts interactive!. Created by @null-jones.from streamlit_plotly_events import plotly_events fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.metric_cards import style_metric_cards col3.metric(label=""No Change"", value=5000, delta=0) style_metric_cards() NextPrevious: Text elementsNext: st.dataframeforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy" https://docs.streamlit.io/deploy/streamlit-community-cloud/manage-your-app#developer-view,"DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudremoveGet startedaddDeploy your appaddManage your appremoveApp analyticsApp settingsDelete your appEdit your appFavorite your appReboot your appShare your appaddManage your accountaddTroubleshootingStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Deploy/Streamlit Community Cloud/Manage your appManage your app You can manage your deployed app from your workspace at share.streamlit.io or directly from .streamlit.app. You can view, deploy, delete, reboot, or favorite an app. Manage your app from your workspace Streamlit Community Cloud is organized into workspaces, which automatically group your apps according to the corresponding GitHub repository's owner. Your workspace is indicated in the upper-right corner. You will have one workspace that matches your GitHub username and additional workspaces for any GitHub organization or user who has granted you access. Additionally, if you have view-only access to an app, you will be able to see that app's workspace. When you do not have developer access to an app, your management options for that app will be restricted as shown in the following sections. To deploy or manage any app, always switch to the workspace matching the repository's owner first. At the top of your workspace, ""Analytics"" is a shortcut to App analytics and ""Settings"" links to your Workspace settings (not to be confused with App settings for each of your apps). App overflow menus Each app has a menu accessible from the overflow icon (more_vert) to the right. Copy URL — See Copy your app's URL Edit — See Edit your app with GitHub Codespaces Favorite — See Favorite your app Analytics — See App analytics Reboot — See Reboot your app Delete — See Delete your app Settings — See App settings If you have view-only access to an app, options will be restricted in that app's menu. Manage your app directly from your app You can manage your deployed app directly from the app itself! Just make sure you are signed in to Streamlit Community Cloud then visit your app. Streamlit Community Cloud logs From your app at .streamlit.app, click ""Manage app"" in the lower-right corner. Once you've clicked on ""Manage app"", you will be able to view your app's logs. This is your primary place to troubleshoot any issues with your app. You can access more developer options by clicking the overflow icon (more_vert) at the bottom of your Cloud logs. To conveniently download your logs, click ""Download log"". Other options accessible from Cloud logs are: Analytics — See App analytics. Reboot app — See Reboot your app. Delete app — See Delete your app. Settings — See App settings. Your apps — Takes you to your app workspace. Documentation — Takes you to our documentation. Support — Takes you to our forums! App menus From your app at .streamlit.app, you can always access your app's menu just like you can when developing locally. The option to deploy your app is removed, but you can still clear your cache from here. Manage your app in GitHub Update your app Your GitHub repository is the source for the app, so that means that any time you push an update to your repo you'll see it reflected in the app in almost real time. Try it out! Streamlit also smartly detects whether you touched your dependencies, in which case it will automatically do a full redeploy for you—which will take a little more time. But since most updates don't involve dependency changes, you should usually see your app update in real time. Add or remove dependencies You can add/remove dependencies at any point by updating requirements.txt (Python dependenciess) or packages.txt (Linux dependencies) and committing the changes to your repository on GitHub. This will cause Streamlit Community Cloud to detect there was a change in your dependencies and automatically trigger (re)installation. It is best practice to pin your Streamlit version in requirements.txt. Otherwise, the version may be auto-upgraded at any point without your knowledge, which could lead to undesired results (e.g. when we deprecate a feature in Streamlit). App resources and limits Resource limits All Streamlit Community Cloud users have access to the same resources and are subject to the same limits. These limits may change at any time without notice. If your app meets or exceeds its limits, it may slow down from throttling or become nonfunctional. The limits as of February 2024 are approximately as follows: CPU: 0.078 cores minimum, 2 cores maximum Memory: 690MB minimum, 2.7GBs maximum Storage: No minimum, 50GB maximum Symptoms that your app is running out of resources include the following: Your app is running slowly. Your app displays ""🤯 This app has gone over its resource limits."" Your app displays ""😦 Oh no."" Good for the world Streamlit offers increased resources for apps with good-for-the-world use cases. Generally, these apps are used by an educational institution or nonprofit organization, are part of an open-source project, or benefit the world in some way. If your app is not primarily used by a for-profit company you can apply for increased resources. If you are an educator or student looking to deploy additional private apps, please apply to our education program instead. Optimizing your app If your app is running slow or showing the error pages mentioned above, we first highly recommend going through and implementing the suggestions in the following blog posts to prevent your app from hitting the resource limits and to detect if your Streamlit app leaks memory: Common app problems: Resource limits 3 steps to fix app memory leaks If your app exceeds its resource limits, developers and viewers alike will see ""😦 Oh no."" If see ""😦 Oh no."" when viewing your app, first check your Cloud logs for any specific errors. If there are no errors in your Cloud logs you are likely dealing with a resource issue. Developer view If you are logged into a developer account for an app over its limits, you can access ""Manage app"" from the lower-right corner of the app to reboot it and clear its memory. ""Manage app"" will be red and have a warning icon (error). App hibernation All apps without traffic for 7 consecutive days will automatically go to sleep. This is done to alleviate resources and allow the best communal use of the platform! If you would like to keep your app awake, simply visit the app to create traffic or commit your app's repository, even if it's an empty commit! If left alone your app will go to sleep at the 7 day mark. When someone visits the app after this, they will see the sleeping page: To wake the app up, click ""Yes, get this app back up!"" This can be done by anyone who has access to view the app, not just the app developer! You can see which of your apps are asleep from your workspace. Sleeping apps have a moon icon (bedtime) to the right. Previous: Deploy your appNext: App analyticsforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy" https://docs.streamlit.io/knowledge-base/using-streamlit/where-file-uploader-store-when-deleted#where-does-stfile_uploader-store-uploaded-files-and-when-do-they-get-deleted,"DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Knowledge base/FAQ/Where does st.file_uploader store uploaded files and when do they get deleted?Where does st.file_uploader store uploaded files and when do they get deleted? When you upload a file using st.file_uploader, the data are copied to the Streamlit backend via the browser, and contained in a BytesIO buffer in Python memory (i.e. RAM, not disk). The data will persist in RAM until the Streamlit app re-runs from top-to-bottom, which is on each widget interaction. If you need to save the data that was uploaded between runs, then you can cache it so that Streamlit persists it across re-runs. As files are stored in memory, they get deleted immediately as soon as they’re not needed anymore. This means Streamlit removes a file from memory when: The user uploads another file, replacing the original one The user clears the file uploader The user closes the browser tab where they uploaded the file Related forum posts: https://discuss.streamlit.io/t/streamlit-sharing-fileupload-where-does-it-go/9267 https://discuss.streamlit.io/t/how-to-update-the-uploaded-file-using-file-uploader/13512/ Previous: What browsers does Streamlit support?Next: Widget updating for every second input when using session stateforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy" https://docs.streamlit.io/develop/api-reference/widgets/st.time_input#sttime_input,"DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceremovePAGE ELEMENTSWrite and magicaddText elementsaddData elementsaddChart elementsaddInput widgetsremoveBUTTONSst.buttonst.download_buttonst.form_submit_buttonlinkst.link_buttonst.page_linkSELECTIONSst.checkboxst.color_pickerst.multiselectst.radiost.selectboxst.select_sliderst.toggleNUMERICst.number_inputst.sliderDATE & TIMEst.date_inputst.time_inputTEXTst.chat_inputlinkst.text_areast.text_inputMEDIA & FILESst.camera_inputst.data_editorlinkst.file_uploaderMedia elementsaddLayouts and containersaddChat elementsaddStatus elementsaddThird-party componentsopen_in_newAPPLICATION LOGICNavigation and pagesaddExecution flowaddCaching and stateaddConnections and secretsaddCustom componentsaddUtilitiesaddConfigurationaddTOOLSApp testingaddCommand lineaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Develop/API reference/Input widgets/st.time_inputst.time_inputStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeDisplay a time input widget. Function signature[source] st.time_input(label, value=""now"", key=None, help=None, on_change=None, args=None, kwargs=None, *, disabled=False, label_visibility=""visible"", step=0:15:00) Parameters label (str) A short label explaining to the user what this time input is for. The label can optionally contain Markdown and supports the following elements: Bold, Italics, Strikethroughs, Inline Code, Emojis, and Links. This also supports: Emoji shortcodes, such as :+1: and :sunglasses:. For a list of all supported codes, see https://share.streamlit.io/streamlit/emoji-shortcodes. LaTeX expressions, by wrapping them in ""$"" or ""$$"" (the ""$$"" must be on their own lines). Supported LaTeX functions are listed at https://katex.org/docs/supported.html. Colored text and background colors for text, using the syntax :color[text to be colored] and :color-background[text to be colored], respectively. color must be replaced with any of the following supported colors: blue, green, orange, red, violet, gray/grey, rainbow. For example, you can use :orange[your text here] or :blue-background[your text here]. Unsupported elements are unwrapped so only their children (text contents) render. Display unsupported elements as literal characters by backslash-escaping them. E.g. 1\. Not an ordered list. For accessibility reasons, you should never set an empty label (label="""") but hide it with label_visibility if needed. In the future, we may disallow empty labels by raising an exception. value (datetime.time/datetime.datetime, ""now"" or None) The value of this widget when it first renders. This will be cast to str internally. If None, will initialize empty and return None until the user selects a time. If ""now"" (default), will initialize with the current time. key (str or int) An optional string or integer to use as the unique key for the widget. If this is omitted, a key will be generated for the widget based on its content. Multiple widgets of the same type may not share the same key. help (str) An optional tooltip that gets displayed next to the input. on_change (callable) An optional callback invoked when this time_input's value changes. args (tuple) An optional tuple of args to pass to the callback. kwargs (dict) An optional dict of kwargs to pass to the callback. disabled (bool) An optional boolean, which disables the time input if set to True. The default is False. label_visibility (""visible"", ""hidden"", or ""collapsed"") The visibility of the label. If ""hidden"", the label doesn't show but there is still empty space for it above the widget (equivalent to label=""""). If ""collapsed"", both the label and the space are removed. Default is ""visible"". step (int or timedelta) The stepping interval in seconds. Defaults to 900, i.e. 15 minutes. You can also pass a datetime.timedelta object. Returns(datetime.time or None) The current value of the time input widget or None if no time has been selected. Example import datetime import streamlit as st t = st.time_input(""Set an alarm for"", datetime.time(8, 45)) st.write(""Alarm is set for"", t) Built with Streamlit 🎈Fullscreen open_in_new To initialize an empty time input, use None as the value: import datetime import streamlit as st t = st.time_input(""Set an alarm for"", value=None) st.write(""Alarm is set for"", t) Built with Streamlit 🎈Fullscreen open_in_new Previous: st.date_inputNext: st.chat_inputforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy" https://docs.streamlit.io/develop/concepts/configuration/serving-static-files#static-file-serving,"DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsremoveCOREArchitecture & executionaddMultipage appsaddApp designaddADDITIONALConnections and secretsaddCustom componentsaddConfiguration and themingremoveConfiguration optionsHTTPS supportServing static filesCustomize your themeApp testingaddAPI referenceaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Develop/Concepts/Configuration and theming/Serving static filesStatic file serving Streamlit apps can host and serve small, static media files to support media embedding use cases that won't work with the normal media elements. To enable this feature, set enableStaticServing = true under [server] in your config file, or environment variable STREAMLIT_SERVER_ENABLE_STATIC_SERVING=true. Media stored in the folder ./static/ relative to the running app file is served at path app/static/[filename], such as http://localhost:8501/app/static/cat.png. Details on usage Files with the following extensions will be served normally: "".jpg"", "".jpeg"", "".png"", "".gif"". Any other file will be sent with header Content-Type:text/plain which will cause browsers to render in plain text. This is included for security - other file types that need to render should be hosted outside the app. Streamlit also sets X-Content-Type-Options:nosniff for all files rendered from the static directory. For apps running on Streamlit Community Cloud: Files available in the Github repo will always be served. Any files generated while the app is running, such as based on user interaction (file upload, etc), are not guaranteed to persist across user sessions. Apps which store and serve many files, or large files, may run into resource limits and be shut down. Example usage Put an image cat.png in the folder ./static/ Add enableStaticServing = true under [server] in your .streamlit/config.toml Any media in the ./static/ folder is served at the relative URL like app/static/cat.png # .streamlit/config.toml [server] enableStaticServing = true # app.py import streamlit as st with st.echo(): st.title(""CAT"") st.markdown(""[![Click me](app/static/cat.png)](https://streamlit.io)"") Additional resources: https://docs.streamlit.io/develop/concepts/configuration https://static-file-serving.streamlit.app/ Built with Streamlit 🎈Fullscreen open_in_newPrevious: HTTPS supportNext: Customize your themeforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy" https://docs.streamlit.io/develop/api-reference#configuration,"DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceremovePAGE ELEMENTSWrite and magicaddText elementsaddData elementsaddChart elementsaddInput widgetsaddMedia elementsaddLayouts and containersaddChat elementsaddStatus elementsaddThird-party componentsopen_in_newAPPLICATION LOGICNavigation and pagesaddExecution flowaddCaching and stateaddConnections and secretsaddCustom componentsaddUtilitiesaddConfigurationaddTOOLSApp testingaddCommand lineaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Develop/API referenceAPI reference Streamlit makes it easy for you to visualize, mutate, and share data. The API reference is organized by activity type, like displaying data or optimizing performance. Each section includes methods associated with the activity type, including examples. Browse our API below and click to learn more about any of our available commands! 🎈 Display almost anything Write and magic st.writeWrite arguments to the app.st.write(""Hello **world**!"") st.write(my_data_frame) st.write(my_mpl_figure) st.write_streamWrite generators or streams to the app with a typewriter effect.st.write_stream(my_generator) st.write_stream(my_llm_stream) MagicAny time Streamlit sees either a variable or literal value on its own line, it automatically writes that to your app using st.write""Hello **world**!"" my_data_frame my_mpl_figure Text elements MarkdownDisplay string formatted as Markdown.st.markdown(""Hello **world**!"") TitleDisplay text in title formatting.st.title(""The app title"") HeaderDisplay text in header formatting.st.header(""This is a header"") SubheaderDisplay text in subheader formatting.st.subheader(""This is a subheader"") CaptionDisplay text in small font.st.caption(""This is written small caption text"") Code blockDisplay a code block with optional syntax highlighting.st.code(""a = 1234"") EchoDisplay some code in the app, then execute it. Useful for tutorials.with st.echo(): st.write('This code will be printed') LaTeXDisplay mathematical expressions formatted as LaTeX.st.latex(""\int a x^2 \,dx"") Preformatted textWrite fixed-width and preformatted text.st.text(""Hello world"") DividerDisplay a horizontal rule.st.divider() Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration! PreviousTagsAdd tags to your Streamlit apps. Created by @gagan3012.st_tags(label='# Enter Keywords:', text='Press enter to add more', value=['Zero', 'One', 'Two'], suggestions=['five', 'six', 'seven', 'eight', 'nine', 'three', 'eleven', 'ten', 'four'], maxtags = 4, key='1') NLUApply text mining on a dataframe. Created by @JohnSnowLabs.nlu.load('sentiment').predict('I love NLU! <3') Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.mention(label=""An awesome Streamlit App"", icon=""streamlit"", url=""https://extras.streamlit.app"",) Annotated textDisplay annotated text in Streamlit apps. Created by @tvst.annotated_text(""This "", (""is"", ""verb""), "" some "", (""annotated"", ""adj""), (""text"", ""noun""), "" for those of "", (""you"", ""pronoun""), "" who "", (""like"", ""verb""), "" this sort of "", (""thing"", ""noun""), ""."") Drawable CanvasProvides a sketching canvas using Fabric.js. Created by @andfanilo.st_canvas(fill_color=""rgba(255, 165, 0, 0.3)"", stroke_width=stroke_width, stroke_color=stroke_color, background_color=bg_color, background_image=Image.open(bg_image) if bg_image else None, update_streamlit=realtime_update, height=150, drawing_mode=drawing_mode, point_display_radius=point_display_radius if drawing_mode == 'point' else 0, key=""canvas"",) TagsAdd tags to your Streamlit apps. Created by @gagan3012.st_tags(label='# Enter Keywords:', text='Press enter to add more', value=['Zero', 'One', 'Two'], suggestions=['five', 'six', 'seven', 'eight', 'nine', 'three', 'eleven', 'ten', 'four'], maxtags = 4, key='1') NLUApply text mining on a dataframe. Created by @JohnSnowLabs.nlu.load('sentiment').predict('I love NLU! <3') Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.mention(label=""An awesome Streamlit App"", icon=""streamlit"", url=""https://extras.streamlit.app"",) Annotated textDisplay annotated text in Streamlit apps. Created by @tvst.annotated_text(""This "", (""is"", ""verb""), "" some "", (""annotated"", ""adj""), (""text"", ""noun""), "" for those of "", (""you"", ""pronoun""), "" who "", (""like"", ""verb""), "" this sort of "", (""thing"", ""noun""), ""."") Drawable CanvasProvides a sketching canvas using Fabric.js. Created by @andfanilo.st_canvas(fill_color=""rgba(255, 165, 0, 0.3)"", stroke_width=stroke_width, stroke_color=stroke_color, background_color=bg_color, background_image=Image.open(bg_image) if bg_image else None, update_streamlit=realtime_update, height=150, drawing_mode=drawing_mode, point_display_radius=point_display_radius if drawing_mode == 'point' else 0, key=""canvas"",) TagsAdd tags to your Streamlit apps. Created by @gagan3012.st_tags(label='# Enter Keywords:', text='Press enter to add more', value=['Zero', 'One', 'Two'], suggestions=['five', 'six', 'seven', 'eight', 'nine', 'three', 'eleven', 'ten', 'four'], maxtags = 4, key='1') NLUApply text mining on a dataframe. Created by @JohnSnowLabs.nlu.load('sentiment').predict('I love NLU! <3') Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.mention(label=""An awesome Streamlit App"", icon=""streamlit"", url=""https://extras.streamlit.app"",) Next Data elements DataframesDisplay a dataframe as an interactive table.st.dataframe(my_data_frame) Data editorDisplay a data editor widget.edited = st.data_editor(df, num_rows=""dynamic"") Column configurationConfigure the display and editing behavior of dataframes and data editors.st.column_config.NumberColumn(""Price (in USD)"", min_value=0, format=""$%d"") Static tablesDisplay a static table.st.table(my_data_frame) MetricsDisplay a metric in big bold font, with an optional indicator of how the metric changed.st.metric(""My metric"", 42, 2) Dicts and JSONDisplay object or string as a pretty-printed JSON string.st.json(my_dict) Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration! PreviousImage CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates value = streamlit_image_coordinates(""https://placekitten.com/200/300"") st.write(value) Plotly EventsMake Plotly charts interactive!. Created by @null-jones.from streamlit_plotly_events import plotly_events fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.metric_cards import style_metric_cards col3.metric(label=""No Change"", value=5000, delta=0) style_metric_cards() Streamlit AggridImplementation of Ag-Grid component for Streamlit. Created by @PablocFonseca.df = pd.DataFrame({'col1': [1, 2, 3], 'col2': [4, 5, 6]}) grid_return = AgGrid(df, editable=True) new_df = grid_return['data'] Streamlit FoliumStreamlit Component for rendering Folium maps. Created by @randyzwitch.m = folium.Map(location=[39.949610, -75.150282], zoom_start=16) folium.Marker([39.949610, -75.150282], popup=""Liberty Bell"", tooltip=""Liberty Bell"").add_to(m) st_data = st_folium(m, width=725) Pandas ProfilingPandas profiling component for Streamlit. Created by @okld.df = pd.read_csv(""https://storage.googleapis.com/tf-datasets/titanic/train.csv"") pr = df.profile_report() st_profile_report(pr) Image CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates value = streamlit_image_coordinates(""https://placekitten.com/200/300"") st.write(value) Plotly EventsMake Plotly charts interactive!. Created by @null-jones.from streamlit_plotly_events import plotly_events fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.metric_cards import style_metric_cards col3.metric(label=""No Change"", value=5000, delta=0) style_metric_cards() Streamlit AggridImplementation of Ag-Grid component for Streamlit. Created by @PablocFonseca.df = pd.DataFrame({'col1': [1, 2, 3], 'col2': [4, 5, 6]}) grid_return = AgGrid(df, editable=True) new_df = grid_return['data'] Streamlit FoliumStreamlit Component for rendering Folium maps. Created by @randyzwitch.m = folium.Map(location=[39.949610, -75.150282], zoom_start=16) folium.Marker([39.949610, -75.150282], popup=""Liberty Bell"", tooltip=""Liberty Bell"").add_to(m) st_data = st_folium(m, width=725) Pandas ProfilingPandas profiling component for Streamlit. Created by @okld.df = pd.read_csv(""https://storage.googleapis.com/tf-datasets/titanic/train.csv"") pr = df.profile_report() st_profile_report(pr) Image CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates value = streamlit_image_coordinates(""https://placekitten.com/200/300"") st.write(value) Plotly EventsMake Plotly charts interactive!. Created by @null-jones.from streamlit_plotly_events import plotly_events fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.metric_cards import style_metric_cards col3.metric(label=""No Change"", value=5000, delta=0) style_metric_cards() Next Chart elements Simple area chartsDisplay an area chart.st.area_chart(my_data_frame) Simple bar chartsDisplay a bar chart.st.bar_chart(my_data_frame) Simple line chartsDisplay a line chart.st.line_chart(my_data_frame) Simple scatter chartsDisplay a line chart.st.scatter_chart(my_data_frame) Scatterplots on mapsDisplay a map with points on it.st.map(my_data_frame) MatplotlibDisplay a matplotlib.pyplot figure.st.pyplot(my_mpl_figure) AltairDisplay a chart using the Altair library.st.altair_chart(my_altair_chart) Vega-LiteDisplay a chart using the Vega-Lite library.st.vega_lite_chart(my_vega_lite_chart) PlotlyDisplay an interactive Plotly chart.st.plotly_chart(my_plotly_chart) BokehDisplay an interactive Bokeh chart.st.bokeh_chart(my_bokeh_chart) PyDeckDisplay a chart using the PyDeck library.st.pydeck_chart(my_pydeck_chart) GraphVizDisplay a graph using the dagre-d3 library.st.graphviz_chart(my_graphviz_spec) Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration! PreviousStreamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl(""https://assets5.lottiefiles.com/packages/lf20_V9t630.json"") st_lottie(lottie_hello, key=""hello"") Plotly EventsMake Plotly charts interactive!. Created by @null-jones.fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.chart += get_annotations_chart(annotations=[(""Mar 01, 2008"", ""Pretty good day for GOOG""), (""Dec 01, 2007"", ""Something's going wrong for GOOG & AAPL""), (""Nov 01, 2008"", ""Market starts again thanks to...""), (""Dec 01, 2009"", ""Small crash for GOOG after...""),],) st.altair_chart(chart, use_container_width=True) PlostA deceptively simple plotting library for Streamlit. Created by @tvst.import plost plost.line_chart(my_dataframe, x='time', y='stock_value', color='stock_name',) HiPlotHigh dimensional Interactive Plotting. Created by @facebookresearch.data = [{'dropout':0.1, 'lr': 0.001, 'loss': 10.0, 'optimizer': 'SGD'}, {'dropout':0.15, 'lr': 0.01, 'loss': 3.5, 'optimizer': 'Adam'}, {'dropout':0.3, 'lr': 0.1, 'loss': 4.5, 'optimizer': 'Adam'}] hip.Experiment.from_iterable(data).display() EChartsHigh dimensional Interactive Plotting. Created by @andfanilo.from streamlit_echarts import st_echarts st_echarts(options=options) Streamlit FoliumStreamlit Component for rendering Folium maps. Created by @randyzwitch.m = folium.Map(location=[39.949610, -75.150282], zoom_start=16) st_data = st_folium(m, width=725) Spacy-StreamlitspaCy building blocks and visualizers for Streamlit apps. Created by @explosion.models = [""en_core_web_sm"", ""en_core_web_md""] spacy_streamlit.visualize(models, ""Sundar Pichai is the CEO of Google."") Streamlit AgraphA Streamlit Graph Vis, based on react-grah-vis. Created by @ChrisDelClea.from streamlit_agraph import agraph, Node, Edge, Config agraph(nodes=nodes, edges=edges, config=config) Streamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl(""https://assets5.lottiefiles.com/packages/lf20_V9t630.json"") st_lottie(lottie_hello, key=""hello"") Plotly EventsMake Plotly charts interactive!. Created by @null-jones.fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.chart += get_annotations_chart(annotations=[(""Mar 01, 2008"", ""Pretty good day for GOOG""), (""Dec 01, 2007"", ""Something's going wrong for GOOG & AAPL""), (""Nov 01, 2008"", ""Market starts again thanks to...""), (""Dec 01, 2009"", ""Small crash for GOOG after...""),],) st.altair_chart(chart, use_container_width=True) PlostA deceptively simple plotting library for Streamlit. Created by @tvst.import plost plost.line_chart(my_dataframe, x='time', y='stock_value', color='stock_name',) HiPlotHigh dimensional Interactive Plotting. Created by @facebookresearch.data = [{'dropout':0.1, 'lr': 0.001, 'loss': 10.0, 'optimizer': 'SGD'}, {'dropout':0.15, 'lr': 0.01, 'loss': 3.5, 'optimizer': 'Adam'}, {'dropout':0.3, 'lr': 0.1, 'loss': 4.5, 'optimizer': 'Adam'}] hip.Experiment.from_iterable(data).display() EChartsHigh dimensional Interactive Plotting. Created by @andfanilo.from streamlit_echarts import st_echarts st_echarts(options=options) Streamlit FoliumStreamlit Component for rendering Folium maps. Created by @randyzwitch.m = folium.Map(location=[39.949610, -75.150282], zoom_start=16) st_data = st_folium(m, width=725) Spacy-StreamlitspaCy building blocks and visualizers for Streamlit apps. Created by @explosion.models = [""en_core_web_sm"", ""en_core_web_md""] spacy_streamlit.visualize(models, ""Sundar Pichai is the CEO of Google."") Streamlit AgraphA Streamlit Graph Vis, based on react-grah-vis. Created by @ChrisDelClea.from streamlit_agraph import agraph, Node, Edge, Config agraph(nodes=nodes, edges=edges, config=config) Streamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl(""https://assets5.lottiefiles.com/packages/lf20_V9t630.json"") st_lottie(lottie_hello, key=""hello"") Plotly EventsMake Plotly charts interactive!. Created by @null-jones.fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.chart += get_annotations_chart(annotations=[(""Mar 01, 2008"", ""Pretty good day for GOOG""), (""Dec 01, 2007"", ""Something's going wrong for GOOG & AAPL""), (""Nov 01, 2008"", ""Market starts again thanks to...""), (""Dec 01, 2009"", ""Small crash for GOOG after...""),],) st.altair_chart(chart, use_container_width=True) Next Input widgets ButtonDisplay a button widget.clicked = st.button(""Click me"") Download buttonDisplay a download button widget.st.download_button(""Download file"", file) Form buttonDisplay a form submit button. For use with st.form.st.form_submit_button(""Sign up"") Link buttonDisplay a link button.st.link_button(""Go to gallery"", url) Page linkDisplay a link to another page in a multipage app.st.page_link(""app.py"", label=""Home"", icon=""🏠"") st.page_link(""pages/profile.py"", label=""My profile"") CheckboxDisplay a checkbox widget.selected = st.checkbox(""I agree"") Color pickerDisplay a color picker widget.color = st.color_picker(""Pick a color"") MultiselectDisplay a multiselect widget. The multiselect widget starts as empty.choices = st.multiselect(""Buy"", [""milk"", ""apples"", ""potatoes""]) RadioDisplay a radio button widget.choice = st.radio(""Pick one"", [""cats"", ""dogs""]) SelectboxDisplay a select widget.choice = st.selectbox(""Pick one"", [""cats"", ""dogs""]) Select-sliderDisplay a slider widget to select items from a list.size = st.select_slider(""Pick a size"", [""S"", ""M"", ""L""]) ToggleDisplay a toggle widget.activated = st.toggle(""Activate"") Number inputDisplay a numeric input widget.choice = st.number_input(""Pick a number"", 0, 10) SliderDisplay a slider widget.number = st.slider(""Pick a number"", 0, 100) Date inputDisplay a date input widget.date = st.date_input(""Your birthday"") Time inputDisplay a time input widget.time = st.time_input(""Meeting time"") Chat inputDisplay a chat input widget.prompt = st.chat_input(""Say something"") if prompt: st.write(f""The user has sent: {prompt}"") Text-areaDisplay a multi-line text input widget.text = st.text_area(""Text to translate"") Text inputDisplay a single-line text input widget.name = st.text_input(""First name"") Data editorDisplay a data editor widget.edited = st.experimental_data_editor(df, num_rows=""dynamic"") File UploaderDisplay a file uploader widget.data = st.file_uploader(""Upload a CSV"") Camera inputDisplay a widget that allows users to upload images directly from a camera.image = st.camera_input(""Take a picture"") Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration! PreviousStreamlit ChatStreamlit Component for a Chatbot UI. Created by @AI-Yash.from streamlit_chat import message message(""My message"") message(""Hello bot!"", is_user=True) # align's the message to the right Streamlit Option MenuSelect a single item from a list of options in a menu. Created by @victoryhb.from streamlit_option_menu import option_menu option_menu(""Main Menu"", [""Home"", 'Settings'], icons=['house', 'gear'], menu_icon=""cast"", default_index=1) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.stoggle import stoggle stoggle( ""Click me!"", """"""🥷 Surprise! Here's some additional content"""""",) Streamlit ElementsCreate a draggable and resizable dashboard in Streamlit. Created by @okls.from streamlit_elements import elements, mui, html with elements(""new_element""): mui.Typography(""Hello world"") TagsAdd tags to your Streamlit apps. Created by @gagan3012.from streamlit_tags import st_tags st_tags(label='# Enter Keywords:', text='Press enter to add more', value=['Zero', 'One', 'Two'], suggestions=['five', 'six', 'seven', 'eight', 'nine', 'three', 'eleven', 'ten', 'four'], maxtags = 4, key='1') StqdmThe simplest way to handle a progress bar in streamlit app. Created by @Wirg.from stqdm import stqdm for _ in stqdm(range(50)): sleep(0.5) TimelineDisplay a Timeline in Streamlit apps using TimelineJS. Created by @innerdoc.from streamlit_timeline import timeline with open('example.json', ""r"") as f: timeline(f.read(), height=800) Camera input liveAlternative for st.camera_input which returns the webcam images live. Created by @blackary.from camera_input_live import camera_input_live image = camera_input_live() st.image(value) Streamlit AceAce editor component for Streamlit. Created by @okld.from streamlit_ace import st_ace content = st_ace() content Streamlit ChatStreamlit Component for a Chatbot UI. Created by @AI-Yash.from streamlit_chat import message message(""My message"") message(""Hello bot!"", is_user=True) # align's the message to the right Streamlit Option MenuSelect a single item from a list of options in a menu. Created by @victoryhb.from streamlit_option_menu import option_menu option_menu(""Main Menu"", [""Home"", 'Settings'], icons=['house', 'gear'], menu_icon=""cast"", default_index=1) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.stoggle import stoggle stoggle( ""Click me!"", """"""🥷 Surprise! Here's some additional content"""""",) Streamlit ElementsCreate a draggable and resizable dashboard in Streamlit. Created by @okls.from streamlit_elements import elements, mui, html with elements(""new_element""): mui.Typography(""Hello world"") TagsAdd tags to your Streamlit apps. Created by @gagan3012.from streamlit_tags import st_tags st_tags(label='# Enter Keywords:', text='Press enter to add more', value=['Zero', 'One', 'Two'], suggestions=['five', 'six', 'seven', 'eight', 'nine', 'three', 'eleven', 'ten', 'four'], maxtags = 4, key='1') StqdmThe simplest way to handle a progress bar in streamlit app. Created by @Wirg.from stqdm import stqdm for _ in stqdm(range(50)): sleep(0.5) TimelineDisplay a Timeline in Streamlit apps using TimelineJS. Created by @innerdoc.from streamlit_timeline import timeline with open('example.json', ""r"") as f: timeline(f.read(), height=800) Camera input liveAlternative for st.camera_input which returns the webcam images live. Created by @blackary.from camera_input_live import camera_input_live image = camera_input_live() st.image(value) Streamlit AceAce editor component for Streamlit. Created by @okld.from streamlit_ace import st_ace content = st_ace() content Streamlit ChatStreamlit Component for a Chatbot UI. Created by @AI-Yash.from streamlit_chat import message message(""My message"") message(""Hello bot!"", is_user=True) # align's the message to the right Streamlit Option MenuSelect a single item from a list of options in a menu. Created by @victoryhb.from streamlit_option_menu import option_menu option_menu(""Main Menu"", [""Home"", 'Settings'], icons=['house', 'gear'], menu_icon=""cast"", default_index=1) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.stoggle import stoggle stoggle( ""Click me!"", """"""🥷 Surprise! Here's some additional content"""""",) Next Media elements ImageDisplay an image or list of images.st.image(numpy_array) st.image(image_bytes) st.image(file) st.image(""https://example.com/myimage.jpg"") AudioDisplay an audio player.st.audio(numpy_array) st.audio(audio_bytes) st.audio(file) st.audio(""https://example.com/myaudio.mp3"", format=""audio/mp3"") VideoDisplay a video player.st.video(numpy_array) st.video(video_bytes) st.video(file) st.video(""https://example.com/myvideo.mp4"", format=""video/mp4"") Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration! PreviousStreamlit CropperA simple image cropper for Streamlit. Created by @turner-anderson.from streamlit_cropper import st_cropper st_cropper(img, realtime_update=realtime_update, box_color=box_color, aspect_ratio=aspect_ratio) Image CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates streamlit_image_coordinates(""https://placekitten.com/200/300"") Streamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl(""https://assets5.lottiefiles.com/packages/lf20_V9t630.json"") st_lottie(lottie_hello, key=""hello"") Streamlit WebrtcHandling and transmitting real-time video/audio streams with Streamlit. Created by @whitphx.from streamlit_webrtc import webrtc_streamer webrtc_streamer(key=""sample"") Drawable CanvasProvides a sketching canvas using Fabric.js. Created by @andfanilo.from streamlit_drawable_canvas import st_canvas st_canvas(fill_color=""rgba(255, 165, 0, 0.3)"", stroke_width=stroke_width, stroke_color=stroke_color, background_color=bg_color, background_image=Image.open(bg_image) if bg_image else None, update_streamlit=realtime_update, height=150, drawing_mode=drawing_mode, point_display_radius=point_display_radius if drawing_mode == 'point' else 0, key=""canvas"",) Image ComparisonCompare images with a slider using JuxtaposeJS. Created by @fcakyon.from streamlit_image_comparison import image_comparison image_comparison(img1=""image1.jpg"", img2=""image2.jpg"",) Streamlit CropperA simple image cropper for Streamlit. Created by @turner-anderson.from streamlit_cropper import st_cropper st_cropper(img, realtime_update=realtime_update, box_color=box_color, aspect_ratio=aspect_ratio) Image CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates streamlit_image_coordinates(""https://placekitten.com/200/300"") Streamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl(""https://assets5.lottiefiles.com/packages/lf20_V9t630.json"") st_lottie(lottie_hello, key=""hello"") Streamlit WebrtcHandling and transmitting real-time video/audio streams with Streamlit. Created by @whitphx.from streamlit_webrtc import webrtc_streamer webrtc_streamer(key=""sample"") Drawable CanvasProvides a sketching canvas using Fabric.js. Created by @andfanilo.from streamlit_drawable_canvas import st_canvas st_canvas(fill_color=""rgba(255, 165, 0, 0.3)"", stroke_width=stroke_width, stroke_color=stroke_color, background_color=bg_color, background_image=Image.open(bg_image) if bg_image else None, update_streamlit=realtime_update, height=150, drawing_mode=drawing_mode, point_display_radius=point_display_radius if drawing_mode == 'point' else 0, key=""canvas"",) Image ComparisonCompare images with a slider using JuxtaposeJS. Created by @fcakyon.from streamlit_image_comparison import image_comparison image_comparison(img1=""image1.jpg"", img2=""image2.jpg"",) Streamlit CropperA simple image cropper for Streamlit. Created by @turner-anderson.from streamlit_cropper import st_cropper st_cropper(img, realtime_update=realtime_update, box_color=box_color, aspect_ratio=aspect_ratio) Image CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates streamlit_image_coordinates(""https://placekitten.com/200/300"") Streamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl(""https://assets5.lottiefiles.com/packages/lf20_V9t630.json"") st_lottie(lottie_hello, key=""hello"") Next Layouts and containers ColumnsInsert containers laid out as side-by-side columns.col1, col2 = st.columns(2) col1.write(""this is column 1"") col2.write(""this is column 2"") ContainerInsert a multi-element container.c = st.container() st.write(""This will show last"") c.write(""This will show first"") c.write(""This will show second"") Modal dialogsInsert a modal dialog that can rerun independently from the rest of the script.@st.experimental_dialog(""Sign up"") def email_form(): name = st.text_input(""Name"") email = st.text_input(""Email"") EmptyInsert a single-element container.c = st.empty() st.write(""This will show last"") c.write(""This will be replaced"") c.write(""This will show first"") ExpanderInsert a multi-element container that can be expanded/collapsed.with st.expander(""Open to see more""): st.write(""This is more content"") PopoverInsert a multi-element popover container that can be opened/closed.with st.popover(""Settings""): st.checkbox(""Show completed"") SidebarDisplay items in a sidebar.st.sidebar.write(""This lives in the sidebar"") st.sidebar.button(""Click me!"") TabsInsert containers separated into tabs.tab1, tab2 = st.tabs([""Tab 1"", ""Tab2""]) tab1.write(""this is tab 1"") tab2.write(""this is tab 2"") Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration!Streamlit ElementsCreate a draggable and resizable dashboard in Streamlit. Created by @okls.from streamlit_elements import elements, mui, html with elements(""new_element""): mui.Typography(""Hello world"") PydanticAuto-generate Streamlit UI from Pydantic Models and Dataclasses. Created by @lukasmasuch.import streamlit_pydantic as sp sp.pydantic_form(key=""my_form"", model=ExampleModel) Streamlit PagesAn experimental version of Streamlit Multi-Page Apps. Created by @blackary.from st_pages import Page, show_pages, add_page_title show_pages([ Page(""streamlit_app.py"", ""Home"", ""🏠""), Page(""other_pages/page2.py"", ""Page 2"", "":books:""), ]) Chat elements Streamlit provides a few commands to help you build conversational apps. These chat elements are designed to be used in conjunction with each other, but you can also use them separately. st.chat_message lets you insert a chat message container into the app so you can display messages from the user or the app. Chat containers can contain other Streamlit elements, including charts, tables, text, and more. st.chat_input lets you display a chat input widget so the user can type in a message. Chat inputDisplay a chat input widget.prompt = st.chat_input(""Say something"") if prompt: st.write(f""The user has sent: {prompt}"") Chat messageInsert a chat message container.import numpy as np with st.chat_message(""user""): st.write(""Hello 👋"") st.line_chart(np.random.randn(30, 3)) Status containerDisplay output of long-running tasks in a container.with st.status('Running'): do_something_slow() st.write_streamWrite generators or streams to the app with a typewriter effect.st.write_stream(my_generator) st.write_stream(my_llm_stream) Status elements Progress barDisplay a progress bar.for i in range(101): st.progress(i) do_something_slow() SpinnerTemporarily displays a message while executing a block of code.with st.spinner(""Please wait...""): do_something_slow() Status containerDisplay output of long-running tasks in a container.with st.status('Running'): do_something_slow() ToastBriefly displays a toast message in the bottom-right corner.st.toast('Butter!', icon='🧈') BalloonsDisplay celebratory balloons!do_something() # Celebrate when all done! st.balloons() SnowflakesDisplay celebratory snowflakes!do_something() # Celebrate when all done! st.snow() Success boxDisplay a success message.st.success(""Match found!"") Info boxDisplay an informational message.st.info(""Dataset is updated every day at midnight."") Warning boxDisplay warning message.st.warning(""Unable to fetch image. Skipping..."") Error boxDisplay error message.st.error(""We encountered an error"") Exception outputDisplay an exception.e = RuntimeError(""This is an exception of type RuntimeError"") st.exception(e) Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration!StqdmThe simplest way to handle a progress bar in streamlit app. Created by @Wirg.from stqdm import stqdm for _ in stqdm(range(50)): sleep(0.5) Custom notification boxA custom notification box with the ability to close it out. Created by @Socvest.from streamlit_custom_notification_box import custom_notification_box styles = {'material-icons':{'color': 'red'}, 'text-icon-link-close-container': {'box-shadow': '#3896de 0px 4px'}, 'notification-text': {'':''}, 'close-button':{'':''}, 'link':{'':''}} custom_notification_box(icon='info', textDisplay='We are almost done with your registration...', externalLink='more info', url='#', styles=styles, key=""foo"") Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.let_it_rain import rain rain(emoji=""🎈"", font_size=54, falling_speed=5, animation_length=""infinite"",) App logic and configuration Navigation and pages Switch pageProgrammatically navigates to a specified page.st.switch_page(""pages/my_page.py"") Page linkDisplay a link to another page in a multipage app.st.page_link(""app.py"", label=""Home"", icon=""🏠"") st.page_link(""pages/profile.py"", label=""My profile"") Execution flow Modal dialogsInsert a modal dialog that can rerun independently from the rest of the script.@st.experimental_dialog(""Sign up"") def email_form(): name = st.text_input(""Name"") email = st.text_input(""Email"") FormsCreate a form that batches elements together with a “Submit"" button.with st.form(key='my_form'): name = st.text_input(""Name"") email = st.text_input(""Email"") st.form_submit_button(""Sign up"") Partial rerunsDefine a fragment to rerun independently from the rest of the script.@st.experimental_fragment(run_every=""10s"") def fragment(): df = get_data() st.line_chart(df) Rerun scriptRerun the script immediately.st.rerun() Stop executionStops execution immediately.st.stop() Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration!AutorefreshForce a refresh without tying up a script. Created by @kmcgrady.from streamlit_autorefresh import st_autorefresh st_autorefresh(interval=2000, limit=100, key=""fizzbuzzcounter"") PydanticAuto-generate Streamlit UI from Pydantic Models and Dataclasses. Created by @lukasmasuch.import streamlit_pydantic as sp sp.pydantic_form(key=""my_form"", model=ExampleModel) Streamlit PagesAn experimental version of Streamlit Multi-Page Apps. Created by @blackary.from st_pages import Page, show_pages, add_page_title show_pages([ Page(""streamlit_app.py"", ""Home"", ""🏠""), Page(""other_pages/page2.py"", ""Page 2"", "":books:""), ]) Caching and state Cache dataFunction decorator to cache functions that return data (e.g. dataframe transforms, database queries, ML inference).@st.cache_data def long_function(param1, param2): # Perform expensive computation here or # fetch data from the web here return data Cache resourceFunction decorator to cache functions that return global resources (e.g. database connections, ML models).@st.cache_resource def init_model(): # Return a global resource here return pipeline( ""sentiment-analysis"", model=""distilbert-base-uncased-finetuned-sst-2-english"" ) Session stateSession state is a way to share variables between reruns, for each user session.st.session_state['key'] = value Query parametersGet, set, or clear the query parameters that are shown in the browser's URL bar.st.query_params[key] = value st.query_params.clear() Connections and databases Setup your connection Create a connectionConnect to a data source or APIconn = st.connection('pets_db', type='sql') pet_owners = conn.query('select * from pet_owners') st.dataframe(pet_owners) Built-in connections SnowflakeConnectionA connection to Snowflake.conn = st.connection('snowflake') SQLConnectionA connection to a SQL database using SQLAlchemy.conn = st.connection('sql') Build your own connections Connection base classBuild your own connection with BaseConnection.class MyConnection(BaseConnection[myconn.MyConnection]): def _connect(self, **kwargs) -> MyConnection: return myconn.connect(**self._secrets, **kwargs) def query(self, query): return self._instance.query(query) Secrets management Secrets singletonAccess secrets from a local TOML file.key = st.secrets[""OpenAI_key""] Secrets fileSave your secrets in a per-project or per-profile TOML file.OpenAI_key = """" Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration!AuthenticatorA secure authentication module to validate user credentials. Created by @mkhorasani.import streamlit_authenticator as stauth authenticator = stauth.Authenticate( config['credentials'], config['cookie']['name'], config['cookie']['key'], config['cookie']['expiry_days'], config['preauthorized']) WS localStorageA simple synchronous way of accessing localStorage from your app. Created by @gagangoku.from streamlit_ws_localstorage import injectWebsocketCode ret = conn.setLocalStorageVal(key='k1', val='v1') st.write('ret: ' + ret) Streamlit Auth0The fastest way to provide comprehensive login inside Streamlit. Created by @conradbez.from auth0_component import login_button user_info = login_button(clientId, domain = domain) st.write(user_info) Custom Components Declare a componentCreate and register a custom component.st.components.v1.declare_component( ""custom_slider"", ""/frontend"", ) HTMLDisplay an HTML string in an iframe.st.components.v1.html( ""

Foo bar.

"" ) iframeLoad a remote URL in an iframe.st.components.v1.iframe( ""docs.streamlit.io"" ) Utilities and user info User infost.experimental_user returns information about the logged-in user of private apps on Streamlit Community Cloud.if st.experimental_user.email == ""foo@corp.com"": st.write(""Welcome back, "", st.experimental_user.email) else: st.write(""You are not authorized to view this page."") Get helpDisplay object’s doc string, nicely formatted.st.help(st.write) st.help(pd.DataFrame) Render HTMLRenders HTML strings to your app.css = """""" """""" st.html(css) Configuration Configuration fileConfigures the default settings for your app.your-project/ ├── .streamlit/ │ └── config.toml └── your_app.py Set page title, favicon, and moreConfigures the default settings of the page.st.set_page_config( page_title=""My app"", page_icon="":shark:"", ) Developer tools App testing st.testing.v1.AppTestst.testing.v1.AppTest simulates a running Streamlit app for testing.from streamlit.testing.v1 import AppTest at = AppTest.from_file(""streamlit_app.py"") at.secrets[""WORD""] = ""Foobar"" at.run() assert not at.exception at.text_input(""word"").input(""Bazbat"").run() assert at.warning[0].value == ""Try again."" AppTest.from_filest.testing.v1.AppTest.from_file initializes a simulated app from a file.from streamlit.testing.v1 import AppTest at = AppTest.from_file(""streamlit_app.py"") at.run() AppTest.from_stringst.testing.v1.AppTest.from_string initializes a simulated app from a string.from streamlit.testing.v1 import AppTest at = AppTest.from_string(app_script_as_string) at.run() AppTest.from_functionst.testing.v1.AppTest.from_function initializes a simulated app from a function.from streamlit.testing.v1 import AppTest at = AppTest.from_function(app_script_as_callable) at.run() BlockA representation of container elements, including: st.chat_message st.columns st.sidebar st.tabs The main body of the app. # at.sidebar returns a Block at.sidebar.button[0].click().run() assert not at.exception ElementThe base class for representation of all elements, including: st.title st.header st.markdown st.dataframe # at.title returns a sequence of Title # Title inherits from Element assert at.title[0].value == ""My awesome app"" ButtonA representation of st.button and st.form_submit_button.at.button[0].click().run() ChatInputA representation of st.chat_input.at.chat_input[0].set_value(""What is Streamlit?"").run() CheckboxA representation of st.checkbox.at.checkbox[0].check().run() ColorPickerA representation of st.color_picker.at.color_picker[0].pick(""#FF4B4B"").run() DateInputA representation of st.date_input.release_date = datetime.date(2023, 10, 26) at.date_input[0].set_value(release_date).run() MultiselectA representation of st.multiselect.at.multiselect[0].select(""New York"").run() NumberInputA representation of st.number_input.at.number_input[0].increment().run() RadioA representation of st.radio.at.radio[0].set_value(""New York"").run() SelectSliderA representation of st.select_slider.at.select_slider[0].set_range(""A"",""C"").run() SelectboxA representation of st.selectbox.at.selectbox[0].select(""New York"").run() SliderA representation of st.slider.at.slider[0].set_range(2,5).run() TextAreaA representation of st.text_area.at.text_area[0].input(""Streamlit is awesome!"").run() TextInputA representation of st.text_input.at.text_input[0].input(""Streamlit"").run() TimeInputA representation of st.time_input.at.time_input[0].increment().run() ToggleA representation of st.toggle.at.toggle[0].set_value(""True"").run() Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration!Pandas ProfilingPandas profiling component for Streamlit. Created by @okld.df = pd.read_csv(""https://storage.googleapis.com/tf-datasets/titanic/train.csv"") pr = df.profile_report() st_profile_report(pr) Streamlit AceAce editor component for Streamlit. Created by @okld.from streamlit_ace import st_ace content = st_ace() content Streamlit AnalyticsTrack & visualize user interactions with your streamlit app. Created by @jrieke.import streamlit_analytics with streamlit_analytics.track(): st.text_input(""Write something"") Previous: ConceptsNext: Write and magicforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy" https://docs.streamlit.io/en/0.69.0/api.html#custom-components,"DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceremovePAGE ELEMENTSWrite and magicaddText elementsaddData elementsaddChart elementsaddInput widgetsaddMedia elementsaddLayouts and containersaddChat elementsaddStatus elementsaddThird-party componentsopen_in_newAPPLICATION LOGICNavigation and pagesaddExecution flowaddCaching and stateaddConnections and secretsaddCustom componentsaddUtilitiesaddConfigurationaddTOOLSApp testingaddCommand lineaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Develop/API referenceAPI reference Streamlit makes it easy for you to visualize, mutate, and share data. The API reference is organized by activity type, like displaying data or optimizing performance. Each section includes methods associated with the activity type, including examples. Browse our API below and click to learn more about any of our available commands! 🎈 Display almost anything Write and magic st.writeWrite arguments to the app.st.write(""Hello **world**!"") st.write(my_data_frame) st.write(my_mpl_figure) st.write_streamWrite generators or streams to the app with a typewriter effect.st.write_stream(my_generator) st.write_stream(my_llm_stream) MagicAny time Streamlit sees either a variable or literal value on its own line, it automatically writes that to your app using st.write""Hello **world**!"" my_data_frame my_mpl_figure Text elements MarkdownDisplay string formatted as Markdown.st.markdown(""Hello **world**!"") TitleDisplay text in title formatting.st.title(""The app title"") HeaderDisplay text in header formatting.st.header(""This is a header"") SubheaderDisplay text in subheader formatting.st.subheader(""This is a subheader"") CaptionDisplay text in small font.st.caption(""This is written small caption text"") Code blockDisplay a code block with optional syntax highlighting.st.code(""a = 1234"") EchoDisplay some code in the app, then execute it. Useful for tutorials.with st.echo(): st.write('This code will be printed') LaTeXDisplay mathematical expressions formatted as LaTeX.st.latex(""\int a x^2 \,dx"") Preformatted textWrite fixed-width and preformatted text.st.text(""Hello world"") DividerDisplay a horizontal rule.st.divider() Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration! PreviousTagsAdd tags to your Streamlit apps. Created by @gagan3012.st_tags(label='# Enter Keywords:', text='Press enter to add more', value=['Zero', 'One', 'Two'], suggestions=['five', 'six', 'seven', 'eight', 'nine', 'three', 'eleven', 'ten', 'four'], maxtags = 4, key='1') NLUApply text mining on a dataframe. Created by @JohnSnowLabs.nlu.load('sentiment').predict('I love NLU! <3') Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.mention(label=""An awesome Streamlit App"", icon=""streamlit"", url=""https://extras.streamlit.app"",) Annotated textDisplay annotated text in Streamlit apps. Created by @tvst.annotated_text(""This "", (""is"", ""verb""), "" some "", (""annotated"", ""adj""), (""text"", ""noun""), "" for those of "", (""you"", ""pronoun""), "" who "", (""like"", ""verb""), "" this sort of "", (""thing"", ""noun""), ""."") Drawable CanvasProvides a sketching canvas using Fabric.js. Created by @andfanilo.st_canvas(fill_color=""rgba(255, 165, 0, 0.3)"", stroke_width=stroke_width, stroke_color=stroke_color, background_color=bg_color, background_image=Image.open(bg_image) if bg_image else None, update_streamlit=realtime_update, height=150, drawing_mode=drawing_mode, point_display_radius=point_display_radius if drawing_mode == 'point' else 0, key=""canvas"",) TagsAdd tags to your Streamlit apps. Created by @gagan3012.st_tags(label='# Enter Keywords:', text='Press enter to add more', value=['Zero', 'One', 'Two'], suggestions=['five', 'six', 'seven', 'eight', 'nine', 'three', 'eleven', 'ten', 'four'], maxtags = 4, key='1') NLUApply text mining on a dataframe. Created by @JohnSnowLabs.nlu.load('sentiment').predict('I love NLU! <3') Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.mention(label=""An awesome Streamlit App"", icon=""streamlit"", url=""https://extras.streamlit.app"",) Annotated textDisplay annotated text in Streamlit apps. Created by @tvst.annotated_text(""This "", (""is"", ""verb""), "" some "", (""annotated"", ""adj""), (""text"", ""noun""), "" for those of "", (""you"", ""pronoun""), "" who "", (""like"", ""verb""), "" this sort of "", (""thing"", ""noun""), ""."") Drawable CanvasProvides a sketching canvas using Fabric.js. Created by @andfanilo.st_canvas(fill_color=""rgba(255, 165, 0, 0.3)"", stroke_width=stroke_width, stroke_color=stroke_color, background_color=bg_color, background_image=Image.open(bg_image) if bg_image else None, update_streamlit=realtime_update, height=150, drawing_mode=drawing_mode, point_display_radius=point_display_radius if drawing_mode == 'point' else 0, key=""canvas"",) TagsAdd tags to your Streamlit apps. Created by @gagan3012.st_tags(label='# Enter Keywords:', text='Press enter to add more', value=['Zero', 'One', 'Two'], suggestions=['five', 'six', 'seven', 'eight', 'nine', 'three', 'eleven', 'ten', 'four'], maxtags = 4, key='1') NLUApply text mining on a dataframe. Created by @JohnSnowLabs.nlu.load('sentiment').predict('I love NLU! <3') Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.mention(label=""An awesome Streamlit App"", icon=""streamlit"", url=""https://extras.streamlit.app"",) Next Data elements DataframesDisplay a dataframe as an interactive table.st.dataframe(my_data_frame) Data editorDisplay a data editor widget.edited = st.data_editor(df, num_rows=""dynamic"") Column configurationConfigure the display and editing behavior of dataframes and data editors.st.column_config.NumberColumn(""Price (in USD)"", min_value=0, format=""$%d"") Static tablesDisplay a static table.st.table(my_data_frame) MetricsDisplay a metric in big bold font, with an optional indicator of how the metric changed.st.metric(""My metric"", 42, 2) Dicts and JSONDisplay object or string as a pretty-printed JSON string.st.json(my_dict) Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration! PreviousImage CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates value = streamlit_image_coordinates(""https://placekitten.com/200/300"") st.write(value) Plotly EventsMake Plotly charts interactive!. Created by @null-jones.from streamlit_plotly_events import plotly_events fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.metric_cards import style_metric_cards col3.metric(label=""No Change"", value=5000, delta=0) style_metric_cards() Streamlit AggridImplementation of Ag-Grid component for Streamlit. Created by @PablocFonseca.df = pd.DataFrame({'col1': [1, 2, 3], 'col2': [4, 5, 6]}) grid_return = AgGrid(df, editable=True) new_df = grid_return['data'] Streamlit FoliumStreamlit Component for rendering Folium maps. Created by @randyzwitch.m = folium.Map(location=[39.949610, -75.150282], zoom_start=16) folium.Marker([39.949610, -75.150282], popup=""Liberty Bell"", tooltip=""Liberty Bell"").add_to(m) st_data = st_folium(m, width=725) Pandas ProfilingPandas profiling component for Streamlit. Created by @okld.df = pd.read_csv(""https://storage.googleapis.com/tf-datasets/titanic/train.csv"") pr = df.profile_report() st_profile_report(pr) Image CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates value = streamlit_image_coordinates(""https://placekitten.com/200/300"") st.write(value) Plotly EventsMake Plotly charts interactive!. Created by @null-jones.from streamlit_plotly_events import plotly_events fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.metric_cards import style_metric_cards col3.metric(label=""No Change"", value=5000, delta=0) style_metric_cards() Streamlit AggridImplementation of Ag-Grid component for Streamlit. Created by @PablocFonseca.df = pd.DataFrame({'col1': [1, 2, 3], 'col2': [4, 5, 6]}) grid_return = AgGrid(df, editable=True) new_df = grid_return['data'] Streamlit FoliumStreamlit Component for rendering Folium maps. Created by @randyzwitch.m = folium.Map(location=[39.949610, -75.150282], zoom_start=16) folium.Marker([39.949610, -75.150282], popup=""Liberty Bell"", tooltip=""Liberty Bell"").add_to(m) st_data = st_folium(m, width=725) Pandas ProfilingPandas profiling component for Streamlit. Created by @okld.df = pd.read_csv(""https://storage.googleapis.com/tf-datasets/titanic/train.csv"") pr = df.profile_report() st_profile_report(pr) Image CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates value = streamlit_image_coordinates(""https://placekitten.com/200/300"") st.write(value) Plotly EventsMake Plotly charts interactive!. Created by @null-jones.from streamlit_plotly_events import plotly_events fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.metric_cards import style_metric_cards col3.metric(label=""No Change"", value=5000, delta=0) style_metric_cards() Next Chart elements Simple area chartsDisplay an area chart.st.area_chart(my_data_frame) Simple bar chartsDisplay a bar chart.st.bar_chart(my_data_frame) Simple line chartsDisplay a line chart.st.line_chart(my_data_frame) Simple scatter chartsDisplay a line chart.st.scatter_chart(my_data_frame) Scatterplots on mapsDisplay a map with points on it.st.map(my_data_frame) MatplotlibDisplay a matplotlib.pyplot figure.st.pyplot(my_mpl_figure) AltairDisplay a chart using the Altair library.st.altair_chart(my_altair_chart) Vega-LiteDisplay a chart using the Vega-Lite library.st.vega_lite_chart(my_vega_lite_chart) PlotlyDisplay an interactive Plotly chart.st.plotly_chart(my_plotly_chart) BokehDisplay an interactive Bokeh chart.st.bokeh_chart(my_bokeh_chart) PyDeckDisplay a chart using the PyDeck library.st.pydeck_chart(my_pydeck_chart) GraphVizDisplay a graph using the dagre-d3 library.st.graphviz_chart(my_graphviz_spec) Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration! PreviousStreamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl(""https://assets5.lottiefiles.com/packages/lf20_V9t630.json"") st_lottie(lottie_hello, key=""hello"") Plotly EventsMake Plotly charts interactive!. Created by @null-jones.fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.chart += get_annotations_chart(annotations=[(""Mar 01, 2008"", ""Pretty good day for GOOG""), (""Dec 01, 2007"", ""Something's going wrong for GOOG & AAPL""), (""Nov 01, 2008"", ""Market starts again thanks to...""), (""Dec 01, 2009"", ""Small crash for GOOG after...""),],) st.altair_chart(chart, use_container_width=True) PlostA deceptively simple plotting library for Streamlit. Created by @tvst.import plost plost.line_chart(my_dataframe, x='time', y='stock_value', color='stock_name',) HiPlotHigh dimensional Interactive Plotting. Created by @facebookresearch.data = [{'dropout':0.1, 'lr': 0.001, 'loss': 10.0, 'optimizer': 'SGD'}, {'dropout':0.15, 'lr': 0.01, 'loss': 3.5, 'optimizer': 'Adam'}, {'dropout':0.3, 'lr': 0.1, 'loss': 4.5, 'optimizer': 'Adam'}] hip.Experiment.from_iterable(data).display() EChartsHigh dimensional Interactive Plotting. Created by @andfanilo.from streamlit_echarts import st_echarts st_echarts(options=options) Streamlit FoliumStreamlit Component for rendering Folium maps. Created by @randyzwitch.m = folium.Map(location=[39.949610, -75.150282], zoom_start=16) st_data = st_folium(m, width=725) Spacy-StreamlitspaCy building blocks and visualizers for Streamlit apps. Created by @explosion.models = [""en_core_web_sm"", ""en_core_web_md""] spacy_streamlit.visualize(models, ""Sundar Pichai is the CEO of Google."") Streamlit AgraphA Streamlit Graph Vis, based on react-grah-vis. Created by @ChrisDelClea.from streamlit_agraph import agraph, Node, Edge, Config agraph(nodes=nodes, edges=edges, config=config) Streamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl(""https://assets5.lottiefiles.com/packages/lf20_V9t630.json"") st_lottie(lottie_hello, key=""hello"") Plotly EventsMake Plotly charts interactive!. Created by @null-jones.fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.chart += get_annotations_chart(annotations=[(""Mar 01, 2008"", ""Pretty good day for GOOG""), (""Dec 01, 2007"", ""Something's going wrong for GOOG & AAPL""), (""Nov 01, 2008"", ""Market starts again thanks to...""), (""Dec 01, 2009"", ""Small crash for GOOG after...""),],) st.altair_chart(chart, use_container_width=True) PlostA deceptively simple plotting library for Streamlit. Created by @tvst.import plost plost.line_chart(my_dataframe, x='time', y='stock_value', color='stock_name',) HiPlotHigh dimensional Interactive Plotting. Created by @facebookresearch.data = [{'dropout':0.1, 'lr': 0.001, 'loss': 10.0, 'optimizer': 'SGD'}, {'dropout':0.15, 'lr': 0.01, 'loss': 3.5, 'optimizer': 'Adam'}, {'dropout':0.3, 'lr': 0.1, 'loss': 4.5, 'optimizer': 'Adam'}] hip.Experiment.from_iterable(data).display() EChartsHigh dimensional Interactive Plotting. Created by @andfanilo.from streamlit_echarts import st_echarts st_echarts(options=options) Streamlit FoliumStreamlit Component for rendering Folium maps. Created by @randyzwitch.m = folium.Map(location=[39.949610, -75.150282], zoom_start=16) st_data = st_folium(m, width=725) Spacy-StreamlitspaCy building blocks and visualizers for Streamlit apps. Created by @explosion.models = [""en_core_web_sm"", ""en_core_web_md""] spacy_streamlit.visualize(models, ""Sundar Pichai is the CEO of Google."") Streamlit AgraphA Streamlit Graph Vis, based on react-grah-vis. Created by @ChrisDelClea.from streamlit_agraph import agraph, Node, Edge, Config agraph(nodes=nodes, edges=edges, config=config) Streamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl(""https://assets5.lottiefiles.com/packages/lf20_V9t630.json"") st_lottie(lottie_hello, key=""hello"") Plotly EventsMake Plotly charts interactive!. Created by @null-jones.fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.chart += get_annotations_chart(annotations=[(""Mar 01, 2008"", ""Pretty good day for GOOG""), (""Dec 01, 2007"", ""Something's going wrong for GOOG & AAPL""), (""Nov 01, 2008"", ""Market starts again thanks to...""), (""Dec 01, 2009"", ""Small crash for GOOG after...""),],) st.altair_chart(chart, use_container_width=True) Next Input widgets ButtonDisplay a button widget.clicked = st.button(""Click me"") Download buttonDisplay a download button widget.st.download_button(""Download file"", file) Form buttonDisplay a form submit button. For use with st.form.st.form_submit_button(""Sign up"") Link buttonDisplay a link button.st.link_button(""Go to gallery"", url) Page linkDisplay a link to another page in a multipage app.st.page_link(""app.py"", label=""Home"", icon=""🏠"") st.page_link(""pages/profile.py"", label=""My profile"") CheckboxDisplay a checkbox widget.selected = st.checkbox(""I agree"") Color pickerDisplay a color picker widget.color = st.color_picker(""Pick a color"") MultiselectDisplay a multiselect widget. The multiselect widget starts as empty.choices = st.multiselect(""Buy"", [""milk"", ""apples"", ""potatoes""]) RadioDisplay a radio button widget.choice = st.radio(""Pick one"", [""cats"", ""dogs""]) SelectboxDisplay a select widget.choice = st.selectbox(""Pick one"", [""cats"", ""dogs""]) Select-sliderDisplay a slider widget to select items from a list.size = st.select_slider(""Pick a size"", [""S"", ""M"", ""L""]) ToggleDisplay a toggle widget.activated = st.toggle(""Activate"") Number inputDisplay a numeric input widget.choice = st.number_input(""Pick a number"", 0, 10) SliderDisplay a slider widget.number = st.slider(""Pick a number"", 0, 100) Date inputDisplay a date input widget.date = st.date_input(""Your birthday"") Time inputDisplay a time input widget.time = st.time_input(""Meeting time"") Chat inputDisplay a chat input widget.prompt = st.chat_input(""Say something"") if prompt: st.write(f""The user has sent: {prompt}"") Text-areaDisplay a multi-line text input widget.text = st.text_area(""Text to translate"") Text inputDisplay a single-line text input widget.name = st.text_input(""First name"") Data editorDisplay a data editor widget.edited = st.experimental_data_editor(df, num_rows=""dynamic"") File UploaderDisplay a file uploader widget.data = st.file_uploader(""Upload a CSV"") Camera inputDisplay a widget that allows users to upload images directly from a camera.image = st.camera_input(""Take a picture"") Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration! PreviousStreamlit ChatStreamlit Component for a Chatbot UI. Created by @AI-Yash.from streamlit_chat import message message(""My message"") message(""Hello bot!"", is_user=True) # align's the message to the right Streamlit Option MenuSelect a single item from a list of options in a menu. Created by @victoryhb.from streamlit_option_menu import option_menu option_menu(""Main Menu"", [""Home"", 'Settings'], icons=['house', 'gear'], menu_icon=""cast"", default_index=1) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.stoggle import stoggle stoggle( ""Click me!"", """"""🥷 Surprise! Here's some additional content"""""",) Streamlit ElementsCreate a draggable and resizable dashboard in Streamlit. Created by @okls.from streamlit_elements import elements, mui, html with elements(""new_element""): mui.Typography(""Hello world"") TagsAdd tags to your Streamlit apps. Created by @gagan3012.from streamlit_tags import st_tags st_tags(label='# Enter Keywords:', text='Press enter to add more', value=['Zero', 'One', 'Two'], suggestions=['five', 'six', 'seven', 'eight', 'nine', 'three', 'eleven', 'ten', 'four'], maxtags = 4, key='1') StqdmThe simplest way to handle a progress bar in streamlit app. Created by @Wirg.from stqdm import stqdm for _ in stqdm(range(50)): sleep(0.5) TimelineDisplay a Timeline in Streamlit apps using TimelineJS. Created by @innerdoc.from streamlit_timeline import timeline with open('example.json', ""r"") as f: timeline(f.read(), height=800) Camera input liveAlternative for st.camera_input which returns the webcam images live. Created by @blackary.from camera_input_live import camera_input_live image = camera_input_live() st.image(value) Streamlit AceAce editor component for Streamlit. Created by @okld.from streamlit_ace import st_ace content = st_ace() content Streamlit ChatStreamlit Component for a Chatbot UI. Created by @AI-Yash.from streamlit_chat import message message(""My message"") message(""Hello bot!"", is_user=True) # align's the message to the right Streamlit Option MenuSelect a single item from a list of options in a menu. Created by @victoryhb.from streamlit_option_menu import option_menu option_menu(""Main Menu"", [""Home"", 'Settings'], icons=['house', 'gear'], menu_icon=""cast"", default_index=1) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.stoggle import stoggle stoggle( ""Click me!"", """"""🥷 Surprise! Here's some additional content"""""",) Streamlit ElementsCreate a draggable and resizable dashboard in Streamlit. Created by @okls.from streamlit_elements import elements, mui, html with elements(""new_element""): mui.Typography(""Hello world"") TagsAdd tags to your Streamlit apps. Created by @gagan3012.from streamlit_tags import st_tags st_tags(label='# Enter Keywords:', text='Press enter to add more', value=['Zero', 'One', 'Two'], suggestions=['five', 'six', 'seven', 'eight', 'nine', 'three', 'eleven', 'ten', 'four'], maxtags = 4, key='1') StqdmThe simplest way to handle a progress bar in streamlit app. Created by @Wirg.from stqdm import stqdm for _ in stqdm(range(50)): sleep(0.5) TimelineDisplay a Timeline in Streamlit apps using TimelineJS. Created by @innerdoc.from streamlit_timeline import timeline with open('example.json', ""r"") as f: timeline(f.read(), height=800) Camera input liveAlternative for st.camera_input which returns the webcam images live. Created by @blackary.from camera_input_live import camera_input_live image = camera_input_live() st.image(value) Streamlit AceAce editor component for Streamlit. Created by @okld.from streamlit_ace import st_ace content = st_ace() content Streamlit ChatStreamlit Component for a Chatbot UI. Created by @AI-Yash.from streamlit_chat import message message(""My message"") message(""Hello bot!"", is_user=True) # align's the message to the right Streamlit Option MenuSelect a single item from a list of options in a menu. Created by @victoryhb.from streamlit_option_menu import option_menu option_menu(""Main Menu"", [""Home"", 'Settings'], icons=['house', 'gear'], menu_icon=""cast"", default_index=1) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.stoggle import stoggle stoggle( ""Click me!"", """"""🥷 Surprise! Here's some additional content"""""",) Next Media elements ImageDisplay an image or list of images.st.image(numpy_array) st.image(image_bytes) st.image(file) st.image(""https://example.com/myimage.jpg"") AudioDisplay an audio player.st.audio(numpy_array) st.audio(audio_bytes) st.audio(file) st.audio(""https://example.com/myaudio.mp3"", format=""audio/mp3"") VideoDisplay a video player.st.video(numpy_array) st.video(video_bytes) st.video(file) st.video(""https://example.com/myvideo.mp4"", format=""video/mp4"") Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration! PreviousStreamlit CropperA simple image cropper for Streamlit. Created by @turner-anderson.from streamlit_cropper import st_cropper st_cropper(img, realtime_update=realtime_update, box_color=box_color, aspect_ratio=aspect_ratio) Image CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates streamlit_image_coordinates(""https://placekitten.com/200/300"") Streamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl(""https://assets5.lottiefiles.com/packages/lf20_V9t630.json"") st_lottie(lottie_hello, key=""hello"") Streamlit WebrtcHandling and transmitting real-time video/audio streams with Streamlit. Created by @whitphx.from streamlit_webrtc import webrtc_streamer webrtc_streamer(key=""sample"") Drawable CanvasProvides a sketching canvas using Fabric.js. Created by @andfanilo.from streamlit_drawable_canvas import st_canvas st_canvas(fill_color=""rgba(255, 165, 0, 0.3)"", stroke_width=stroke_width, stroke_color=stroke_color, background_color=bg_color, background_image=Image.open(bg_image) if bg_image else None, update_streamlit=realtime_update, height=150, drawing_mode=drawing_mode, point_display_radius=point_display_radius if drawing_mode == 'point' else 0, key=""canvas"",) Image ComparisonCompare images with a slider using JuxtaposeJS. Created by @fcakyon.from streamlit_image_comparison import image_comparison image_comparison(img1=""image1.jpg"", img2=""image2.jpg"",) Streamlit CropperA simple image cropper for Streamlit. Created by @turner-anderson.from streamlit_cropper import st_cropper st_cropper(img, realtime_update=realtime_update, box_color=box_color, aspect_ratio=aspect_ratio) Image CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates streamlit_image_coordinates(""https://placekitten.com/200/300"") Streamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl(""https://assets5.lottiefiles.com/packages/lf20_V9t630.json"") st_lottie(lottie_hello, key=""hello"") Streamlit WebrtcHandling and transmitting real-time video/audio streams with Streamlit. Created by @whitphx.from streamlit_webrtc import webrtc_streamer webrtc_streamer(key=""sample"") Drawable CanvasProvides a sketching canvas using Fabric.js. Created by @andfanilo.from streamlit_drawable_canvas import st_canvas st_canvas(fill_color=""rgba(255, 165, 0, 0.3)"", stroke_width=stroke_width, stroke_color=stroke_color, background_color=bg_color, background_image=Image.open(bg_image) if bg_image else None, update_streamlit=realtime_update, height=150, drawing_mode=drawing_mode, point_display_radius=point_display_radius if drawing_mode == 'point' else 0, key=""canvas"",) Image ComparisonCompare images with a slider using JuxtaposeJS. Created by @fcakyon.from streamlit_image_comparison import image_comparison image_comparison(img1=""image1.jpg"", img2=""image2.jpg"",) Streamlit CropperA simple image cropper for Streamlit. Created by @turner-anderson.from streamlit_cropper import st_cropper st_cropper(img, realtime_update=realtime_update, box_color=box_color, aspect_ratio=aspect_ratio) Image CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates streamlit_image_coordinates(""https://placekitten.com/200/300"") Streamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl(""https://assets5.lottiefiles.com/packages/lf20_V9t630.json"") st_lottie(lottie_hello, key=""hello"") Next Layouts and containers ColumnsInsert containers laid out as side-by-side columns.col1, col2 = st.columns(2) col1.write(""this is column 1"") col2.write(""this is column 2"") ContainerInsert a multi-element container.c = st.container() st.write(""This will show last"") c.write(""This will show first"") c.write(""This will show second"") Modal dialogsInsert a modal dialog that can rerun independently from the rest of the script.@st.experimental_dialog(""Sign up"") def email_form(): name = st.text_input(""Name"") email = st.text_input(""Email"") EmptyInsert a single-element container.c = st.empty() st.write(""This will show last"") c.write(""This will be replaced"") c.write(""This will show first"") ExpanderInsert a multi-element container that can be expanded/collapsed.with st.expander(""Open to see more""): st.write(""This is more content"") PopoverInsert a multi-element popover container that can be opened/closed.with st.popover(""Settings""): st.checkbox(""Show completed"") SidebarDisplay items in a sidebar.st.sidebar.write(""This lives in the sidebar"") st.sidebar.button(""Click me!"") TabsInsert containers separated into tabs.tab1, tab2 = st.tabs([""Tab 1"", ""Tab2""]) tab1.write(""this is tab 1"") tab2.write(""this is tab 2"") Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration!Streamlit ElementsCreate a draggable and resizable dashboard in Streamlit. Created by @okls.from streamlit_elements import elements, mui, html with elements(""new_element""): mui.Typography(""Hello world"") PydanticAuto-generate Streamlit UI from Pydantic Models and Dataclasses. Created by @lukasmasuch.import streamlit_pydantic as sp sp.pydantic_form(key=""my_form"", model=ExampleModel) Streamlit PagesAn experimental version of Streamlit Multi-Page Apps. Created by @blackary.from st_pages import Page, show_pages, add_page_title show_pages([ Page(""streamlit_app.py"", ""Home"", ""🏠""), Page(""other_pages/page2.py"", ""Page 2"", "":books:""), ]) Chat elements Streamlit provides a few commands to help you build conversational apps. These chat elements are designed to be used in conjunction with each other, but you can also use them separately. st.chat_message lets you insert a chat message container into the app so you can display messages from the user or the app. Chat containers can contain other Streamlit elements, including charts, tables, text, and more. st.chat_input lets you display a chat input widget so the user can type in a message. Chat inputDisplay a chat input widget.prompt = st.chat_input(""Say something"") if prompt: st.write(f""The user has sent: {prompt}"") Chat messageInsert a chat message container.import numpy as np with st.chat_message(""user""): st.write(""Hello 👋"") st.line_chart(np.random.randn(30, 3)) Status containerDisplay output of long-running tasks in a container.with st.status('Running'): do_something_slow() st.write_streamWrite generators or streams to the app with a typewriter effect.st.write_stream(my_generator) st.write_stream(my_llm_stream) Status elements Progress barDisplay a progress bar.for i in range(101): st.progress(i) do_something_slow() SpinnerTemporarily displays a message while executing a block of code.with st.spinner(""Please wait...""): do_something_slow() Status containerDisplay output of long-running tasks in a container.with st.status('Running'): do_something_slow() ToastBriefly displays a toast message in the bottom-right corner.st.toast('Butter!', icon='🧈') BalloonsDisplay celebratory balloons!do_something() # Celebrate when all done! st.balloons() SnowflakesDisplay celebratory snowflakes!do_something() # Celebrate when all done! st.snow() Success boxDisplay a success message.st.success(""Match found!"") Info boxDisplay an informational message.st.info(""Dataset is updated every day at midnight."") Warning boxDisplay warning message.st.warning(""Unable to fetch image. Skipping..."") Error boxDisplay error message.st.error(""We encountered an error"") Exception outputDisplay an exception.e = RuntimeError(""This is an exception of type RuntimeError"") st.exception(e) Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration!StqdmThe simplest way to handle a progress bar in streamlit app. Created by @Wirg.from stqdm import stqdm for _ in stqdm(range(50)): sleep(0.5) Custom notification boxA custom notification box with the ability to close it out. Created by @Socvest.from streamlit_custom_notification_box import custom_notification_box styles = {'material-icons':{'color': 'red'}, 'text-icon-link-close-container': {'box-shadow': '#3896de 0px 4px'}, 'notification-text': {'':''}, 'close-button':{'':''}, 'link':{'':''}} custom_notification_box(icon='info', textDisplay='We are almost done with your registration...', externalLink='more info', url='#', styles=styles, key=""foo"") Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.let_it_rain import rain rain(emoji=""🎈"", font_size=54, falling_speed=5, animation_length=""infinite"",) App logic and configuration Navigation and pages Switch pageProgrammatically navigates to a specified page.st.switch_page(""pages/my_page.py"") Page linkDisplay a link to another page in a multipage app.st.page_link(""app.py"", label=""Home"", icon=""🏠"") st.page_link(""pages/profile.py"", label=""My profile"") Execution flow Modal dialogsInsert a modal dialog that can rerun independently from the rest of the script.@st.experimental_dialog(""Sign up"") def email_form(): name = st.text_input(""Name"") email = st.text_input(""Email"") FormsCreate a form that batches elements together with a “Submit"" button.with st.form(key='my_form'): name = st.text_input(""Name"") email = st.text_input(""Email"") st.form_submit_button(""Sign up"") Partial rerunsDefine a fragment to rerun independently from the rest of the script.@st.experimental_fragment(run_every=""10s"") def fragment(): df = get_data() st.line_chart(df) Rerun scriptRerun the script immediately.st.rerun() Stop executionStops execution immediately.st.stop() Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration!AutorefreshForce a refresh without tying up a script. Created by @kmcgrady.from streamlit_autorefresh import st_autorefresh st_autorefresh(interval=2000, limit=100, key=""fizzbuzzcounter"") PydanticAuto-generate Streamlit UI from Pydantic Models and Dataclasses. Created by @lukasmasuch.import streamlit_pydantic as sp sp.pydantic_form(key=""my_form"", model=ExampleModel) Streamlit PagesAn experimental version of Streamlit Multi-Page Apps. Created by @blackary.from st_pages import Page, show_pages, add_page_title show_pages([ Page(""streamlit_app.py"", ""Home"", ""🏠""), Page(""other_pages/page2.py"", ""Page 2"", "":books:""), ]) Caching and state Cache dataFunction decorator to cache functions that return data (e.g. dataframe transforms, database queries, ML inference).@st.cache_data def long_function(param1, param2): # Perform expensive computation here or # fetch data from the web here return data Cache resourceFunction decorator to cache functions that return global resources (e.g. database connections, ML models).@st.cache_resource def init_model(): # Return a global resource here return pipeline( ""sentiment-analysis"", model=""distilbert-base-uncased-finetuned-sst-2-english"" ) Session stateSession state is a way to share variables between reruns, for each user session.st.session_state['key'] = value Query parametersGet, set, or clear the query parameters that are shown in the browser's URL bar.st.query_params[key] = value st.query_params.clear() Connections and databases Setup your connection Create a connectionConnect to a data source or APIconn = st.connection('pets_db', type='sql') pet_owners = conn.query('select * from pet_owners') st.dataframe(pet_owners) Built-in connections SnowflakeConnectionA connection to Snowflake.conn = st.connection('snowflake') SQLConnectionA connection to a SQL database using SQLAlchemy.conn = st.connection('sql') Build your own connections Connection base classBuild your own connection with BaseConnection.class MyConnection(BaseConnection[myconn.MyConnection]): def _connect(self, **kwargs) -> MyConnection: return myconn.connect(**self._secrets, **kwargs) def query(self, query): return self._instance.query(query) Secrets management Secrets singletonAccess secrets from a local TOML file.key = st.secrets[""OpenAI_key""] Secrets fileSave your secrets in a per-project or per-profile TOML file.OpenAI_key = """" Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration!AuthenticatorA secure authentication module to validate user credentials. Created by @mkhorasani.import streamlit_authenticator as stauth authenticator = stauth.Authenticate( config['credentials'], config['cookie']['name'], config['cookie']['key'], config['cookie']['expiry_days'], config['preauthorized']) WS localStorageA simple synchronous way of accessing localStorage from your app. Created by @gagangoku.from streamlit_ws_localstorage import injectWebsocketCode ret = conn.setLocalStorageVal(key='k1', val='v1') st.write('ret: ' + ret) Streamlit Auth0The fastest way to provide comprehensive login inside Streamlit. Created by @conradbez.from auth0_component import login_button user_info = login_button(clientId, domain = domain) st.write(user_info) Custom Components Declare a componentCreate and register a custom component.st.components.v1.declare_component( ""custom_slider"", ""/frontend"", ) HTMLDisplay an HTML string in an iframe.st.components.v1.html( ""

Foo bar.

"" ) iframeLoad a remote URL in an iframe.st.components.v1.iframe( ""docs.streamlit.io"" ) Utilities and user info User infost.experimental_user returns information about the logged-in user of private apps on Streamlit Community Cloud.if st.experimental_user.email == ""foo@corp.com"": st.write(""Welcome back, "", st.experimental_user.email) else: st.write(""You are not authorized to view this page."") Get helpDisplay object’s doc string, nicely formatted.st.help(st.write) st.help(pd.DataFrame) Render HTMLRenders HTML strings to your app.css = """""" """""" st.html(css) Configuration Configuration fileConfigures the default settings for your app.your-project/ ├── .streamlit/ │ └── config.toml └── your_app.py Set page title, favicon, and moreConfigures the default settings of the page.st.set_page_config( page_title=""My app"", page_icon="":shark:"", ) Developer tools App testing st.testing.v1.AppTestst.testing.v1.AppTest simulates a running Streamlit app for testing.from streamlit.testing.v1 import AppTest at = AppTest.from_file(""streamlit_app.py"") at.secrets[""WORD""] = ""Foobar"" at.run() assert not at.exception at.text_input(""word"").input(""Bazbat"").run() assert at.warning[0].value == ""Try again."" AppTest.from_filest.testing.v1.AppTest.from_file initializes a simulated app from a file.from streamlit.testing.v1 import AppTest at = AppTest.from_file(""streamlit_app.py"") at.run() AppTest.from_stringst.testing.v1.AppTest.from_string initializes a simulated app from a string.from streamlit.testing.v1 import AppTest at = AppTest.from_string(app_script_as_string) at.run() AppTest.from_functionst.testing.v1.AppTest.from_function initializes a simulated app from a function.from streamlit.testing.v1 import AppTest at = AppTest.from_function(app_script_as_callable) at.run() BlockA representation of container elements, including: st.chat_message st.columns st.sidebar st.tabs The main body of the app. # at.sidebar returns a Block at.sidebar.button[0].click().run() assert not at.exception ElementThe base class for representation of all elements, including: st.title st.header st.markdown st.dataframe # at.title returns a sequence of Title # Title inherits from Element assert at.title[0].value == ""My awesome app"" ButtonA representation of st.button and st.form_submit_button.at.button[0].click().run() ChatInputA representation of st.chat_input.at.chat_input[0].set_value(""What is Streamlit?"").run() CheckboxA representation of st.checkbox.at.checkbox[0].check().run() ColorPickerA representation of st.color_picker.at.color_picker[0].pick(""#FF4B4B"").run() DateInputA representation of st.date_input.release_date = datetime.date(2023, 10, 26) at.date_input[0].set_value(release_date).run() MultiselectA representation of st.multiselect.at.multiselect[0].select(""New York"").run() NumberInputA representation of st.number_input.at.number_input[0].increment().run() RadioA representation of st.radio.at.radio[0].set_value(""New York"").run() SelectSliderA representation of st.select_slider.at.select_slider[0].set_range(""A"",""C"").run() SelectboxA representation of st.selectbox.at.selectbox[0].select(""New York"").run() SliderA representation of st.slider.at.slider[0].set_range(2,5).run() TextAreaA representation of st.text_area.at.text_area[0].input(""Streamlit is awesome!"").run() TextInputA representation of st.text_input.at.text_input[0].input(""Streamlit"").run() TimeInputA representation of st.time_input.at.time_input[0].increment().run() ToggleA representation of st.toggle.at.toggle[0].set_value(""True"").run() Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration!Pandas ProfilingPandas profiling component for Streamlit. Created by @okld.df = pd.read_csv(""https://storage.googleapis.com/tf-datasets/titanic/train.csv"") pr = df.profile_report() st_profile_report(pr) Streamlit AceAce editor component for Streamlit. Created by @okld.from streamlit_ace import st_ace content = st_ace() content Streamlit AnalyticsTrack & visualize user interactions with your streamlit app. Created by @jrieke.import streamlit_analytics with streamlit_analytics.track(): st.text_input(""Write something"") Previous: ConceptsNext: Write and magicforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy" https://docs.streamlit.io/en/0.70.0/api.html#app-logic-and-configuration,"DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceremovePAGE ELEMENTSWrite and magicaddText elementsaddData elementsaddChart elementsaddInput widgetsaddMedia elementsaddLayouts and containersaddChat elementsaddStatus elementsaddThird-party componentsopen_in_newAPPLICATION LOGICNavigation and pagesaddExecution flowaddCaching and stateaddConnections and secretsaddCustom componentsaddUtilitiesaddConfigurationaddTOOLSApp testingaddCommand lineaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Develop/API referenceAPI reference Streamlit makes it easy for you to visualize, mutate, and share data. The API reference is organized by activity type, like displaying data or optimizing performance. Each section includes methods associated with the activity type, including examples. Browse our API below and click to learn more about any of our available commands! 🎈 Display almost anything Write and magic st.writeWrite arguments to the app.st.write(""Hello **world**!"") st.write(my_data_frame) st.write(my_mpl_figure) st.write_streamWrite generators or streams to the app with a typewriter effect.st.write_stream(my_generator) st.write_stream(my_llm_stream) MagicAny time Streamlit sees either a variable or literal value on its own line, it automatically writes that to your app using st.write""Hello **world**!"" my_data_frame my_mpl_figure Text elements MarkdownDisplay string formatted as Markdown.st.markdown(""Hello **world**!"") TitleDisplay text in title formatting.st.title(""The app title"") HeaderDisplay text in header formatting.st.header(""This is a header"") SubheaderDisplay text in subheader formatting.st.subheader(""This is a subheader"") CaptionDisplay text in small font.st.caption(""This is written small caption text"") Code blockDisplay a code block with optional syntax highlighting.st.code(""a = 1234"") EchoDisplay some code in the app, then execute it. Useful for tutorials.with st.echo(): st.write('This code will be printed') LaTeXDisplay mathematical expressions formatted as LaTeX.st.latex(""\int a x^2 \,dx"") Preformatted textWrite fixed-width and preformatted text.st.text(""Hello world"") DividerDisplay a horizontal rule.st.divider() Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration! PreviousTagsAdd tags to your Streamlit apps. Created by @gagan3012.st_tags(label='# Enter Keywords:', text='Press enter to add more', value=['Zero', 'One', 'Two'], suggestions=['five', 'six', 'seven', 'eight', 'nine', 'three', 'eleven', 'ten', 'four'], maxtags = 4, key='1') NLUApply text mining on a dataframe. Created by @JohnSnowLabs.nlu.load('sentiment').predict('I love NLU! <3') Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.mention(label=""An awesome Streamlit App"", icon=""streamlit"", url=""https://extras.streamlit.app"",) Annotated textDisplay annotated text in Streamlit apps. Created by @tvst.annotated_text(""This "", (""is"", ""verb""), "" some "", (""annotated"", ""adj""), (""text"", ""noun""), "" for those of "", (""you"", ""pronoun""), "" who "", (""like"", ""verb""), "" this sort of "", (""thing"", ""noun""), ""."") Drawable CanvasProvides a sketching canvas using Fabric.js. Created by @andfanilo.st_canvas(fill_color=""rgba(255, 165, 0, 0.3)"", stroke_width=stroke_width, stroke_color=stroke_color, background_color=bg_color, background_image=Image.open(bg_image) if bg_image else None, update_streamlit=realtime_update, height=150, drawing_mode=drawing_mode, point_display_radius=point_display_radius if drawing_mode == 'point' else 0, key=""canvas"",) TagsAdd tags to your Streamlit apps. Created by @gagan3012.st_tags(label='# Enter Keywords:', text='Press enter to add more', value=['Zero', 'One', 'Two'], suggestions=['five', 'six', 'seven', 'eight', 'nine', 'three', 'eleven', 'ten', 'four'], maxtags = 4, key='1') NLUApply text mining on a dataframe. Created by @JohnSnowLabs.nlu.load('sentiment').predict('I love NLU! <3') Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.mention(label=""An awesome Streamlit App"", icon=""streamlit"", url=""https://extras.streamlit.app"",) Annotated textDisplay annotated text in Streamlit apps. Created by @tvst.annotated_text(""This "", (""is"", ""verb""), "" some "", (""annotated"", ""adj""), (""text"", ""noun""), "" for those of "", (""you"", ""pronoun""), "" who "", (""like"", ""verb""), "" this sort of "", (""thing"", ""noun""), ""."") Drawable CanvasProvides a sketching canvas using Fabric.js. Created by @andfanilo.st_canvas(fill_color=""rgba(255, 165, 0, 0.3)"", stroke_width=stroke_width, stroke_color=stroke_color, background_color=bg_color, background_image=Image.open(bg_image) if bg_image else None, update_streamlit=realtime_update, height=150, drawing_mode=drawing_mode, point_display_radius=point_display_radius if drawing_mode == 'point' else 0, key=""canvas"",) TagsAdd tags to your Streamlit apps. Created by @gagan3012.st_tags(label='# Enter Keywords:', text='Press enter to add more', value=['Zero', 'One', 'Two'], suggestions=['five', 'six', 'seven', 'eight', 'nine', 'three', 'eleven', 'ten', 'four'], maxtags = 4, key='1') NLUApply text mining on a dataframe. Created by @JohnSnowLabs.nlu.load('sentiment').predict('I love NLU! <3') Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.mention(label=""An awesome Streamlit App"", icon=""streamlit"", url=""https://extras.streamlit.app"",) Next Data elements DataframesDisplay a dataframe as an interactive table.st.dataframe(my_data_frame) Data editorDisplay a data editor widget.edited = st.data_editor(df, num_rows=""dynamic"") Column configurationConfigure the display and editing behavior of dataframes and data editors.st.column_config.NumberColumn(""Price (in USD)"", min_value=0, format=""$%d"") Static tablesDisplay a static table.st.table(my_data_frame) MetricsDisplay a metric in big bold font, with an optional indicator of how the metric changed.st.metric(""My metric"", 42, 2) Dicts and JSONDisplay object or string as a pretty-printed JSON string.st.json(my_dict) Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration! PreviousImage CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates value = streamlit_image_coordinates(""https://placekitten.com/200/300"") st.write(value) Plotly EventsMake Plotly charts interactive!. Created by @null-jones.from streamlit_plotly_events import plotly_events fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.metric_cards import style_metric_cards col3.metric(label=""No Change"", value=5000, delta=0) style_metric_cards() Streamlit AggridImplementation of Ag-Grid component for Streamlit. Created by @PablocFonseca.df = pd.DataFrame({'col1': [1, 2, 3], 'col2': [4, 5, 6]}) grid_return = AgGrid(df, editable=True) new_df = grid_return['data'] Streamlit FoliumStreamlit Component for rendering Folium maps. Created by @randyzwitch.m = folium.Map(location=[39.949610, -75.150282], zoom_start=16) folium.Marker([39.949610, -75.150282], popup=""Liberty Bell"", tooltip=""Liberty Bell"").add_to(m) st_data = st_folium(m, width=725) Pandas ProfilingPandas profiling component for Streamlit. Created by @okld.df = pd.read_csv(""https://storage.googleapis.com/tf-datasets/titanic/train.csv"") pr = df.profile_report() st_profile_report(pr) Image CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates value = streamlit_image_coordinates(""https://placekitten.com/200/300"") st.write(value) Plotly EventsMake Plotly charts interactive!. Created by @null-jones.from streamlit_plotly_events import plotly_events fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.metric_cards import style_metric_cards col3.metric(label=""No Change"", value=5000, delta=0) style_metric_cards() Streamlit AggridImplementation of Ag-Grid component for Streamlit. Created by @PablocFonseca.df = pd.DataFrame({'col1': [1, 2, 3], 'col2': [4, 5, 6]}) grid_return = AgGrid(df, editable=True) new_df = grid_return['data'] Streamlit FoliumStreamlit Component for rendering Folium maps. Created by @randyzwitch.m = folium.Map(location=[39.949610, -75.150282], zoom_start=16) folium.Marker([39.949610, -75.150282], popup=""Liberty Bell"", tooltip=""Liberty Bell"").add_to(m) st_data = st_folium(m, width=725) Pandas ProfilingPandas profiling component for Streamlit. Created by @okld.df = pd.read_csv(""https://storage.googleapis.com/tf-datasets/titanic/train.csv"") pr = df.profile_report() st_profile_report(pr) Image CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates value = streamlit_image_coordinates(""https://placekitten.com/200/300"") st.write(value) Plotly EventsMake Plotly charts interactive!. Created by @null-jones.from streamlit_plotly_events import plotly_events fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.metric_cards import style_metric_cards col3.metric(label=""No Change"", value=5000, delta=0) style_metric_cards() Next Chart elements Simple area chartsDisplay an area chart.st.area_chart(my_data_frame) Simple bar chartsDisplay a bar chart.st.bar_chart(my_data_frame) Simple line chartsDisplay a line chart.st.line_chart(my_data_frame) Simple scatter chartsDisplay a line chart.st.scatter_chart(my_data_frame) Scatterplots on mapsDisplay a map with points on it.st.map(my_data_frame) MatplotlibDisplay a matplotlib.pyplot figure.st.pyplot(my_mpl_figure) AltairDisplay a chart using the Altair library.st.altair_chart(my_altair_chart) Vega-LiteDisplay a chart using the Vega-Lite library.st.vega_lite_chart(my_vega_lite_chart) PlotlyDisplay an interactive Plotly chart.st.plotly_chart(my_plotly_chart) BokehDisplay an interactive Bokeh chart.st.bokeh_chart(my_bokeh_chart) PyDeckDisplay a chart using the PyDeck library.st.pydeck_chart(my_pydeck_chart) GraphVizDisplay a graph using the dagre-d3 library.st.graphviz_chart(my_graphviz_spec) Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration! PreviousStreamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl(""https://assets5.lottiefiles.com/packages/lf20_V9t630.json"") st_lottie(lottie_hello, key=""hello"") Plotly EventsMake Plotly charts interactive!. Created by @null-jones.fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.chart += get_annotations_chart(annotations=[(""Mar 01, 2008"", ""Pretty good day for GOOG""), (""Dec 01, 2007"", ""Something's going wrong for GOOG & AAPL""), (""Nov 01, 2008"", ""Market starts again thanks to...""), (""Dec 01, 2009"", ""Small crash for GOOG after...""),],) st.altair_chart(chart, use_container_width=True) PlostA deceptively simple plotting library for Streamlit. Created by @tvst.import plost plost.line_chart(my_dataframe, x='time', y='stock_value', color='stock_name',) HiPlotHigh dimensional Interactive Plotting. Created by @facebookresearch.data = [{'dropout':0.1, 'lr': 0.001, 'loss': 10.0, 'optimizer': 'SGD'}, {'dropout':0.15, 'lr': 0.01, 'loss': 3.5, 'optimizer': 'Adam'}, {'dropout':0.3, 'lr': 0.1, 'loss': 4.5, 'optimizer': 'Adam'}] hip.Experiment.from_iterable(data).display() EChartsHigh dimensional Interactive Plotting. Created by @andfanilo.from streamlit_echarts import st_echarts st_echarts(options=options) Streamlit FoliumStreamlit Component for rendering Folium maps. Created by @randyzwitch.m = folium.Map(location=[39.949610, -75.150282], zoom_start=16) st_data = st_folium(m, width=725) Spacy-StreamlitspaCy building blocks and visualizers for Streamlit apps. Created by @explosion.models = [""en_core_web_sm"", ""en_core_web_md""] spacy_streamlit.visualize(models, ""Sundar Pichai is the CEO of Google."") Streamlit AgraphA Streamlit Graph Vis, based on react-grah-vis. Created by @ChrisDelClea.from streamlit_agraph import agraph, Node, Edge, Config agraph(nodes=nodes, edges=edges, config=config) Streamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl(""https://assets5.lottiefiles.com/packages/lf20_V9t630.json"") st_lottie(lottie_hello, key=""hello"") Plotly EventsMake Plotly charts interactive!. Created by @null-jones.fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.chart += get_annotations_chart(annotations=[(""Mar 01, 2008"", ""Pretty good day for GOOG""), (""Dec 01, 2007"", ""Something's going wrong for GOOG & AAPL""), (""Nov 01, 2008"", ""Market starts again thanks to...""), (""Dec 01, 2009"", ""Small crash for GOOG after...""),],) st.altair_chart(chart, use_container_width=True) PlostA deceptively simple plotting library for Streamlit. Created by @tvst.import plost plost.line_chart(my_dataframe, x='time', y='stock_value', color='stock_name',) HiPlotHigh dimensional Interactive Plotting. Created by @facebookresearch.data = [{'dropout':0.1, 'lr': 0.001, 'loss': 10.0, 'optimizer': 'SGD'}, {'dropout':0.15, 'lr': 0.01, 'loss': 3.5, 'optimizer': 'Adam'}, {'dropout':0.3, 'lr': 0.1, 'loss': 4.5, 'optimizer': 'Adam'}] hip.Experiment.from_iterable(data).display() EChartsHigh dimensional Interactive Plotting. Created by @andfanilo.from streamlit_echarts import st_echarts st_echarts(options=options) Streamlit FoliumStreamlit Component for rendering Folium maps. Created by @randyzwitch.m = folium.Map(location=[39.949610, -75.150282], zoom_start=16) st_data = st_folium(m, width=725) Spacy-StreamlitspaCy building blocks and visualizers for Streamlit apps. Created by @explosion.models = [""en_core_web_sm"", ""en_core_web_md""] spacy_streamlit.visualize(models, ""Sundar Pichai is the CEO of Google."") Streamlit AgraphA Streamlit Graph Vis, based on react-grah-vis. Created by @ChrisDelClea.from streamlit_agraph import agraph, Node, Edge, Config agraph(nodes=nodes, edges=edges, config=config) Streamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl(""https://assets5.lottiefiles.com/packages/lf20_V9t630.json"") st_lottie(lottie_hello, key=""hello"") Plotly EventsMake Plotly charts interactive!. Created by @null-jones.fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.chart += get_annotations_chart(annotations=[(""Mar 01, 2008"", ""Pretty good day for GOOG""), (""Dec 01, 2007"", ""Something's going wrong for GOOG & AAPL""), (""Nov 01, 2008"", ""Market starts again thanks to...""), (""Dec 01, 2009"", ""Small crash for GOOG after...""),],) st.altair_chart(chart, use_container_width=True) Next Input widgets ButtonDisplay a button widget.clicked = st.button(""Click me"") Download buttonDisplay a download button widget.st.download_button(""Download file"", file) Form buttonDisplay a form submit button. For use with st.form.st.form_submit_button(""Sign up"") Link buttonDisplay a link button.st.link_button(""Go to gallery"", url) Page linkDisplay a link to another page in a multipage app.st.page_link(""app.py"", label=""Home"", icon=""🏠"") st.page_link(""pages/profile.py"", label=""My profile"") CheckboxDisplay a checkbox widget.selected = st.checkbox(""I agree"") Color pickerDisplay a color picker widget.color = st.color_picker(""Pick a color"") MultiselectDisplay a multiselect widget. The multiselect widget starts as empty.choices = st.multiselect(""Buy"", [""milk"", ""apples"", ""potatoes""]) RadioDisplay a radio button widget.choice = st.radio(""Pick one"", [""cats"", ""dogs""]) SelectboxDisplay a select widget.choice = st.selectbox(""Pick one"", [""cats"", ""dogs""]) Select-sliderDisplay a slider widget to select items from a list.size = st.select_slider(""Pick a size"", [""S"", ""M"", ""L""]) ToggleDisplay a toggle widget.activated = st.toggle(""Activate"") Number inputDisplay a numeric input widget.choice = st.number_input(""Pick a number"", 0, 10) SliderDisplay a slider widget.number = st.slider(""Pick a number"", 0, 100) Date inputDisplay a date input widget.date = st.date_input(""Your birthday"") Time inputDisplay a time input widget.time = st.time_input(""Meeting time"") Chat inputDisplay a chat input widget.prompt = st.chat_input(""Say something"") if prompt: st.write(f""The user has sent: {prompt}"") Text-areaDisplay a multi-line text input widget.text = st.text_area(""Text to translate"") Text inputDisplay a single-line text input widget.name = st.text_input(""First name"") Data editorDisplay a data editor widget.edited = st.experimental_data_editor(df, num_rows=""dynamic"") File UploaderDisplay a file uploader widget.data = st.file_uploader(""Upload a CSV"") Camera inputDisplay a widget that allows users to upload images directly from a camera.image = st.camera_input(""Take a picture"") Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration! PreviousStreamlit ChatStreamlit Component for a Chatbot UI. Created by @AI-Yash.from streamlit_chat import message message(""My message"") message(""Hello bot!"", is_user=True) # align's the message to the right Streamlit Option MenuSelect a single item from a list of options in a menu. Created by @victoryhb.from streamlit_option_menu import option_menu option_menu(""Main Menu"", [""Home"", 'Settings'], icons=['house', 'gear'], menu_icon=""cast"", default_index=1) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.stoggle import stoggle stoggle( ""Click me!"", """"""🥷 Surprise! Here's some additional content"""""",) Streamlit ElementsCreate a draggable and resizable dashboard in Streamlit. Created by @okls.from streamlit_elements import elements, mui, html with elements(""new_element""): mui.Typography(""Hello world"") TagsAdd tags to your Streamlit apps. Created by @gagan3012.from streamlit_tags import st_tags st_tags(label='# Enter Keywords:', text='Press enter to add more', value=['Zero', 'One', 'Two'], suggestions=['five', 'six', 'seven', 'eight', 'nine', 'three', 'eleven', 'ten', 'four'], maxtags = 4, key='1') StqdmThe simplest way to handle a progress bar in streamlit app. Created by @Wirg.from stqdm import stqdm for _ in stqdm(range(50)): sleep(0.5) TimelineDisplay a Timeline in Streamlit apps using TimelineJS. Created by @innerdoc.from streamlit_timeline import timeline with open('example.json', ""r"") as f: timeline(f.read(), height=800) Camera input liveAlternative for st.camera_input which returns the webcam images live. Created by @blackary.from camera_input_live import camera_input_live image = camera_input_live() st.image(value) Streamlit AceAce editor component for Streamlit. Created by @okld.from streamlit_ace import st_ace content = st_ace() content Streamlit ChatStreamlit Component for a Chatbot UI. Created by @AI-Yash.from streamlit_chat import message message(""My message"") message(""Hello bot!"", is_user=True) # align's the message to the right Streamlit Option MenuSelect a single item from a list of options in a menu. Created by @victoryhb.from streamlit_option_menu import option_menu option_menu(""Main Menu"", [""Home"", 'Settings'], icons=['house', 'gear'], menu_icon=""cast"", default_index=1) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.stoggle import stoggle stoggle( ""Click me!"", """"""🥷 Surprise! Here's some additional content"""""",) Streamlit ElementsCreate a draggable and resizable dashboard in Streamlit. Created by @okls.from streamlit_elements import elements, mui, html with elements(""new_element""): mui.Typography(""Hello world"") TagsAdd tags to your Streamlit apps. Created by @gagan3012.from streamlit_tags import st_tags st_tags(label='# Enter Keywords:', text='Press enter to add more', value=['Zero', 'One', 'Two'], suggestions=['five', 'six', 'seven', 'eight', 'nine', 'three', 'eleven', 'ten', 'four'], maxtags = 4, key='1') StqdmThe simplest way to handle a progress bar in streamlit app. Created by @Wirg.from stqdm import stqdm for _ in stqdm(range(50)): sleep(0.5) TimelineDisplay a Timeline in Streamlit apps using TimelineJS. Created by @innerdoc.from streamlit_timeline import timeline with open('example.json', ""r"") as f: timeline(f.read(), height=800) Camera input liveAlternative for st.camera_input which returns the webcam images live. Created by @blackary.from camera_input_live import camera_input_live image = camera_input_live() st.image(value) Streamlit AceAce editor component for Streamlit. Created by @okld.from streamlit_ace import st_ace content = st_ace() content Streamlit ChatStreamlit Component for a Chatbot UI. Created by @AI-Yash.from streamlit_chat import message message(""My message"") message(""Hello bot!"", is_user=True) # align's the message to the right Streamlit Option MenuSelect a single item from a list of options in a menu. Created by @victoryhb.from streamlit_option_menu import option_menu option_menu(""Main Menu"", [""Home"", 'Settings'], icons=['house', 'gear'], menu_icon=""cast"", default_index=1) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.stoggle import stoggle stoggle( ""Click me!"", """"""🥷 Surprise! Here's some additional content"""""",) Next Media elements ImageDisplay an image or list of images.st.image(numpy_array) st.image(image_bytes) st.image(file) st.image(""https://example.com/myimage.jpg"") AudioDisplay an audio player.st.audio(numpy_array) st.audio(audio_bytes) st.audio(file) st.audio(""https://example.com/myaudio.mp3"", format=""audio/mp3"") VideoDisplay a video player.st.video(numpy_array) st.video(video_bytes) st.video(file) st.video(""https://example.com/myvideo.mp4"", format=""video/mp4"") Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration! PreviousStreamlit CropperA simple image cropper for Streamlit. Created by @turner-anderson.from streamlit_cropper import st_cropper st_cropper(img, realtime_update=realtime_update, box_color=box_color, aspect_ratio=aspect_ratio) Image CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates streamlit_image_coordinates(""https://placekitten.com/200/300"") Streamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl(""https://assets5.lottiefiles.com/packages/lf20_V9t630.json"") st_lottie(lottie_hello, key=""hello"") Streamlit WebrtcHandling and transmitting real-time video/audio streams with Streamlit. Created by @whitphx.from streamlit_webrtc import webrtc_streamer webrtc_streamer(key=""sample"") Drawable CanvasProvides a sketching canvas using Fabric.js. Created by @andfanilo.from streamlit_drawable_canvas import st_canvas st_canvas(fill_color=""rgba(255, 165, 0, 0.3)"", stroke_width=stroke_width, stroke_color=stroke_color, background_color=bg_color, background_image=Image.open(bg_image) if bg_image else None, update_streamlit=realtime_update, height=150, drawing_mode=drawing_mode, point_display_radius=point_display_radius if drawing_mode == 'point' else 0, key=""canvas"",) Image ComparisonCompare images with a slider using JuxtaposeJS. Created by @fcakyon.from streamlit_image_comparison import image_comparison image_comparison(img1=""image1.jpg"", img2=""image2.jpg"",) Streamlit CropperA simple image cropper for Streamlit. Created by @turner-anderson.from streamlit_cropper import st_cropper st_cropper(img, realtime_update=realtime_update, box_color=box_color, aspect_ratio=aspect_ratio) Image CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates streamlit_image_coordinates(""https://placekitten.com/200/300"") Streamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl(""https://assets5.lottiefiles.com/packages/lf20_V9t630.json"") st_lottie(lottie_hello, key=""hello"") Streamlit WebrtcHandling and transmitting real-time video/audio streams with Streamlit. Created by @whitphx.from streamlit_webrtc import webrtc_streamer webrtc_streamer(key=""sample"") Drawable CanvasProvides a sketching canvas using Fabric.js. Created by @andfanilo.from streamlit_drawable_canvas import st_canvas st_canvas(fill_color=""rgba(255, 165, 0, 0.3)"", stroke_width=stroke_width, stroke_color=stroke_color, background_color=bg_color, background_image=Image.open(bg_image) if bg_image else None, update_streamlit=realtime_update, height=150, drawing_mode=drawing_mode, point_display_radius=point_display_radius if drawing_mode == 'point' else 0, key=""canvas"",) Image ComparisonCompare images with a slider using JuxtaposeJS. Created by @fcakyon.from streamlit_image_comparison import image_comparison image_comparison(img1=""image1.jpg"", img2=""image2.jpg"",) Streamlit CropperA simple image cropper for Streamlit. Created by @turner-anderson.from streamlit_cropper import st_cropper st_cropper(img, realtime_update=realtime_update, box_color=box_color, aspect_ratio=aspect_ratio) Image CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates streamlit_image_coordinates(""https://placekitten.com/200/300"") Streamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl(""https://assets5.lottiefiles.com/packages/lf20_V9t630.json"") st_lottie(lottie_hello, key=""hello"") Next Layouts and containers ColumnsInsert containers laid out as side-by-side columns.col1, col2 = st.columns(2) col1.write(""this is column 1"") col2.write(""this is column 2"") ContainerInsert a multi-element container.c = st.container() st.write(""This will show last"") c.write(""This will show first"") c.write(""This will show second"") Modal dialogsInsert a modal dialog that can rerun independently from the rest of the script.@st.experimental_dialog(""Sign up"") def email_form(): name = st.text_input(""Name"") email = st.text_input(""Email"") EmptyInsert a single-element container.c = st.empty() st.write(""This will show last"") c.write(""This will be replaced"") c.write(""This will show first"") ExpanderInsert a multi-element container that can be expanded/collapsed.with st.expander(""Open to see more""): st.write(""This is more content"") PopoverInsert a multi-element popover container that can be opened/closed.with st.popover(""Settings""): st.checkbox(""Show completed"") SidebarDisplay items in a sidebar.st.sidebar.write(""This lives in the sidebar"") st.sidebar.button(""Click me!"") TabsInsert containers separated into tabs.tab1, tab2 = st.tabs([""Tab 1"", ""Tab2""]) tab1.write(""this is tab 1"") tab2.write(""this is tab 2"") Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration!Streamlit ElementsCreate a draggable and resizable dashboard in Streamlit. Created by @okls.from streamlit_elements import elements, mui, html with elements(""new_element""): mui.Typography(""Hello world"") PydanticAuto-generate Streamlit UI from Pydantic Models and Dataclasses. Created by @lukasmasuch.import streamlit_pydantic as sp sp.pydantic_form(key=""my_form"", model=ExampleModel) Streamlit PagesAn experimental version of Streamlit Multi-Page Apps. Created by @blackary.from st_pages import Page, show_pages, add_page_title show_pages([ Page(""streamlit_app.py"", ""Home"", ""🏠""), Page(""other_pages/page2.py"", ""Page 2"", "":books:""), ]) Chat elements Streamlit provides a few commands to help you build conversational apps. These chat elements are designed to be used in conjunction with each other, but you can also use them separately. st.chat_message lets you insert a chat message container into the app so you can display messages from the user or the app. Chat containers can contain other Streamlit elements, including charts, tables, text, and more. st.chat_input lets you display a chat input widget so the user can type in a message. Chat inputDisplay a chat input widget.prompt = st.chat_input(""Say something"") if prompt: st.write(f""The user has sent: {prompt}"") Chat messageInsert a chat message container.import numpy as np with st.chat_message(""user""): st.write(""Hello 👋"") st.line_chart(np.random.randn(30, 3)) Status containerDisplay output of long-running tasks in a container.with st.status('Running'): do_something_slow() st.write_streamWrite generators or streams to the app with a typewriter effect.st.write_stream(my_generator) st.write_stream(my_llm_stream) Status elements Progress barDisplay a progress bar.for i in range(101): st.progress(i) do_something_slow() SpinnerTemporarily displays a message while executing a block of code.with st.spinner(""Please wait...""): do_something_slow() Status containerDisplay output of long-running tasks in a container.with st.status('Running'): do_something_slow() ToastBriefly displays a toast message in the bottom-right corner.st.toast('Butter!', icon='🧈') BalloonsDisplay celebratory balloons!do_something() # Celebrate when all done! st.balloons() SnowflakesDisplay celebratory snowflakes!do_something() # Celebrate when all done! st.snow() Success boxDisplay a success message.st.success(""Match found!"") Info boxDisplay an informational message.st.info(""Dataset is updated every day at midnight."") Warning boxDisplay warning message.st.warning(""Unable to fetch image. Skipping..."") Error boxDisplay error message.st.error(""We encountered an error"") Exception outputDisplay an exception.e = RuntimeError(""This is an exception of type RuntimeError"") st.exception(e) Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration!StqdmThe simplest way to handle a progress bar in streamlit app. Created by @Wirg.from stqdm import stqdm for _ in stqdm(range(50)): sleep(0.5) Custom notification boxA custom notification box with the ability to close it out. Created by @Socvest.from streamlit_custom_notification_box import custom_notification_box styles = {'material-icons':{'color': 'red'}, 'text-icon-link-close-container': {'box-shadow': '#3896de 0px 4px'}, 'notification-text': {'':''}, 'close-button':{'':''}, 'link':{'':''}} custom_notification_box(icon='info', textDisplay='We are almost done with your registration...', externalLink='more info', url='#', styles=styles, key=""foo"") Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.let_it_rain import rain rain(emoji=""🎈"", font_size=54, falling_speed=5, animation_length=""infinite"",) App logic and configuration Navigation and pages Switch pageProgrammatically navigates to a specified page.st.switch_page(""pages/my_page.py"") Page linkDisplay a link to another page in a multipage app.st.page_link(""app.py"", label=""Home"", icon=""🏠"") st.page_link(""pages/profile.py"", label=""My profile"") Execution flow Modal dialogsInsert a modal dialog that can rerun independently from the rest of the script.@st.experimental_dialog(""Sign up"") def email_form(): name = st.text_input(""Name"") email = st.text_input(""Email"") FormsCreate a form that batches elements together with a “Submit"" button.with st.form(key='my_form'): name = st.text_input(""Name"") email = st.text_input(""Email"") st.form_submit_button(""Sign up"") Partial rerunsDefine a fragment to rerun independently from the rest of the script.@st.experimental_fragment(run_every=""10s"") def fragment(): df = get_data() st.line_chart(df) Rerun scriptRerun the script immediately.st.rerun() Stop executionStops execution immediately.st.stop() Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration!AutorefreshForce a refresh without tying up a script. Created by @kmcgrady.from streamlit_autorefresh import st_autorefresh st_autorefresh(interval=2000, limit=100, key=""fizzbuzzcounter"") PydanticAuto-generate Streamlit UI from Pydantic Models and Dataclasses. Created by @lukasmasuch.import streamlit_pydantic as sp sp.pydantic_form(key=""my_form"", model=ExampleModel) Streamlit PagesAn experimental version of Streamlit Multi-Page Apps. Created by @blackary.from st_pages import Page, show_pages, add_page_title show_pages([ Page(""streamlit_app.py"", ""Home"", ""🏠""), Page(""other_pages/page2.py"", ""Page 2"", "":books:""), ]) Caching and state Cache dataFunction decorator to cache functions that return data (e.g. dataframe transforms, database queries, ML inference).@st.cache_data def long_function(param1, param2): # Perform expensive computation here or # fetch data from the web here return data Cache resourceFunction decorator to cache functions that return global resources (e.g. database connections, ML models).@st.cache_resource def init_model(): # Return a global resource here return pipeline( ""sentiment-analysis"", model=""distilbert-base-uncased-finetuned-sst-2-english"" ) Session stateSession state is a way to share variables between reruns, for each user session.st.session_state['key'] = value Query parametersGet, set, or clear the query parameters that are shown in the browser's URL bar.st.query_params[key] = value st.query_params.clear() Connections and databases Setup your connection Create a connectionConnect to a data source or APIconn = st.connection('pets_db', type='sql') pet_owners = conn.query('select * from pet_owners') st.dataframe(pet_owners) Built-in connections SnowflakeConnectionA connection to Snowflake.conn = st.connection('snowflake') SQLConnectionA connection to a SQL database using SQLAlchemy.conn = st.connection('sql') Build your own connections Connection base classBuild your own connection with BaseConnection.class MyConnection(BaseConnection[myconn.MyConnection]): def _connect(self, **kwargs) -> MyConnection: return myconn.connect(**self._secrets, **kwargs) def query(self, query): return self._instance.query(query) Secrets management Secrets singletonAccess secrets from a local TOML file.key = st.secrets[""OpenAI_key""] Secrets fileSave your secrets in a per-project or per-profile TOML file.OpenAI_key = """" Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration!AuthenticatorA secure authentication module to validate user credentials. Created by @mkhorasani.import streamlit_authenticator as stauth authenticator = stauth.Authenticate( config['credentials'], config['cookie']['name'], config['cookie']['key'], config['cookie']['expiry_days'], config['preauthorized']) WS localStorageA simple synchronous way of accessing localStorage from your app. Created by @gagangoku.from streamlit_ws_localstorage import injectWebsocketCode ret = conn.setLocalStorageVal(key='k1', val='v1') st.write('ret: ' + ret) Streamlit Auth0The fastest way to provide comprehensive login inside Streamlit. Created by @conradbez.from auth0_component import login_button user_info = login_button(clientId, domain = domain) st.write(user_info) Custom Components Declare a componentCreate and register a custom component.st.components.v1.declare_component( ""custom_slider"", ""/frontend"", ) HTMLDisplay an HTML string in an iframe.st.components.v1.html( ""

Foo bar.

"" ) iframeLoad a remote URL in an iframe.st.components.v1.iframe( ""docs.streamlit.io"" ) Utilities and user info User infost.experimental_user returns information about the logged-in user of private apps on Streamlit Community Cloud.if st.experimental_user.email == ""foo@corp.com"": st.write(""Welcome back, "", st.experimental_user.email) else: st.write(""You are not authorized to view this page."") Get helpDisplay object’s doc string, nicely formatted.st.help(st.write) st.help(pd.DataFrame) Render HTMLRenders HTML strings to your app.css = """""" """""" st.html(css) Configuration Configuration fileConfigures the default settings for your app.your-project/ ├── .streamlit/ │ └── config.toml └── your_app.py Set page title, favicon, and moreConfigures the default settings of the page.st.set_page_config( page_title=""My app"", page_icon="":shark:"", ) Developer tools App testing st.testing.v1.AppTestst.testing.v1.AppTest simulates a running Streamlit app for testing.from streamlit.testing.v1 import AppTest at = AppTest.from_file(""streamlit_app.py"") at.secrets[""WORD""] = ""Foobar"" at.run() assert not at.exception at.text_input(""word"").input(""Bazbat"").run() assert at.warning[0].value == ""Try again."" AppTest.from_filest.testing.v1.AppTest.from_file initializes a simulated app from a file.from streamlit.testing.v1 import AppTest at = AppTest.from_file(""streamlit_app.py"") at.run() AppTest.from_stringst.testing.v1.AppTest.from_string initializes a simulated app from a string.from streamlit.testing.v1 import AppTest at = AppTest.from_string(app_script_as_string) at.run() AppTest.from_functionst.testing.v1.AppTest.from_function initializes a simulated app from a function.from streamlit.testing.v1 import AppTest at = AppTest.from_function(app_script_as_callable) at.run() BlockA representation of container elements, including: st.chat_message st.columns st.sidebar st.tabs The main body of the app. # at.sidebar returns a Block at.sidebar.button[0].click().run() assert not at.exception ElementThe base class for representation of all elements, including: st.title st.header st.markdown st.dataframe # at.title returns a sequence of Title # Title inherits from Element assert at.title[0].value == ""My awesome app"" ButtonA representation of st.button and st.form_submit_button.at.button[0].click().run() ChatInputA representation of st.chat_input.at.chat_input[0].set_value(""What is Streamlit?"").run() CheckboxA representation of st.checkbox.at.checkbox[0].check().run() ColorPickerA representation of st.color_picker.at.color_picker[0].pick(""#FF4B4B"").run() DateInputA representation of st.date_input.release_date = datetime.date(2023, 10, 26) at.date_input[0].set_value(release_date).run() MultiselectA representation of st.multiselect.at.multiselect[0].select(""New York"").run() NumberInputA representation of st.number_input.at.number_input[0].increment().run() RadioA representation of st.radio.at.radio[0].set_value(""New York"").run() SelectSliderA representation of st.select_slider.at.select_slider[0].set_range(""A"",""C"").run() SelectboxA representation of st.selectbox.at.selectbox[0].select(""New York"").run() SliderA representation of st.slider.at.slider[0].set_range(2,5).run() TextAreaA representation of st.text_area.at.text_area[0].input(""Streamlit is awesome!"").run() TextInputA representation of st.text_input.at.text_input[0].input(""Streamlit"").run() TimeInputA representation of st.time_input.at.time_input[0].increment().run() ToggleA representation of st.toggle.at.toggle[0].set_value(""True"").run() Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration!Pandas ProfilingPandas profiling component for Streamlit. Created by @okld.df = pd.read_csv(""https://storage.googleapis.com/tf-datasets/titanic/train.csv"") pr = df.profile_report() st_profile_report(pr) Streamlit AceAce editor component for Streamlit. Created by @okld.from streamlit_ace import st_ace content = st_ace() content Streamlit AnalyticsTrack & visualize user interactions with your streamlit app. Created by @jrieke.import streamlit_analytics with streamlit_analytics.track(): st.text_input(""Write something"") Previous: ConceptsNext: Write and magicforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy" https://docs.streamlit.io/en/latest/api.html#pre-release-features,"DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceremovePAGE ELEMENTSWrite and magicaddText elementsaddData elementsaddChart elementsaddInput widgetsaddMedia elementsaddLayouts and containersaddChat elementsaddStatus elementsaddThird-party componentsopen_in_newAPPLICATION LOGICNavigation and pagesaddExecution flowaddCaching and stateaddConnections and secretsaddCustom componentsaddUtilitiesaddConfigurationaddTOOLSApp testingaddCommand lineaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Develop/API referenceAPI reference Streamlit makes it easy for you to visualize, mutate, and share data. The API reference is organized by activity type, like displaying data or optimizing performance. Each section includes methods associated with the activity type, including examples. Browse our API below and click to learn more about any of our available commands! 🎈 Display almost anything Write and magic st.writeWrite arguments to the app.st.write(""Hello **world**!"") st.write(my_data_frame) st.write(my_mpl_figure) st.write_streamWrite generators or streams to the app with a typewriter effect.st.write_stream(my_generator) st.write_stream(my_llm_stream) MagicAny time Streamlit sees either a variable or literal value on its own line, it automatically writes that to your app using st.write""Hello **world**!"" my_data_frame my_mpl_figure Text elements MarkdownDisplay string formatted as Markdown.st.markdown(""Hello **world**!"") TitleDisplay text in title formatting.st.title(""The app title"") HeaderDisplay text in header formatting.st.header(""This is a header"") SubheaderDisplay text in subheader formatting.st.subheader(""This is a subheader"") CaptionDisplay text in small font.st.caption(""This is written small caption text"") Code blockDisplay a code block with optional syntax highlighting.st.code(""a = 1234"") EchoDisplay some code in the app, then execute it. Useful for tutorials.with st.echo(): st.write('This code will be printed') LaTeXDisplay mathematical expressions formatted as LaTeX.st.latex(""\int a x^2 \,dx"") Preformatted textWrite fixed-width and preformatted text.st.text(""Hello world"") DividerDisplay a horizontal rule.st.divider() Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration! PreviousTagsAdd tags to your Streamlit apps. Created by @gagan3012.st_tags(label='# Enter Keywords:', text='Press enter to add more', value=['Zero', 'One', 'Two'], suggestions=['five', 'six', 'seven', 'eight', 'nine', 'three', 'eleven', 'ten', 'four'], maxtags = 4, key='1') NLUApply text mining on a dataframe. Created by @JohnSnowLabs.nlu.load('sentiment').predict('I love NLU! <3') Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.mention(label=""An awesome Streamlit App"", icon=""streamlit"", url=""https://extras.streamlit.app"",) Annotated textDisplay annotated text in Streamlit apps. Created by @tvst.annotated_text(""This "", (""is"", ""verb""), "" some "", (""annotated"", ""adj""), (""text"", ""noun""), "" for those of "", (""you"", ""pronoun""), "" who "", (""like"", ""verb""), "" this sort of "", (""thing"", ""noun""), ""."") Drawable CanvasProvides a sketching canvas using Fabric.js. Created by @andfanilo.st_canvas(fill_color=""rgba(255, 165, 0, 0.3)"", stroke_width=stroke_width, stroke_color=stroke_color, background_color=bg_color, background_image=Image.open(bg_image) if bg_image else None, update_streamlit=realtime_update, height=150, drawing_mode=drawing_mode, point_display_radius=point_display_radius if drawing_mode == 'point' else 0, key=""canvas"",) TagsAdd tags to your Streamlit apps. Created by @gagan3012.st_tags(label='# Enter Keywords:', text='Press enter to add more', value=['Zero', 'One', 'Two'], suggestions=['five', 'six', 'seven', 'eight', 'nine', 'three', 'eleven', 'ten', 'four'], maxtags = 4, key='1') NLUApply text mining on a dataframe. Created by @JohnSnowLabs.nlu.load('sentiment').predict('I love NLU! <3') Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.mention(label=""An awesome Streamlit App"", icon=""streamlit"", url=""https://extras.streamlit.app"",) Annotated textDisplay annotated text in Streamlit apps. Created by @tvst.annotated_text(""This "", (""is"", ""verb""), "" some "", (""annotated"", ""adj""), (""text"", ""noun""), "" for those of "", (""you"", ""pronoun""), "" who "", (""like"", ""verb""), "" this sort of "", (""thing"", ""noun""), ""."") Drawable CanvasProvides a sketching canvas using Fabric.js. Created by @andfanilo.st_canvas(fill_color=""rgba(255, 165, 0, 0.3)"", stroke_width=stroke_width, stroke_color=stroke_color, background_color=bg_color, background_image=Image.open(bg_image) if bg_image else None, update_streamlit=realtime_update, height=150, drawing_mode=drawing_mode, point_display_radius=point_display_radius if drawing_mode == 'point' else 0, key=""canvas"",) TagsAdd tags to your Streamlit apps. Created by @gagan3012.st_tags(label='# Enter Keywords:', text='Press enter to add more', value=['Zero', 'One', 'Two'], suggestions=['five', 'six', 'seven', 'eight', 'nine', 'three', 'eleven', 'ten', 'four'], maxtags = 4, key='1') NLUApply text mining on a dataframe. Created by @JohnSnowLabs.nlu.load('sentiment').predict('I love NLU! <3') Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.mention(label=""An awesome Streamlit App"", icon=""streamlit"", url=""https://extras.streamlit.app"",) Next Data elements DataframesDisplay a dataframe as an interactive table.st.dataframe(my_data_frame) Data editorDisplay a data editor widget.edited = st.data_editor(df, num_rows=""dynamic"") Column configurationConfigure the display and editing behavior of dataframes and data editors.st.column_config.NumberColumn(""Price (in USD)"", min_value=0, format=""$%d"") Static tablesDisplay a static table.st.table(my_data_frame) MetricsDisplay a metric in big bold font, with an optional indicator of how the metric changed.st.metric(""My metric"", 42, 2) Dicts and JSONDisplay object or string as a pretty-printed JSON string.st.json(my_dict) Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration! PreviousImage CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates value = streamlit_image_coordinates(""https://placekitten.com/200/300"") st.write(value) Plotly EventsMake Plotly charts interactive!. Created by @null-jones.from streamlit_plotly_events import plotly_events fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.metric_cards import style_metric_cards col3.metric(label=""No Change"", value=5000, delta=0) style_metric_cards() Streamlit AggridImplementation of Ag-Grid component for Streamlit. Created by @PablocFonseca.df = pd.DataFrame({'col1': [1, 2, 3], 'col2': [4, 5, 6]}) grid_return = AgGrid(df, editable=True) new_df = grid_return['data'] Streamlit FoliumStreamlit Component for rendering Folium maps. Created by @randyzwitch.m = folium.Map(location=[39.949610, -75.150282], zoom_start=16) folium.Marker([39.949610, -75.150282], popup=""Liberty Bell"", tooltip=""Liberty Bell"").add_to(m) st_data = st_folium(m, width=725) Pandas ProfilingPandas profiling component for Streamlit. Created by @okld.df = pd.read_csv(""https://storage.googleapis.com/tf-datasets/titanic/train.csv"") pr = df.profile_report() st_profile_report(pr) Image CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates value = streamlit_image_coordinates(""https://placekitten.com/200/300"") st.write(value) Plotly EventsMake Plotly charts interactive!. Created by @null-jones.from streamlit_plotly_events import plotly_events fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.metric_cards import style_metric_cards col3.metric(label=""No Change"", value=5000, delta=0) style_metric_cards() Streamlit AggridImplementation of Ag-Grid component for Streamlit. Created by @PablocFonseca.df = pd.DataFrame({'col1': [1, 2, 3], 'col2': [4, 5, 6]}) grid_return = AgGrid(df, editable=True) new_df = grid_return['data'] Streamlit FoliumStreamlit Component for rendering Folium maps. Created by @randyzwitch.m = folium.Map(location=[39.949610, -75.150282], zoom_start=16) folium.Marker([39.949610, -75.150282], popup=""Liberty Bell"", tooltip=""Liberty Bell"").add_to(m) st_data = st_folium(m, width=725) Pandas ProfilingPandas profiling component for Streamlit. Created by @okld.df = pd.read_csv(""https://storage.googleapis.com/tf-datasets/titanic/train.csv"") pr = df.profile_report() st_profile_report(pr) Image CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates value = streamlit_image_coordinates(""https://placekitten.com/200/300"") st.write(value) Plotly EventsMake Plotly charts interactive!. Created by @null-jones.from streamlit_plotly_events import plotly_events fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.metric_cards import style_metric_cards col3.metric(label=""No Change"", value=5000, delta=0) style_metric_cards() Next Chart elements Simple area chartsDisplay an area chart.st.area_chart(my_data_frame) Simple bar chartsDisplay a bar chart.st.bar_chart(my_data_frame) Simple line chartsDisplay a line chart.st.line_chart(my_data_frame) Simple scatter chartsDisplay a line chart.st.scatter_chart(my_data_frame) Scatterplots on mapsDisplay a map with points on it.st.map(my_data_frame) MatplotlibDisplay a matplotlib.pyplot figure.st.pyplot(my_mpl_figure) AltairDisplay a chart using the Altair library.st.altair_chart(my_altair_chart) Vega-LiteDisplay a chart using the Vega-Lite library.st.vega_lite_chart(my_vega_lite_chart) PlotlyDisplay an interactive Plotly chart.st.plotly_chart(my_plotly_chart) BokehDisplay an interactive Bokeh chart.st.bokeh_chart(my_bokeh_chart) PyDeckDisplay a chart using the PyDeck library.st.pydeck_chart(my_pydeck_chart) GraphVizDisplay a graph using the dagre-d3 library.st.graphviz_chart(my_graphviz_spec) Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration! PreviousStreamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl(""https://assets5.lottiefiles.com/packages/lf20_V9t630.json"") st_lottie(lottie_hello, key=""hello"") Plotly EventsMake Plotly charts interactive!. Created by @null-jones.fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.chart += get_annotations_chart(annotations=[(""Mar 01, 2008"", ""Pretty good day for GOOG""), (""Dec 01, 2007"", ""Something's going wrong for GOOG & AAPL""), (""Nov 01, 2008"", ""Market starts again thanks to...""), (""Dec 01, 2009"", ""Small crash for GOOG after...""),],) st.altair_chart(chart, use_container_width=True) PlostA deceptively simple plotting library for Streamlit. Created by @tvst.import plost plost.line_chart(my_dataframe, x='time', y='stock_value', color='stock_name',) HiPlotHigh dimensional Interactive Plotting. Created by @facebookresearch.data = [{'dropout':0.1, 'lr': 0.001, 'loss': 10.0, 'optimizer': 'SGD'}, {'dropout':0.15, 'lr': 0.01, 'loss': 3.5, 'optimizer': 'Adam'}, {'dropout':0.3, 'lr': 0.1, 'loss': 4.5, 'optimizer': 'Adam'}] hip.Experiment.from_iterable(data).display() EChartsHigh dimensional Interactive Plotting. Created by @andfanilo.from streamlit_echarts import st_echarts st_echarts(options=options) Streamlit FoliumStreamlit Component for rendering Folium maps. Created by @randyzwitch.m = folium.Map(location=[39.949610, -75.150282], zoom_start=16) st_data = st_folium(m, width=725) Spacy-StreamlitspaCy building blocks and visualizers for Streamlit apps. Created by @explosion.models = [""en_core_web_sm"", ""en_core_web_md""] spacy_streamlit.visualize(models, ""Sundar Pichai is the CEO of Google."") Streamlit AgraphA Streamlit Graph Vis, based on react-grah-vis. Created by @ChrisDelClea.from streamlit_agraph import agraph, Node, Edge, Config agraph(nodes=nodes, edges=edges, config=config) Streamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl(""https://assets5.lottiefiles.com/packages/lf20_V9t630.json"") st_lottie(lottie_hello, key=""hello"") Plotly EventsMake Plotly charts interactive!. Created by @null-jones.fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.chart += get_annotations_chart(annotations=[(""Mar 01, 2008"", ""Pretty good day for GOOG""), (""Dec 01, 2007"", ""Something's going wrong for GOOG & AAPL""), (""Nov 01, 2008"", ""Market starts again thanks to...""), (""Dec 01, 2009"", ""Small crash for GOOG after...""),],) st.altair_chart(chart, use_container_width=True) PlostA deceptively simple plotting library for Streamlit. Created by @tvst.import plost plost.line_chart(my_dataframe, x='time', y='stock_value', color='stock_name',) HiPlotHigh dimensional Interactive Plotting. Created by @facebookresearch.data = [{'dropout':0.1, 'lr': 0.001, 'loss': 10.0, 'optimizer': 'SGD'}, {'dropout':0.15, 'lr': 0.01, 'loss': 3.5, 'optimizer': 'Adam'}, {'dropout':0.3, 'lr': 0.1, 'loss': 4.5, 'optimizer': 'Adam'}] hip.Experiment.from_iterable(data).display() EChartsHigh dimensional Interactive Plotting. Created by @andfanilo.from streamlit_echarts import st_echarts st_echarts(options=options) Streamlit FoliumStreamlit Component for rendering Folium maps. Created by @randyzwitch.m = folium.Map(location=[39.949610, -75.150282], zoom_start=16) st_data = st_folium(m, width=725) Spacy-StreamlitspaCy building blocks and visualizers for Streamlit apps. Created by @explosion.models = [""en_core_web_sm"", ""en_core_web_md""] spacy_streamlit.visualize(models, ""Sundar Pichai is the CEO of Google."") Streamlit AgraphA Streamlit Graph Vis, based on react-grah-vis. Created by @ChrisDelClea.from streamlit_agraph import agraph, Node, Edge, Config agraph(nodes=nodes, edges=edges, config=config) Streamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl(""https://assets5.lottiefiles.com/packages/lf20_V9t630.json"") st_lottie(lottie_hello, key=""hello"") Plotly EventsMake Plotly charts interactive!. Created by @null-jones.fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.chart += get_annotations_chart(annotations=[(""Mar 01, 2008"", ""Pretty good day for GOOG""), (""Dec 01, 2007"", ""Something's going wrong for GOOG & AAPL""), (""Nov 01, 2008"", ""Market starts again thanks to...""), (""Dec 01, 2009"", ""Small crash for GOOG after...""),],) st.altair_chart(chart, use_container_width=True) Next Input widgets ButtonDisplay a button widget.clicked = st.button(""Click me"") Download buttonDisplay a download button widget.st.download_button(""Download file"", file) Form buttonDisplay a form submit button. For use with st.form.st.form_submit_button(""Sign up"") Link buttonDisplay a link button.st.link_button(""Go to gallery"", url) Page linkDisplay a link to another page in a multipage app.st.page_link(""app.py"", label=""Home"", icon=""🏠"") st.page_link(""pages/profile.py"", label=""My profile"") CheckboxDisplay a checkbox widget.selected = st.checkbox(""I agree"") Color pickerDisplay a color picker widget.color = st.color_picker(""Pick a color"") MultiselectDisplay a multiselect widget. The multiselect widget starts as empty.choices = st.multiselect(""Buy"", [""milk"", ""apples"", ""potatoes""]) RadioDisplay a radio button widget.choice = st.radio(""Pick one"", [""cats"", ""dogs""]) SelectboxDisplay a select widget.choice = st.selectbox(""Pick one"", [""cats"", ""dogs""]) Select-sliderDisplay a slider widget to select items from a list.size = st.select_slider(""Pick a size"", [""S"", ""M"", ""L""]) ToggleDisplay a toggle widget.activated = st.toggle(""Activate"") Number inputDisplay a numeric input widget.choice = st.number_input(""Pick a number"", 0, 10) SliderDisplay a slider widget.number = st.slider(""Pick a number"", 0, 100) Date inputDisplay a date input widget.date = st.date_input(""Your birthday"") Time inputDisplay a time input widget.time = st.time_input(""Meeting time"") Chat inputDisplay a chat input widget.prompt = st.chat_input(""Say something"") if prompt: st.write(f""The user has sent: {prompt}"") Text-areaDisplay a multi-line text input widget.text = st.text_area(""Text to translate"") Text inputDisplay a single-line text input widget.name = st.text_input(""First name"") Data editorDisplay a data editor widget.edited = st.experimental_data_editor(df, num_rows=""dynamic"") File UploaderDisplay a file uploader widget.data = st.file_uploader(""Upload a CSV"") Camera inputDisplay a widget that allows users to upload images directly from a camera.image = st.camera_input(""Take a picture"") Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration! PreviousStreamlit ChatStreamlit Component for a Chatbot UI. Created by @AI-Yash.from streamlit_chat import message message(""My message"") message(""Hello bot!"", is_user=True) # align's the message to the right Streamlit Option MenuSelect a single item from a list of options in a menu. Created by @victoryhb.from streamlit_option_menu import option_menu option_menu(""Main Menu"", [""Home"", 'Settings'], icons=['house', 'gear'], menu_icon=""cast"", default_index=1) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.stoggle import stoggle stoggle( ""Click me!"", """"""🥷 Surprise! Here's some additional content"""""",) Streamlit ElementsCreate a draggable and resizable dashboard in Streamlit. Created by @okls.from streamlit_elements import elements, mui, html with elements(""new_element""): mui.Typography(""Hello world"") TagsAdd tags to your Streamlit apps. Created by @gagan3012.from streamlit_tags import st_tags st_tags(label='# Enter Keywords:', text='Press enter to add more', value=['Zero', 'One', 'Two'], suggestions=['five', 'six', 'seven', 'eight', 'nine', 'three', 'eleven', 'ten', 'four'], maxtags = 4, key='1') StqdmThe simplest way to handle a progress bar in streamlit app. Created by @Wirg.from stqdm import stqdm for _ in stqdm(range(50)): sleep(0.5) TimelineDisplay a Timeline in Streamlit apps using TimelineJS. Created by @innerdoc.from streamlit_timeline import timeline with open('example.json', ""r"") as f: timeline(f.read(), height=800) Camera input liveAlternative for st.camera_input which returns the webcam images live. Created by @blackary.from camera_input_live import camera_input_live image = camera_input_live() st.image(value) Streamlit AceAce editor component for Streamlit. Created by @okld.from streamlit_ace import st_ace content = st_ace() content Streamlit ChatStreamlit Component for a Chatbot UI. Created by @AI-Yash.from streamlit_chat import message message(""My message"") message(""Hello bot!"", is_user=True) # align's the message to the right Streamlit Option MenuSelect a single item from a list of options in a menu. Created by @victoryhb.from streamlit_option_menu import option_menu option_menu(""Main Menu"", [""Home"", 'Settings'], icons=['house', 'gear'], menu_icon=""cast"", default_index=1) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.stoggle import stoggle stoggle( ""Click me!"", """"""🥷 Surprise! Here's some additional content"""""",) Streamlit ElementsCreate a draggable and resizable dashboard in Streamlit. Created by @okls.from streamlit_elements import elements, mui, html with elements(""new_element""): mui.Typography(""Hello world"") TagsAdd tags to your Streamlit apps. Created by @gagan3012.from streamlit_tags import st_tags st_tags(label='# Enter Keywords:', text='Press enter to add more', value=['Zero', 'One', 'Two'], suggestions=['five', 'six', 'seven', 'eight', 'nine', 'three', 'eleven', 'ten', 'four'], maxtags = 4, key='1') StqdmThe simplest way to handle a progress bar in streamlit app. Created by @Wirg.from stqdm import stqdm for _ in stqdm(range(50)): sleep(0.5) TimelineDisplay a Timeline in Streamlit apps using TimelineJS. Created by @innerdoc.from streamlit_timeline import timeline with open('example.json', ""r"") as f: timeline(f.read(), height=800) Camera input liveAlternative for st.camera_input which returns the webcam images live. Created by @blackary.from camera_input_live import camera_input_live image = camera_input_live() st.image(value) Streamlit AceAce editor component for Streamlit. Created by @okld.from streamlit_ace import st_ace content = st_ace() content Streamlit ChatStreamlit Component for a Chatbot UI. Created by @AI-Yash.from streamlit_chat import message message(""My message"") message(""Hello bot!"", is_user=True) # align's the message to the right Streamlit Option MenuSelect a single item from a list of options in a menu. Created by @victoryhb.from streamlit_option_menu import option_menu option_menu(""Main Menu"", [""Home"", 'Settings'], icons=['house', 'gear'], menu_icon=""cast"", default_index=1) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.stoggle import stoggle stoggle( ""Click me!"", """"""🥷 Surprise! Here's some additional content"""""",) Next Media elements ImageDisplay an image or list of images.st.image(numpy_array) st.image(image_bytes) st.image(file) st.image(""https://example.com/myimage.jpg"") AudioDisplay an audio player.st.audio(numpy_array) st.audio(audio_bytes) st.audio(file) st.audio(""https://example.com/myaudio.mp3"", format=""audio/mp3"") VideoDisplay a video player.st.video(numpy_array) st.video(video_bytes) st.video(file) st.video(""https://example.com/myvideo.mp4"", format=""video/mp4"") Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration! PreviousStreamlit CropperA simple image cropper for Streamlit. Created by @turner-anderson.from streamlit_cropper import st_cropper st_cropper(img, realtime_update=realtime_update, box_color=box_color, aspect_ratio=aspect_ratio) Image CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates streamlit_image_coordinates(""https://placekitten.com/200/300"") Streamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl(""https://assets5.lottiefiles.com/packages/lf20_V9t630.json"") st_lottie(lottie_hello, key=""hello"") Streamlit WebrtcHandling and transmitting real-time video/audio streams with Streamlit. Created by @whitphx.from streamlit_webrtc import webrtc_streamer webrtc_streamer(key=""sample"") Drawable CanvasProvides a sketching canvas using Fabric.js. Created by @andfanilo.from streamlit_drawable_canvas import st_canvas st_canvas(fill_color=""rgba(255, 165, 0, 0.3)"", stroke_width=stroke_width, stroke_color=stroke_color, background_color=bg_color, background_image=Image.open(bg_image) if bg_image else None, update_streamlit=realtime_update, height=150, drawing_mode=drawing_mode, point_display_radius=point_display_radius if drawing_mode == 'point' else 0, key=""canvas"",) Image ComparisonCompare images with a slider using JuxtaposeJS. Created by @fcakyon.from streamlit_image_comparison import image_comparison image_comparison(img1=""image1.jpg"", img2=""image2.jpg"",) Streamlit CropperA simple image cropper for Streamlit. Created by @turner-anderson.from streamlit_cropper import st_cropper st_cropper(img, realtime_update=realtime_update, box_color=box_color, aspect_ratio=aspect_ratio) Image CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates streamlit_image_coordinates(""https://placekitten.com/200/300"") Streamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl(""https://assets5.lottiefiles.com/packages/lf20_V9t630.json"") st_lottie(lottie_hello, key=""hello"") Streamlit WebrtcHandling and transmitting real-time video/audio streams with Streamlit. Created by @whitphx.from streamlit_webrtc import webrtc_streamer webrtc_streamer(key=""sample"") Drawable CanvasProvides a sketching canvas using Fabric.js. Created by @andfanilo.from streamlit_drawable_canvas import st_canvas st_canvas(fill_color=""rgba(255, 165, 0, 0.3)"", stroke_width=stroke_width, stroke_color=stroke_color, background_color=bg_color, background_image=Image.open(bg_image) if bg_image else None, update_streamlit=realtime_update, height=150, drawing_mode=drawing_mode, point_display_radius=point_display_radius if drawing_mode == 'point' else 0, key=""canvas"",) Image ComparisonCompare images with a slider using JuxtaposeJS. Created by @fcakyon.from streamlit_image_comparison import image_comparison image_comparison(img1=""image1.jpg"", img2=""image2.jpg"",) Streamlit CropperA simple image cropper for Streamlit. Created by @turner-anderson.from streamlit_cropper import st_cropper st_cropper(img, realtime_update=realtime_update, box_color=box_color, aspect_ratio=aspect_ratio) Image CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates streamlit_image_coordinates(""https://placekitten.com/200/300"") Streamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl(""https://assets5.lottiefiles.com/packages/lf20_V9t630.json"") st_lottie(lottie_hello, key=""hello"") Next Layouts and containers ColumnsInsert containers laid out as side-by-side columns.col1, col2 = st.columns(2) col1.write(""this is column 1"") col2.write(""this is column 2"") ContainerInsert a multi-element container.c = st.container() st.write(""This will show last"") c.write(""This will show first"") c.write(""This will show second"") Modal dialogsInsert a modal dialog that can rerun independently from the rest of the script.@st.experimental_dialog(""Sign up"") def email_form(): name = st.text_input(""Name"") email = st.text_input(""Email"") EmptyInsert a single-element container.c = st.empty() st.write(""This will show last"") c.write(""This will be replaced"") c.write(""This will show first"") ExpanderInsert a multi-element container that can be expanded/collapsed.with st.expander(""Open to see more""): st.write(""This is more content"") PopoverInsert a multi-element popover container that can be opened/closed.with st.popover(""Settings""): st.checkbox(""Show completed"") SidebarDisplay items in a sidebar.st.sidebar.write(""This lives in the sidebar"") st.sidebar.button(""Click me!"") TabsInsert containers separated into tabs.tab1, tab2 = st.tabs([""Tab 1"", ""Tab2""]) tab1.write(""this is tab 1"") tab2.write(""this is tab 2"") Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration!Streamlit ElementsCreate a draggable and resizable dashboard in Streamlit. Created by @okls.from streamlit_elements import elements, mui, html with elements(""new_element""): mui.Typography(""Hello world"") PydanticAuto-generate Streamlit UI from Pydantic Models and Dataclasses. Created by @lukasmasuch.import streamlit_pydantic as sp sp.pydantic_form(key=""my_form"", model=ExampleModel) Streamlit PagesAn experimental version of Streamlit Multi-Page Apps. Created by @blackary.from st_pages import Page, show_pages, add_page_title show_pages([ Page(""streamlit_app.py"", ""Home"", ""🏠""), Page(""other_pages/page2.py"", ""Page 2"", "":books:""), ]) Chat elements Streamlit provides a few commands to help you build conversational apps. These chat elements are designed to be used in conjunction with each other, but you can also use them separately. st.chat_message lets you insert a chat message container into the app so you can display messages from the user or the app. Chat containers can contain other Streamlit elements, including charts, tables, text, and more. st.chat_input lets you display a chat input widget so the user can type in a message. Chat inputDisplay a chat input widget.prompt = st.chat_input(""Say something"") if prompt: st.write(f""The user has sent: {prompt}"") Chat messageInsert a chat message container.import numpy as np with st.chat_message(""user""): st.write(""Hello 👋"") st.line_chart(np.random.randn(30, 3)) Status containerDisplay output of long-running tasks in a container.with st.status('Running'): do_something_slow() st.write_streamWrite generators or streams to the app with a typewriter effect.st.write_stream(my_generator) st.write_stream(my_llm_stream) Status elements Progress barDisplay a progress bar.for i in range(101): st.progress(i) do_something_slow() SpinnerTemporarily displays a message while executing a block of code.with st.spinner(""Please wait...""): do_something_slow() Status containerDisplay output of long-running tasks in a container.with st.status('Running'): do_something_slow() ToastBriefly displays a toast message in the bottom-right corner.st.toast('Butter!', icon='🧈') BalloonsDisplay celebratory balloons!do_something() # Celebrate when all done! st.balloons() SnowflakesDisplay celebratory snowflakes!do_something() # Celebrate when all done! st.snow() Success boxDisplay a success message.st.success(""Match found!"") Info boxDisplay an informational message.st.info(""Dataset is updated every day at midnight."") Warning boxDisplay warning message.st.warning(""Unable to fetch image. Skipping..."") Error boxDisplay error message.st.error(""We encountered an error"") Exception outputDisplay an exception.e = RuntimeError(""This is an exception of type RuntimeError"") st.exception(e) Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration!StqdmThe simplest way to handle a progress bar in streamlit app. Created by @Wirg.from stqdm import stqdm for _ in stqdm(range(50)): sleep(0.5) Custom notification boxA custom notification box with the ability to close it out. Created by @Socvest.from streamlit_custom_notification_box import custom_notification_box styles = {'material-icons':{'color': 'red'}, 'text-icon-link-close-container': {'box-shadow': '#3896de 0px 4px'}, 'notification-text': {'':''}, 'close-button':{'':''}, 'link':{'':''}} custom_notification_box(icon='info', textDisplay='We are almost done with your registration...', externalLink='more info', url='#', styles=styles, key=""foo"") Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.let_it_rain import rain rain(emoji=""🎈"", font_size=54, falling_speed=5, animation_length=""infinite"",) App logic and configuration Navigation and pages Switch pageProgrammatically navigates to a specified page.st.switch_page(""pages/my_page.py"") Page linkDisplay a link to another page in a multipage app.st.page_link(""app.py"", label=""Home"", icon=""🏠"") st.page_link(""pages/profile.py"", label=""My profile"") Execution flow Modal dialogsInsert a modal dialog that can rerun independently from the rest of the script.@st.experimental_dialog(""Sign up"") def email_form(): name = st.text_input(""Name"") email = st.text_input(""Email"") FormsCreate a form that batches elements together with a “Submit"" button.with st.form(key='my_form'): name = st.text_input(""Name"") email = st.text_input(""Email"") st.form_submit_button(""Sign up"") Partial rerunsDefine a fragment to rerun independently from the rest of the script.@st.experimental_fragment(run_every=""10s"") def fragment(): df = get_data() st.line_chart(df) Rerun scriptRerun the script immediately.st.rerun() Stop executionStops execution immediately.st.stop() Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration!AutorefreshForce a refresh without tying up a script. Created by @kmcgrady.from streamlit_autorefresh import st_autorefresh st_autorefresh(interval=2000, limit=100, key=""fizzbuzzcounter"") PydanticAuto-generate Streamlit UI from Pydantic Models and Dataclasses. Created by @lukasmasuch.import streamlit_pydantic as sp sp.pydantic_form(key=""my_form"", model=ExampleModel) Streamlit PagesAn experimental version of Streamlit Multi-Page Apps. Created by @blackary.from st_pages import Page, show_pages, add_page_title show_pages([ Page(""streamlit_app.py"", ""Home"", ""🏠""), Page(""other_pages/page2.py"", ""Page 2"", "":books:""), ]) Caching and state Cache dataFunction decorator to cache functions that return data (e.g. dataframe transforms, database queries, ML inference).@st.cache_data def long_function(param1, param2): # Perform expensive computation here or # fetch data from the web here return data Cache resourceFunction decorator to cache functions that return global resources (e.g. database connections, ML models).@st.cache_resource def init_model(): # Return a global resource here return pipeline( ""sentiment-analysis"", model=""distilbert-base-uncased-finetuned-sst-2-english"" ) Session stateSession state is a way to share variables between reruns, for each user session.st.session_state['key'] = value Query parametersGet, set, or clear the query parameters that are shown in the browser's URL bar.st.query_params[key] = value st.query_params.clear() Connections and databases Setup your connection Create a connectionConnect to a data source or APIconn = st.connection('pets_db', type='sql') pet_owners = conn.query('select * from pet_owners') st.dataframe(pet_owners) Built-in connections SnowflakeConnectionA connection to Snowflake.conn = st.connection('snowflake') SQLConnectionA connection to a SQL database using SQLAlchemy.conn = st.connection('sql') Build your own connections Connection base classBuild your own connection with BaseConnection.class MyConnection(BaseConnection[myconn.MyConnection]): def _connect(self, **kwargs) -> MyConnection: return myconn.connect(**self._secrets, **kwargs) def query(self, query): return self._instance.query(query) Secrets management Secrets singletonAccess secrets from a local TOML file.key = st.secrets[""OpenAI_key""] Secrets fileSave your secrets in a per-project or per-profile TOML file.OpenAI_key = """" Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration!AuthenticatorA secure authentication module to validate user credentials. Created by @mkhorasani.import streamlit_authenticator as stauth authenticator = stauth.Authenticate( config['credentials'], config['cookie']['name'], config['cookie']['key'], config['cookie']['expiry_days'], config['preauthorized']) WS localStorageA simple synchronous way of accessing localStorage from your app. Created by @gagangoku.from streamlit_ws_localstorage import injectWebsocketCode ret = conn.setLocalStorageVal(key='k1', val='v1') st.write('ret: ' + ret) Streamlit Auth0The fastest way to provide comprehensive login inside Streamlit. Created by @conradbez.from auth0_component import login_button user_info = login_button(clientId, domain = domain) st.write(user_info) Custom Components Declare a componentCreate and register a custom component.st.components.v1.declare_component( ""custom_slider"", ""/frontend"", ) HTMLDisplay an HTML string in an iframe.st.components.v1.html( ""

Foo bar.

"" ) iframeLoad a remote URL in an iframe.st.components.v1.iframe( ""docs.streamlit.io"" ) Utilities and user info User infost.experimental_user returns information about the logged-in user of private apps on Streamlit Community Cloud.if st.experimental_user.email == ""foo@corp.com"": st.write(""Welcome back, "", st.experimental_user.email) else: st.write(""You are not authorized to view this page."") Get helpDisplay object’s doc string, nicely formatted.st.help(st.write) st.help(pd.DataFrame) Render HTMLRenders HTML strings to your app.css = """""" """""" st.html(css) Configuration Configuration fileConfigures the default settings for your app.your-project/ ├── .streamlit/ │ └── config.toml └── your_app.py Set page title, favicon, and moreConfigures the default settings of the page.st.set_page_config( page_title=""My app"", page_icon="":shark:"", ) Developer tools App testing st.testing.v1.AppTestst.testing.v1.AppTest simulates a running Streamlit app for testing.from streamlit.testing.v1 import AppTest at = AppTest.from_file(""streamlit_app.py"") at.secrets[""WORD""] = ""Foobar"" at.run() assert not at.exception at.text_input(""word"").input(""Bazbat"").run() assert at.warning[0].value == ""Try again."" AppTest.from_filest.testing.v1.AppTest.from_file initializes a simulated app from a file.from streamlit.testing.v1 import AppTest at = AppTest.from_file(""streamlit_app.py"") at.run() AppTest.from_stringst.testing.v1.AppTest.from_string initializes a simulated app from a string.from streamlit.testing.v1 import AppTest at = AppTest.from_string(app_script_as_string) at.run() AppTest.from_functionst.testing.v1.AppTest.from_function initializes a simulated app from a function.from streamlit.testing.v1 import AppTest at = AppTest.from_function(app_script_as_callable) at.run() BlockA representation of container elements, including: st.chat_message st.columns st.sidebar st.tabs The main body of the app. # at.sidebar returns a Block at.sidebar.button[0].click().run() assert not at.exception ElementThe base class for representation of all elements, including: st.title st.header st.markdown st.dataframe # at.title returns a sequence of Title # Title inherits from Element assert at.title[0].value == ""My awesome app"" ButtonA representation of st.button and st.form_submit_button.at.button[0].click().run() ChatInputA representation of st.chat_input.at.chat_input[0].set_value(""What is Streamlit?"").run() CheckboxA representation of st.checkbox.at.checkbox[0].check().run() ColorPickerA representation of st.color_picker.at.color_picker[0].pick(""#FF4B4B"").run() DateInputA representation of st.date_input.release_date = datetime.date(2023, 10, 26) at.date_input[0].set_value(release_date).run() MultiselectA representation of st.multiselect.at.multiselect[0].select(""New York"").run() NumberInputA representation of st.number_input.at.number_input[0].increment().run() RadioA representation of st.radio.at.radio[0].set_value(""New York"").run() SelectSliderA representation of st.select_slider.at.select_slider[0].set_range(""A"",""C"").run() SelectboxA representation of st.selectbox.at.selectbox[0].select(""New York"").run() SliderA representation of st.slider.at.slider[0].set_range(2,5).run() TextAreaA representation of st.text_area.at.text_area[0].input(""Streamlit is awesome!"").run() TextInputA representation of st.text_input.at.text_input[0].input(""Streamlit"").run() TimeInputA representation of st.time_input.at.time_input[0].increment().run() ToggleA representation of st.toggle.at.toggle[0].set_value(""True"").run() Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration!Pandas ProfilingPandas profiling component for Streamlit. Created by @okld.df = pd.read_csv(""https://storage.googleapis.com/tf-datasets/titanic/train.csv"") pr = df.profile_report() st_profile_report(pr) Streamlit AceAce editor component for Streamlit. Created by @okld.from streamlit_ace import st_ace content = st_ace() content Streamlit AnalyticsTrack & visualize user interactions with your streamlit app. Created by @jrieke.import streamlit_analytics with streamlit_analytics.track(): st.text_input(""Write something"") Previous: ConceptsNext: Write and magicforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy" https://docs.streamlit.io/develop/concepts/app-testing/beyond-the-basics#working-with-session-state-in-app-testing,"DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsremoveCOREArchitecture & executionaddMultipage appsaddApp designaddADDITIONALConnections and secretsaddCustom componentsaddConfiguration and themingaddApp testingremoveGet startedBeyond the basicsAutomate your testsExampleCheat sheetAPI referenceaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Develop/Concepts/App testing/Beyond the basicsBeyond the basics of app testing Now that you're comfortable with executing a basic test for a Streamlit app let's cover the mutable attributes of AppTest: AppTest.secrets AppTest.session_state AppTest.query_params You can read and update values using dict-like syntax for all three attributes. For .secrets and .query_params, you can use key notation but not attribute notation. For example, the .secrets attribute for AppTest accepts at.secrets[""my_key""] but not at.secrets.my_key. This differs from how you can use the associated command in the main library. On the other hand, .session_state allows both key notation and attribute notation. For these attributes, the typical pattern is to declare any values before executing the app's first run. Values can be inspected at any time in a test. There are a few extra considerations for secrets and Session State, which we'll cover now. Using secrets with app testing Be careful not to include secrets directly in your tests. Consider this simple project with pytest executed in the project's root directory: myproject/ ├── .streamlit/ │ ├── config.toml │ └── secrets.toml ├── app.py └── tests/ └── test_app.py cd myproject pytest tests/ In the above scenario, your simulated app will have access to your secrets.toml file. However, since you don't want to commit your secrets to your repository, you may need to write tests where you securely pull your secrets into memory or use dummy secrets. Example: declaring secrets in a test Within a test, declare each secret after initializing your AppTest instance but before the first run. (A missing secret may result in an app that doesn't run!) For example, consider the following secrets file and corresponding test initialization to assign the same secrets manually: Secrets file: db_username = ""Jane"" db_password = ""mypassword"" [my_other_secrets] things_i_like = [""Streamlit"", ""Python""] Testing file with equivalent secrets: # Initialize an AppTest instance. at = AppTest.from_file(""app.py"") # Declare the secrets. at.secrets[""db_username""] = ""Jane"" at.secrets[""db_password""] = ""mypassword"" at.secrets[""my_other_secrets.things_i_like""] = [""Streamlit"", ""Python""] # Run the app. at.run() Generally, you want to avoid typing your secrets directly into your test. If you don't need your real secrets for your test, you can declare dummy secrets as in the example above. If your app uses secrets to connect to an external service like a database or API, consider mocking that service in your app tests. If you need to use the real secrets and actually connect, you should use an API to pass them securely and anonymously. If you are automating your tests with GitHub actions, check out their Security guide. at.secrets[""my_key""] = Working with Session State in app testing The .session_state attribute for AppTest lets you read and update Session State values using key notation (at.session_state[""my_key""]) and attribute notation (at.session_state.my_key). By manually declaring values in Session State, you can directly jump to a specific state instead of simulating many steps to get there. Additionally, the testing framework does not provide native support for multipage apps. An instance of AppTest can only test one page. You must manually declare Session State values to simulate a user carrying data from another page. Example: testing a multipage app Consider a simple multipage app where the first page can modify a value in Session State. To test the second page, set Session State manually and run the simulated app within the test: Project structure: myproject/ ├── pages/ │ └── second.py ├── first.py └── tests/ └── test_second.py First app page: """"""first.py"""""" import streamlit as st st.session_state.magic_word = st.session_state.get(""magic_word"", ""Streamlit"") new_word = st.text_input(""Magic word:"") if st.button(""Set the magic word""): st.session_state.magic_word = new_word Second app page: """"""second.py"""""" import streamlit as st st.session_state.magic_word = st.session_state.get(""magic_word"", ""Streamlit"") if st.session_state.magic_word == ""Balloons"": st.markdown("":balloon:"") Testing file: """"""test_second.py"""""" from streamlit.testing.v1 import AppTest def test_balloons(): at = AppTest.from_file(""pages/second.py"") at.session_state[""magic_word""] = ""Balloons"" at.run() assert at.markdown[0].value == "":balloon:"" By setting the value at.session_state[""magic_word""] = ""Balloons"" within the test, you can simulate a user navigating to second.py after entering and saving ""Balloons"" on first.py.Previous: Get startedNext: Automate your testsforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy" https://docs.streamlit.io/deploy/streamlit-community-cloud/share-your-app/indexability#what-if-i-dont-want-my-app-to-be-indexed,"DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudremoveGet startedaddDeploy your appaddManage your appaddShare your appremoveEmbed your appSearch indexabilityShare previewsManage your accountaddTroubleshootingStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Deploy/Streamlit Community Cloud/Share your app/Search indexabilitySEO and search indexability When you deploy a public app to Streamlit Community Cloud, it is automatically indexed by search engines like Google and Bing on a weekly basis. 🎈 This means that anyone can find your app by searching for its custom subdomain (e.g. ""traingenerator.streamlit.app"") or by searching for the app's title. Get the most out of app indexability Here are some tips to help you get the most out of app indexability: Make sure your app is public Choose a custom subdomain early Choose a descriptive app title Customize your app's meta description Make sure your app is public All public apps hosted on Streamlit Community Cloud are indexed by search engines. If your app is private, it will not be indexed by search engines. To make your private app public, read Share your app. Choose a custom subdomain early Streamlit Community Cloud automatically generates a random subdomain for your app. However, subdomains are customizable! Custom subdomains modify your app URLs to reflect your app content, personal branding, or whatever you’d like. Read more about custom subdomains in Custom subdomains. By choosing a custom subdomain, you can use it to help people find your app. For example, if you're deploying an app that generates training data, you might choose a subdomain like traingenerator.streamlit.app. This makes it easy for people to find your app by searching for ""training generator"" or ""train generator streamlit app."" We recommend choosing a custom subdomain when you deploy your app. This ensures that your app is indexed by search engines using your custom subdomain, rather than the automatically generated one. If you choose a custom subdomain later, your app may be indexed multiple times—once using the default subdomain and once using your custom subdomain. In this case, your old URL will result in a 404 error which can confuse users who are searching for your app. Choose a descriptive app title The meta title of your app is the text that appears in search engine results. It is also the text that appears in the browser tab when your app is open. By default, the meta title of your app is the same as the title of your app. However, you can customize the meta title of your app by setting the st.set_page_config parameter page_title to a custom string. For example: st.set_page_config(page_title=""Traingenerator"") This will change the meta title of your app to ""Traingenerator."" This makes it easier for people to find your app by searching for ""Traingenerator"" or ""train generator streamlit app"": Google search results for ""train generator streamlit app"" Customize your app's meta description Meta descriptions are the short descriptions that appear in search engine results. Search engines use the meta description to help users understand what your app is about. From our observations, search engines seem to favor the content in both st.header and st.text over st.title. If you put a description at the top of your app under st.header or st.text, there’s a good chance search engines will use this for the meta description. What does my indexed app look like? If you're curious about what your app looks like in search engine results, you can type the following into Google Search: site:.streamlit.app Example: site:traingenerator.streamlit.app Google search results for ""site:traingenerator.streamlit.app"" What if I don't want my app to be indexed? If you don't want your app to be indexed by search engines, you can make it private. Read Share your app to learn more about making your app private. Note: each workspace can only have one private app. If you want to make your app private, you must first delete any other private app in your workspace or make it public. That said, Streamlit Community Cloud is an open and free platform for the community to deploy, discover, and share Streamlit apps and code with each other. As such, we encourage you to make your app public so that it can be indexed by search engines and discovered by other Streamlit users and community members.Previous: Embed your appNext: Share previewsforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy" https://docs.streamlit.io/deploy/streamlit-community-cloud/manage-your-account/update-your-email#update-your-email,"DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudremoveGet startedaddDeploy your appaddManage your appaddShare your appaddManage your accountremoveSign in & sign outWorkspace settingsManage your GitHub connectionUpdate your emailDelete your accountTroubleshootingStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Deploy/Streamlit Community Cloud/Manage your account/Update your emailUpdate your email If you wish to update your email on Streamlit Community Cloud, you can do so via your Workspace settings. Updating your email changes the primary identity of your account. Once updated, if your account's email is associated with a Google account, you can sign in with Google OAuth. Otherwise, you through emailed links. The latter involves typing in your email, after which we'll send you a unique, single-use link (valid for 15 minutes). If you are signed in to GitHub and don't already have a primary identity on your account, see Connect Google to your account. How to update your email Sign in to Streamlit Community Cloud at share.streamlit.io. Click ""Settings"" in the page's top-right corner. Click ""Update email"" within the ""Linked accounts"" section. Enter your new email and click ""Update email."" You'll see a confirmation dialog asking you to check your email for a confirmation link. Click ""Done."" Your account settings will show ""Update pending"" until you complete the next step. Check your inbox for an email from Streamlit containing a ""Change email"" button and a confirmation link. This one-time link expires in 15 minutes. Click either one to confirm your new email address for Streamlit Community Cloud. Before doing so, ensure you access the link from the same browser session where you are logged in to Streamlit Community Cloud. priority_highImportantIf you access the confirmation link from a browser session where you are not logged in to Streamlit Community Cloud, the confirmation link will not complete the process. You will be prompted to sign in. If you try to sign in with your new email, you will create a second account instead. See Troubleshooting. A confirmation will display to confirm your email update is complete! 🎈 Resend your confirmation link If your confirmation link expires, don't worry! You can resend it by following these steps: Sign in to Streamlit Community Cloud at share.streamlit.io and click ""Settings"" in the page's top-right corner. Click ""Update pending"" Click ""Resend email"" Continue from step 4 of How to update your email. Troubleshooting If you click the confirmation link in a browser session where you are not signed in, you will be informed that ""Sign in is required."" If you try to sign in with your new email, you will create a second account instead. You cannot resend your confirmation link while you have this second account. If you accidentally created a second account, you can follow the steps to Delete your account to get rid of the duplicate. Afterwards, Resend your confirmation link from your first account. Connect Google to your account If you signed up with GitHub and did not create a primary identity, your workspace will show a warning icon in the upper right corner. Click ""Settings"" to access your workspace settings. When you access your workspace settings, a warning is displayed: ""You are not signed in with a primary identity account."" Click ""Sign in with Google"" and follow Google's authentication prompts. Your account now has both a primary identity and source control account. Previous: Manage your GitHub connectionNext: Delete your accountforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy" https://docs.streamlit.io/develop/api-reference/app-testing/st.testing.v1.apptest#apptestcode,"DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceremovePAGE ELEMENTSWrite and magicaddText elementsaddData elementsaddChart elementsaddInput widgetsaddMedia elementsaddLayouts and containersaddChat elementsaddStatus elementsaddThird-party componentsopen_in_newAPPLICATION LOGICNavigation and pagesaddExecution flowaddCaching and stateaddConnections and secretsaddCustom componentsaddUtilitiesaddConfigurationaddTOOLSApp testingremovest.testing.v1.AppTestTesting element classesCommand lineaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Develop/API reference/App testing/st.testing.v1.AppTest The AppTest class st.testing.v1.AppTestStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA simulated Streamlit app to check the correctness of displayed elements and outputs. An instance of AppTest simulates a running Streamlit app. This class provides methods to set up, manipulate, and inspect the app contents via API instead of a browser UI. It can be used to write automated tests of an app in various scenarios. These can then be run using a tool like pytest. AppTest can be initialized by one of three class methods: st.testing.v1.AppTest.from_file (recommended) st.testing.v1.AppTest.from_string st.testing.v1.AppTest.from_function Once initialized, Session State and widget values can be updated and the script can be run. Unlike an actual live-running Streamlit app, you need to call AppTest.run() explicitly to re-run the app after changing a widget value. Switching pages also requires an explicit, follow-up call to AppTest.run(). AppTest enables developers to build tests on their app as-is, in the familiar python test format, without major refactoring or abstracting out logic to be tested separately from the UI. Tests can run quickly with very low overhead. A typical pattern is to build a suite of tests for an app that ensure consistent functionality as the app evolves, and run the tests locally and/or in a CI environment like Github Actions. Note AppTest only supports testing a single page of an app per instance. For multipage apps, each page will need to be tested separately. No methods exist to programatically switch pages within AppTest. Class description[source] st.testing.v1.AppTest(script_path, *, default_timeout, args=None, kwargs=None) Methods get(element_type) Get elements or widgets of the specified type. run(*, timeout=None) Run the script from the current state. switch_page(page_path) Switch to another page of the app. Attributes secrets (dict[str, Any]) Dictionary of secrets to be used the simulated app. Use dict-like syntax to set secret values for the simulated app. session_state (SafeSessionState) Session State for the simulated app. SafeSessionState object supports read and write operations as usual for Streamlit apps. query_params (dict[str, Any]) Dictionary of query parameters to be used by the simluated app. Use dict-like syntax to set query_params values for the simulated app. button Sequence of all st.button and st.form_submit_button widgets. caption Sequence of all st.caption elements. chat_input Sequence of all st.chat_input widgets. chat_message Sequence of all st.chat_message elements. checkbox Sequence of all st.checkbox widgets. code Sequence of all st.code elements. color_picker Sequence of all st.color_picker widgets. columns Sequence of all columns within st.columns elements. dataframe Sequence of all st.dataframe elements. date_input Sequence of all st.date_input widgets. divider Sequence of all st.divider elements. error Sequence of all st.error elements. exception Sequence of all st.exception elements. expander Sequence of all st.expander elements. header Sequence of all st.header elements. info Sequence of all st.info elements. json Sequence of all st.json elements. latex Sequence of all st.latex elements. main Sequence of elements within the main body of the app. markdown Sequence of all st.markdown elements. metric Sequence of all st.metric elements. multiselect Sequence of all st.multiselect widgets. number_input Sequence of all st.number_input widgets. radio Sequence of all st.radio widgets. select_slider Sequence of all st.select_slider widgets. selectbox Sequence of all st.selectbox widgets. sidebar Sequence of all elements within st.sidebar. slider Sequence of all st.slider widgets. status Sequence of all st.status elements. subheader Sequence of all st.subheader elements. success Sequence of all st.success elements. table Sequence of all st.table elements. tabs Sequence of all tabs within st.tabs elements. text Sequence of all st.text elements. text_area Sequence of all st.text_area widgets. text_input Sequence of all st.text_input widgets. time_input Sequence of all st.time_input widgets. title Sequence of all st.title elements. toast Sequence of all st.toast elements. toggle Sequence of all st.toggle widgets. warning Sequence of all st.warning elements. Initialize a simulated app using AppTest AppTest.from_fileStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeCreate an instance of AppTest to simulate an app page defined within a file. This option is most convenient for CI workflows and testing of published apps. The script must be executable on its own and so must contain all necessary imports. Function signature[source] AppTest.from_file(cls, script_path, *, default_timeout=3) Parameters script_path (str) Path to a script file. The path should be absolute or relative to the file calling .from_file. default_timeout (float) Default time in seconds before a script run is timed out. Can be overridden for individual .run() calls. Returns(AppTest) A simulated Streamlit app for testing. The simulated app can be executed via .run(). AppTest.from_stringStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeCreate an instance of AppTest to simulate an app page defined within a string. This is useful for testing short scripts that fit comfortably as an inline string in the test itself, without having to create a separate file for it. The script must be executable on its own and so must contain all necessary imports. Function signature[source] AppTest.from_string(cls, script, *, default_timeout=3) Parameters script (str) The string contents of the script to be run. default_timeout (float) Default time in seconds before a script run is timed out. Can be overridden for individual .run() calls. Returns(AppTest) A simulated Streamlit app for testing. The simulated app can be executed via .run(). AppTest.from_functionStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeCreate an instance of AppTest to simulate an app page defined within a function. This is similar to AppTest.from_string(), but more convenient to write with IDE assistance. The script must be executable on its own and so must contain all necessary imports. Function signature[source] AppTest.from_function(cls, script, *, default_timeout=3, args=None, kwargs=None) Parameters script (Callable) A function whose body will be used as a script. Must be runnable in isolation, so it must include any necessary imports. default_timeout (float) Default time in seconds before a script run is timed out. Can be overridden for individual .run() calls. args (tuple) An optional tuple of args to pass to the script function. kwargs (dict) An optional dict of kwargs to pass to the script function. Returns(AppTest) A simulated Streamlit app for testing. The simulated app can be executed via .run(). Run an AppTest script AppTest.runStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeRun the script from the current state. This is equivalent to manually rerunning the app or the rerun that occurs upon user interaction. AppTest.run() must be manually called after updating a widget value or switching pages as script reruns do not occur automatically as they do for live-running Streamlit apps. Function signature[source] AppTest.run(*, timeout=None) Parameters timeout (null) The maximum number of seconds to run the script. None means use the default timeout set for the instance of AppTest. Returns(AppTest) self AppTest.switch_pageStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSwitch to another page of the app. This method does not automatically rerun the app. Use a follow-up call to AppTest.run() to obtain the elements on the selected page. Function signature[source] AppTest.switch_page(page_path) Parameters page_path (str) Path of the page to switch to. The path must be relative to the main script's location (e.g. ""pages/my_page.py""). Returns(AppTest) self Get AppTest script elements The main value of AppTest is providing an API to programmatically inspect and interact with the elements and widgets produced by a running Streamlit app. Using the AppTest. properties or AppTest.get() method returns a collection of all the elements or widgets of the specified type that would have been displayed by running the app. Note that you can also retrieve elements within a specific container in the same way - first retrieve the container, then retrieve the elements just in that container. AppTest.getStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeGet elements or widgets of the specified type. This method returns the collection of all elements or widgets of the specified type on the current page. Retrieve a specific element by using its index (order on page) or key lookup. Function signature[source] AppTest.get(element_type) Parameters element_type (str) An element attribute of AppTest. For example, ""button"", ""caption"", or ""chat_input"". Returns(Sequence of Elements) Sequence of elements of the given type. Individual elements can be accessed from a Sequence by index (order on the page). When getting and element_type that is a widget, individual widgets can be accessed by key. For example, at.get(""text"")[0] for the first st.text element or at.get(""slider"")(key=""my_key"") for the st.slider widget with a given key. AppTest.buttonStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.button and st.form_submit_button widgets. Function signature[source] AppTest.button Returns(WidgetList of Button) Sequence of all st.button and st.form_submit_button widgets. Individual widgets can be accessed from a WidgetList by index (order on the page) or key. For example, at.button[0] for the first widget or at.button(key=""my_key"") for a widget with a given key. AppTest.captionStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.caption elements. Function signature[source] AppTest.caption Returns(ElementList of Caption) Sequence of all st.caption elements. Individual elements can be accessed from an ElementList by index (order on the page). For example, at.caption[0] for the first element. Caption is an extension of the Element class. AppTest.chat_inputStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.chat_input widgets. Function signature[source] AppTest.chat_input Returns(WidgetList of ChatInput) Sequence of all st.chat_input widgets. Individual widgets can be accessed from a WidgetList by index (order on the page) or key. For example, at.chat_input[0] for the first widget or at.chat_input(key=""my_key"") for a widget with a given key. AppTest.chat_messageStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.chat_message elements. Function signature[source] AppTest.chat_message Returns(Sequence of ChatMessage) Sequence of all st.chat_message elements. Individual elements can be accessed from an ElementList by index (order on the page). For example, at.chat_message[0] for the first element. ChatMessage is an extension of the Block class. AppTest.checkboxStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.checkbox widgets. Function signature[source] AppTest.checkbox Returns(WidgetList of Checkbox) Sequence of all st.checkbox widgets. Individual widgets can be accessed from a WidgetList by index (order on the page) or key. For example, at.checkbox[0] for the first widget or at.checkbox(key=""my_key"") for a widget with a given key. AppTest.codeStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.code elements. Function signature[source] AppTest.code Returns(ElementList of Code) Sequence of all st.code elements. Individual elements can be accessed from an ElementList by index (order on the page). For example, at.code[0] for the first element. Code is an extension of the Element class. AppTest.color_pickerStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.color_picker widgets. Function signature[source] AppTest.color_picker Returns(WidgetList of ColorPicker) Sequence of all st.color_picker widgets. Individual widgets can be accessed from a WidgetList by index (order on the page) or key. For example, at.color_picker[0] for the first widget or at.color_picker(key=""my_key"") for a widget with a given key. AppTest.columnsStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all columns within st.columns elements. Each column within a single st.columns will be returned as a separate Column in the Sequence. Function signature[source] AppTest.columns Returns(Sequence of Column) Sequence of all columns within st.columns elements. Individual columns can be accessed from an ElementList by index (order on the page). For example, at.columns[0] for the first column. Column is an extension of the Block class. AppTest.dataframeStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.dataframe elements. Function signature[source] AppTest.dataframe Returns(ElementList of Dataframe) Sequence of all st.dataframe elements. Individual elements can be accessed from an ElementList by index (order on the page). For example, at.dataframe[0] for the first element. Dataframe is an extension of the Element class. AppTest.date_inputStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.date_input widgets. Function signature[source] AppTest.date_input Returns(WidgetList of DateInput) Sequence of all st.date_input widgets. Individual widgets can be accessed from a WidgetList by index (order on the page) or key. For example, at.date_input[0] for the first widget or at.date_input(key=""my_key"") for a widget with a given key. AppTest.dividerStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.divider elements. Function signature[source] AppTest.divider Returns(ElementList of Divider) Sequence of all st.divider elements. Individual elements can be accessed from an ElementList by index (order on the page). For example, at.divider[0] for the first element. Divider is an extension of the Element class. AppTest.errorStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.error elements. Function signature[source] AppTest.error Returns(ElementList of Error) Sequence of all st.error elements. Individual elements can be accessed from an ElementList by index (order on the page). For example, at.error[0] for the first element. Error is an extension of the Element class. AppTest.exceptionStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.exception elements. Function signature[source] AppTest.exception Returns(ElementList of Exception) Sequence of all st.exception elements. Individual elements can be accessed from an ElementList by index (order on the page). For example, at.exception[0] for the first element. Exception is an extension of the Element class. AppTest.expanderStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.expander elements. Function signature[source] AppTest.expander Returns(Sequence of Expandable) Sequence of all st.expander elements. Individual elements can be accessed from a Sequence by index (order on the page). For example, at.expander[0] for the first element. Expandable is an extension of the Block class. AppTest.headerStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.header elements. Function signature[source] AppTest.header Returns(ElementList of Header) Sequence of all st.header elements. Individual elements can be accessed from an ElementList by index (order on the page). For example, at.header[0] for the first element. Header is an extension of the Element class. AppTest.infoStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.info elements. Function signature[source] AppTest.info Returns(ElementList of Info) Sequence of all st.info elements. Individual elements can be accessed from an ElementList by index (order on the page). For example, at.info[0] for the first element. Info is an extension of the Element class. AppTest.jsonStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.json elements. Function signature[source] AppTest.json Returns(ElementList of Json) Sequence of all st.json elements. Individual elements can be accessed from an ElementList by index (order on the page). For example, at.json[0] for the first element. Json is an extension of the Element class. AppTest.latexStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.latex elements. Function signature[source] AppTest.latex Returns(ElementList of Latex) Sequence of all st.latex elements. Individual elements can be accessed from an ElementList by index (order on the page). For example, at.latex[0] for the first element. Latex is an extension of the Element class. AppTest.mainStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of elements within the main body of the app. Function signature[source] AppTest.main Returns(Block) A container of elements. Block can be queried for elements in the same manner as AppTest. For example, Block.checkbox will return all st.checkbox within the associated container. AppTest.markdownStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.markdown elements. Function signature[source] AppTest.markdown Returns(ElementList of Markdown) Sequence of all st.markdown elements. Individual elements can be accessed from an ElementList by index (order on the page). For example, at.markdown[0] for the first element. Markdown is an extension of the Element class. AppTest.metricStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.metric elements. Function signature[source] AppTest.metric Returns(ElementList of Metric) Sequence of all st.metric elements. Individual elements can be accessed from an ElementList by index (order on the page). For example, at.metric[0] for the first element. Metric is an extension of the Element class. AppTest.multiselectStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.multiselect widgets. Function signature[source] AppTest.multiselect Returns(WidgetList of Multiselect) Sequence of all st.multiselect widgets. Individual widgets can be accessed from a WidgetList by index (order on the page) or key. For example, at.multiselect[0] for the first widget or at.multiselect(key=""my_key"") for a widget with a given key. AppTest.number_inputStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.number_input widgets. Function signature[source] AppTest.number_input Returns(WidgetList of NumberInput) Sequence of all st.number_input widgets. Individual widgets can be accessed from a WidgetList by index (order on the page) or key. For example, at.number_input[0] for the first widget or at.number_input(key=""my_key"") for a widget with a given key. AppTest.radioStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.radio widgets. Function signature[source] AppTest.radio Returns(WidgetList of Radio) Sequence of all st.radio widgets. Individual widgets can be accessed from a WidgetList by index (order on the page) or key. For example, at.radio[0] for the first widget or at.radio(key=""my_key"") for a widget with a given key. AppTest.select_sliderStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.select_slider widgets. Function signature[source] AppTest.select_slider Returns(WidgetList of SelectSlider) Sequence of all st.select_slider widgets. Individual widgets can be accessed from a WidgetList by index (order on the page) or key. For example, at.select_slider[0] for the first widget or at.select_slider(key=""my_key"") for a widget with a given key. AppTest.selectboxStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.selectbox widgets. Function signature[source] AppTest.selectbox Returns(WidgetList of Selectbox) Sequence of all st.selectbox widgets. Individual widgets can be accessed from a WidgetList by index (order on the page) or key. For example, at.selectbox[0] for the first widget or at.selectbox(key=""my_key"") for a widget with a given key. AppTest.sidebarStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all elements within st.sidebar. Function signature[source] AppTest.sidebar Returns(Block) A container of elements. Block can be queried for elements in the same manner as AppTest. For example, Block.checkbox will return all st.checkbox within the associated container. AppTest.sliderStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.slider widgets. Function signature[source] AppTest.slider Returns(WidgetList of Slider) Sequence of all st.slider widgets. Individual widgets can be accessed from a WidgetList by index (order on the page) or key. For example, at.slider[0] for the first widget or at.slider(key=""my_key"") for a widget with a given key. AppTest.subheaderStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.subheader elements. Function signature[source] AppTest.subheader Returns(ElementList of Subheader) Sequence of all st.subheader elements. Individual elements can be accessed from an ElementList by index (order on the page). For example, at.subheader[0] for the first element. Subheader is an extension of the Element class. AppTest.successStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.success elements. Function signature[source] AppTest.success Returns(ElementList of Success) Sequence of all st.success elements. Individual elements can be accessed from an ElementList by index (order on the page). For example, at.success[0] for the first element. Success is an extension of the Element class. AppTest.statusStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.status elements. Function signature[source] AppTest.status Returns(Sequence of Status) Sequence of all st.status elements. Individual elements can be accessed from a Sequence by index (order on the page). For example, at.status[0] for the first element. Status is an extension of the Block class. AppTest.tableStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.table elements. Function signature[source] AppTest.table Returns(ElementList of Table) Sequence of all st.table elements. Individual elements can be accessed from an ElementList by index (order on the page). For example, at.table[0] for the first element. Table is an extension of the Element class. AppTest.tabsStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all tabs within st.tabs elements. Each tab within a single st.tabs will be returned as a separate Tab in the Sequence. Additionally, the tab labels are forwarded to each Tab element as a property. For example, st.tabs(""A"",""B"") will yield two Tab objects, with Tab.label returning ""A"" and ""B"", respectively. Function signature[source] AppTest.tabs Returns(Sequence of Tab) Sequence of all tabs within st.tabs elements. Individual tabs can be accessed from an ElementList by index (order on the page). For example, at.tabs[0] for the first tab. Tab is an extension of the Block class. AppTest.textStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.text elements. Function signature[source] AppTest.text Returns(ElementList of Text) Sequence of all st.text elements. Individual elements can be accessed from an ElementList by index (order on the page). For example, at.text[0] for the first element. Text is an extension of the Element class. AppTest.text_areaStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.text_area widgets. Function signature[source] AppTest.text_area Returns(WidgetList of TextArea) Sequence of all st.text_area widgets. Individual widgets can be accessed from a WidgetList by index (order on the page) or key. For example, at.text_area[0] for the first widget or at.text_area(key=""my_key"") for a widget with a given key. AppTest.text_inputStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.text_input widgets. Function signature[source] AppTest.text_input Returns(WidgetList of TextInput) Sequence of all st.text_input widgets. Individual widgets can be accessed from a WidgetList by index (order on the page) or key. For example, at.text_input[0] for the first widget or at.text_input(key=""my_key"") for a widget with a given key. AppTest.time_inputStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.time_input widgets. Function signature[source] AppTest.time_input Returns(WidgetList of TimeInput) Sequence of all st.time_input widgets. Individual widgets can be accessed from a WidgetList by index (order on the page) or key. For example, at.time_input[0] for the first widget or at.time_input(key=""my_key"") for a widget with a given key. AppTest.titleStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.title elements. Function signature[source] AppTest.title Returns(ElementList of Title) Sequence of all st.title elements. Individual elements can be accessed from an ElementList by index (order on the page). For example, at.title[0] for the first element. Title is an extension of the Element class. AppTest.toastStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.toast elements. Function signature[source] AppTest.toast Returns(ElementList of Toast) Sequence of all st.toast elements. Individual elements can be accessed from an ElementList by index (order on the page). For example, at.toast[0] for the first element. Toast is an extension of the Element class. AppTest.toggleStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.toggle widgets. Function signature[source] AppTest.toggle Returns(WidgetList of Toggle) Sequence of all st.toggle widgets. Individual widgets can be accessed from a WidgetList by index (order on the page) or key. For example, at.toggle[0] for the first widget or at.toggle(key=""my_key"") for a widget with a given key. AppTest.warningStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.warning elements. Function signature[source] AppTest.warning Returns(ElementList of Warning) Sequence of all st.warning elements. Individual elements can be accessed from an ElementList by index (order on the page). For example, at.warning[0] for the first element. Warning is an extension of the Element class. Previous: App testingNext: Testing element classesforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy" https://docs.streamlit.io/develop/api-reference/text/st.caption#stcaption,"DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceremovePAGE ELEMENTSWrite and magicaddText elementsremoveHEADINGS & BODYst.titlest.headerst.subheaderst.markdownFORMATTED TEXTst.captionst.codest.dividerst.echost.latexst.textData elementsaddChart elementsaddInput widgetsaddMedia elementsaddLayouts and containersaddChat elementsaddStatus elementsaddThird-party componentsopen_in_newAPPLICATION LOGICNavigation and pagesaddExecution flowaddCaching and stateaddConnections and secretsaddCustom componentsaddUtilitiesaddConfigurationaddTOOLSApp testingaddCommand lineaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Develop/API reference/Text elements/st.captionst.captionStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeDisplay text in small font. This should be used for captions, asides, footnotes, sidenotes, and other explanatory text. Function signature[source] st.caption(body, unsafe_allow_html=False, *, help=None) Parameters body (str) The text to display as Github-flavored Markdown. Syntax information can be found at: https://github.github.com/gfm. This also supports: Emoji shortcodes, such as :+1: and :sunglasses:. For a list of all supported codes, see https://share.streamlit.io/streamlit/emoji-shortcodes. LaTeX expressions, by wrapping them in ""$"" or ""$$"" (the ""$$"" must be on their own lines). Supported LaTeX functions are listed at https://katex.org/docs/supported.html. Colored text and background colors for text, using the syntax :color[text to be colored] and :color-background[text to be colored], respectively. color must be replaced with any of the following supported colors: blue, green, orange, red, violet, gray/grey, rainbow. For example, you can use :orange[your text here] or :blue-background[your text here]. unsafe_allow_html (bool) By default, any HTML tags found in strings will be escaped and therefore treated as pure text. This behavior may be turned off by setting this argument to True. That said, we strongly advise against it. It is hard to write secure HTML, so by using this argument you may be compromising your users' security. For more information, see: https://github.com/streamlit/streamlit/issues/152 help (str) An optional tooltip that gets displayed next to the caption. Examples import streamlit as st st.caption('This is a string that explains something above.') st.caption('A caption with _italics_ :blue[colors] and emojis :sunglasses:') Previous: st.markdownNext: st.codeforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy" https://docs.streamlit.io/knowledge-base/deploy/authentication-without-sso#step-1-add-usernames--passwords-to-your-local-app-secrets,"DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Knowledge base/Deployment issues/Authentication without SSOAuthentication without SSO Introduction Want to secure your Streamlit app with passwords, but cannot implement single sign-on? We got you covered! This guide shows you two simple techniques for adding basic authentication to your Streamlit app, using Secrets management. priority_highWarningWhile this technique adds some level of security, it is NOT comparable to proper authentication with an SSO provider. Option 1: One global password for all users This is the easiest option! Your app will ask for a password that's shared between all users. It will be stored in the app secrets using Secrets management. If you want to change this password or revoke a user's access, you will need to change it for everyone. If you want to have one password per user instead, jump to Option 2 below. Step 1: Add the password to your local app secrets Your local Streamlit app will read secrets from a file .streamlit/secrets.toml in your app's root dir. Create this file if it doesn't exist yet and add your password to it as shown below: # .streamlit/secrets.toml password = ""streamlit123"" priority_highImportantBe sure to add this file to your .gitignore so you don't commit your secrets! Step 2: Copy your app secrets to the cloud As the secrets.toml file above is not committed to GitHub, you need to pass its content to your deployed app (on Streamlit Community Cloud) separately. Go to the app dashboard and in the app's dropdown menu, click on Edit Secrets. Copy the content of secrets.toml into the text area. More information is available at Secrets management. Step 3: Ask for the password in your Streamlit app Copy the code below to your Streamlit app, insert your normal app code below the check_password() function call at the bottom, and run it: # streamlit_app.py import hmac import streamlit as st def check_password(): """"""Returns `True` if the user had the correct password."""""" def password_entered(): """"""Checks whether a password entered by the user is correct."""""" if hmac.compare_digest(st.session_state[""password""], st.secrets[""password""]): st.session_state[""password_correct""] = True del st.session_state[""password""] # Don't store the password. else: st.session_state[""password_correct""] = False # Return True if the password is validated. if st.session_state.get(""password_correct"", False): return True # Show input for password. st.text_input( ""Password"", type=""password"", on_change=password_entered, key=""password"" ) if ""password_correct"" in st.session_state: st.error(""😕 Password incorrect"") return False if not check_password(): st.stop() # Do not continue if check_password is not True. # Main Streamlit app starts here st.write(""Here goes your normal Streamlit app..."") st.button(""Click me"") If everything worked out, your app should look like this: Option 2: Individual password for each user This option allows you to set a username and password for each user of your app. Like in Option 1, both values will be stored in the app secrets using Secrets management. Step 1: Add usernames & passwords to your local app secrets Your local Streamlit app will read secrets from a file .streamlit/secrets.toml in your app's root dir. Create this file if it doesn't exist yet and add the usernames & password to it as shown below: # .streamlit/secrets.toml [passwords] # Follow the rule: username = ""password"" alice_foo = ""streamlit123"" bob_bar = ""mycrazypw"" priority_highImportantBe sure to add this file to your .gitignore so you don't commit your secrets! Alternatively, you could set up and manage usernames & passwords via a spreadsheet or database. To use secrets to securely connect to Google Sheets, AWS, and other data providers, read our tutorials on how to Connect Streamlit to data sources. Step 2: Copy your app secrets to the cloud As the secrets.toml file above is not committed to GitHub, you need to pass its content to your deployed app (on Streamlit Community Cloud) separately. Go to the app dashboard and in the app's dropdown menu, click on Edit Secrets. Copy the content of secrets.toml into the text area. More information is available at Secrets management. Step 3: Ask for username & password in your Streamlit app Copy the code below to your Streamlit app, insert your normal app code below the check_password() function call at the bottom, and run it: # streamlit_app.py import hmac import streamlit as st def check_password(): """"""Returns `True` if the user had a correct password."""""" def login_form(): """"""Form with widgets to collect user information"""""" with st.form(""Credentials""): st.text_input(""Username"", key=""username"") st.text_input(""Password"", type=""password"", key=""password"") st.form_submit_button(""Log in"", on_click=password_entered) def password_entered(): """"""Checks whether a password entered by the user is correct."""""" if st.session_state[""username""] in st.secrets[ ""passwords"" ] and hmac.compare_digest( st.session_state[""password""], st.secrets.passwords[st.session_state[""username""]], ): st.session_state[""password_correct""] = True del st.session_state[""password""] # Don't store the username or password. del st.session_state[""username""] else: st.session_state[""password_correct""] = False # Return True if the username + password is validated. if st.session_state.get(""password_correct"", False): return True # Show inputs for username + password. login_form() if ""password_correct"" in st.session_state: st.error(""😕 User not known or password incorrect"") return False if not check_password(): st.stop() # Main Streamlit app starts here st.write(""Here goes your normal Streamlit app..."") st.button(""Click me"") If everything worked out, your app should look like this: Previous: Deployment issuesNext: How can I deploy multiple Streamlit apps on different subdomains?forumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy" https://docs.streamlit.io/get-started/installation/streamlit-in-snowflake#create-a-warehouse-and-database-to-hold-your-streamlit-apps,"DocumentationsearchSearchrocket_launchGet startedInstallationremoveUse command lineUse Anaconda DistributionUse GitHub CodespacesUse SnowflakeFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Get started/Installation/Use SnowflakeUse Streamlit in Snowflake to code in a secure environment Snowflake is a single, global platform that powers the Data Cloud. If you want to use a secure platform with role-based access control, this is the option for you! This page walks you through creating a trial Snowflake account and building a simple ""Hello world"" app. Your trial account comes with an account credit so you can try out the service without entering any payment information. push_pinNoteStreamlit in Snowflake is currently based on Streamlit version 1.22.0 with some Limitations and unsupported features. We are working on supporting newer versions and more features. Prerequisites All you need is an email address! Everything else happens in your 30-day trial account. Create an account Go to signup.snowflake.com. (This link will open in a new tab.) Fill in your information and click ""CONTINUE."" Select ""Standard"" for your Snowflake edition and ""Amazon Web Services"" for your cloud provider. Choose the region nearest you, accept the terms, and click ""GET STARTED."" Answer or skip a few questions to let us know more about yourself. A message will display to confirm ""You're now signed up!"" Go to your email and click on the activation link. (Within your link, note the subdomain. This is your Snowflake account identifier. https://.snowflakecomputing.com) Set your username and password. This will be an admin user account within your Snowflake account. Your Snowflake account can have multiple users within it. If you are not signed in after setting your password, follow the instructions to enter your Snowflake account identifier before entering your username and password. If you've accidentally closed your browser, you can log in at app.snowflake.com. Congratulations! You have a trial Snowflake account. The first thing you will see are some sample databases. (This interface is called Snowsight. Check out the Snowflake docs for a quick tour.) Accept the use of Anaconda on your Snowflake account In the left navigation, go to ""Admin"" then ""Billing & Terms."" In the ""Anaconda"" section, click ""Enable."" Accept the terms. The ""Anaconda"" section will now show ""Acknowledged."" Create a warehouse and database to hold your Streamlit apps Click on your name in the left navigation. Hover over ""Switch Role"" and select ""ACCOUNTADMIN"" to use your account in the context of an admin. In the left navigation under ""Admin,"" click on ""Warehouses."" In the upper-right corner, click the blue ""add Warehouse"" button. Enter ""STREAMLITWAREHOUSE"" for the name and keep the defaults of ""Standard"" type and ""X-Small"" size. Click ""Create Warehouse."" In the left navigation, go to ""Data"" then ""Databases."" (This is back where you started!) In the upper-right corner, click the blue ""add Database"" button. Enter ""STREAMLITAPPSDB"" for the name. Click ""Create."" Yay! You now have a new database to hold all your Streamlit apps. Create a ""Hello World"" Streamlit app In the left navigation, click on ""Streamlit."" In the upper-right corner, click the blue ""add Streamlit App"" button. Enter ""Hello World"" for the name of your app. Your new warehouse and database should already be filled in, along with the ""PUBLIC"" schema for your database. Click ""Create."" (Note that the app will run with the rights of ""ACCOUNTADMIN"" for simplicity. You can curate your roles and permissions to choose who can create and access apps.) Your new app, prefilled with example code, will open in editing mode. The left panel shows your code. The right panel shows the resulting app. You can explore the example if you want, but we'll proceed here with a simpler example. (Don't worry! You can always make another app to get the same example again.) Delete the code on the left and replace it with: import streamlit as st st.write(""Hello World"") In the upper-right corner, click the blue ""play_arrow Run"" button to make the running app reflect your changes. Hooray! You just wrote a Streamlit app. Change st.write to st.title: import streamlit as st st.title(""Hello World"") In the upper-right corner, click the blue ""play_arrow Run"" button to make the running app reflect your changes. You've just edited your app. It's that easy. When you're done, click ""chevron_left Streamlit Apps"" in the upper-left corner to go back to Snowsight. Returning to your app When you are ready to return to your app, go to your Snowsight interface. (If you are returning to the site, you can log in at app.snowflake.com.) In the left navigation, go to ""Streamlit."" Click on ""Hello World."" (If you don't see your app, check that you have your role set to ""ACCOUNTADMIN"" as above.) Your app will open in viewing mode. Just click ""Edit"" in the upper-right corner to modify your app again. What's next? Read about our Basic concepts and try out more commands in your app. To create more apps in your account, you can proceed from Create a ""Hello World"" Streamlit app. The warehouse and database setup do not need to be repeated. For more information about creating and managing Streamlit in Snowflake apps, check out the Snowflake docs.Previous: Use GitHub CodespacesNext: FundamentalsforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy" https://docs.streamlit.io/knowledge-base/using-streamlit/serializable-session-state#serializable-session-state,"DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Knowledge base/FAQ/What is serializable session state?What is serializable session state? Serializable Session State Serialization refers to the process of converting an object or data structure into a format that can be persisted and shared, and allowing you to recover the data’s original structure. Python’s built-in pickle module serializes Python objects to a byte stream (""pickling"") and deserializes the stream into an object (""unpickling""). By default, Streamlit’s Session State allows you to persist any Python object for the duration of the session, irrespective of the object’s pickle-serializability. This property lets you store Python primitives such as integers, floating-point numbers, complex numbers and booleans, dataframes, and even lambdas returned by functions. However, some execution environments may require serializing all data in Session State, so it may be useful to detect incompatibility during development, or when the execution environment will stop supporting it in the future. To that end, Streamlit provides a runner.enforceSerializableSessionState configuration option that, when set to true, only allows pickle-serializable objects in Session State. To enable the option, either create a global or project config file with the following or use it as a command-line flag: # .streamlit/config.toml [runner] enforceSerializableSessionState = true By ""pickle-serializable"", we mean calling pickle.dumps(obj) should not raise a PicklingError exception. When the config option is enabled, adding unserializable data to session state should result in an exception. E.g., import streamlit as st def unserializable_data(): return lambda x: x #👇 results in an exception when enforceSerializableSessionState is on st.session_state.unserializable = unserializable_data() Previous: Why does Streamlit restrict nested st.columns?Next: Installing dependenciesforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy" https://docs.streamlit.io/develop/concepts/architecture/fragments,"DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsremoveCOREArchitecture & executionremoveRunning your appStreamlit's architectureThe app chromeCachingSession StateFormsFragmentsWidget behaviorMultipage appsaddApp designaddADDITIONALConnections and secretsaddCustom componentsaddConfiguration and themingaddApp testingaddAPI referenceaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Develop/Concepts/Architecture & execution/FragmentsWorking with fragments and partial reruns Reruns are a central part of every Streamlit app. When users interact with widgets, your script reruns from top to bottom, and your app's frontend is updated. Streamlit provides several features to help you develop your app within this execution model. Streamlit version 1.33.0 introduced fragments to allow rerunning a portion of your code instead of your full script. As your app grows larger and more complex, these partial reruns help your app be efficient and performant. Fragments give you finer, easy-to-understand control over your app's execution flow. Before you read about fragments, we recommend having a basic understanding of caching, Session State, and forms. Use cases for fragments Fragments are versatile and applicable to a wide variety of circumstances. Here are just a few, common scenarios where fragments are useful: Your app has multiple visualizations and each one takes time to load, but you have a filter input that only updates one of them. You have a dynamic form that doesn't need to update the rest of your app (until the form is complete). You want to automatically update a single component or group of components to stream data. Defining and calling a fragment Streamlit provides a decorator (st.experimental_fragment) to turn any function into a fragment function. When you call a fragment function that contains a widget function, a user triggers a partial rerun instead of a full rerun when they interact with that fragment's widget. During a partial rerun, your fragment function is re-executed. Anything within the main body of your fragment is updated on the frontend, while the rest of your app remains the same. We'll describe fragments written across multiple containers later on. Here is a basic example of defining and calling a fragment function. Just like with caching, remember to call your function after defining it. import streamlit as st @st.experimental_fragment def fragment_function(): if st.button(""Hi!""): st.write(""Hi back!"") fragment_function() If you want the main body of your fragment to appear in the sidebar or another container, call your fragment function inside a context manager. with st.sidebar: fragment_function() Partial rerun execution flow Consider the following code with the explanation and diagram below. import streamlit as st st.title(""My Awesome App"") @st.experimental_fragment() def toggle_and_text(): cols = st.columns(2) cols[0].toggle(""Toggle"") cols[1].text_area(""Enter text"") @st.experimental_fragment() def filter_and_file(): cols = st.columns(2) cols[0].checkbox(""Filter"") cols[1].file_uploader(""Upload image"") toggle_and_text() cols = st.columns(2) cols[0].selectbox(""Select"", [1,2,3], None) cols[1].button(""Update"") filter_and_file() When a user interacts with an input widget inside a fragment, only the fragment reruns instead of the full script. When a user interacts with an input widget outside a fragment, the full script reruns as usual. If you run the code above, the full script will run top to bottom on your app's initial load. If you flip the toggle button in your running app, the first fragment (toggle_and_text()) will rerun, redrawing the toggle and text area while leaving everything else unchanged. If you click the checkbox, the second fragment (filter_and_file()) will rerun and consequently redraw the checkbox and file uploader. Everything else remains unchanged. Finally, if you click the update button, the full script will rerun, and Streamlit will redraw everything. Fragment return values and interacting with the rest of your app Streamlit ignores fragment return values during fragment reruns, so defining return values for your fragment functions is not recommended. Instead, if your fragment needs to share data with the rest of your app, use Session State. Fragments are just functions in your script, so they can access Session State, imported modules, and other Streamlit elements like containers. If your fragment writes to any container created outside of itself, note the following difference in behavior: Elements drawn in the main body of your fragment are cleared and redrawn in place during a fragment rerun. Repeated fragment reruns will not cause additional elements to appear. Elements drawn to containers outside the main body of fragment will not be cleared with each fragment rerun. Instead, Streamlit will draw them additively and these elements will accumulate until the next full-script rerun. To prevent elements from accumulating in outside containers, use st.empty containers. For a related tutorial, see Create a fragment across multiple containers. If you need to trigger a full-script rerun from inside a fragment, call st.rerun. For a related tutorial, see Trigger a full-script rerun from inside a fragment. Automate fragment reruns st.experimental_fragment includes a convenient run_every parameter that causes the fragment to rerun automatically at the specified time interval. These reruns are in addition to any reruns (fragment or full-script) triggered by your user. The automatic fragment reruns will continue even if your user is not interacting with your app. This is a great way to show a live data stream or status on a running background job, efficiently updating your rendered data and only your rendered data. @st.experimental_fragment(run_every=""10s"") def auto_function(): # This will update every 10 seconds! df = get_latest_updates() st.line_chart(df) auto_function() For a related tutorial, see Start and stop a streaming fragment. Compare fragments to other Streamlit features Fragments vs forms Here is a comparison between fragments and forms: Forms allow users to interact with widgets without rerunning your app. Streamlit does not send user actions within a form to your app's Python backend until the form is submitted. Widgets within a form can not dynamically update other widgets (in or out of the form) in real-time. Fragments run independently from the rest of your code. As your users interact with fragment widgets, their actions are immediately processed by your app's Python backend and your fragment code is rerun. Widgets within a fragment can dynamically update other widgets within the same fragment in real-time. A form batches user input without interaction between any widgets. A fragment immediately processes user input but limits the scope of the rerun. Fragments vs callbacks Here is a comparison between fragments and callbacks: Callbacks allow you to execute a function at the beginning of a script rerun. A callback is a single prefix to your script rerun. Fragments allow you to rerun a portion of your script. A fragment is a repeatable postfix to your script, running each time a user interacts with a fragment widget, or automatically in sequence when run_every is set. When callbacks render elements to your page, they are rendered before the rest of your page elements. When fragments render elements to your page, they are updated with each fragment rerun (unless they are written to containers outside of the fragment, in which case they accumulate there). Fragments vs custom components Here is a comparison between fragments and custom components: Components are custom frontend code that can interact with the Python code, native elements, and widgets in your Streamlit app. Custom components extend what’s possible with Streamlit. They follow the normal Streamlit execution flow. Fragments are parts of your app that can rerun independently of the full app. Fragments can be composed of multiple Streamlit elements, widgets, or any Python code. A fragment can include one or more custom components. A custom component could not easily include a fragment! Fragments vs caching Here is a comparison between fragments and caching: Caching: allows you to skip over a function and return a previously computed value. When you use caching, you execute everything except the cached function (if you've already run it before). Fragments: allow you to freeze most of your app and just execute the fragment. When you use fragments, you execute only the fragment (when triggering a fragment rerun). Caching saves you from unnecessarily running a piece of your app while the rest runs. Fragments save you from running your full app when you only want to run one piece. Limitations and unsupported behavior Fragments can't detect a change in input values. It is best to use Session State for dynamic input and output for fragment functions. Calling fragments within fragments is unsupported. Using caching and fragments on the same function is unsupported. Previous: FormsNext: Widget behaviorforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy" https://docs.streamlit.io/develop/api-reference/data/st.data_editor,"DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceremovePAGE ELEMENTSWrite and magicaddText elementsaddData elementsremovest.dataframest.data_editorst.column_configaddst.tablest.metricst.jsonChart elementsaddInput widgetsaddMedia elementsaddLayouts and containersaddChat elementsaddStatus elementsaddThird-party componentsopen_in_newAPPLICATION LOGICNavigation and pagesaddExecution flowaddCaching and stateaddConnections and secretsaddCustom componentsaddUtilitiesaddConfigurationaddTOOLSApp testingaddCommand lineaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Develop/API reference/Data elements/st.data_editorstarTipThis page only contains information on the st.data_editor API. For an overview of working with dataframes and to learn more about the data editor's capabilities and limitations, read Dataframes. st.data_editorStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeDisplay a data editor widget. The data editor widget allows you to edit dataframes and many other data structures in a table-like UI. Warning When going from st.experimental_data_editor to st.data_editor in 1.23.0, the data editor's representation in st.session_state was changed. The edited_cells dictionary is now called edited_rows and uses a different format ({0: {""column name"": ""edited value""}} instead of {""0:1"": ""edited value""}). You may need to adjust the code if your app uses st.experimental_data_editor in combination with st.session_state. Function signature[source] st.data_editor(data, *, width=None, height=None, use_container_width=False, hide_index=None, column_order=None, column_config=None, num_rows=""fixed"", disabled=False, key=None, on_change=None, args=None, kwargs=None) Parameters data (pandas.DataFrame, pandas.Series, pandas.Styler, pandas.Index, pyarrow.Table, numpy.ndarray, pyspark.sql.DataFrame, snowflake.snowpark.DataFrame, list, set, tuple, dict, or None) The data to edit in the data editor. Note Styles from pandas.Styler will only be applied to non-editable columns. Mixing data types within a column can make the column uneditable. Additionally, the following data types are not yet supported for editing: complex, list, tuple, bytes, bytearray, memoryview, dict, set, frozenset, fractions.Fraction, pandas.Interval, and pandas.Period. To prevent overflow in JavaScript, columns containing datetime.timedelta and pandas.Timedelta values will default to uneditable but this can be changed through column configuration. width (int or None) Desired width of the data editor expressed in pixels. If None, the width will be automatically determined. height (int or None) Desired height of the data editor expressed in pixels. If None, the height will be automatically determined. use_container_width (bool) If True, set the data editor width to the width of the parent container. This takes precedence over the width argument. Defaults to False. hide_index (bool or None) Whether to hide the index column(s). If None (default), the visibility of index columns is automatically determined based on the data. column_order (Iterable of str or None) Specifies the display order of columns. This also affects which columns are visible. For example, column_order=(""col2"", ""col1"") will display 'col2' first, followed by 'col1', and will hide all other non-index columns. If None (default), the order is inherited from the original data structure. column_config (dict or None) Configures how columns are displayed, e.g. their title, visibility, type, or format, as well as editing properties such as min/max value or step. This needs to be a dictionary where each key is a column name and the value is one of: None to hide the column. A string to set the display label of the column. One of the column types defined under st.column_config, e.g. st.column_config.NumberColumn(""Dollar values”, format=”$ %d"") to show a column as dollar amounts. See more info on the available column types and config options here. To configure the index column(s), use _index as the column name. num_rows (""fixed"" or ""dynamic"") Specifies if the user can add and delete rows in the data editor. If ""fixed"", the user cannot add or delete rows. If ""dynamic"", the user can add and delete rows in the data editor, but column sorting is disabled. Defaults to ""fixed"". disabled (bool or Iterable of str) Controls the editing of columns. If True, editing is disabled for all columns. If an Iterable of column names is provided (e.g., disabled=(""col1"", ""col2"")), only the specified columns will be disabled for editing. If False (default), all columns that support editing are editable. key (str) An optional string to use as the unique key for this widget. If this is omitted, a key will be generated for the widget based on its content. Multiple widgets of the same type may not share the same key. on_change (callable) An optional callback invoked when this data_editor's value changes. args (tuple) An optional tuple of args to pass to the callback. kwargs (dict) An optional dict of kwargs to pass to the callback. Returns(pandas.DataFrame, pandas.Series, pyarrow.Table, numpy.ndarray, list, set, tuple, or dict.) The edited data. The edited data is returned in its original data type if it corresponds to any of the supported return types. All other data types are returned as a pandas.DataFrame. Examples import streamlit as st import pandas as pd df = pd.DataFrame( [ {""command"": ""st.selectbox"", ""rating"": 4, ""is_widget"": True}, {""command"": ""st.balloons"", ""rating"": 5, ""is_widget"": False}, {""command"": ""st.time_input"", ""rating"": 3, ""is_widget"": True}, ] ) edited_df = st.data_editor(df) favorite_command = edited_df.loc[edited_df[""rating""].idxmax()][""command""] st.markdown(f""Your favorite command is **{favorite_command}** 🎈"") Built with Streamlit 🎈Fullscreen open_in_new You can also allow the user to add and delete rows by setting num_rows to ""dynamic"": import streamlit as st import pandas as pd df = pd.DataFrame( [ {""command"": ""st.selectbox"", ""rating"": 4, ""is_widget"": True}, {""command"": ""st.balloons"", ""rating"": 5, ""is_widget"": False}, {""command"": ""st.time_input"", ""rating"": 3, ""is_widget"": True}, ] ) edited_df = st.data_editor(df, num_rows=""dynamic"") favorite_command = edited_df.loc[edited_df[""rating""].idxmax()][""command""] st.markdown(f""Your favorite command is **{favorite_command}** 🎈"") Built with Streamlit 🎈Fullscreen open_in_new Or you can customize the data editor via column_config, hide_index, column_order, or disabled: import pandas as pd import streamlit as st df = pd.DataFrame( [ {""command"": ""st.selectbox"", ""rating"": 4, ""is_widget"": True}, {""command"": ""st.balloons"", ""rating"": 5, ""is_widget"": False}, {""command"": ""st.time_input"", ""rating"": 3, ""is_widget"": True}, ] ) edited_df = st.data_editor( df, column_config={ ""command"": ""Streamlit Command"", ""rating"": st.column_config.NumberColumn( ""Your rating"", help=""How much do you like this command (1-5)?"", min_value=1, max_value=5, step=1, format=""%d ⭐"", ), ""is_widget"": ""Widget ?"", }, disabled=[""command"", ""is_widget""], hide_index=True, ) favorite_command = edited_df.loc[edited_df[""rating""].idxmax()][""command""] st.markdown(f""Your favorite command is **{favorite_command}** 🎈"") Built with Streamlit 🎈Fullscreen open_in_new Configuring columns You can configure the display and editing behavior of columns in st.dataframe and st.data_editor via the Column configuration API. We have developed the API to let you add images, charts, and clickable URLs in dataframe and data editor columns. Additionally, you can make individual columns editable, set columns as categorical and specify which options they can take, hide the index of the dataframe, and much more. Built with Streamlit 🎈Fullscreen open_in_newPrevious: st.dataframeNext: st.column_configforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy" https://docs.streamlit.io/en/0.75.0/api.html#input-widgets,"DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceremovePAGE ELEMENTSWrite and magicaddText elementsaddData elementsaddChart elementsaddInput widgetsaddMedia elementsaddLayouts and containersaddChat elementsaddStatus elementsaddThird-party componentsopen_in_newAPPLICATION LOGICNavigation and pagesaddExecution flowaddCaching and stateaddConnections and secretsaddCustom componentsaddUtilitiesaddConfigurationaddTOOLSApp testingaddCommand lineaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Develop/API referenceAPI reference Streamlit makes it easy for you to visualize, mutate, and share data. The API reference is organized by activity type, like displaying data or optimizing performance. Each section includes methods associated with the activity type, including examples. Browse our API below and click to learn more about any of our available commands! 🎈 Display almost anything Write and magic st.writeWrite arguments to the app.st.write(""Hello **world**!"") st.write(my_data_frame) st.write(my_mpl_figure) st.write_streamWrite generators or streams to the app with a typewriter effect.st.write_stream(my_generator) st.write_stream(my_llm_stream) MagicAny time Streamlit sees either a variable or literal value on its own line, it automatically writes that to your app using st.write""Hello **world**!"" my_data_frame my_mpl_figure Text elements MarkdownDisplay string formatted as Markdown.st.markdown(""Hello **world**!"") TitleDisplay text in title formatting.st.title(""The app title"") HeaderDisplay text in header formatting.st.header(""This is a header"") SubheaderDisplay text in subheader formatting.st.subheader(""This is a subheader"") CaptionDisplay text in small font.st.caption(""This is written small caption text"") Code blockDisplay a code block with optional syntax highlighting.st.code(""a = 1234"") EchoDisplay some code in the app, then execute it. Useful for tutorials.with st.echo(): st.write('This code will be printed') LaTeXDisplay mathematical expressions formatted as LaTeX.st.latex(""\int a x^2 \,dx"") Preformatted textWrite fixed-width and preformatted text.st.text(""Hello world"") DividerDisplay a horizontal rule.st.divider() Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration! PreviousTagsAdd tags to your Streamlit apps. Created by @gagan3012.st_tags(label='# Enter Keywords:', text='Press enter to add more', value=['Zero', 'One', 'Two'], suggestions=['five', 'six', 'seven', 'eight', 'nine', 'three', 'eleven', 'ten', 'four'], maxtags = 4, key='1') NLUApply text mining on a dataframe. Created by @JohnSnowLabs.nlu.load('sentiment').predict('I love NLU! <3') Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.mention(label=""An awesome Streamlit App"", icon=""streamlit"", url=""https://extras.streamlit.app"",) Annotated textDisplay annotated text in Streamlit apps. Created by @tvst.annotated_text(""This "", (""is"", ""verb""), "" some "", (""annotated"", ""adj""), (""text"", ""noun""), "" for those of "", (""you"", ""pronoun""), "" who "", (""like"", ""verb""), "" this sort of "", (""thing"", ""noun""), ""."") Drawable CanvasProvides a sketching canvas using Fabric.js. Created by @andfanilo.st_canvas(fill_color=""rgba(255, 165, 0, 0.3)"", stroke_width=stroke_width, stroke_color=stroke_color, background_color=bg_color, background_image=Image.open(bg_image) if bg_image else None, update_streamlit=realtime_update, height=150, drawing_mode=drawing_mode, point_display_radius=point_display_radius if drawing_mode == 'point' else 0, key=""canvas"",) TagsAdd tags to your Streamlit apps. Created by @gagan3012.st_tags(label='# Enter Keywords:', text='Press enter to add more', value=['Zero', 'One', 'Two'], suggestions=['five', 'six', 'seven', 'eight', 'nine', 'three', 'eleven', 'ten', 'four'], maxtags = 4, key='1') NLUApply text mining on a dataframe. Created by @JohnSnowLabs.nlu.load('sentiment').predict('I love NLU! <3') Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.mention(label=""An awesome Streamlit App"", icon=""streamlit"", url=""https://extras.streamlit.app"",) Annotated textDisplay annotated text in Streamlit apps. Created by @tvst.annotated_text(""This "", (""is"", ""verb""), "" some "", (""annotated"", ""adj""), (""text"", ""noun""), "" for those of "", (""you"", ""pronoun""), "" who "", (""like"", ""verb""), "" this sort of "", (""thing"", ""noun""), ""."") Drawable CanvasProvides a sketching canvas using Fabric.js. Created by @andfanilo.st_canvas(fill_color=""rgba(255, 165, 0, 0.3)"", stroke_width=stroke_width, stroke_color=stroke_color, background_color=bg_color, background_image=Image.open(bg_image) if bg_image else None, update_streamlit=realtime_update, height=150, drawing_mode=drawing_mode, point_display_radius=point_display_radius if drawing_mode == 'point' else 0, key=""canvas"",) TagsAdd tags to your Streamlit apps. Created by @gagan3012.st_tags(label='# Enter Keywords:', text='Press enter to add more', value=['Zero', 'One', 'Two'], suggestions=['five', 'six', 'seven', 'eight', 'nine', 'three', 'eleven', 'ten', 'four'], maxtags = 4, key='1') NLUApply text mining on a dataframe. Created by @JohnSnowLabs.nlu.load('sentiment').predict('I love NLU! <3') Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.mention(label=""An awesome Streamlit App"", icon=""streamlit"", url=""https://extras.streamlit.app"",) Next Data elements DataframesDisplay a dataframe as an interactive table.st.dataframe(my_data_frame) Data editorDisplay a data editor widget.edited = st.data_editor(df, num_rows=""dynamic"") Column configurationConfigure the display and editing behavior of dataframes and data editors.st.column_config.NumberColumn(""Price (in USD)"", min_value=0, format=""$%d"") Static tablesDisplay a static table.st.table(my_data_frame) MetricsDisplay a metric in big bold font, with an optional indicator of how the metric changed.st.metric(""My metric"", 42, 2) Dicts and JSONDisplay object or string as a pretty-printed JSON string.st.json(my_dict) Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration! PreviousImage CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates value = streamlit_image_coordinates(""https://placekitten.com/200/300"") st.write(value) Plotly EventsMake Plotly charts interactive!. Created by @null-jones.from streamlit_plotly_events import plotly_events fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.metric_cards import style_metric_cards col3.metric(label=""No Change"", value=5000, delta=0) style_metric_cards() Streamlit AggridImplementation of Ag-Grid component for Streamlit. Created by @PablocFonseca.df = pd.DataFrame({'col1': [1, 2, 3], 'col2': [4, 5, 6]}) grid_return = AgGrid(df, editable=True) new_df = grid_return['data'] Streamlit FoliumStreamlit Component for rendering Folium maps. Created by @randyzwitch.m = folium.Map(location=[39.949610, -75.150282], zoom_start=16) folium.Marker([39.949610, -75.150282], popup=""Liberty Bell"", tooltip=""Liberty Bell"").add_to(m) st_data = st_folium(m, width=725) Pandas ProfilingPandas profiling component for Streamlit. Created by @okld.df = pd.read_csv(""https://storage.googleapis.com/tf-datasets/titanic/train.csv"") pr = df.profile_report() st_profile_report(pr) Image CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates value = streamlit_image_coordinates(""https://placekitten.com/200/300"") st.write(value) Plotly EventsMake Plotly charts interactive!. Created by @null-jones.from streamlit_plotly_events import plotly_events fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.metric_cards import style_metric_cards col3.metric(label=""No Change"", value=5000, delta=0) style_metric_cards() Streamlit AggridImplementation of Ag-Grid component for Streamlit. Created by @PablocFonseca.df = pd.DataFrame({'col1': [1, 2, 3], 'col2': [4, 5, 6]}) grid_return = AgGrid(df, editable=True) new_df = grid_return['data'] Streamlit FoliumStreamlit Component for rendering Folium maps. Created by @randyzwitch.m = folium.Map(location=[39.949610, -75.150282], zoom_start=16) folium.Marker([39.949610, -75.150282], popup=""Liberty Bell"", tooltip=""Liberty Bell"").add_to(m) st_data = st_folium(m, width=725) Pandas ProfilingPandas profiling component for Streamlit. Created by @okld.df = pd.read_csv(""https://storage.googleapis.com/tf-datasets/titanic/train.csv"") pr = df.profile_report() st_profile_report(pr) Image CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates value = streamlit_image_coordinates(""https://placekitten.com/200/300"") st.write(value) Plotly EventsMake Plotly charts interactive!. Created by @null-jones.from streamlit_plotly_events import plotly_events fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.metric_cards import style_metric_cards col3.metric(label=""No Change"", value=5000, delta=0) style_metric_cards() Next Chart elements Simple area chartsDisplay an area chart.st.area_chart(my_data_frame) Simple bar chartsDisplay a bar chart.st.bar_chart(my_data_frame) Simple line chartsDisplay a line chart.st.line_chart(my_data_frame) Simple scatter chartsDisplay a line chart.st.scatter_chart(my_data_frame) Scatterplots on mapsDisplay a map with points on it.st.map(my_data_frame) MatplotlibDisplay a matplotlib.pyplot figure.st.pyplot(my_mpl_figure) AltairDisplay a chart using the Altair library.st.altair_chart(my_altair_chart) Vega-LiteDisplay a chart using the Vega-Lite library.st.vega_lite_chart(my_vega_lite_chart) PlotlyDisplay an interactive Plotly chart.st.plotly_chart(my_plotly_chart) BokehDisplay an interactive Bokeh chart.st.bokeh_chart(my_bokeh_chart) PyDeckDisplay a chart using the PyDeck library.st.pydeck_chart(my_pydeck_chart) GraphVizDisplay a graph using the dagre-d3 library.st.graphviz_chart(my_graphviz_spec) Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration! PreviousStreamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl(""https://assets5.lottiefiles.com/packages/lf20_V9t630.json"") st_lottie(lottie_hello, key=""hello"") Plotly EventsMake Plotly charts interactive!. Created by @null-jones.fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.chart += get_annotations_chart(annotations=[(""Mar 01, 2008"", ""Pretty good day for GOOG""), (""Dec 01, 2007"", ""Something's going wrong for GOOG & AAPL""), (""Nov 01, 2008"", ""Market starts again thanks to...""), (""Dec 01, 2009"", ""Small crash for GOOG after...""),],) st.altair_chart(chart, use_container_width=True) PlostA deceptively simple plotting library for Streamlit. Created by @tvst.import plost plost.line_chart(my_dataframe, x='time', y='stock_value', color='stock_name',) HiPlotHigh dimensional Interactive Plotting. Created by @facebookresearch.data = [{'dropout':0.1, 'lr': 0.001, 'loss': 10.0, 'optimizer': 'SGD'}, {'dropout':0.15, 'lr': 0.01, 'loss': 3.5, 'optimizer': 'Adam'}, {'dropout':0.3, 'lr': 0.1, 'loss': 4.5, 'optimizer': 'Adam'}] hip.Experiment.from_iterable(data).display() EChartsHigh dimensional Interactive Plotting. Created by @andfanilo.from streamlit_echarts import st_echarts st_echarts(options=options) Streamlit FoliumStreamlit Component for rendering Folium maps. Created by @randyzwitch.m = folium.Map(location=[39.949610, -75.150282], zoom_start=16) st_data = st_folium(m, width=725) Spacy-StreamlitspaCy building blocks and visualizers for Streamlit apps. Created by @explosion.models = [""en_core_web_sm"", ""en_core_web_md""] spacy_streamlit.visualize(models, ""Sundar Pichai is the CEO of Google."") Streamlit AgraphA Streamlit Graph Vis, based on react-grah-vis. Created by @ChrisDelClea.from streamlit_agraph import agraph, Node, Edge, Config agraph(nodes=nodes, edges=edges, config=config) Streamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl(""https://assets5.lottiefiles.com/packages/lf20_V9t630.json"") st_lottie(lottie_hello, key=""hello"") Plotly EventsMake Plotly charts interactive!. Created by @null-jones.fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.chart += get_annotations_chart(annotations=[(""Mar 01, 2008"", ""Pretty good day for GOOG""), (""Dec 01, 2007"", ""Something's going wrong for GOOG & AAPL""), (""Nov 01, 2008"", ""Market starts again thanks to...""), (""Dec 01, 2009"", ""Small crash for GOOG after...""),],) st.altair_chart(chart, use_container_width=True) PlostA deceptively simple plotting library for Streamlit. Created by @tvst.import plost plost.line_chart(my_dataframe, x='time', y='stock_value', color='stock_name',) HiPlotHigh dimensional Interactive Plotting. Created by @facebookresearch.data = [{'dropout':0.1, 'lr': 0.001, 'loss': 10.0, 'optimizer': 'SGD'}, {'dropout':0.15, 'lr': 0.01, 'loss': 3.5, 'optimizer': 'Adam'}, {'dropout':0.3, 'lr': 0.1, 'loss': 4.5, 'optimizer': 'Adam'}] hip.Experiment.from_iterable(data).display() EChartsHigh dimensional Interactive Plotting. Created by @andfanilo.from streamlit_echarts import st_echarts st_echarts(options=options) Streamlit FoliumStreamlit Component for rendering Folium maps. Created by @randyzwitch.m = folium.Map(location=[39.949610, -75.150282], zoom_start=16) st_data = st_folium(m, width=725) Spacy-StreamlitspaCy building blocks and visualizers for Streamlit apps. Created by @explosion.models = [""en_core_web_sm"", ""en_core_web_md""] spacy_streamlit.visualize(models, ""Sundar Pichai is the CEO of Google."") Streamlit AgraphA Streamlit Graph Vis, based on react-grah-vis. Created by @ChrisDelClea.from streamlit_agraph import agraph, Node, Edge, Config agraph(nodes=nodes, edges=edges, config=config) Streamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl(""https://assets5.lottiefiles.com/packages/lf20_V9t630.json"") st_lottie(lottie_hello, key=""hello"") Plotly EventsMake Plotly charts interactive!. Created by @null-jones.fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.chart += get_annotations_chart(annotations=[(""Mar 01, 2008"", ""Pretty good day for GOOG""), (""Dec 01, 2007"", ""Something's going wrong for GOOG & AAPL""), (""Nov 01, 2008"", ""Market starts again thanks to...""), (""Dec 01, 2009"", ""Small crash for GOOG after...""),],) st.altair_chart(chart, use_container_width=True) Next Input widgets ButtonDisplay a button widget.clicked = st.button(""Click me"") Download buttonDisplay a download button widget.st.download_button(""Download file"", file) Form buttonDisplay a form submit button. For use with st.form.st.form_submit_button(""Sign up"") Link buttonDisplay a link button.st.link_button(""Go to gallery"", url) Page linkDisplay a link to another page in a multipage app.st.page_link(""app.py"", label=""Home"", icon=""🏠"") st.page_link(""pages/profile.py"", label=""My profile"") CheckboxDisplay a checkbox widget.selected = st.checkbox(""I agree"") Color pickerDisplay a color picker widget.color = st.color_picker(""Pick a color"") MultiselectDisplay a multiselect widget. The multiselect widget starts as empty.choices = st.multiselect(""Buy"", [""milk"", ""apples"", ""potatoes""]) RadioDisplay a radio button widget.choice = st.radio(""Pick one"", [""cats"", ""dogs""]) SelectboxDisplay a select widget.choice = st.selectbox(""Pick one"", [""cats"", ""dogs""]) Select-sliderDisplay a slider widget to select items from a list.size = st.select_slider(""Pick a size"", [""S"", ""M"", ""L""]) ToggleDisplay a toggle widget.activated = st.toggle(""Activate"") Number inputDisplay a numeric input widget.choice = st.number_input(""Pick a number"", 0, 10) SliderDisplay a slider widget.number = st.slider(""Pick a number"", 0, 100) Date inputDisplay a date input widget.date = st.date_input(""Your birthday"") Time inputDisplay a time input widget.time = st.time_input(""Meeting time"") Chat inputDisplay a chat input widget.prompt = st.chat_input(""Say something"") if prompt: st.write(f""The user has sent: {prompt}"") Text-areaDisplay a multi-line text input widget.text = st.text_area(""Text to translate"") Text inputDisplay a single-line text input widget.name = st.text_input(""First name"") Data editorDisplay a data editor widget.edited = st.experimental_data_editor(df, num_rows=""dynamic"") File UploaderDisplay a file uploader widget.data = st.file_uploader(""Upload a CSV"") Camera inputDisplay a widget that allows users to upload images directly from a camera.image = st.camera_input(""Take a picture"") Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration! PreviousStreamlit ChatStreamlit Component for a Chatbot UI. Created by @AI-Yash.from streamlit_chat import message message(""My message"") message(""Hello bot!"", is_user=True) # align's the message to the right Streamlit Option MenuSelect a single item from a list of options in a menu. Created by @victoryhb.from streamlit_option_menu import option_menu option_menu(""Main Menu"", [""Home"", 'Settings'], icons=['house', 'gear'], menu_icon=""cast"", default_index=1) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.stoggle import stoggle stoggle( ""Click me!"", """"""🥷 Surprise! Here's some additional content"""""",) Streamlit ElementsCreate a draggable and resizable dashboard in Streamlit. Created by @okls.from streamlit_elements import elements, mui, html with elements(""new_element""): mui.Typography(""Hello world"") TagsAdd tags to your Streamlit apps. Created by @gagan3012.from streamlit_tags import st_tags st_tags(label='# Enter Keywords:', text='Press enter to add more', value=['Zero', 'One', 'Two'], suggestions=['five', 'six', 'seven', 'eight', 'nine', 'three', 'eleven', 'ten', 'four'], maxtags = 4, key='1') StqdmThe simplest way to handle a progress bar in streamlit app. Created by @Wirg.from stqdm import stqdm for _ in stqdm(range(50)): sleep(0.5) TimelineDisplay a Timeline in Streamlit apps using TimelineJS. Created by @innerdoc.from streamlit_timeline import timeline with open('example.json', ""r"") as f: timeline(f.read(), height=800) Camera input liveAlternative for st.camera_input which returns the webcam images live. Created by @blackary.from camera_input_live import camera_input_live image = camera_input_live() st.image(value) Streamlit AceAce editor component for Streamlit. Created by @okld.from streamlit_ace import st_ace content = st_ace() content Streamlit ChatStreamlit Component for a Chatbot UI. Created by @AI-Yash.from streamlit_chat import message message(""My message"") message(""Hello bot!"", is_user=True) # align's the message to the right Streamlit Option MenuSelect a single item from a list of options in a menu. Created by @victoryhb.from streamlit_option_menu import option_menu option_menu(""Main Menu"", [""Home"", 'Settings'], icons=['house', 'gear'], menu_icon=""cast"", default_index=1) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.stoggle import stoggle stoggle( ""Click me!"", """"""🥷 Surprise! Here's some additional content"""""",) Streamlit ElementsCreate a draggable and resizable dashboard in Streamlit. Created by @okls.from streamlit_elements import elements, mui, html with elements(""new_element""): mui.Typography(""Hello world"") TagsAdd tags to your Streamlit apps. Created by @gagan3012.from streamlit_tags import st_tags st_tags(label='# Enter Keywords:', text='Press enter to add more', value=['Zero', 'One', 'Two'], suggestions=['five', 'six', 'seven', 'eight', 'nine', 'three', 'eleven', 'ten', 'four'], maxtags = 4, key='1') StqdmThe simplest way to handle a progress bar in streamlit app. Created by @Wirg.from stqdm import stqdm for _ in stqdm(range(50)): sleep(0.5) TimelineDisplay a Timeline in Streamlit apps using TimelineJS. Created by @innerdoc.from streamlit_timeline import timeline with open('example.json', ""r"") as f: timeline(f.read(), height=800) Camera input liveAlternative for st.camera_input which returns the webcam images live. Created by @blackary.from camera_input_live import camera_input_live image = camera_input_live() st.image(value) Streamlit AceAce editor component for Streamlit. Created by @okld.from streamlit_ace import st_ace content = st_ace() content Streamlit ChatStreamlit Component for a Chatbot UI. Created by @AI-Yash.from streamlit_chat import message message(""My message"") message(""Hello bot!"", is_user=True) # align's the message to the right Streamlit Option MenuSelect a single item from a list of options in a menu. Created by @victoryhb.from streamlit_option_menu import option_menu option_menu(""Main Menu"", [""Home"", 'Settings'], icons=['house', 'gear'], menu_icon=""cast"", default_index=1) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.stoggle import stoggle stoggle( ""Click me!"", """"""🥷 Surprise! Here's some additional content"""""",) Next Media elements ImageDisplay an image or list of images.st.image(numpy_array) st.image(image_bytes) st.image(file) st.image(""https://example.com/myimage.jpg"") AudioDisplay an audio player.st.audio(numpy_array) st.audio(audio_bytes) st.audio(file) st.audio(""https://example.com/myaudio.mp3"", format=""audio/mp3"") VideoDisplay a video player.st.video(numpy_array) st.video(video_bytes) st.video(file) st.video(""https://example.com/myvideo.mp4"", format=""video/mp4"") Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration! PreviousStreamlit CropperA simple image cropper for Streamlit. Created by @turner-anderson.from streamlit_cropper import st_cropper st_cropper(img, realtime_update=realtime_update, box_color=box_color, aspect_ratio=aspect_ratio) Image CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates streamlit_image_coordinates(""https://placekitten.com/200/300"") Streamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl(""https://assets5.lottiefiles.com/packages/lf20_V9t630.json"") st_lottie(lottie_hello, key=""hello"") Streamlit WebrtcHandling and transmitting real-time video/audio streams with Streamlit. Created by @whitphx.from streamlit_webrtc import webrtc_streamer webrtc_streamer(key=""sample"") Drawable CanvasProvides a sketching canvas using Fabric.js. Created by @andfanilo.from streamlit_drawable_canvas import st_canvas st_canvas(fill_color=""rgba(255, 165, 0, 0.3)"", stroke_width=stroke_width, stroke_color=stroke_color, background_color=bg_color, background_image=Image.open(bg_image) if bg_image else None, update_streamlit=realtime_update, height=150, drawing_mode=drawing_mode, point_display_radius=point_display_radius if drawing_mode == 'point' else 0, key=""canvas"",) Image ComparisonCompare images with a slider using JuxtaposeJS. Created by @fcakyon.from streamlit_image_comparison import image_comparison image_comparison(img1=""image1.jpg"", img2=""image2.jpg"",) Streamlit CropperA simple image cropper for Streamlit. Created by @turner-anderson.from streamlit_cropper import st_cropper st_cropper(img, realtime_update=realtime_update, box_color=box_color, aspect_ratio=aspect_ratio) Image CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates streamlit_image_coordinates(""https://placekitten.com/200/300"") Streamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl(""https://assets5.lottiefiles.com/packages/lf20_V9t630.json"") st_lottie(lottie_hello, key=""hello"") Streamlit WebrtcHandling and transmitting real-time video/audio streams with Streamlit. Created by @whitphx.from streamlit_webrtc import webrtc_streamer webrtc_streamer(key=""sample"") Drawable CanvasProvides a sketching canvas using Fabric.js. Created by @andfanilo.from streamlit_drawable_canvas import st_canvas st_canvas(fill_color=""rgba(255, 165, 0, 0.3)"", stroke_width=stroke_width, stroke_color=stroke_color, background_color=bg_color, background_image=Image.open(bg_image) if bg_image else None, update_streamlit=realtime_update, height=150, drawing_mode=drawing_mode, point_display_radius=point_display_radius if drawing_mode == 'point' else 0, key=""canvas"",) Image ComparisonCompare images with a slider using JuxtaposeJS. Created by @fcakyon.from streamlit_image_comparison import image_comparison image_comparison(img1=""image1.jpg"", img2=""image2.jpg"",) Streamlit CropperA simple image cropper for Streamlit. Created by @turner-anderson.from streamlit_cropper import st_cropper st_cropper(img, realtime_update=realtime_update, box_color=box_color, aspect_ratio=aspect_ratio) Image CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates streamlit_image_coordinates(""https://placekitten.com/200/300"") Streamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl(""https://assets5.lottiefiles.com/packages/lf20_V9t630.json"") st_lottie(lottie_hello, key=""hello"") Next Layouts and containers ColumnsInsert containers laid out as side-by-side columns.col1, col2 = st.columns(2) col1.write(""this is column 1"") col2.write(""this is column 2"") ContainerInsert a multi-element container.c = st.container() st.write(""This will show last"") c.write(""This will show first"") c.write(""This will show second"") Modal dialogsInsert a modal dialog that can rerun independently from the rest of the script.@st.experimental_dialog(""Sign up"") def email_form(): name = st.text_input(""Name"") email = st.text_input(""Email"") EmptyInsert a single-element container.c = st.empty() st.write(""This will show last"") c.write(""This will be replaced"") c.write(""This will show first"") ExpanderInsert a multi-element container that can be expanded/collapsed.with st.expander(""Open to see more""): st.write(""This is more content"") PopoverInsert a multi-element popover container that can be opened/closed.with st.popover(""Settings""): st.checkbox(""Show completed"") SidebarDisplay items in a sidebar.st.sidebar.write(""This lives in the sidebar"") st.sidebar.button(""Click me!"") TabsInsert containers separated into tabs.tab1, tab2 = st.tabs([""Tab 1"", ""Tab2""]) tab1.write(""this is tab 1"") tab2.write(""this is tab 2"") Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration!Streamlit ElementsCreate a draggable and resizable dashboard in Streamlit. Created by @okls.from streamlit_elements import elements, mui, html with elements(""new_element""): mui.Typography(""Hello world"") PydanticAuto-generate Streamlit UI from Pydantic Models and Dataclasses. Created by @lukasmasuch.import streamlit_pydantic as sp sp.pydantic_form(key=""my_form"", model=ExampleModel) Streamlit PagesAn experimental version of Streamlit Multi-Page Apps. Created by @blackary.from st_pages import Page, show_pages, add_page_title show_pages([ Page(""streamlit_app.py"", ""Home"", ""🏠""), Page(""other_pages/page2.py"", ""Page 2"", "":books:""), ]) Chat elements Streamlit provides a few commands to help you build conversational apps. These chat elements are designed to be used in conjunction with each other, but you can also use them separately. st.chat_message lets you insert a chat message container into the app so you can display messages from the user or the app. Chat containers can contain other Streamlit elements, including charts, tables, text, and more. st.chat_input lets you display a chat input widget so the user can type in a message. Chat inputDisplay a chat input widget.prompt = st.chat_input(""Say something"") if prompt: st.write(f""The user has sent: {prompt}"") Chat messageInsert a chat message container.import numpy as np with st.chat_message(""user""): st.write(""Hello 👋"") st.line_chart(np.random.randn(30, 3)) Status containerDisplay output of long-running tasks in a container.with st.status('Running'): do_something_slow() st.write_streamWrite generators or streams to the app with a typewriter effect.st.write_stream(my_generator) st.write_stream(my_llm_stream) Status elements Progress barDisplay a progress bar.for i in range(101): st.progress(i) do_something_slow() SpinnerTemporarily displays a message while executing a block of code.with st.spinner(""Please wait...""): do_something_slow() Status containerDisplay output of long-running tasks in a container.with st.status('Running'): do_something_slow() ToastBriefly displays a toast message in the bottom-right corner.st.toast('Butter!', icon='🧈') BalloonsDisplay celebratory balloons!do_something() # Celebrate when all done! st.balloons() SnowflakesDisplay celebratory snowflakes!do_something() # Celebrate when all done! st.snow() Success boxDisplay a success message.st.success(""Match found!"") Info boxDisplay an informational message.st.info(""Dataset is updated every day at midnight."") Warning boxDisplay warning message.st.warning(""Unable to fetch image. Skipping..."") Error boxDisplay error message.st.error(""We encountered an error"") Exception outputDisplay an exception.e = RuntimeError(""This is an exception of type RuntimeError"") st.exception(e) Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration!StqdmThe simplest way to handle a progress bar in streamlit app. Created by @Wirg.from stqdm import stqdm for _ in stqdm(range(50)): sleep(0.5) Custom notification boxA custom notification box with the ability to close it out. Created by @Socvest.from streamlit_custom_notification_box import custom_notification_box styles = {'material-icons':{'color': 'red'}, 'text-icon-link-close-container': {'box-shadow': '#3896de 0px 4px'}, 'notification-text': {'':''}, 'close-button':{'':''}, 'link':{'':''}} custom_notification_box(icon='info', textDisplay='We are almost done with your registration...', externalLink='more info', url='#', styles=styles, key=""foo"") Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.let_it_rain import rain rain(emoji=""🎈"", font_size=54, falling_speed=5, animation_length=""infinite"",) App logic and configuration Navigation and pages Switch pageProgrammatically navigates to a specified page.st.switch_page(""pages/my_page.py"") Page linkDisplay a link to another page in a multipage app.st.page_link(""app.py"", label=""Home"", icon=""🏠"") st.page_link(""pages/profile.py"", label=""My profile"") Execution flow Modal dialogsInsert a modal dialog that can rerun independently from the rest of the script.@st.experimental_dialog(""Sign up"") def email_form(): name = st.text_input(""Name"") email = st.text_input(""Email"") FormsCreate a form that batches elements together with a “Submit"" button.with st.form(key='my_form'): name = st.text_input(""Name"") email = st.text_input(""Email"") st.form_submit_button(""Sign up"") Partial rerunsDefine a fragment to rerun independently from the rest of the script.@st.experimental_fragment(run_every=""10s"") def fragment(): df = get_data() st.line_chart(df) Rerun scriptRerun the script immediately.st.rerun() Stop executionStops execution immediately.st.stop() Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration!AutorefreshForce a refresh without tying up a script. Created by @kmcgrady.from streamlit_autorefresh import st_autorefresh st_autorefresh(interval=2000, limit=100, key=""fizzbuzzcounter"") PydanticAuto-generate Streamlit UI from Pydantic Models and Dataclasses. Created by @lukasmasuch.import streamlit_pydantic as sp sp.pydantic_form(key=""my_form"", model=ExampleModel) Streamlit PagesAn experimental version of Streamlit Multi-Page Apps. Created by @blackary.from st_pages import Page, show_pages, add_page_title show_pages([ Page(""streamlit_app.py"", ""Home"", ""🏠""), Page(""other_pages/page2.py"", ""Page 2"", "":books:""), ]) Caching and state Cache dataFunction decorator to cache functions that return data (e.g. dataframe transforms, database queries, ML inference).@st.cache_data def long_function(param1, param2): # Perform expensive computation here or # fetch data from the web here return data Cache resourceFunction decorator to cache functions that return global resources (e.g. database connections, ML models).@st.cache_resource def init_model(): # Return a global resource here return pipeline( ""sentiment-analysis"", model=""distilbert-base-uncased-finetuned-sst-2-english"" ) Session stateSession state is a way to share variables between reruns, for each user session.st.session_state['key'] = value Query parametersGet, set, or clear the query parameters that are shown in the browser's URL bar.st.query_params[key] = value st.query_params.clear() Connections and databases Setup your connection Create a connectionConnect to a data source or APIconn = st.connection('pets_db', type='sql') pet_owners = conn.query('select * from pet_owners') st.dataframe(pet_owners) Built-in connections SnowflakeConnectionA connection to Snowflake.conn = st.connection('snowflake') SQLConnectionA connection to a SQL database using SQLAlchemy.conn = st.connection('sql') Build your own connections Connection base classBuild your own connection with BaseConnection.class MyConnection(BaseConnection[myconn.MyConnection]): def _connect(self, **kwargs) -> MyConnection: return myconn.connect(**self._secrets, **kwargs) def query(self, query): return self._instance.query(query) Secrets management Secrets singletonAccess secrets from a local TOML file.key = st.secrets[""OpenAI_key""] Secrets fileSave your secrets in a per-project or per-profile TOML file.OpenAI_key = """" Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration!AuthenticatorA secure authentication module to validate user credentials. Created by @mkhorasani.import streamlit_authenticator as stauth authenticator = stauth.Authenticate( config['credentials'], config['cookie']['name'], config['cookie']['key'], config['cookie']['expiry_days'], config['preauthorized']) WS localStorageA simple synchronous way of accessing localStorage from your app. Created by @gagangoku.from streamlit_ws_localstorage import injectWebsocketCode ret = conn.setLocalStorageVal(key='k1', val='v1') st.write('ret: ' + ret) Streamlit Auth0The fastest way to provide comprehensive login inside Streamlit. Created by @conradbez.from auth0_component import login_button user_info = login_button(clientId, domain = domain) st.write(user_info) Custom Components Declare a componentCreate and register a custom component.st.components.v1.declare_component( ""custom_slider"", ""/frontend"", ) HTMLDisplay an HTML string in an iframe.st.components.v1.html( ""

Foo bar.

"" ) iframeLoad a remote URL in an iframe.st.components.v1.iframe( ""docs.streamlit.io"" ) Utilities and user info User infost.experimental_user returns information about the logged-in user of private apps on Streamlit Community Cloud.if st.experimental_user.email == ""foo@corp.com"": st.write(""Welcome back, "", st.experimental_user.email) else: st.write(""You are not authorized to view this page."") Get helpDisplay object’s doc string, nicely formatted.st.help(st.write) st.help(pd.DataFrame) Render HTMLRenders HTML strings to your app.css = """""" """""" st.html(css) Configuration Configuration fileConfigures the default settings for your app.your-project/ ├── .streamlit/ │ └── config.toml └── your_app.py Set page title, favicon, and moreConfigures the default settings of the page.st.set_page_config( page_title=""My app"", page_icon="":shark:"", ) Developer tools App testing st.testing.v1.AppTestst.testing.v1.AppTest simulates a running Streamlit app for testing.from streamlit.testing.v1 import AppTest at = AppTest.from_file(""streamlit_app.py"") at.secrets[""WORD""] = ""Foobar"" at.run() assert not at.exception at.text_input(""word"").input(""Bazbat"").run() assert at.warning[0].value == ""Try again."" AppTest.from_filest.testing.v1.AppTest.from_file initializes a simulated app from a file.from streamlit.testing.v1 import AppTest at = AppTest.from_file(""streamlit_app.py"") at.run() AppTest.from_stringst.testing.v1.AppTest.from_string initializes a simulated app from a string.from streamlit.testing.v1 import AppTest at = AppTest.from_string(app_script_as_string) at.run() AppTest.from_functionst.testing.v1.AppTest.from_function initializes a simulated app from a function.from streamlit.testing.v1 import AppTest at = AppTest.from_function(app_script_as_callable) at.run() BlockA representation of container elements, including: st.chat_message st.columns st.sidebar st.tabs The main body of the app. # at.sidebar returns a Block at.sidebar.button[0].click().run() assert not at.exception ElementThe base class for representation of all elements, including: st.title st.header st.markdown st.dataframe # at.title returns a sequence of Title # Title inherits from Element assert at.title[0].value == ""My awesome app"" ButtonA representation of st.button and st.form_submit_button.at.button[0].click().run() ChatInputA representation of st.chat_input.at.chat_input[0].set_value(""What is Streamlit?"").run() CheckboxA representation of st.checkbox.at.checkbox[0].check().run() ColorPickerA representation of st.color_picker.at.color_picker[0].pick(""#FF4B4B"").run() DateInputA representation of st.date_input.release_date = datetime.date(2023, 10, 26) at.date_input[0].set_value(release_date).run() MultiselectA representation of st.multiselect.at.multiselect[0].select(""New York"").run() NumberInputA representation of st.number_input.at.number_input[0].increment().run() RadioA representation of st.radio.at.radio[0].set_value(""New York"").run() SelectSliderA representation of st.select_slider.at.select_slider[0].set_range(""A"",""C"").run() SelectboxA representation of st.selectbox.at.selectbox[0].select(""New York"").run() SliderA representation of st.slider.at.slider[0].set_range(2,5).run() TextAreaA representation of st.text_area.at.text_area[0].input(""Streamlit is awesome!"").run() TextInputA representation of st.text_input.at.text_input[0].input(""Streamlit"").run() TimeInputA representation of st.time_input.at.time_input[0].increment().run() ToggleA representation of st.toggle.at.toggle[0].set_value(""True"").run() Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration!Pandas ProfilingPandas profiling component for Streamlit. Created by @okld.df = pd.read_csv(""https://storage.googleapis.com/tf-datasets/titanic/train.csv"") pr = df.profile_report() st_profile_report(pr) Streamlit AceAce editor component for Streamlit. Created by @okld.from streamlit_ace import st_ace content = st_ace() content Streamlit AnalyticsTrack & visualize user interactions with your streamlit app. Created by @jrieke.import streamlit_analytics with streamlit_analytics.track(): st.text_input(""Write something"") Previous: ConceptsNext: Write and magicforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy" https://docs.streamlit.io/develop/concepts/connections/secrets-management#develop-locally-and-set-up-secrets,"DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsremoveCOREArchitecture & executionaddMultipage appsaddApp designaddADDITIONALConnections and secretsremoveConnecting to dataSecrets managementSecurity remindersCustom componentsaddConfiguration and themingaddApp testingaddAPI referenceaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Develop/Concepts/Connections and secrets/Secrets managementSecrets management Storing unencrypted secrets in a git repository is a bad practice. For applications that require access to sensitive credentials, the recommended solution is to store those credentials outside the repository - such as using a credentials file not committed to the repository or passing them as environment variables. Streamlit provides native file-based secrets management to easily store and securely access your secrets in your Streamlit app. push_pinNoteExisting secrets management tools, such as dotenv files, AWS credentials files, Google Cloud Secret Manager, or Hashicorp Vault, will work fine in Streamlit. We just add native secrets management for times when it's useful. How to use secrets management Develop locally and set up secrets Streamlit provides two ways to set up secrets locally using TOML format: In a global secrets file at ~/.streamlit/secrets.toml for macOS/Linux or %userprofile%/.streamlit/secrets.toml for Windows: # Everything in this section will be available as an environment variable db_username = ""Jane"" db_password = ""mypassword"" # You can also add other sections if you like. # The contents of sections as shown below will not become environment variables, # but they'll be easily accessible from within Streamlit anyway as we show # later in this doc. [my_other_secrets] things_i_like = [""Streamlit"", ""Python""] If you use the global secrets file, you don't have to duplicate secrets across several project-level files if multiple Streamlit apps share the same secrets. In a per-project secrets file at $CWD/.streamlit/secrets.toml, where $CWD is the folder you're running Streamlit from. If both a global secrets file and a per-project secrets file exist, secrets in the per-project file overwrite those defined in the global file. priority_highImportantAdd this file to your .gitignore so you don't commit your secrets! Use secrets in your app Access your secrets by querying the st.secrets dict, or as environment variables. For example, if you enter the secrets from the section above, the code below shows you how to access them within your Streamlit app. import streamlit as st # Everything is accessible via the st.secrets dict: st.write(""DB username:"", st.secrets[""db_username""]) st.write(""DB password:"", st.secrets[""db_password""]) # And the root-level secrets are also accessible as environment variables: import os st.write( ""Has environment variables been set:"", os.environ[""db_username""] == st.secrets[""db_username""], ) starTipYou can access st.secrets via attribute notation (e.g. st.secrets.key), in addition to key notation (e.g. st.secrets[""key""]) — like st.session_state. You can even compactly use TOML sections to pass multiple secrets as a single attribute. Consider the following secrets: [db_credentials] username = ""my_username"" password = ""my_password"" Rather than passing each secret as attributes in a function, you can more compactly pass the section to achieve the same result. See the notional code below, which uses the secrets above: # Verbose version my_db.connect(username=st.secrets.db_credentials.username, password=st.secrets.db_credentials.password) # Far more compact version! my_db.connect(**st.secrets.db_credentials) Error handling Here are some common errors you might encounter when using secrets management. If a .streamlit/secrets.toml is created while the app is running, the server needs to be restarted for changes to be reflected in the app. If you try accessing a secret, but no secrets.toml file exists, Streamlit will raise a FileNotFoundError exception: If you try accessing a secret that doesn't exist, Streamlit will raise a KeyError exception: import streamlit as st st.write(st.secrets[""nonexistent_key""]) Use secrets on Streamlit Community Cloud When you deploy your app to Streamlit Community Cloud, you can use the same secrets management workflow as you would locally. However, you'll need to also set up your secrets in the Community Cloud Secrets Management console. Learn how to do so via the Cloud-specific Secrets management documentation.Previous: Connecting to dataNext: Security remindersforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy" https://docs.streamlit.io/develop/concepts/app-testing/cheat-sheet#status-elements,"DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsremoveCOREArchitecture & executionaddMultipage appsaddApp designaddADDITIONALConnections and secretsaddCustom componentsaddConfiguration and themingaddApp testingremoveGet startedBeyond the basicsAutomate your testsExampleCheat sheetAPI referenceaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Develop/Concepts/App testing/Cheat sheetApp testing cheat sheet Text elements from streamlit.testing.v1 import AppTest at = AppTest.from_file(""cheatsheet_app.py"") # Headers assert ""My app"" in at.title[0].value assert ""New topic"" in at.header[0].value assert ""Interesting sub-topic"" in at.subheader[0].value assert len(at.divider) == 2 # Body / code assert ""Hello, world!"" in at.markdown[0].value assert ""import streamlit as st"" in at.code[0].value assert ""A cool diagram"" in at.caption[0].value assert ""Hello again, world!"" in at.text[0].value assert ""\int a x^2 \,dx"" in at.latex[0].value Input widgets from streamlit.testing.v1 import AppTest at = AppTest.from_file(""cheatsheet_app.py"") # button assert at.button[0].value == False at.button[0].click().run() assert at.button[0].value == True # checkbox assert at.checkbox[0].value == False at.checkbox[0].check().run() # uncheck() is also supported assert at.checkbox[0].value == True # color_picker assert at.color_picker[0].value == ""#FFFFFF"" at.color_picker[0].pick(""#000000"").run() # date_input assert at.date_input[0].value == datetime.date(2019, 7, 6) at.date_input[0].set_value(datetime.date(2022, 12, 21)).run() # form_submit_button - shows up just like a button assert at.button[0].value == False at.button[0].click().run() assert at.button[0].value == True # multiselect assert at.multiselect[0].value == [""foo"", ""bar""] at.multiselect[0].select(""baz"").unselect(""foo"").run() # number_input assert at.number_input[0].value == 5 at.number_input[0].increment().run() # radio assert at.radio[0].value == ""Bar"" assert at.radio[0].index == 3 at.radio[0].set_value(""Foo"").run() # selectbox assert at.selectbox[0].value == ""Bar"" assert at.selectbox[0].index == 3 at.selectbox[0].set_value(""Foo"").run() # select_slider assert at.select_slider[0].value == ""Feb"" at.select_slider[0].set_value(""Mar"").run() at.select_slider[0].set_range(""Apr"", ""Jun"").run() # slider assert at.slider[0].value == 2 at.slider[0].set_value(3).run() at.slider[0].set_range(4, 6).run() # text_area assert at.text_area[0].value == ""Hello, world!"" at.text_area[0].set_value(""Hello, yourself!"").run() # text_input assert at.text_input[0].value == ""Hello, world!"") at.text_input[0].set_value(""Hello, yourself!"").run() # time_input assert at.time_input[0].value == datetime.time(8, 45) at.time_input[0].set_value(datetime.time(12, 30)) # toggle assert at.toggle[0].value == False assert at.toggle[0].label == ""Debug mode"" at.toggle[0].set_value(True).run() assert at.toggle[0].value == True Data elements from streamlit.testing.v1 import AppTest at = AppTest.from_file(""cheatsheet_app.py"") # dataframe expected_df = pd.DataFrame([1, 2, 3]) assert at.dataframe[0].value.equals(expected_df) # metric assert at.metric[0].value == ""9500"" assert at.metric[0].delta == ""1000"" # json assert at.json[0].value == '[""hi"", {""foo"": ""bar""}]' # table table_df = pd.DataFrame([1, 2, 3]) assert at.table[0].value.equals(table_df) Layouts and containers from streamlit.testing.v1 import AppTest at = AppTest.from_file(""cheatsheet_app.py"") # sidebar at.sidebar.text_input[0].set_value(""Jane Doe"") # columns at.columns[1].markdown[0].value == ""Hello, world!"" # tabs at.tabs[2].markdown[0].value == ""Hello, yourself!"" Chat elements from streamlit.testing.v1 import AppTest at = AppTest.from_file(""cheatsheet_app.py"") # chat_input at.chat_input[0].set_value(""Do you know any jokes?"").run() # Note: chat_input value clears after every re-run (like in a real app) # chat_message assert at.chat_message[0].markdown[0].value == ""Do you know any jokes?"" assert at.chat_message[0].avatar == ""user"" Status elements from streamlit.testing.v1 import AppTest at = AppTest.from_file(""cheatsheet_app.py"") # exception assert len(at.exception) == 1 assert ""TypeError"" in at.exception[0].value # Other in-line alerts: success, info, warning, error assert at.success[0].value == ""Great job!"" assert at.info[0].value == ""Please enter an API key to continue"" assert at.warning[0].value == ""Sorry, the passwords didn't match"" assert at.error[0].value == ""Something went wrong :("" # toast assert at.toast[0].value == ""That was lit!"" and at.toast[0].icon == ""🔥"" Limitations As of Streamlit 1.28, the following Streamlit features are not natively supported by AppTest. However, workarounds are possible for many of them by inspecting the underlying proto directly using AppTest.get(). We plan to regularly add support for missing elements until all features are supported. Chart elements (st.bar_chart, st.line_chart, etc) Media elements (st.image, st.video, st.audio) st.file_uploader st.data_editor st.expander st.status st.camera_input st.download_button st.link_button Previous: ExampleNext: API referenceforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy" https://docs.streamlit.io/library/api-reference/data/st.column_config#column-configuration,"DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceremovePAGE ELEMENTSWrite and magicaddText elementsaddData elementsremovest.dataframest.data_editorst.column_configremoveColumnText columnNumber columnCheckbox columnSelectbox columnDatetime columnDate columnTime columnList columnLink columnImage columnArea chart columnLine chart columnBar chart columnProgress columnst.tablest.metricst.jsonChart elementsaddInput widgetsaddMedia elementsaddLayouts and containersaddChat elementsaddStatus elementsaddThird-party componentsopen_in_newAPPLICATION LOGICNavigation and pagesaddExecution flowaddCaching and stateaddConnections and secretsaddCustom componentsaddUtilitiesaddConfigurationaddTOOLSApp testingaddCommand lineaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Develop/API reference/Data elements/st.column_configColumn configuration When working with data in Streamlit, the st.column_config class is a powerful tool for configuring data display and interaction. Specifically designed for the column_config parameter in st.dataframe and st.data_editor, it provides a suite of methods to tailor your columns to various data types - from simple text and numbers to lists, URLs, images, and more. Whether it's translating temporal data into user-friendly formats or utilizing charts and progress bars for clearer data visualization, column configuration not only provides the user with an enriched data viewing experience but also ensures that you're equipped with the tools to present and interact with your data, just the way you want it. ColumnConfigure a generic column.Column(""Streamlit Widgets"", width=""medium"", help=""Streamlit **widget** commands 🎈"") Text columnConfigure a text column.TextColumn(""Widgets"", max_chars=50, validate=""^st\.[a-z_]+$"") Number columnConfigure a number column.NumberColumn(""Price (in USD)"", min_value=0, format=""$%d"") Checkbox columnConfigure a checkbox column.CheckboxColumn(""Your favorite?"", help=""Select your **favorite** widgets"") Selectbox columnConfigure a selectbox column.SelectboxColumn(""App Category"", options=[""🤖 LLM"", ""📈 Data Viz""]) Datetime columnConfigure a datetime column.DatetimeColumn(""Appointment"", min_value=datetime(2023, 6, 1), format=""D MMM YYYY, h:mm a"") Date columnConfigure a date column.DateColumn(""Birthday"", max_value=date(2005, 1, 1), format=""DD.MM.YYYY"") Time columnConfigure a time column.TimeColumn(""Appointment"", min_value=time(8, 0, 0), format=""hh:mm a"") List columnConfigure a list column.ListColumn(""Sales (last 6 months)"", width=""medium"") Link columnConfigure a link column.LinkColumn(""Trending apps"", max_chars=100, validate=""^https://.*$"") Image columnConfigure an image column.ImageColumn(""Preview Image"", help=""The preview screenshots"") Area chart columnConfigure an area chart column.AreaChartColumn(""Sales (last 6 months)"" y_min=0, y_max=100) Line chart columnConfigure a line chart column.LineChartColumn(""Sales (last 6 months)"" y_min=0, y_max=100) Bar chart columnConfigure a bar chart column.BarChartColumn(""Marketing spend"" y_min=0, y_max=100) Progress columnConfigure a progress column.ProgressColumn(""Sales volume"", min_value=0, max_value=1000, format=""$%f"") Previous: st.data_editorNext: ColumnforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy" https://docs.streamlit.io/knowledge-base/using-streamlit/how-download-file-streamlit#how-to-download-a-file-in-streamlit,"DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Knowledge base/FAQ/How to download a file in Streamlit?How to download a file in Streamlit? Use the st.download_button widget that is natively built into Streamlit. Check out a sample app demonstrating how you can use st.download_button to download common file formats. Example usage import streamlit as st # Text files text_contents = ''' Foo, Bar 123, 456 789, 000 ''' # Different ways to use the API st.download_button('Download CSV', text_contents, 'text/csv') st.download_button('Download CSV', text_contents) # Defaults to 'text/plain' with open('myfile.csv') as f: st.download_button('Download CSV', f) # Defaults to 'text/plain' # --- # Binary files binary_contents = b'whatever' # Different ways to use the API st.download_button('Download file', binary_contents) # Defaults to 'application/octet-stream' with open('myfile.zip', 'rb') as f: st.download_button('Download Zip', f, file_name='archive.zip') # Defaults to 'application/octet-stream' # You can also grab the return value of the button, # just like with any other button. if st.download_button(...): st.write('Thanks for downloading!') Additional resources: https://blog.streamlit.io/0-88-0-release-notes/ https://streamlit-release-demos-0-88streamlit-app-0-88-v8ram3.streamlit.app/ https://docs.streamlit.io/develop/api-reference/widgets/st.download_button Previous: Enabling camera access in your browserNext: How to download a Pandas DataFrame as a CSV?forumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy" https://docs.streamlit.io/develop/api-reference/app-testing/testing-element-classes#buttonrun,"DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceremovePAGE ELEMENTSWrite and magicaddText elementsaddData elementsaddChart elementsaddInput widgetsaddMedia elementsaddLayouts and containersaddChat elementsaddStatus elementsaddThird-party componentsopen_in_newAPPLICATION LOGICNavigation and pagesaddExecution flowaddCaching and stateaddConnections and secretsaddCustom componentsaddUtilitiesaddConfigurationaddTOOLSApp testingremovest.testing.v1.AppTestTesting element classesCommand lineaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Develop/API reference/App testing/Testing element classesTesting element classes st.testing.v1.element_tree.Block The Block class has the same methods and attributes as AppTest. A Block instance represents a container of elements just as AppTest represents the entire app. For example, Block.button will produce a WidgetList of Button in the same manner as AppTest.button. ChatMessage, Column, and Tab all inherit from Block. For all container classes, parameters of the original element can be obtained as properties. For example, ChatMessage.avatar and Tab.label. st.testing.v1.element_tree.ElementStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeElement base class for testing. This class's methods and attributes are universal for all elements implemented in testing. For example, Caption, Code, Text, and Title inherit from Element. All widget classes also inherit from Element, but have additional methods specific to each widget type. See the AppTest class for the full list of supported elements. For all element classes, parameters of the original element can be obtained as properties. For example, Button.label, Caption.help, and Toast.icon. Class description[source] st.testing.v1.element_tree.Element(proto, root) Methods run(*, timeout=None) Run the AppTest script which contains the element. Attributes value The value or contents of the element. st.testing.v1.element_tree.ButtonStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.button and st.form_submit_button. Class description[source] st.testing.v1.element_tree.Button(proto, root) Methods click() Set the value of the button to True. run(*, timeout=None) Run the AppTest script which contains the element. set_value(v) Set the value of the button. Attributes value The value of the button. (bool) st.testing.v1.element_tree.ChatInputStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.chat_input. Class description[source] st.testing.v1.element_tree.ChatInput(proto, root) Methods run(*, timeout=None) Run the AppTest script which contains the element. set_value(v) Set the value of the widget. Attributes value The value of the widget. (str) st.testing.v1.element_tree.CheckboxStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.checkbox. Class description[source] st.testing.v1.element_tree.Checkbox(proto, root) Methods check() Set the value of the widget to True. run(*, timeout=None) Run the AppTest script which contains the element. set_value(v) Set the value of the widget. uncheck() Set the value of the widget to False. Attributes value The value of the widget. (bool) st.testing.v1.element_tree.ColorPickerStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.color_picker. Class description[source] st.testing.v1.element_tree.ColorPicker(proto, root) Methods pick(v) Set the value of the widget as a hex string. May omit the ""#"" prefix. run(*, timeout=None) Run the AppTest script which contains the element. set_value(v) Set the value of the widget as a hex string. Attributes value The currently selected value as a hex string. (str) st.testing.v1.element_tree.DateInputStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.date_input. Class description[source] st.testing.v1.element_tree.DateInput(proto, root) Methods run(*, timeout=None) Run the AppTest script which contains the element. set_value(v) Set the value of the widget. Attributes value The value of the widget. (date or Tuple of date) st.testing.v1.element_tree.MultiselectStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.multiselect. Class description[source] st.testing.v1.element_tree.Multiselect(proto, root) Methods run(*, timeout=None) Run the AppTest script which contains the element. select(v) Add a selection to the widget. Do nothing if the value is already selected. If testing a multiselect widget with repeated options, use set_value instead. set_value(v) Set the value of the multiselect widget. (list) unselect(v) Remove a selection from the widget. Do nothing if the value is not already selected. If a value is selected multiple times, the first instance is removed. Attributes format_func The widget's formatting function for displaying options. (callable) indices The indices of the currently selected values from the options. (list) value The currently selected values from the options. (list) st.testing.v1.element_tree.NumberInputStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.number_input. Class description[source] st.testing.v1.element_tree.NumberInput(proto, root) Methods decrement() Decrement the st.number_input widget as if the user clicked ""-"". increment() Increment the st.number_input widget as if the user clicked ""+"". run(*, timeout=None) Run the AppTest script which contains the element. set_value(v) Set the value of the st.number_input widget. Attributes value Get the current value of the st.number_input widget. st.testing.v1.element_tree.RadioStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.radio. Class description[source] st.testing.v1.element_tree.Radio(proto, root) Methods run(*, timeout=None) Run the AppTest script which contains the element. set_value(v) Set the selection by value. Attributes format_func The widget's formatting function for displaying options. (callable) index The index of the current selection. (int) value The currently selected value from the options. (Any) st.testing.v1.element_tree.SelectSliderStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.select_slider. Class description[source] st.testing.v1.element_tree.SelectSlider(proto, root) Methods run(*, timeout=None) Run the AppTest script which contains the element. set_range(lower, upper) Set the ranged selection by values. set_value(v) Set the (single) selection by value. Attributes format_func The widget's formatting function for displaying options. (callable) value The currently selected value or range. (Any or Sequence of Any) st.testing.v1.element_tree.SelectboxStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.selectbox. Class description[source] st.testing.v1.element_tree.Selectbox(proto, root) Methods run(*, timeout=None) Run the AppTest script which contains the element. select(v) Set the selection by value. select_index(index) Set the selection by index. set_value(v) Set the selection by value. Attributes format_func The widget's formatting function for displaying options. (callable) index The index of the current selection. (int) value The currently selected value from the options. (Any) st.testing.v1.element_tree.SliderStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.slider. Class description[source] st.testing.v1.element_tree.Slider(proto, root) Methods run(*, timeout=None) Run the AppTest script which contains the element. set_range(lower, upper) Set the ranged value of the slider. set_value(v) Set the (single) value of the slider. Attributes value The currently selected value or range. (Any or Sequence of Any) st.testing.v1.element_tree.TextAreaStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.text_area. Class description[source] st.testing.v1.element_tree.TextArea(proto, root) Methods input(v) Set the value of the widget only if the value does not exceed the maximum allowed characters. run(*, timeout=None) Run the AppTest script which contains the element. set_value(v) Set the value of the widget. Attributes value The current value of the widget. (str) st.testing.v1.element_tree.TextInputStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.text_input. Class description[source] st.testing.v1.element_tree.TextInput(proto, root) Methods input(v) Set the value of the widget only if the value does not exceed the maximum allowed characters. run(*, timeout=None) Run the AppTest script which contains the element. set_value(v) Set the value of the widget. Attributes value The current value of the widget. (str) st.testing.v1.element_tree.TimeInputStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.time_input. Class description[source] st.testing.v1.element_tree.TimeInput(proto, root) Methods decrement() Select the previous available time. increment() Select the next available time. run(*, timeout=None) Run the AppTest script which contains the element. set_value(v) Set the value of the widget. Attributes value The current value of the widget. (time) st.testing.v1.element_tree.ToggleStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.toggle. Class description[source] st.testing.v1.element_tree.Toggle(proto, root) Methods run(*, timeout=None) Run the AppTest script which contains the element. set_value(v) Set the value of the widget. Attributes value The current value of the widget. (bool) Previous: st.testing.v1.AppTestNext: Command lineforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy" https://docs.streamlit.io/develop/tutorials/databases/mongodb#create-a-mongodb-database,"DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceaddTutorialsremoveExecution flowaddConnect to data sourcesremoveAWS S3BigQueryDeta BaseFirestoreopen_in_newGoogle Cloud StorageMicrosoft SQL ServerMongoDBMySQLNeonPostgreSQLPrivate Google SheetPublic Google SheetSnowflakeSupabaseTableauTiDBTigerGraphMultipage appsaddWork with LLMsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Develop/Tutorials/Connect to data sources/MongoDBConnect Streamlit to MongoDB Introduction This guide explains how to securely access a remote MongoDB database from Streamlit Community Cloud. It uses the PyMongo library and Streamlit's Secrets management. Create a MongoDB Database push_pinNoteIf you already have a database that you want to use, feel free to skip to the next step. First, follow the official tutorials to install MongoDB, set up authentication (note down the username and password!), and connect to the MongoDB instance. Once you are connected, open the mongo shell and enter the following two commands to create a collection with some example values: use mydb db.mycollection.insertMany([{""name"" : ""Mary"", ""pet"": ""dog""}, {""name"" : ""John"", ""pet"": ""cat""}, {""name"" : ""Robert"", ""pet"": ""bird""}]) Add username and password to your local app secrets Your local Streamlit app will read secrets from a file .streamlit/secrets.toml in your app's root directory. Create this file if it doesn't exist yet and add the database information as shown below: # .streamlit/secrets.toml [mongo] host = ""localhost"" port = 27017 username = ""xxx"" password = ""xxx"" priority_highImportantWhen copying your app secrets to Streamlit Community Cloud, be sure to replace the values of host, port, username, and password with those of your remote MongoDB database!Add this file to .gitignore and don't commit it to your GitHub repo! Copy your app secrets to the cloud As the secrets.toml file above is not committed to GitHub, you need to pass its content to your deployed app (on Streamlit Community Cloud) separately. Go to the app dashboard and in the app's dropdown menu, click on Edit Secrets. Copy the content of secrets.toml into the text area. More information is available at Secrets management. Add PyMongo to your requirements file Add the PyMongo package to your requirements.txt file, preferably pinning its version (replace x.x.x with the version you want installed): # requirements.txt pymongo==x.x.x Write your Streamlit app Copy the code below to your Streamlit app and run it. Make sure to adapt the name of your database and collection. # streamlit_app.py import streamlit as st import pymongo # Initialize connection. # Uses st.cache_resource to only run once. @st.cache_resource def init_connection(): return pymongo.MongoClient(**st.secrets[""mongo""]) client = init_connection() # Pull data from the collection. # Uses st.cache_data to only rerun when the query changes or after 10 min. @st.cache_data(ttl=600) def get_data(): db = client.mydb items = db.mycollection.find() items = list(items) # make hashable for st.cache_data return items items = get_data() # Print results. for item in items: st.write(f""{item['name']} has a :{item['pet']}:"") See st.cache_data above? Without it, Streamlit would run the query every time the app reruns (e.g. on a widget interaction). With st.cache_data, it only runs when the query changes or after 10 minutes (that's what ttl is for). Watch out: If your database updates more frequently, you should adapt ttl or remove caching so viewers always see the latest data. Learn more in Caching. If everything worked out (and you used the example data we created above), your app should look like this: Previous: Microsoft SQL ServerNext: MySQLforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy" https://docs.streamlit.io/develop/tutorials/execution-flow/create-a-multiple-container-fragment#summary,"DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceaddTutorialsremoveExecution flowremoveFRAGMENTSRerun your app from a fragmentCreate a multiple-container fragmentStart and stop a streaming fragmentConnect to data sourcesaddMultipage appsaddWork with LLMsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Develop/Tutorials/Execution flow/Create a multiple container fragmentCreate a fragment across multiple containers Streamlit lets you turn functions into fragments, which can rerun independently from the full script. If your fragment doesn't write to outside containers, Streamlit will clear and redraw all the fragment elements with each fragment rerun. However, if your fragment does write elements to outside containers, Streamlit will not clear those elements during a fragment rerun. Instead, those elements accumulate with each fragment rerun until the next full-script rerun. If you want a fragment to update multiple containers in your app, use st.empty() containers to prevent accumulating elements. Applied concepts Use fragments to run two independent processes separately. Distribute a fragment across multiple containers. Prerequisites streamlit>=1.33.0 This tutorial uses fragments, which require Streamlit version 1.33.0 or later. This tutorial assumes you have a clean working directory called your-repository. You should have a basic understanding of fragments and st.empty(). Summary In this toy example, you'll build an app with six containers. Three containers will have orange cats. The other three containers will have black cats. You'll have three buttons in the sidebar: ""Herd the black cats,"" ""Herd the orange cats,"" and ""Herd all the cats."" Since herding cats is slow, you'll use fragments to help Streamlit run the associated processes efficiently. You'll create two fragments, one for the black cats and one for the orange cats. Since the buttons will be in the sidebar and the fragments will update containers in the main body, you'll use a trick with st.empty() to ensure you don't end up with too many cats in your app (if it's even possible to have too many cats). 😻 Here's a look at what you'll build: Complete codeexpand_moreimport streamlit as st import time st.title(""Cats!"") row1 = st.columns(3) row2 = st.columns(3) grid = [col.container(height=200) for col in row1 + row2] safe_grid = [card.empty() for card in grid] def black_cats(): time.sleep(1) st.title(""🐈‍⬛ 🐈‍⬛"") st.markdown(""🐾 🐾 🐾 🐾"") def orange_cats(): time.sleep(1) st.title(""🐈 🐈"") st.markdown(""🐾 🐾 🐾 🐾"") @st.experimental_fragment def herd_black_cats(card_a, card_b, card_c): st.button(""Herd the black cats"") container_a = card_a.container() container_b = card_b.container() container_c = card_c.container() with container_a: black_cats() with container_b: black_cats() with container_c: black_cats() @st.experimental_fragment def herd_orange_cats(card_a, card_b, card_c): st.button(""Herd the orange cats"") container_a = card_a.container() container_b = card_b.container() container_c = card_c.container() with container_a: orange_cats() with container_b: orange_cats() with container_c: orange_cats() with st.sidebar: herd_black_cats(grid[0].empty(), grid[2].empty(), grid[4].empty()) herd_orange_cats(grid[1].empty(), grid[3].empty(), grid[5].empty()) st.button(""Herd all the cats"") Built with Streamlit 🎈Fullscreen open_in_new Build the example Initialize your app In your_repository, create a file named app.py. In a terminal, change directories to your_repository and start your app. streamlit run app.py Your app will be blank since you still need to add code. In app.py, write the following: import streamlit as st import time You'll use time.sleep() to slow things down and see the fragments working. Save your app.py file and view your running app. Click ""Always rerun"" or hit your ""A"" key in your running app. Your running preview will automatically update as you save changes to app.py. Your preview will still be blank. Return to your code. Frame out your app's containers Add a title to your app and two rows of three containers. st.title(""Cats!"") row1 = st.columns(3) row2 = st.columns(3) grid = [col.container(height=200) for col in row1 + row2] Save your file to see your updated preview. Define a helper function to draw two black cats. def black_cats(): time.sleep(1) st.title(""🐈‍⬛ 🐈‍⬛"") st.markdown(""🐾 🐾 🐾 🐾"") This function represents ""herding two cats"" and uses time.sleep() to simulate a slower process. You will use this to draw two cats in one of your grid cards later on. Define another helper function to draw two orange cats. def orange_cats(): time.sleep(1) st.title(""🐈 🐈"") st.markdown(""🐾 🐾 🐾 🐾"") (Optional) Test out your functions by calling each one within a grid card. with grid[0]: black_cats() with grid[1]: orange_cats() Save your app.py file to see the preview. Delete these four lines when finished. Define your fragments Since each fragment will span across the sidebar and three additional containers, you'll use the sidebar to hold the main body of the fragment and pass the three containers as function arguments. Use an @st.experimental_fragment decorator and start your black-cat fragment definition. @st.experimental_fragment def herd_black_cats(card_a, card_b, card_c): Add a button for rerunning this fragment. st.button(""Herd the black cats"") Write to each container using your helper function. with card_a: black_cats() with card_b: black_cats() with card_c: black_cats() This code above will not behave as desired, but you'll explore and correct this in the following steps. Test out your code. Call your fragment function in the sidebar. with st.sidebar: herd_black_cats(grid[0], grid[2], grid[4]) Save your file and try using the button in the sidebar. More and more cats are appear in the cards with each fragment rerun! This is the expected behavior when fragments write to outside containers. To fix this, you will pass st.empty() containers to your fragment function. Delete the lines of code from the previous two steps. To prepare for using st.empty() containers, correct your cat-herding function as follows. After the button, define containers to place in the st.empty() cards you'll pass to your fragment. container_a = card_a.container() container_b = card_b.container() container_c = card_c.container() with container_a: black_cats() with container_b: black_cats() with container_c: black_cats() In this new version, card_a, card_b, and card_c will be st.empty() containers. You create container_a, container_b, and container_c to allow Streamlit to draw multiple elements on each grid card. Similarly define your orange-cat fragment function. @st.experimental_fragment def herd_orange_cats(card_a, card_b, card_c): st.button(""Herd the orange cats"") container_a = card_a.container() container_b = card_b.container() container_c = card_c.container() with container_a: orange_cats() with container_b: orange_cats() with container_c: orange_cats() Put the functions together together to create an app Call both of your fragments in the sidebar. with st.sidebar: herd_black_cats(grid[0].empty(), grid[2].empty(), grid[4].empty()) herd_orange_cats(grid[1].empty(), grid[3].empty(), grid[5].empty()) By creating st.empty() containers in each card and passing them to your fragments, you prevent elements from accumulating in the cards with each fragment rerun. If you create the st.empty() containers earlier in your app, full-script reruns will clear the orange-cat cards while (first) rendering the black-cat cards. Include a button outside of your fragments. When clicked, the button will trigger a full-script rerun since you're calling its widget function outside of any fragment. st.button(""Herd all the cats"") Save your file and try out the app! When you click ""Herd the black cats"" or ""Herd the orange cats,"" Streamlit will only redraw the three related cards. When you click ""Herd all the cats,"" Streamlit redraws all six cards. Previous: Rerun your app from a fragmentNext: Start and stop a streaming fragmentforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy" https://docs.streamlit.io/develop/api-reference/data#data-elements,"DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceremovePAGE ELEMENTSWrite and magicaddText elementsaddData elementsremovest.dataframest.data_editorst.column_configaddst.tablest.metricst.jsonChart elementsaddInput widgetsaddMedia elementsaddLayouts and containersaddChat elementsaddStatus elementsaddThird-party componentsopen_in_newAPPLICATION LOGICNavigation and pagesaddExecution flowaddCaching and stateaddConnections and secretsaddCustom componentsaddUtilitiesaddConfigurationaddTOOLSApp testingaddCommand lineaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Develop/API reference/Data elementsData elements When you're working with data, it is extremely valuable to visualize that data quickly, interactively, and from multiple different angles. That's what Streamlit is actually built and optimized for. You can display data via charts, and you can display it in raw form. These are the Streamlit commands you can use to display and interact with raw data. DataframesDisplay a dataframe as an interactive table.st.dataframe(my_data_frame) Data editorDisplay a data editor widget.edited = st.data_editor(df, num_rows=""dynamic"") Column configurationConfigure the display and editing behavior of dataframes and data editors.st.column_config.NumberColumn(""Price (in USD)"", min_value=0, format=""$%d"") Static tablesDisplay a static table.st.table(my_data_frame) MetricsDisplay a metric in big bold font, with an optional indicator of how the metric changed.st.metric(""My metric"", 42, 2) Dicts and JSONDisplay object or string as a pretty-printed JSON string.st.json(my_dict) Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration! PreviousImage CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates value = streamlit_image_coordinates(""https://placekitten.com/200/300"") st.write(value) Plotly EventsMake Plotly charts interactive!. Created by @null-jones.from streamlit_plotly_events import plotly_events fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.metric_cards import style_metric_cards col3.metric(label=""No Change"", value=5000, delta=0) style_metric_cards() Streamlit AggridImplementation of Ag-Grid component for Streamlit. Created by @PablocFonseca.df = pd.DataFrame({'col1': [1, 2, 3], 'col2': [4, 5, 6]}) grid_return = AgGrid(df, editable=True) new_df = grid_return['data'] Streamlit FoliumStreamlit Component for rendering Folium maps. Created by @randyzwitch.m = folium.Map(location=[39.949610, -75.150282], zoom_start=16) folium.Marker([39.949610, -75.150282], popup=""Liberty Bell"", tooltip=""Liberty Bell"").add_to(m) st_data = st_folium(m, width=725) Pandas ProfilingPandas profiling component for Streamlit. Created by @okld.df = pd.read_csv(""https://storage.googleapis.com/tf-datasets/titanic/train.csv"") pr = df.profile_report() st_profile_report(pr) Image CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates value = streamlit_image_coordinates(""https://placekitten.com/200/300"") st.write(value) Plotly EventsMake Plotly charts interactive!. Created by @null-jones.from streamlit_plotly_events import plotly_events fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.metric_cards import style_metric_cards col3.metric(label=""No Change"", value=5000, delta=0) style_metric_cards() Streamlit AggridImplementation of Ag-Grid component for Streamlit. Created by @PablocFonseca.df = pd.DataFrame({'col1': [1, 2, 3], 'col2': [4, 5, 6]}) grid_return = AgGrid(df, editable=True) new_df = grid_return['data'] Streamlit FoliumStreamlit Component for rendering Folium maps. Created by @randyzwitch.m = folium.Map(location=[39.949610, -75.150282], zoom_start=16) folium.Marker([39.949610, -75.150282], popup=""Liberty Bell"", tooltip=""Liberty Bell"").add_to(m) st_data = st_folium(m, width=725) Pandas ProfilingPandas profiling component for Streamlit. Created by @okld.df = pd.read_csv(""https://storage.googleapis.com/tf-datasets/titanic/train.csv"") pr = df.profile_report() st_profile_report(pr) Image CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates value = streamlit_image_coordinates(""https://placekitten.com/200/300"") st.write(value) Plotly EventsMake Plotly charts interactive!. Created by @null-jones.from streamlit_plotly_events import plotly_events fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.metric_cards import style_metric_cards col3.metric(label=""No Change"", value=5000, delta=0) style_metric_cards() NextPrevious: Text elementsNext: st.dataframeforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy" https://docs.streamlit.io/develop/tutorials/databases/tableau#connect-streamlit-to-tableau,"DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceaddTutorialsremoveExecution flowaddConnect to data sourcesremoveAWS S3BigQueryDeta BaseFirestoreopen_in_newGoogle Cloud StorageMicrosoft SQL ServerMongoDBMySQLNeonPostgreSQLPrivate Google SheetPublic Google SheetSnowflakeSupabaseTableauTiDBTigerGraphMultipage appsaddWork with LLMsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Develop/Tutorials/Connect to data sources/TableauConnect Streamlit to Tableau Introduction This guide explains how to securely access data on Tableau from Streamlit Community Cloud. It uses the tableauserverclient library and Streamlit's Secrets management. Create a Tableau site push_pinNoteIf you already have a database that you want to use, feel free to skip to the next step. For simplicity, we are using the cloud version of Tableau here but this guide works equally well for self-hosted deployments. First, sign up for Tableau Online or log in. Create a workbook or run one of the example workbooks under ""Dashboard Starters"". Create personal access tokens While the Tableau API allows authentication via username and password, you should use personal access tokens for a production app. Go to your Tableau Online homepage, create an access token and note down the token name and secret. push_pinNotePersonal access tokens will expire if not used after 15 consecutive days. Add token to your local app secrets Your local Streamlit app will read secrets from a file .streamlit/secrets.toml in your app's root directory. Create this file if it doesn't exist yet and add your token, the site name you created during setup, and the URL of your Tableau server like below: # .streamlit/secrets.toml [tableau] token_name = ""xxx"" token_secret = ""xxx"" server_url = ""https://abc01.online.tableau.com/"" site_id = ""streamlitexample"" # in your site's URL behind the server_url priority_highImportantAdd this file to .gitignore and don't commit it to your GitHub repo! Copy your app secrets to the cloud As the secrets.toml file above is not committed to GitHub, you need to pass its content to your deployed app (on Streamlit Community Cloud) separately. Go to the app dashboard and in the app's dropdown menu, click on Edit Secrets. Copy the content of secrets.toml into the text area. More information is available at Secrets management. Add tableauserverclient to your requirements file Add the tableauserverclient package to your requirements.txt file, preferably pinning its version (replace x.x.x with the version you want installed): # requirements.txt tableauserverclient==x.x.x Write your Streamlit app Copy the code below to your Streamlit app and run it. Note that this code just shows a few options of data you can get – explore the tableauserverclient library to find more! # streamlit_app.py import streamlit as st import tableauserverclient as TSC # Set up connection. tableau_auth = TSC.PersonalAccessTokenAuth( st.secrets[""tableau""][""token_name""], st.secrets[""tableau""][""personal_access_token""], st.secrets[""tableau""][""site_id""], ) server = TSC.Server(st.secrets[""tableau""][""server_url""], use_server_version=True) # Get various data. # Explore the tableauserverclient library for more options. # Uses st.cache_data to only rerun when the query changes or after 10 min. @st.cache_data(ttl=600) def run_query(): with server.auth.sign_in(tableau_auth): # Get all workbooks. workbooks, pagination_item = server.workbooks.get() workbooks_names = [w.name for w in workbooks] # Get views for first workbook. server.workbooks.populate_views(workbooks[0]) views_names = [v.name for v in workbooks[0].views] # Get image & CSV for first view of first workbook. view_item = workbooks[0].views[0] server.views.populate_image(view_item) server.views.populate_csv(view_item) view_name = view_item.name view_image = view_item.image # `view_item.csv` is a list of binary objects, convert to str. view_csv = b"""".join(view_item.csv).decode(""utf-8"") return workbooks_names, views_names, view_name, view_image, view_csv workbooks_names, views_names, view_name, view_image, view_csv = run_query() # Print results. st.subheader(""📓 Workbooks"") st.write(""Found the following workbooks:"", "", "".join(workbooks_names)) st.subheader(""👁️ Views"") st.write( f""Workbook *{workbooks_names[0]}* has the following views:"", "", "".join(views_names), ) st.subheader(""🖼️ Image"") st.write(f""Here's what view *{view_name}* looks like:"") st.image(view_image, width=300) st.subheader(""📊 Data"") st.write(f""And here's the data for view *{view_name}*:"") st.write(pd.read_csv(StringIO(view_csv))) See st.cache_data above? Without it, Streamlit would run the query every time the app reruns (e.g. on a widget interaction). With st.cache_data, it only runs when the query changes or after 10 minutes (that's what ttl is for). Watch out: If your database updates more frequently, you should adapt ttl or remove caching so viewers always see the latest data. Learn more in Caching. If everything worked out, your app should look like this (can differ based on your workbooks): Previous: SupabaseNext: TiDBforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy" https://docs.streamlit.io/develop/api-reference/widgets/st.checkbox#featured-videos,"DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceremovePAGE ELEMENTSWrite and magicaddText elementsaddData elementsaddChart elementsaddInput widgetsremoveBUTTONSst.buttonst.download_buttonst.form_submit_buttonlinkst.link_buttonst.page_linkSELECTIONSst.checkboxst.color_pickerst.multiselectst.radiost.selectboxst.select_sliderst.toggleNUMERICst.number_inputst.sliderDATE & TIMEst.date_inputst.time_inputTEXTst.chat_inputlinkst.text_areast.text_inputMEDIA & FILESst.camera_inputst.data_editorlinkst.file_uploaderMedia elementsaddLayouts and containersaddChat elementsaddStatus elementsaddThird-party componentsopen_in_newAPPLICATION LOGICNavigation and pagesaddExecution flowaddCaching and stateaddConnections and secretsaddCustom componentsaddUtilitiesaddConfigurationaddTOOLSApp testingaddCommand lineaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Develop/API reference/Input widgets/st.checkboxst.checkboxStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeDisplay a checkbox widget. Function signature[source] st.checkbox(label, value=False, key=None, help=None, on_change=None, args=None, kwargs=None, *, disabled=False, label_visibility=""visible"") Parameters label (str) A short label explaining to the user what this checkbox is for. The label can optionally contain Markdown and supports the following elements: Bold, Italics, Strikethroughs, Inline Code, Emojis, and Links. This also supports: Emoji shortcodes, such as :+1: and :sunglasses:. For a list of all supported codes, see https://share.streamlit.io/streamlit/emoji-shortcodes. LaTeX expressions, by wrapping them in ""$"" or ""$$"" (the ""$$"" must be on their own lines). Supported LaTeX functions are listed at https://katex.org/docs/supported.html. Colored text and background colors for text, using the syntax :color[text to be colored] and :color-background[text to be colored], respectively. color must be replaced with any of the following supported colors: blue, green, orange, red, violet, gray/grey, rainbow. For example, you can use :orange[your text here] or :blue-background[your text here]. Unsupported elements are unwrapped so only their children (text contents) render. Display unsupported elements as literal characters by backslash-escaping them. E.g. 1\. Not an ordered list. For accessibility reasons, you should never set an empty label (label="""") but hide it with label_visibility if needed. In the future, we may disallow empty labels by raising an exception. value (bool) Preselect the checkbox when it first renders. This will be cast to bool internally. key (str or int) An optional string or integer to use as the unique key for the widget. If this is omitted, a key will be generated for the widget based on its content. Multiple widgets of the same type may not share the same key. help (str) An optional tooltip that gets displayed next to the checkbox. on_change (callable) An optional callback invoked when this checkbox's value changes. args (tuple) An optional tuple of args to pass to the callback. kwargs (dict) An optional dict of kwargs to pass to the callback. disabled (bool) An optional boolean, which disables the checkbox if set to True. The default is False. label_visibility (""visible"", ""hidden"", or ""collapsed"") The visibility of the label. If ""hidden"", the label doesn't show but there is still empty space for it (equivalent to label=""""). If ""collapsed"", both the label and the space are removed. Default is ""visible"". Returns(bool) Whether or not the checkbox is checked. Example import streamlit as st agree = st.checkbox(""I agree"") if agree: st.write(""Great!"") Built with Streamlit 🎈Fullscreen open_in_new Featured videos Check out our video on how to use one of Streamlit's core functions, the checkbox! ☑ In the video below, we'll take it a step further and learn how to combine a button, checkbox and radio button! Previous: st.page_linkNext: st.color_pickerforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy" https://docs.streamlit.io/knowledge-base/deploy/sign-in-without-sso#sign-in-with-email,"DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudremoveGet startedaddDeploy your appaddManage your appaddShare your appaddManage your accountremoveSign in & sign outWorkspace settingsManage your GitHub connectionUpdate your emailDelete your accountTroubleshootingStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Deploy/Streamlit Community Cloud/Manage your account/Sign in & sign outSign in & sign out Once you've created your account, you can sign in to share.streamlit.io and follow the steps below. Sign in with Google Visit share.streamlit.io and click ""Continue with Google"". Enter your Google account credentials. If your account is already linked to GitHub, you may be immediately prompted to sign in with GitHub. Once you have signed in, you can Explore your workspace!. 🎈 Sign in with GitHub Visit share.streamlit.io and click ""Continue with GitHub"". Enter your GitHub credentials. Once you have signed in to GitHub, you can Explore your workspace!. 🎈 Sign in with Email Visit share.streamlit.io and enter the email you used to create your Streamlit Community Cloud account. Click ""Continue with email"". You will see a confirmation message asking you to check your email. Check your inbox for an email with the subject ""Sign in to Streamlit Cloud"". Click the link in the email to sign in to Streamlit Community Cloud. Note that this link will expire in 15 minutes and can only be used once. Once you click the link in your email, you can Explore your workspace!. 🎈 Sign out of your account From your workspace, click on your workspace name in the upper-right corner. Click ""Sign out"". Previous: Manage your accountNext: Workspace settingsforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy" https://docs.streamlit.io/knowledge-base/dependencies/libgl,"DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Knowledge base/Installing dependencies/ImportError libGL.so.1 cannot open shared object file No such file or directoryImportError libGL.so.1 cannot open shared object file No such file or directory Problem You receive the error ImportError libGL.so.1 cannot open shared object file No such file or directory when using OpenCV in your app deployed on Streamlit Community Cloud. Solution If you use OpenCV in your app, include opencv-python-headless in your requirements file on Streamlit Community Cloud in place of opencv_contrib_python and opencv-python. If opencv-python is a required (non-optional) dependency of your app or a dependency of a library used in your app, the above solution is not applicable. Instead, you can use the following solution: Create a packages.txt file in your repo with the following line to install the apt-get dependency libgl: libgl1 Previous: How to install a package not on PyPI or Conda but available on GitHubNext: ModuleNotFoundError No module namedforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy" https://docs.streamlit.io/develop/concepts/configuration/theming#theming,"DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsremoveCOREArchitecture & executionaddMultipage appsaddApp designaddADDITIONALConnections and secretsaddCustom componentsaddConfiguration and themingremoveConfiguration optionsHTTPS supportServing static filesCustomize your themeApp testingaddAPI referenceaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Develop/Concepts/Configuration and theming/Customize your themeTheming In this guide, we provide examples of how Streamlit page elements are affected by the various theme config options. For a more high-level overview of Streamlit themes, see the Themes section of the main concepts documentation. Streamlit themes are defined using regular config options: a theme can be set via command line flag when starting your app using streamlit run or by defining it in the [theme] section of a .streamlit/config.toml file. For more information on setting config options, please refer to the Streamlit configuration documentation. The following config options show the default Streamlit Light theme recreated in the [theme] section of a .streamlit/config.toml file. [theme] primaryColor=""#F63366"" backgroundColor=""#FFFFFF"" secondaryBackgroundColor=""#F0F2F6"" textColor=""#262730"" font=""sans serif"" Let's go through each of these options, providing screenshots to demonstrate what parts of a Streamlit app they affect where needed. primaryColor primaryColor defines the accent color most often used throughout a Streamlit app. A few examples of Streamlit widgets that use primaryColor include st.checkbox, st.slider, and st.text_input (when focused). starTipAny CSS color can be used as the value for primaryColor and the other color options below. This means that theme colors can be specified in hex or with browser-supported color names like ""green"", ""yellow"", and ""chartreuse"". They can even be defined in the RGB and HSL formats! backgroundColor Defines the background color used in the main content area of your app. secondaryBackgroundColor This color is used where a second background color is needed for added contrast. Most notably, it is the sidebar's background color. It is also used as the background color for most interactive widgets. textColor This option controls the text color for most of your Streamlit app. font Selects the font used in your Streamlit app. Valid values are ""sans serif"", ""serif"", and ""monospace"". This option defaults to ""sans serif"" if unset or invalid. Note that code blocks are always rendered using the monospace font regardless of the font selected here. base An easy way to define custom themes that make small changes to one of the preset Streamlit themes is to use the base option. Using base, the Streamlit Light theme can be recreated as a custom theme by writing the following: [theme] base=""light"" The base option allows you to specify a preset Streamlit theme that your custom theme inherits from. Any theme config options not defined in your theme settings have their values set to those of the base theme. Valid values for base are ""light"" and ""dark"". For example, the following theme config defines a custom theme nearly identical to the Streamlit Dark theme, but with a new primaryColor. [theme] base=""dark"" primaryColor=""purple"" If base itself is omitted, it defaults to ""light"", so you can define a custom theme that changes the font of the Streamlit Light theme to serif with the following config [theme] font=""serif"" Previous: Serving static filesNext: App testingforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy" https://docs.streamlit.io/deploy/streamlit-community-cloud/share-your-app/embed-your-app#example,"DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudremoveGet startedaddDeploy your appaddManage your appaddShare your appremoveEmbed your appSearch indexabilityShare previewsManage your accountaddTroubleshootingStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Deploy/Streamlit Community Cloud/Share your app/Embed your appEmbed your app Embedding Streamlit Community Cloud apps enriches your content by integrating interactive, data-driven applications directly within your pages. Whether you're writing a blog post, a technical document, or sharing resources on platforms like Medium, Notion, or even StackOverflow, embedding Streamlit apps adds a dynamic component to your content. This allows your audience to interact with your ideas, rather than merely reading about them or looking at screenshots. Streamlit Community Cloud supports both iframe and oEmbed methods for embedding public apps. This flexibility enables you to share your apps across a wide array of platforms, broadening your app's visibility and impact. In this guide, we'll cover how to use both methods effectively to share your Streamlit apps with the world. Embedding with iframes Streamlit Community Cloud supports embedding public apps using the subdomain scheme. To embed a public app, add the query parameter /?embed=true to the end of the *.streamlit.app URL. For example, say you want to embed the 30DaysOfStreamlit app. The URL to include in your iframe is: https://30days.streamlit.app/?embed=true: Built with Streamlit 🎈Fullscreen open_in_new priority_highImportantThere will be no official support for embedding private apps. In addition to allowing you to embed apps via iframes, the ?embed=true query parameter also does the following: Removes the toolbar with the app menu icon (more_vert). Removes the padding at the top and bottom of the app. Removes the footer. Removes the colored line from the top of the app. For granular control over the embedding behavior, Streamlit allows you to specify one or more instances of the ?embed_options query parameter (e.g. to show the toolbar, open the app in dark theme, etc). Click here for a full list of Embed options. Embedding with oEmbed Streamlit's oEmbed support allows for a simpler embedding experience. You can directly drop a Streamlit app's URL into a Medium, Ghost, or Notion page (or any of more than 700 content providers that supports oEmbed or embed.ly). The embedded app will automatically appear! This helps Streamlit Community Cloud apps seamlessly integrate into these platforms, improving the visibility and accessibility of your apps. Example When creating content in a Notion page, Medium article, or Ghost blog, you only need to paste the app's URL and hit ""Enter"". The app will then render automatically at that spot in your content. You can use your undecorated app URL without the ?embed=true query parameter. https://30days.streamlit.app/ Here's an example of @chrieke's Prettymapp app embedded in a Medium article: starTipEnsure the platform hosting the embedded Streamlit app supports oEmbed or embed.ly. Key Sites for oEmbed oEmbed should work out of the box for several platforms including but not limited to: Medium Notion Looker Tableau Ghost Discourse StackOverflow W3 Reddit Please check the specific platform's documentation to verify support for oEmbed. iframe versus oEmbed The only noteworthy differences between the methods is that iframing allows you to customize the app's embedding behavior (e.g. showing the toolbar, opening the app in dark theme, etc) using the various ?embed_options described in the next section. Embed options When Embedding with iframes, Streamlit allows you to specify one or more instances of the ?embed_options query parameter for granular control over the embedding behavior. Both ?embed and ?embed_options are invisible to st.query_params and its precursors, st.experimental_get_query_params and st.experimental_set_query_params. You can't get or set their values. The supported values for ?embed_options are listed below: Show the toolbar at the top right of the app which includes the app menu (more_vert), running man, and link to GitHub. /?embed=true&embed_options=show_toolbar Show padding at the top and bottom of the app. /?embed=true&embed_options=show_padding Show the footer reading ""Made with Streamlit."" (This doesn't apply to Streamlit versions 1.29.0 and later since the footer was removed from the library.) /?embed=true&embed_options=show_footer Show the colored line at the top of the app. /?embed=true&embed_options=show_colored_line Hide the ""skeleton"" that appears while an app is loading. /?embed=true&embed_options=hide_loading_screen Disable scrolling for the main body of the app. (The sidebar will still be scrollable.) /?embed=true&embed_options=disable_scrolling Open the app with light theme. /?embed=true&embed_options=light_theme Open the app with dark theme. /?embed=true&embed_options=dark_theme You can also combine the params: /?embed=true&embed_options=show_toolbar&embed_options=show_padding&embed_options=show_footer&embed_options=show_colored_line&embed_options=disable_scrolling Build an embed link You can conveniently build an embed link for your app — right from your app! From your app at .streamlit.app, click ""Share"" in the upper-right corner. Click ""Embed"" to access a list of selectable embed options. Select your embed options and click ""Get embed link"" to copy the embed link to your clipboard. Previous: Share your appNext: Search indexabilityforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy" https://docs.streamlit.io/develop/api-reference/caching-and-state/st.cache_resource#stcache_resourceclear,"DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceremovePAGE ELEMENTSWrite and magicaddText elementsaddData elementsaddChart elementsaddInput widgetsaddMedia elementsaddLayouts and containersaddChat elementsaddStatus elementsaddThird-party componentsopen_in_newAPPLICATION LOGICNavigation and pagesaddExecution flowaddCaching and stateremovest.cache_datast.cache_resourcest.cachedeletest.session_statest.query_paramsst.experimental_get_query_paramsdeletest.experimental_set_query_paramsdeleteConnections and secretsaddCustom componentsaddUtilitiesaddConfigurationaddTOOLSApp testingaddCommand lineaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Develop/API reference/Caching and state/st.cache_resourcestarTipThis page only contains information on the st.cache_resource API. For a deeper dive into caching and how to use it, check out Caching. st.cache_resourceStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeDecorator to cache functions that return global resources (e.g. database connections, ML models). Cached objects are shared across all users, sessions, and reruns. They must be thread-safe because they can be accessed from multiple threads concurrently. If thread safety is an issue, consider using st.session_state to store resources per session instead. You can clear a function's cache with func.clear() or clear the entire cache with st.cache_resource.clear(). To cache data, use st.cache_data instead. Learn more about caching at https://docs.streamlit.io/library/advanced-features/caching. Function signature[source] st.cache_resource(func, *, ttl, max_entries, show_spinner, validate, experimental_allow_widgets, hash_funcs=None) Parameters func (callable) The function that creates the cached resource. Streamlit hashes the function's source code. ttl (float, timedelta, str, or None) The maximum time to keep an entry in the cache. Can be one of: None if cache entries should never expire (default). A number specifying the time in seconds. A string specifying the time in a format supported by Pandas's Timedelta constructor, e.g. ""1d"", ""1.5 days"", or ""1h23s"". A timedelta object from Python's built-in datetime library, e.g. timedelta(days=1). max_entries (int or None) The maximum number of entries to keep in the cache, or None for an unbounded cache. When a new entry is added to a full cache, the oldest cached entry will be removed. Defaults to None. show_spinner (bool or str) Enable the spinner. Default is True to show a spinner when there is a ""cache miss"" and the cached resource is being created. If string, value of show_spinner param will be used for spinner text. validate (callable or None) An optional validation function for cached data. validate is called each time the cached value is accessed. It receives the cached value as its only parameter and it must return a boolean. If validate returns False, the current cached value is discarded, and the decorated function is called to compute a new value. This is useful e.g. to check the health of database connections. experimental_allow_widgets (bool) Allow widgets to be used in the cached function. Defaults to False. Support for widgets in cached functions is currently experimental. Setting this parameter to True may lead to excessive memory use since the widget value is treated as an additional input parameter to the cache. We may remove support for this option at any time without notice. hash_funcs (dict or None) Mapping of types or fully qualified names to hash functions. This is used to override the behavior of the hasher inside Streamlit's caching mechanism: when the hasher encounters an object, it will first check to see if its type matches a key in this dict and, if so, will use the provided function to generate a hash for it. See below for an example of how this can be used. Example import streamlit as st @st.cache_resource def get_database_session(url): # Create a database session object that points to the URL. return session s1 = get_database_session(SESSION_URL_1) # Actually executes the function, since this is the first time it was # encountered. s2 = get_database_session(SESSION_URL_1) # Does not execute the function. Instead, returns its previously computed # value. This means that now the connection object in s1 is the same as in s2. s3 = get_database_session(SESSION_URL_2) # This is a different URL, so the function executes. By default, all parameters to a cache_resource function must be hashable. Any parameter whose name begins with _ will not be hashed. You can use this as an ""escape hatch"" for parameters that are not hashable: import streamlit as st @st.cache_resource def get_database_session(_sessionmaker, url): # Create a database connection object that points to the URL. return connection s1 = get_database_session(create_sessionmaker(), DATA_URL_1) # Actually executes the function, since this is the first time it was # encountered. s2 = get_database_session(create_sessionmaker(), DATA_URL_1) # Does not execute the function. Instead, returns its previously computed # value - even though the _sessionmaker parameter was different # in both calls. A cache_resource function's cache can be procedurally cleared: import streamlit as st @st.cache_resource def get_database_session(_sessionmaker, url): # Create a database connection object that points to the URL. return connection fetch_and_clean_data.clear(_sessionmaker, ""https://streamlit.io/"") # Clear the cached entry for the arguments provided. get_database_session.clear() # Clear all cached entries for this function. To override the default hashing behavior, pass a custom hash function. You can do that by mapping a type (e.g. Person) to a hash function (str) like this: import streamlit as st from pydantic import BaseModel class Person(BaseModel): name: str @st.cache_resource(hash_funcs={Person: str}) def get_person_name(person: Person): return person.name Alternatively, you can map the type's fully-qualified name (e.g. ""__main__.Person"") to the hash function instead: import streamlit as st from pydantic import BaseModel class Person(BaseModel): name: str @st.cache_resource(hash_funcs={""__main__.Person"": str}) def get_person_name(person: Person): return person.name st.cache_resource.clearStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeClear all cache_resource caches. Function signature[source] st.cache_resource.clear() Example In the example below, pressing the ""Clear All"" button will clear all cache_resource caches. i.e. Clears cached global resources from all functions decorated with @st.cache_resource. import streamlit as st from transformers import BertModel @st.cache_resource def get_database_session(url): # Create a database session object that points to the URL. return session @st.cache_resource def get_model(model_type): # Create a model of the specified type. return BertModel.from_pretrained(model_type) if st.button(""Clear All""): # Clears all st.cache_resource caches: st.cache_resource.clear() CachedFunc.clearStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeClear the cached function's associated cache. If no arguments are passed, Streamlit will clear all values cached for the function. If arguments are passed, Streamlit will clear the cached value for these arguments only. Function signature[source] CachedFunc.clear(*args, **kwargs) Parameters *args (Any) Arguments of the cached functions. **kwargs (Any) Keyword arguments of the cached function. Example import streamlit as st import time @st.cache_data def foo(bar): time.sleep(2) st.write(f""Executed foo({bar})."") return bar if st.button(""Clear all cached values for `foo`"", on_click=foo.clear): foo.clear() if st.button(""Clear the cached value of `foo(1)`""): foo.clear(1) foo(1) foo(2) Using Streamlit commands in cached functions Static elements Since version 1.16.0, cached functions can contain Streamlit commands! For example, you can do this: from transformers import pipeline @st.cache_resource def load_model(): model = pipeline(""sentiment-analysis"") st.success(""Loaded NLP model from Hugging Face!"") # 👈 Show a success message return model As we know, Streamlit only runs this function if it hasn’t been cached before. On this first run, the st.success message will appear in the app. But what happens on subsequent runs? It still shows up! Streamlit realizes that there is an st. command inside the cached function, saves it during the first run, and replays it on subsequent runs. Replaying static elements works for both caching decorators. You can also use this functionality to cache entire parts of your UI: @st.cache_resource def load_model(): st.header(""Data analysis"") model = torchvision.models.resnet50(weights=ResNet50_Weights.DEFAULT) st.success(""Loaded model!"") st.write(""Turning on evaluation mode..."") model.eval() st.write(""Here's the model:"") return model Input widgets You can also use interactive input widgets like st.slider or st.text_input in cached functions. Widget replay is an experimental feature at the moment. To enable it, you need to set the experimental_allow_widgets parameter: @st.cache_resource(experimental_allow_widgets=True) # 👈 Set the parameter def load_model(): pretrained = st.checkbox(""Use pre-trained model:"") # 👈 Add a checkbox model = torchvision.models.resnet50(weights=ResNet50_Weights.DEFAULT, pretrained=pretrained) return model Streamlit treats the checkbox like an additional input parameter to the cached function. If you uncheck it, Streamlit will see if it has already cached the function for this checkbox state. If yes, it will return the cached value. If not, it will rerun the function using the new slider value. Using widgets in cached functions is extremely powerful because it lets you cache entire parts of your app. But it can be dangerous! Since Streamlit treats the widget value as an additional input parameter, it can easily lead to excessive memory usage. Imagine your cached function has five sliders and returns a 100 MB DataFrame. Then we’ll add 100 MB to the cache for every permutation of these five slider values – even if the sliders do not influence the returned data! These additions can make your cache explode very quickly. Please be aware of this limitation if you use widgets in cached functions. We recommend using this feature only for isolated parts of your UI where the widgets directly influence the cached return value. priority_highWarningSupport for widgets in cached functions is currently experimental. We may change or remove it anytime without warning. Please use it with care! push_pinNoteTwo widgets are currently not supported in cached functions: st.file_uploader and st.camera_input. We may support them in the future. Feel free to open a GitHub issue if you need them!Previous: st.cache_dataNext: st.cacheforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy" https://docs.streamlit.io/en/0.75.0/api.html#connections-and-databases,"DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceremovePAGE ELEMENTSWrite and magicaddText elementsaddData elementsaddChart elementsaddInput widgetsaddMedia elementsaddLayouts and containersaddChat elementsaddStatus elementsaddThird-party componentsopen_in_newAPPLICATION LOGICNavigation and pagesaddExecution flowaddCaching and stateaddConnections and secretsaddCustom componentsaddUtilitiesaddConfigurationaddTOOLSApp testingaddCommand lineaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Develop/API referenceAPI reference Streamlit makes it easy for you to visualize, mutate, and share data. The API reference is organized by activity type, like displaying data or optimizing performance. Each section includes methods associated with the activity type, including examples. Browse our API below and click to learn more about any of our available commands! 🎈 Display almost anything Write and magic st.writeWrite arguments to the app.st.write(""Hello **world**!"") st.write(my_data_frame) st.write(my_mpl_figure) st.write_streamWrite generators or streams to the app with a typewriter effect.st.write_stream(my_generator) st.write_stream(my_llm_stream) MagicAny time Streamlit sees either a variable or literal value on its own line, it automatically writes that to your app using st.write""Hello **world**!"" my_data_frame my_mpl_figure Text elements MarkdownDisplay string formatted as Markdown.st.markdown(""Hello **world**!"") TitleDisplay text in title formatting.st.title(""The app title"") HeaderDisplay text in header formatting.st.header(""This is a header"") SubheaderDisplay text in subheader formatting.st.subheader(""This is a subheader"") CaptionDisplay text in small font.st.caption(""This is written small caption text"") Code blockDisplay a code block with optional syntax highlighting.st.code(""a = 1234"") EchoDisplay some code in the app, then execute it. Useful for tutorials.with st.echo(): st.write('This code will be printed') LaTeXDisplay mathematical expressions formatted as LaTeX.st.latex(""\int a x^2 \,dx"") Preformatted textWrite fixed-width and preformatted text.st.text(""Hello world"") DividerDisplay a horizontal rule.st.divider() Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration! PreviousTagsAdd tags to your Streamlit apps. Created by @gagan3012.st_tags(label='# Enter Keywords:', text='Press enter to add more', value=['Zero', 'One', 'Two'], suggestions=['five', 'six', 'seven', 'eight', 'nine', 'three', 'eleven', 'ten', 'four'], maxtags = 4, key='1') NLUApply text mining on a dataframe. Created by @JohnSnowLabs.nlu.load('sentiment').predict('I love NLU! <3') Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.mention(label=""An awesome Streamlit App"", icon=""streamlit"", url=""https://extras.streamlit.app"",) Annotated textDisplay annotated text in Streamlit apps. Created by @tvst.annotated_text(""This "", (""is"", ""verb""), "" some "", (""annotated"", ""adj""), (""text"", ""noun""), "" for those of "", (""you"", ""pronoun""), "" who "", (""like"", ""verb""), "" this sort of "", (""thing"", ""noun""), ""."") Drawable CanvasProvides a sketching canvas using Fabric.js. Created by @andfanilo.st_canvas(fill_color=""rgba(255, 165, 0, 0.3)"", stroke_width=stroke_width, stroke_color=stroke_color, background_color=bg_color, background_image=Image.open(bg_image) if bg_image else None, update_streamlit=realtime_update, height=150, drawing_mode=drawing_mode, point_display_radius=point_display_radius if drawing_mode == 'point' else 0, key=""canvas"",) TagsAdd tags to your Streamlit apps. Created by @gagan3012.st_tags(label='# Enter Keywords:', text='Press enter to add more', value=['Zero', 'One', 'Two'], suggestions=['five', 'six', 'seven', 'eight', 'nine', 'three', 'eleven', 'ten', 'four'], maxtags = 4, key='1') NLUApply text mining on a dataframe. Created by @JohnSnowLabs.nlu.load('sentiment').predict('I love NLU! <3') Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.mention(label=""An awesome Streamlit App"", icon=""streamlit"", url=""https://extras.streamlit.app"",) Annotated textDisplay annotated text in Streamlit apps. Created by @tvst.annotated_text(""This "", (""is"", ""verb""), "" some "", (""annotated"", ""adj""), (""text"", ""noun""), "" for those of "", (""you"", ""pronoun""), "" who "", (""like"", ""verb""), "" this sort of "", (""thing"", ""noun""), ""."") Drawable CanvasProvides a sketching canvas using Fabric.js. Created by @andfanilo.st_canvas(fill_color=""rgba(255, 165, 0, 0.3)"", stroke_width=stroke_width, stroke_color=stroke_color, background_color=bg_color, background_image=Image.open(bg_image) if bg_image else None, update_streamlit=realtime_update, height=150, drawing_mode=drawing_mode, point_display_radius=point_display_radius if drawing_mode == 'point' else 0, key=""canvas"",) TagsAdd tags to your Streamlit apps. Created by @gagan3012.st_tags(label='# Enter Keywords:', text='Press enter to add more', value=['Zero', 'One', 'Two'], suggestions=['five', 'six', 'seven', 'eight', 'nine', 'three', 'eleven', 'ten', 'four'], maxtags = 4, key='1') NLUApply text mining on a dataframe. Created by @JohnSnowLabs.nlu.load('sentiment').predict('I love NLU! <3') Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.mention(label=""An awesome Streamlit App"", icon=""streamlit"", url=""https://extras.streamlit.app"",) Next Data elements DataframesDisplay a dataframe as an interactive table.st.dataframe(my_data_frame) Data editorDisplay a data editor widget.edited = st.data_editor(df, num_rows=""dynamic"") Column configurationConfigure the display and editing behavior of dataframes and data editors.st.column_config.NumberColumn(""Price (in USD)"", min_value=0, format=""$%d"") Static tablesDisplay a static table.st.table(my_data_frame) MetricsDisplay a metric in big bold font, with an optional indicator of how the metric changed.st.metric(""My metric"", 42, 2) Dicts and JSONDisplay object or string as a pretty-printed JSON string.st.json(my_dict) Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration! PreviousImage CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates value = streamlit_image_coordinates(""https://placekitten.com/200/300"") st.write(value) Plotly EventsMake Plotly charts interactive!. Created by @null-jones.from streamlit_plotly_events import plotly_events fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.metric_cards import style_metric_cards col3.metric(label=""No Change"", value=5000, delta=0) style_metric_cards() Streamlit AggridImplementation of Ag-Grid component for Streamlit. Created by @PablocFonseca.df = pd.DataFrame({'col1': [1, 2, 3], 'col2': [4, 5, 6]}) grid_return = AgGrid(df, editable=True) new_df = grid_return['data'] Streamlit FoliumStreamlit Component for rendering Folium maps. Created by @randyzwitch.m = folium.Map(location=[39.949610, -75.150282], zoom_start=16) folium.Marker([39.949610, -75.150282], popup=""Liberty Bell"", tooltip=""Liberty Bell"").add_to(m) st_data = st_folium(m, width=725) Pandas ProfilingPandas profiling component for Streamlit. Created by @okld.df = pd.read_csv(""https://storage.googleapis.com/tf-datasets/titanic/train.csv"") pr = df.profile_report() st_profile_report(pr) Image CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates value = streamlit_image_coordinates(""https://placekitten.com/200/300"") st.write(value) Plotly EventsMake Plotly charts interactive!. Created by @null-jones.from streamlit_plotly_events import plotly_events fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.metric_cards import style_metric_cards col3.metric(label=""No Change"", value=5000, delta=0) style_metric_cards() Streamlit AggridImplementation of Ag-Grid component for Streamlit. Created by @PablocFonseca.df = pd.DataFrame({'col1': [1, 2, 3], 'col2': [4, 5, 6]}) grid_return = AgGrid(df, editable=True) new_df = grid_return['data'] Streamlit FoliumStreamlit Component for rendering Folium maps. Created by @randyzwitch.m = folium.Map(location=[39.949610, -75.150282], zoom_start=16) folium.Marker([39.949610, -75.150282], popup=""Liberty Bell"", tooltip=""Liberty Bell"").add_to(m) st_data = st_folium(m, width=725) Pandas ProfilingPandas profiling component for Streamlit. Created by @okld.df = pd.read_csv(""https://storage.googleapis.com/tf-datasets/titanic/train.csv"") pr = df.profile_report() st_profile_report(pr) Image CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates value = streamlit_image_coordinates(""https://placekitten.com/200/300"") st.write(value) Plotly EventsMake Plotly charts interactive!. Created by @null-jones.from streamlit_plotly_events import plotly_events fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.metric_cards import style_metric_cards col3.metric(label=""No Change"", value=5000, delta=0) style_metric_cards() Next Chart elements Simple area chartsDisplay an area chart.st.area_chart(my_data_frame) Simple bar chartsDisplay a bar chart.st.bar_chart(my_data_frame) Simple line chartsDisplay a line chart.st.line_chart(my_data_frame) Simple scatter chartsDisplay a line chart.st.scatter_chart(my_data_frame) Scatterplots on mapsDisplay a map with points on it.st.map(my_data_frame) MatplotlibDisplay a matplotlib.pyplot figure.st.pyplot(my_mpl_figure) AltairDisplay a chart using the Altair library.st.altair_chart(my_altair_chart) Vega-LiteDisplay a chart using the Vega-Lite library.st.vega_lite_chart(my_vega_lite_chart) PlotlyDisplay an interactive Plotly chart.st.plotly_chart(my_plotly_chart) BokehDisplay an interactive Bokeh chart.st.bokeh_chart(my_bokeh_chart) PyDeckDisplay a chart using the PyDeck library.st.pydeck_chart(my_pydeck_chart) GraphVizDisplay a graph using the dagre-d3 library.st.graphviz_chart(my_graphviz_spec) Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration! PreviousStreamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl(""https://assets5.lottiefiles.com/packages/lf20_V9t630.json"") st_lottie(lottie_hello, key=""hello"") Plotly EventsMake Plotly charts interactive!. Created by @null-jones.fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.chart += get_annotations_chart(annotations=[(""Mar 01, 2008"", ""Pretty good day for GOOG""), (""Dec 01, 2007"", ""Something's going wrong for GOOG & AAPL""), (""Nov 01, 2008"", ""Market starts again thanks to...""), (""Dec 01, 2009"", ""Small crash for GOOG after...""),],) st.altair_chart(chart, use_container_width=True) PlostA deceptively simple plotting library for Streamlit. Created by @tvst.import plost plost.line_chart(my_dataframe, x='time', y='stock_value', color='stock_name',) HiPlotHigh dimensional Interactive Plotting. Created by @facebookresearch.data = [{'dropout':0.1, 'lr': 0.001, 'loss': 10.0, 'optimizer': 'SGD'}, {'dropout':0.15, 'lr': 0.01, 'loss': 3.5, 'optimizer': 'Adam'}, {'dropout':0.3, 'lr': 0.1, 'loss': 4.5, 'optimizer': 'Adam'}] hip.Experiment.from_iterable(data).display() EChartsHigh dimensional Interactive Plotting. Created by @andfanilo.from streamlit_echarts import st_echarts st_echarts(options=options) Streamlit FoliumStreamlit Component for rendering Folium maps. Created by @randyzwitch.m = folium.Map(location=[39.949610, -75.150282], zoom_start=16) st_data = st_folium(m, width=725) Spacy-StreamlitspaCy building blocks and visualizers for Streamlit apps. Created by @explosion.models = [""en_core_web_sm"", ""en_core_web_md""] spacy_streamlit.visualize(models, ""Sundar Pichai is the CEO of Google."") Streamlit AgraphA Streamlit Graph Vis, based on react-grah-vis. Created by @ChrisDelClea.from streamlit_agraph import agraph, Node, Edge, Config agraph(nodes=nodes, edges=edges, config=config) Streamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl(""https://assets5.lottiefiles.com/packages/lf20_V9t630.json"") st_lottie(lottie_hello, key=""hello"") Plotly EventsMake Plotly charts interactive!. Created by @null-jones.fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.chart += get_annotations_chart(annotations=[(""Mar 01, 2008"", ""Pretty good day for GOOG""), (""Dec 01, 2007"", ""Something's going wrong for GOOG & AAPL""), (""Nov 01, 2008"", ""Market starts again thanks to...""), (""Dec 01, 2009"", ""Small crash for GOOG after...""),],) st.altair_chart(chart, use_container_width=True) PlostA deceptively simple plotting library for Streamlit. Created by @tvst.import plost plost.line_chart(my_dataframe, x='time', y='stock_value', color='stock_name',) HiPlotHigh dimensional Interactive Plotting. Created by @facebookresearch.data = [{'dropout':0.1, 'lr': 0.001, 'loss': 10.0, 'optimizer': 'SGD'}, {'dropout':0.15, 'lr': 0.01, 'loss': 3.5, 'optimizer': 'Adam'}, {'dropout':0.3, 'lr': 0.1, 'loss': 4.5, 'optimizer': 'Adam'}] hip.Experiment.from_iterable(data).display() EChartsHigh dimensional Interactive Plotting. Created by @andfanilo.from streamlit_echarts import st_echarts st_echarts(options=options) Streamlit FoliumStreamlit Component for rendering Folium maps. Created by @randyzwitch.m = folium.Map(location=[39.949610, -75.150282], zoom_start=16) st_data = st_folium(m, width=725) Spacy-StreamlitspaCy building blocks and visualizers for Streamlit apps. Created by @explosion.models = [""en_core_web_sm"", ""en_core_web_md""] spacy_streamlit.visualize(models, ""Sundar Pichai is the CEO of Google."") Streamlit AgraphA Streamlit Graph Vis, based on react-grah-vis. Created by @ChrisDelClea.from streamlit_agraph import agraph, Node, Edge, Config agraph(nodes=nodes, edges=edges, config=config) Streamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl(""https://assets5.lottiefiles.com/packages/lf20_V9t630.json"") st_lottie(lottie_hello, key=""hello"") Plotly EventsMake Plotly charts interactive!. Created by @null-jones.fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.chart += get_annotations_chart(annotations=[(""Mar 01, 2008"", ""Pretty good day for GOOG""), (""Dec 01, 2007"", ""Something's going wrong for GOOG & AAPL""), (""Nov 01, 2008"", ""Market starts again thanks to...""), (""Dec 01, 2009"", ""Small crash for GOOG after...""),],) st.altair_chart(chart, use_container_width=True) Next Input widgets ButtonDisplay a button widget.clicked = st.button(""Click me"") Download buttonDisplay a download button widget.st.download_button(""Download file"", file) Form buttonDisplay a form submit button. For use with st.form.st.form_submit_button(""Sign up"") Link buttonDisplay a link button.st.link_button(""Go to gallery"", url) Page linkDisplay a link to another page in a multipage app.st.page_link(""app.py"", label=""Home"", icon=""🏠"") st.page_link(""pages/profile.py"", label=""My profile"") CheckboxDisplay a checkbox widget.selected = st.checkbox(""I agree"") Color pickerDisplay a color picker widget.color = st.color_picker(""Pick a color"") MultiselectDisplay a multiselect widget. The multiselect widget starts as empty.choices = st.multiselect(""Buy"", [""milk"", ""apples"", ""potatoes""]) RadioDisplay a radio button widget.choice = st.radio(""Pick one"", [""cats"", ""dogs""]) SelectboxDisplay a select widget.choice = st.selectbox(""Pick one"", [""cats"", ""dogs""]) Select-sliderDisplay a slider widget to select items from a list.size = st.select_slider(""Pick a size"", [""S"", ""M"", ""L""]) ToggleDisplay a toggle widget.activated = st.toggle(""Activate"") Number inputDisplay a numeric input widget.choice = st.number_input(""Pick a number"", 0, 10) SliderDisplay a slider widget.number = st.slider(""Pick a number"", 0, 100) Date inputDisplay a date input widget.date = st.date_input(""Your birthday"") Time inputDisplay a time input widget.time = st.time_input(""Meeting time"") Chat inputDisplay a chat input widget.prompt = st.chat_input(""Say something"") if prompt: st.write(f""The user has sent: {prompt}"") Text-areaDisplay a multi-line text input widget.text = st.text_area(""Text to translate"") Text inputDisplay a single-line text input widget.name = st.text_input(""First name"") Data editorDisplay a data editor widget.edited = st.experimental_data_editor(df, num_rows=""dynamic"") File UploaderDisplay a file uploader widget.data = st.file_uploader(""Upload a CSV"") Camera inputDisplay a widget that allows users to upload images directly from a camera.image = st.camera_input(""Take a picture"") Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration! PreviousStreamlit ChatStreamlit Component for a Chatbot UI. Created by @AI-Yash.from streamlit_chat import message message(""My message"") message(""Hello bot!"", is_user=True) # align's the message to the right Streamlit Option MenuSelect a single item from a list of options in a menu. Created by @victoryhb.from streamlit_option_menu import option_menu option_menu(""Main Menu"", [""Home"", 'Settings'], icons=['house', 'gear'], menu_icon=""cast"", default_index=1) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.stoggle import stoggle stoggle( ""Click me!"", """"""🥷 Surprise! Here's some additional content"""""",) Streamlit ElementsCreate a draggable and resizable dashboard in Streamlit. Created by @okls.from streamlit_elements import elements, mui, html with elements(""new_element""): mui.Typography(""Hello world"") TagsAdd tags to your Streamlit apps. Created by @gagan3012.from streamlit_tags import st_tags st_tags(label='# Enter Keywords:', text='Press enter to add more', value=['Zero', 'One', 'Two'], suggestions=['five', 'six', 'seven', 'eight', 'nine', 'three', 'eleven', 'ten', 'four'], maxtags = 4, key='1') StqdmThe simplest way to handle a progress bar in streamlit app. Created by @Wirg.from stqdm import stqdm for _ in stqdm(range(50)): sleep(0.5) TimelineDisplay a Timeline in Streamlit apps using TimelineJS. Created by @innerdoc.from streamlit_timeline import timeline with open('example.json', ""r"") as f: timeline(f.read(), height=800) Camera input liveAlternative for st.camera_input which returns the webcam images live. Created by @blackary.from camera_input_live import camera_input_live image = camera_input_live() st.image(value) Streamlit AceAce editor component for Streamlit. Created by @okld.from streamlit_ace import st_ace content = st_ace() content Streamlit ChatStreamlit Component for a Chatbot UI. Created by @AI-Yash.from streamlit_chat import message message(""My message"") message(""Hello bot!"", is_user=True) # align's the message to the right Streamlit Option MenuSelect a single item from a list of options in a menu. Created by @victoryhb.from streamlit_option_menu import option_menu option_menu(""Main Menu"", [""Home"", 'Settings'], icons=['house', 'gear'], menu_icon=""cast"", default_index=1) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.stoggle import stoggle stoggle( ""Click me!"", """"""🥷 Surprise! Here's some additional content"""""",) Streamlit ElementsCreate a draggable and resizable dashboard in Streamlit. Created by @okls.from streamlit_elements import elements, mui, html with elements(""new_element""): mui.Typography(""Hello world"") TagsAdd tags to your Streamlit apps. Created by @gagan3012.from streamlit_tags import st_tags st_tags(label='# Enter Keywords:', text='Press enter to add more', value=['Zero', 'One', 'Two'], suggestions=['five', 'six', 'seven', 'eight', 'nine', 'three', 'eleven', 'ten', 'four'], maxtags = 4, key='1') StqdmThe simplest way to handle a progress bar in streamlit app. Created by @Wirg.from stqdm import stqdm for _ in stqdm(range(50)): sleep(0.5) TimelineDisplay a Timeline in Streamlit apps using TimelineJS. Created by @innerdoc.from streamlit_timeline import timeline with open('example.json', ""r"") as f: timeline(f.read(), height=800) Camera input liveAlternative for st.camera_input which returns the webcam images live. Created by @blackary.from camera_input_live import camera_input_live image = camera_input_live() st.image(value) Streamlit AceAce editor component for Streamlit. Created by @okld.from streamlit_ace import st_ace content = st_ace() content Streamlit ChatStreamlit Component for a Chatbot UI. Created by @AI-Yash.from streamlit_chat import message message(""My message"") message(""Hello bot!"", is_user=True) # align's the message to the right Streamlit Option MenuSelect a single item from a list of options in a menu. Created by @victoryhb.from streamlit_option_menu import option_menu option_menu(""Main Menu"", [""Home"", 'Settings'], icons=['house', 'gear'], menu_icon=""cast"", default_index=1) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.stoggle import stoggle stoggle( ""Click me!"", """"""🥷 Surprise! Here's some additional content"""""",) Next Media elements ImageDisplay an image or list of images.st.image(numpy_array) st.image(image_bytes) st.image(file) st.image(""https://example.com/myimage.jpg"") AudioDisplay an audio player.st.audio(numpy_array) st.audio(audio_bytes) st.audio(file) st.audio(""https://example.com/myaudio.mp3"", format=""audio/mp3"") VideoDisplay a video player.st.video(numpy_array) st.video(video_bytes) st.video(file) st.video(""https://example.com/myvideo.mp4"", format=""video/mp4"") Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration! PreviousStreamlit CropperA simple image cropper for Streamlit. Created by @turner-anderson.from streamlit_cropper import st_cropper st_cropper(img, realtime_update=realtime_update, box_color=box_color, aspect_ratio=aspect_ratio) Image CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates streamlit_image_coordinates(""https://placekitten.com/200/300"") Streamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl(""https://assets5.lottiefiles.com/packages/lf20_V9t630.json"") st_lottie(lottie_hello, key=""hello"") Streamlit WebrtcHandling and transmitting real-time video/audio streams with Streamlit. Created by @whitphx.from streamlit_webrtc import webrtc_streamer webrtc_streamer(key=""sample"") Drawable CanvasProvides a sketching canvas using Fabric.js. Created by @andfanilo.from streamlit_drawable_canvas import st_canvas st_canvas(fill_color=""rgba(255, 165, 0, 0.3)"", stroke_width=stroke_width, stroke_color=stroke_color, background_color=bg_color, background_image=Image.open(bg_image) if bg_image else None, update_streamlit=realtime_update, height=150, drawing_mode=drawing_mode, point_display_radius=point_display_radius if drawing_mode == 'point' else 0, key=""canvas"",) Image ComparisonCompare images with a slider using JuxtaposeJS. Created by @fcakyon.from streamlit_image_comparison import image_comparison image_comparison(img1=""image1.jpg"", img2=""image2.jpg"",) Streamlit CropperA simple image cropper for Streamlit. Created by @turner-anderson.from streamlit_cropper import st_cropper st_cropper(img, realtime_update=realtime_update, box_color=box_color, aspect_ratio=aspect_ratio) Image CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates streamlit_image_coordinates(""https://placekitten.com/200/300"") Streamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl(""https://assets5.lottiefiles.com/packages/lf20_V9t630.json"") st_lottie(lottie_hello, key=""hello"") Streamlit WebrtcHandling and transmitting real-time video/audio streams with Streamlit. Created by @whitphx.from streamlit_webrtc import webrtc_streamer webrtc_streamer(key=""sample"") Drawable CanvasProvides a sketching canvas using Fabric.js. Created by @andfanilo.from streamlit_drawable_canvas import st_canvas st_canvas(fill_color=""rgba(255, 165, 0, 0.3)"", stroke_width=stroke_width, stroke_color=stroke_color, background_color=bg_color, background_image=Image.open(bg_image) if bg_image else None, update_streamlit=realtime_update, height=150, drawing_mode=drawing_mode, point_display_radius=point_display_radius if drawing_mode == 'point' else 0, key=""canvas"",) Image ComparisonCompare images with a slider using JuxtaposeJS. Created by @fcakyon.from streamlit_image_comparison import image_comparison image_comparison(img1=""image1.jpg"", img2=""image2.jpg"",) Streamlit CropperA simple image cropper for Streamlit. Created by @turner-anderson.from streamlit_cropper import st_cropper st_cropper(img, realtime_update=realtime_update, box_color=box_color, aspect_ratio=aspect_ratio) Image CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates streamlit_image_coordinates(""https://placekitten.com/200/300"") Streamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl(""https://assets5.lottiefiles.com/packages/lf20_V9t630.json"") st_lottie(lottie_hello, key=""hello"") Next Layouts and containers ColumnsInsert containers laid out as side-by-side columns.col1, col2 = st.columns(2) col1.write(""this is column 1"") col2.write(""this is column 2"") ContainerInsert a multi-element container.c = st.container() st.write(""This will show last"") c.write(""This will show first"") c.write(""This will show second"") Modal dialogsInsert a modal dialog that can rerun independently from the rest of the script.@st.experimental_dialog(""Sign up"") def email_form(): name = st.text_input(""Name"") email = st.text_input(""Email"") EmptyInsert a single-element container.c = st.empty() st.write(""This will show last"") c.write(""This will be replaced"") c.write(""This will show first"") ExpanderInsert a multi-element container that can be expanded/collapsed.with st.expander(""Open to see more""): st.write(""This is more content"") PopoverInsert a multi-element popover container that can be opened/closed.with st.popover(""Settings""): st.checkbox(""Show completed"") SidebarDisplay items in a sidebar.st.sidebar.write(""This lives in the sidebar"") st.sidebar.button(""Click me!"") TabsInsert containers separated into tabs.tab1, tab2 = st.tabs([""Tab 1"", ""Tab2""]) tab1.write(""this is tab 1"") tab2.write(""this is tab 2"") Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration!Streamlit ElementsCreate a draggable and resizable dashboard in Streamlit. Created by @okls.from streamlit_elements import elements, mui, html with elements(""new_element""): mui.Typography(""Hello world"") PydanticAuto-generate Streamlit UI from Pydantic Models and Dataclasses. Created by @lukasmasuch.import streamlit_pydantic as sp sp.pydantic_form(key=""my_form"", model=ExampleModel) Streamlit PagesAn experimental version of Streamlit Multi-Page Apps. Created by @blackary.from st_pages import Page, show_pages, add_page_title show_pages([ Page(""streamlit_app.py"", ""Home"", ""🏠""), Page(""other_pages/page2.py"", ""Page 2"", "":books:""), ]) Chat elements Streamlit provides a few commands to help you build conversational apps. These chat elements are designed to be used in conjunction with each other, but you can also use them separately. st.chat_message lets you insert a chat message container into the app so you can display messages from the user or the app. Chat containers can contain other Streamlit elements, including charts, tables, text, and more. st.chat_input lets you display a chat input widget so the user can type in a message. Chat inputDisplay a chat input widget.prompt = st.chat_input(""Say something"") if prompt: st.write(f""The user has sent: {prompt}"") Chat messageInsert a chat message container.import numpy as np with st.chat_message(""user""): st.write(""Hello 👋"") st.line_chart(np.random.randn(30, 3)) Status containerDisplay output of long-running tasks in a container.with st.status('Running'): do_something_slow() st.write_streamWrite generators or streams to the app with a typewriter effect.st.write_stream(my_generator) st.write_stream(my_llm_stream) Status elements Progress barDisplay a progress bar.for i in range(101): st.progress(i) do_something_slow() SpinnerTemporarily displays a message while executing a block of code.with st.spinner(""Please wait...""): do_something_slow() Status containerDisplay output of long-running tasks in a container.with st.status('Running'): do_something_slow() ToastBriefly displays a toast message in the bottom-right corner.st.toast('Butter!', icon='🧈') BalloonsDisplay celebratory balloons!do_something() # Celebrate when all done! st.balloons() SnowflakesDisplay celebratory snowflakes!do_something() # Celebrate when all done! st.snow() Success boxDisplay a success message.st.success(""Match found!"") Info boxDisplay an informational message.st.info(""Dataset is updated every day at midnight."") Warning boxDisplay warning message.st.warning(""Unable to fetch image. Skipping..."") Error boxDisplay error message.st.error(""We encountered an error"") Exception outputDisplay an exception.e = RuntimeError(""This is an exception of type RuntimeError"") st.exception(e) Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration!StqdmThe simplest way to handle a progress bar in streamlit app. Created by @Wirg.from stqdm import stqdm for _ in stqdm(range(50)): sleep(0.5) Custom notification boxA custom notification box with the ability to close it out. Created by @Socvest.from streamlit_custom_notification_box import custom_notification_box styles = {'material-icons':{'color': 'red'}, 'text-icon-link-close-container': {'box-shadow': '#3896de 0px 4px'}, 'notification-text': {'':''}, 'close-button':{'':''}, 'link':{'':''}} custom_notification_box(icon='info', textDisplay='We are almost done with your registration...', externalLink='more info', url='#', styles=styles, key=""foo"") Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.let_it_rain import rain rain(emoji=""🎈"", font_size=54, falling_speed=5, animation_length=""infinite"",) App logic and configuration Navigation and pages Switch pageProgrammatically navigates to a specified page.st.switch_page(""pages/my_page.py"") Page linkDisplay a link to another page in a multipage app.st.page_link(""app.py"", label=""Home"", icon=""🏠"") st.page_link(""pages/profile.py"", label=""My profile"") Execution flow Modal dialogsInsert a modal dialog that can rerun independently from the rest of the script.@st.experimental_dialog(""Sign up"") def email_form(): name = st.text_input(""Name"") email = st.text_input(""Email"") FormsCreate a form that batches elements together with a “Submit"" button.with st.form(key='my_form'): name = st.text_input(""Name"") email = st.text_input(""Email"") st.form_submit_button(""Sign up"") Partial rerunsDefine a fragment to rerun independently from the rest of the script.@st.experimental_fragment(run_every=""10s"") def fragment(): df = get_data() st.line_chart(df) Rerun scriptRerun the script immediately.st.rerun() Stop executionStops execution immediately.st.stop() Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration!AutorefreshForce a refresh without tying up a script. Created by @kmcgrady.from streamlit_autorefresh import st_autorefresh st_autorefresh(interval=2000, limit=100, key=""fizzbuzzcounter"") PydanticAuto-generate Streamlit UI from Pydantic Models and Dataclasses. Created by @lukasmasuch.import streamlit_pydantic as sp sp.pydantic_form(key=""my_form"", model=ExampleModel) Streamlit PagesAn experimental version of Streamlit Multi-Page Apps. Created by @blackary.from st_pages import Page, show_pages, add_page_title show_pages([ Page(""streamlit_app.py"", ""Home"", ""🏠""), Page(""other_pages/page2.py"", ""Page 2"", "":books:""), ]) Caching and state Cache dataFunction decorator to cache functions that return data (e.g. dataframe transforms, database queries, ML inference).@st.cache_data def long_function(param1, param2): # Perform expensive computation here or # fetch data from the web here return data Cache resourceFunction decorator to cache functions that return global resources (e.g. database connections, ML models).@st.cache_resource def init_model(): # Return a global resource here return pipeline( ""sentiment-analysis"", model=""distilbert-base-uncased-finetuned-sst-2-english"" ) Session stateSession state is a way to share variables between reruns, for each user session.st.session_state['key'] = value Query parametersGet, set, or clear the query parameters that are shown in the browser's URL bar.st.query_params[key] = value st.query_params.clear() Connections and databases Setup your connection Create a connectionConnect to a data source or APIconn = st.connection('pets_db', type='sql') pet_owners = conn.query('select * from pet_owners') st.dataframe(pet_owners) Built-in connections SnowflakeConnectionA connection to Snowflake.conn = st.connection('snowflake') SQLConnectionA connection to a SQL database using SQLAlchemy.conn = st.connection('sql') Build your own connections Connection base classBuild your own connection with BaseConnection.class MyConnection(BaseConnection[myconn.MyConnection]): def _connect(self, **kwargs) -> MyConnection: return myconn.connect(**self._secrets, **kwargs) def query(self, query): return self._instance.query(query) Secrets management Secrets singletonAccess secrets from a local TOML file.key = st.secrets[""OpenAI_key""] Secrets fileSave your secrets in a per-project or per-profile TOML file.OpenAI_key = """" Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration!AuthenticatorA secure authentication module to validate user credentials. Created by @mkhorasani.import streamlit_authenticator as stauth authenticator = stauth.Authenticate( config['credentials'], config['cookie']['name'], config['cookie']['key'], config['cookie']['expiry_days'], config['preauthorized']) WS localStorageA simple synchronous way of accessing localStorage from your app. Created by @gagangoku.from streamlit_ws_localstorage import injectWebsocketCode ret = conn.setLocalStorageVal(key='k1', val='v1') st.write('ret: ' + ret) Streamlit Auth0The fastest way to provide comprehensive login inside Streamlit. Created by @conradbez.from auth0_component import login_button user_info = login_button(clientId, domain = domain) st.write(user_info) Custom Components Declare a componentCreate and register a custom component.st.components.v1.declare_component( ""custom_slider"", ""/frontend"", ) HTMLDisplay an HTML string in an iframe.st.components.v1.html( ""

Foo bar.

"" ) iframeLoad a remote URL in an iframe.st.components.v1.iframe( ""docs.streamlit.io"" ) Utilities and user info User infost.experimental_user returns information about the logged-in user of private apps on Streamlit Community Cloud.if st.experimental_user.email == ""foo@corp.com"": st.write(""Welcome back, "", st.experimental_user.email) else: st.write(""You are not authorized to view this page."") Get helpDisplay object’s doc string, nicely formatted.st.help(st.write) st.help(pd.DataFrame) Render HTMLRenders HTML strings to your app.css = """""" """""" st.html(css) Configuration Configuration fileConfigures the default settings for your app.your-project/ ├── .streamlit/ │ └── config.toml └── your_app.py Set page title, favicon, and moreConfigures the default settings of the page.st.set_page_config( page_title=""My app"", page_icon="":shark:"", ) Developer tools App testing st.testing.v1.AppTestst.testing.v1.AppTest simulates a running Streamlit app for testing.from streamlit.testing.v1 import AppTest at = AppTest.from_file(""streamlit_app.py"") at.secrets[""WORD""] = ""Foobar"" at.run() assert not at.exception at.text_input(""word"").input(""Bazbat"").run() assert at.warning[0].value == ""Try again."" AppTest.from_filest.testing.v1.AppTest.from_file initializes a simulated app from a file.from streamlit.testing.v1 import AppTest at = AppTest.from_file(""streamlit_app.py"") at.run() AppTest.from_stringst.testing.v1.AppTest.from_string initializes a simulated app from a string.from streamlit.testing.v1 import AppTest at = AppTest.from_string(app_script_as_string) at.run() AppTest.from_functionst.testing.v1.AppTest.from_function initializes a simulated app from a function.from streamlit.testing.v1 import AppTest at = AppTest.from_function(app_script_as_callable) at.run() BlockA representation of container elements, including: st.chat_message st.columns st.sidebar st.tabs The main body of the app. # at.sidebar returns a Block at.sidebar.button[0].click().run() assert not at.exception ElementThe base class for representation of all elements, including: st.title st.header st.markdown st.dataframe # at.title returns a sequence of Title # Title inherits from Element assert at.title[0].value == ""My awesome app"" ButtonA representation of st.button and st.form_submit_button.at.button[0].click().run() ChatInputA representation of st.chat_input.at.chat_input[0].set_value(""What is Streamlit?"").run() CheckboxA representation of st.checkbox.at.checkbox[0].check().run() ColorPickerA representation of st.color_picker.at.color_picker[0].pick(""#FF4B4B"").run() DateInputA representation of st.date_input.release_date = datetime.date(2023, 10, 26) at.date_input[0].set_value(release_date).run() MultiselectA representation of st.multiselect.at.multiselect[0].select(""New York"").run() NumberInputA representation of st.number_input.at.number_input[0].increment().run() RadioA representation of st.radio.at.radio[0].set_value(""New York"").run() SelectSliderA representation of st.select_slider.at.select_slider[0].set_range(""A"",""C"").run() SelectboxA representation of st.selectbox.at.selectbox[0].select(""New York"").run() SliderA representation of st.slider.at.slider[0].set_range(2,5).run() TextAreaA representation of st.text_area.at.text_area[0].input(""Streamlit is awesome!"").run() TextInputA representation of st.text_input.at.text_input[0].input(""Streamlit"").run() TimeInputA representation of st.time_input.at.time_input[0].increment().run() ToggleA representation of st.toggle.at.toggle[0].set_value(""True"").run() Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration!Pandas ProfilingPandas profiling component for Streamlit. Created by @okld.df = pd.read_csv(""https://storage.googleapis.com/tf-datasets/titanic/train.csv"") pr = df.profile_report() st_profile_report(pr) Streamlit AceAce editor component for Streamlit. Created by @okld.from streamlit_ace import st_ace content = st_ace() content Streamlit AnalyticsTrack & visualize user interactions with your streamlit app. Created by @jrieke.import streamlit_analytics with streamlit_analytics.track(): st.text_input(""Write something"") Previous: ConceptsNext: Write and magicforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy" https://docs.streamlit.io/develop/tutorials/llms/build-conversational-apps#add-openai-api-key-to-streamlit-secrets,"DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceaddTutorialsremoveExecution flowaddConnect to data sourcesaddMultipage appsaddWork with LLMsremoveBuild a basic LLM chat appBuild an LLM app using LangChainQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Develop/Tutorials/Work with LLMs/Build a basic LLM chat appBuild a basic LLM chat app Introduction The advent of large language models like GPT has revolutionized the ease of developing chat-based applications. Streamlit offers several Chat elements, enabling you to build Graphical User Interfaces (GUIs) for conversational agents or chatbots. Leveraging session state along with these elements allows you to construct anything from a basic chatbot to a more advanced, ChatGPT-like experience using purely Python code. In this tutorial, we'll start by walking through Streamlit's chat elements, st.chat_message and st.chat_input. Then we'll proceed to construct three distinct applications, each showcasing an increasing level of complexity and functionality: First, we'll Build a bot that mirrors your input to get a feel for the chat elements and how they work. We'll also introduce session state and how it can be used to store the chat history. This section will serve as a foundation for the rest of the tutorial. Next, you'll learn how to Build a simple chatbot GUI with streaming. Finally, we'll Build a ChatGPT-like app that leverages session state to remember conversational context, all within less than 50 lines of code. Here's a sneak peek of the LLM-powered chatbot GUI with streaming we'll build in this tutorial: Built with Streamlit 🎈Fullscreen open_in_new Play around with the above demo to get a feel for what we'll build in this tutorial. A few things to note: There's a chat input at the bottom of the screen that's always visible. It contains some placeholder text. You can type in a message and press Enter or click the run button to send it. When you enter a message, it appears as a chat message in the container above. The container is scrollable, so you can scroll up to see previous messages. A default avatar is displayed to your messages' left. The assistant's responses are streamed to the frontend and are displayed with a different default avatar. Before we start building, let's take a closer look at the chat elements we'll use. Chat elements Streamlit offers several commands to help you build conversational apps. These chat elements are designed to be used in conjunction with each other, but you can also use them separately. st.chat_message lets you insert a chat message container into the app so you can display messages from the user or the app. Chat containers can contain other Streamlit elements, including charts, tables, text, and more. st.chat_input lets you display a chat input widget so the user can type in a message. For an overview of the API, check out this video tutorial by Chanin Nantasenamat (@dataprofessor), a Senior Developer Advocate at Streamlit. st.chat_message st.chat_message lets you insert a multi-element chat message container into your app. The returned container can contain any Streamlit element, including charts, tables, text, and more. To add elements to the returned container, you can use with notation. st.chat_message's first parameter is the name of the message author, which can be either ""user"" or ""assistant"" to enable preset styling and avatars, like in the demo above. You can also pass in a custom string to use as the author name. Currently, the name is not shown in the UI but is only set as an accessibility label. For accessibility reasons, you should not use an empty string. Here's an minimal example of how to use st.chat_message to display a welcome message: import streamlit as st with st.chat_message(""user""): st.write(""Hello 👋"") Notice the message is displayed with a default avatar and styling since we passed in ""user"" as the author name. You can also pass in ""assistant"" as the author name to use a different default avatar and styling, or pass in a custom name and avatar. See the API reference for more details. import streamlit as st import numpy as np with st.chat_message(""assistant""): st.write(""Hello human"") st.bar_chart(np.random.randn(30, 3)) Built with Streamlit 🎈Fullscreen open_in_new While we've used the preferred with notation in the above examples, you can also just call methods directly in the returned objects. The below example is equivalent to the one above: import streamlit as st import numpy as np message = st.chat_message(""assistant"") message.write(""Hello human"") message.bar_chart(np.random.randn(30, 3)) So far, we've displayed predefined messages. But what if we want to display messages based on user input? st.chat_input st.chat_input lets you display a chat input widget so the user can type in a message. The returned value is the user's input, which is None if the user hasn't sent a message yet. You can also pass in a default prompt to display in the input widget. Here's an example of how to use st.chat_input to display a chat input widget and show the user's input: import streamlit as st prompt = st.chat_input(""Say something"") if prompt: st.write(f""User has sent the following prompt: {prompt}"") Built with Streamlit 🎈Fullscreen open_in_new Pretty straightforward, right? Now let's combine st.chat_message and st.chat_input to build a bot the mirrors or echoes your input. Build a bot that mirrors your input In this section, we'll build a bot that mirrors or echoes your input. More specifically, the bot will respond to your input with the same message. We'll use st.chat_message to display the user's input and st.chat_input to accept user input. We'll also use session state to store the chat history so we can display it in the chat message container. First, let's think about the different components we'll need to build our bot: Two chat message containers to display messages from the user and the bot, respectively. A chat input widget so the user can type in a message. A way to store the chat history so we can display it in the chat message containers. We can use a list to store the messages, and append to it every time the user or bot sends a message. Each entry in the list will be a dictionary with the following keys: role (the author of the message), and content (the message content). import streamlit as st st.title(""Echo Bot"") # Initialize chat history if ""messages"" not in st.session_state: st.session_state.messages = [] # Display chat messages from history on app rerun for message in st.session_state.messages: with st.chat_message(message[""role""]): st.markdown(message[""content""]) In the above snippet, we've added a title to our app and a for loop to iterate through the chat history and display each message in the chat message container (with the author role and message content). We've also added a check to see if the messages key is in st.session_state. If it's not, we initialize it to an empty list. This is because we'll be adding messages to the list later on, and we don't want to overwrite the list every time the app reruns. Now let's accept user input with st.chat_input, display the user's message in the chat message container, and add it to the chat history. # React to user input if prompt := st.chat_input(""What is up?""): # Display user message in chat message container with st.chat_message(""user""): st.markdown(prompt) # Add user message to chat history st.session_state.messages.append({""role"": ""user"", ""content"": prompt}) We used the := operator to assign the user's input to the prompt variable and checked if it's not None in the same line. If the user has sent a message, we display the message in the chat message container and append it to the chat history. All that's left to do is add the chatbot's responses within the if block. We'll use the same logic as before to display the bot's response (which is just the user's prompt) in the chat message container and add it to the history. response = f""Echo: {prompt}"" # Display assistant response in chat message container with st.chat_message(""assistant""): st.markdown(response) # Add assistant response to chat history st.session_state.messages.append({""role"": ""assistant"", ""content"": response}) Putting it all together, here's the full code for our simple chatbot GUI and the result: View full codeexpand_moreimport streamlit as st st.title(""Echo Bot"") # Initialize chat history if ""messages"" not in st.session_state: st.session_state.messages = [] # Display chat messages from history on app rerun for message in st.session_state.messages: with st.chat_message(message[""role""]): st.markdown(message[""content""]) # React to user input if prompt := st.chat_input(""What is up?""): # Display user message in chat message container st.chat_message(""user"").markdown(prompt) # Add user message to chat history st.session_state.messages.append({""role"": ""user"", ""content"": prompt}) response = f""Echo: {prompt}"" # Display assistant response in chat message container with st.chat_message(""assistant""): st.markdown(response) # Add assistant response to chat history st.session_state.messages.append({""role"": ""assistant"", ""content"": response}) Built with Streamlit 🎈Fullscreen open_in_new While the above example is very simple, it's a good starting point for building more complex conversational apps. Notice how the bot responds instantly to your input. In the next section, we'll add a delay to simulate the bot ""thinking"" before responding. Build a simple chatbot GUI with streaming In this section, we'll build a simple chatbot GUI that responds to user input with a random message from a list of pre-determind responses. In the next section, we'll convert this simple toy example into a ChatGPT-like experience using OpenAI. Just like previously, we still require the same components to build our chatbot. Two chat message containers to display messages from the user and the bot, respectively. A chat input widget so the user can type in a message. And a way to store the chat history so we can display it in the chat message containers. Let's just copy the code from the previous section and add a few tweaks to it. import streamlit as st import random import time st.title(""Simple chat"") # Initialize chat history if ""messages"" not in st.session_state: st.session_state.messages = [] # Display chat messages from history on app rerun for message in st.session_state.messages: with st.chat_message(message[""role""]): st.markdown(message[""content""]) # Accept user input if prompt := st.chat_input(""What is up?""): # Display user message in chat message container with st.chat_message(""user""): st.markdown(prompt) # Add user message to chat history st.session_state.messages.append({""role"": ""user"", ""content"": prompt}) The only difference so far is we've changed the title of our app and added imports for random and time. We'll use random to randomly select a response from a list of responses and time to add a delay to simulate the chatbot ""thinking"" before responding. All that's left to do is add the chatbot's responses within the if block. We'll use a list of responses and randomly select one to display. We'll also add a delay to simulate the chatbot ""thinking"" before responding (or stream its response). Let's make a helper function for this and insert it at the top of our app. # Streamed response emulator def response_generator(): response = random.choice( [ ""Hello there! How can I assist you today?"", ""Hi, human! Is there anything I can help you with?"", ""Do you need help?"", ] ) for word in response.split(): yield word + "" "" time.sleep(0.05) Back to writing the response in our chat interface, we'll use st.write_stream to write out the streamed response with a typewriter effect. # Display assistant response in chat message container with st.chat_message(""assistant""): response = st.write_stream(response_generator()) # Add assistant response to chat history st.session_state.messages.append({""role"": ""assistant"", ""content"": response}) Above, we've added a placeholder to display the chatbot's response. We've also added a for loop to iterate through the response and display it one word at a time. We've added a delay of 0.05 seconds between each word to simulate the chatbot ""thinking"" before responding. Finally, we append the chatbot's response to the chat history. As you've probably guessed, this is a naive implementation of streaming. We'll see how to implement streaming with OpenAI in the next section. Putting it all together, here's the full code for our simple chatbot GUI and the result: View full codeexpand_moreimport streamlit as st import random import time # Streamed response emulator def response_generator(): response = random.choice( [ ""Hello there! How can I assist you today?"", ""Hi, human! Is there anything I can help you with?"", ""Do you need help?"", ] ) for word in response.split(): yield word + "" "" time.sleep(0.05) st.title(""Simple chat"") # Initialize chat history if ""messages"" not in st.session_state: st.session_state.messages = [] # Display chat messages from history on app rerun for message in st.session_state.messages: with st.chat_message(message[""role""]): st.markdown(message[""content""]) # Accept user input if prompt := st.chat_input(""What is up?""): # Add user message to chat history st.session_state.messages.append({""role"": ""user"", ""content"": prompt}) # Display user message in chat message container with st.chat_message(""user""): st.markdown(prompt) # Display assistant response in chat message container with st.chat_message(""assistant""): response = st.write_stream(response_generator()) # Add assistant response to chat history st.session_state.messages.append({""role"": ""assistant"", ""content"": response}) Built with Streamlit 🎈Fullscreen open_in_new Play around with the above demo to get a feel for what we've built. It's a very simple chatbot GUI, but it has all the components of a more sophisticated chatbot. In the next section, we'll see how to build a ChatGPT-like app using OpenAI. Build a ChatGPT-like app Now that you've understood the basics of Streamlit's chat elements, let's make a few tweaks to it to build our own ChatGPT-like app. You'll need to install the OpenAI Python library and get an API key to follow along. Install dependencies First let's install the dependencies we'll need for this section: pip install openai streamlit Add OpenAI API key to Streamlit secrets Next, let's add our OpenAI API key to Streamlit secrets. We do this by creating .streamlit/secrets.toml file in our project directory and adding the following lines to it: # .streamlit/secrets.toml OPENAI_API_KEY = ""YOUR_API_KEY"" Write the app Now let's write the app. We'll use the same code as before, but we'll replace the list of responses with a call to the OpenAI API. We'll also add a few more tweaks to make the app more ChatGPT-like. import streamlit as st from openai import OpenAI st.title(""ChatGPT-like clone"") # Set OpenAI API key from Streamlit secrets client = OpenAI(api_key=st.secrets[""OPENAI_API_KEY""]) # Set a default model if ""openai_model"" not in st.session_state: st.session_state[""openai_model""] = ""gpt-3.5-turbo"" # Initialize chat history if ""messages"" not in st.session_state: st.session_state.messages = [] # Display chat messages from history on app rerun for message in st.session_state.messages: with st.chat_message(message[""role""]): st.markdown(message[""content""]) # Accept user input if prompt := st.chat_input(""What is up?""): # Add user message to chat history st.session_state.messages.append({""role"": ""user"", ""content"": prompt}) # Display user message in chat message container with st.chat_message(""user""): st.markdown(prompt) All that's changed is that we've added a default model to st.session_state and set our OpenAI API key from Streamlit secrets. Here's where it gets interesting. We can replace our emulated stream with the model's responses from OpenAI: # Display assistant response in chat message container with st.chat_message(""assistant""): stream = client.chat.completions.create( model=st.session_state[""openai_model""], messages=[ {""role"": m[""role""], ""content"": m[""content""]} for m in st.session_state.messages ], stream=True, ) response = st.write_stream(stream) st.session_state.messages.append({""role"": ""assistant"", ""content"": response}) Above, we've replaced the list of responses with a call to OpenAI().chat.completions.create. We've set stream=True to stream the responses to the frontend. In the API call, we pass the model name we hardcoded in session state and pass the chat history as a list of messages. We also pass the role and content of each message in the chat history. Finally, OpenAI returns a stream of responses (split into chunks of tokens), which we iterate through and display each chunk. Putting it all together, here's the full code for our ChatGPT-like app and the result: View full codeexpand_morefrom openai import OpenAI import streamlit as st st.title(""ChatGPT-like clone"") client = OpenAI(api_key=st.secrets[""OPENAI_API_KEY""]) if ""openai_model"" not in st.session_state: st.session_state[""openai_model""] = ""gpt-3.5-turbo"" if ""messages"" not in st.session_state: st.session_state.messages = [] for message in st.session_state.messages: with st.chat_message(message[""role""]): st.markdown(message[""content""]) if prompt := st.chat_input(""What is up?""): st.session_state.messages.append({""role"": ""user"", ""content"": prompt}) with st.chat_message(""user""): st.markdown(prompt) with st.chat_message(""assistant""): stream = client.chat.completions.create( model=st.session_state[""openai_model""], messages=[ {""role"": m[""role""], ""content"": m[""content""]} for m in st.session_state.messages ], stream=True, ) response = st.write_stream(stream) st.session_state.messages.append({""role"": ""assistant"", ""content"": response}) Built with Streamlit 🎈Fullscreen open_in_new Congratulations! You've built your own ChatGPT-like app in less than 50 lines of code. We're very excited to see what you'll build with Streamlit's chat elements. Experiment with different models and tweak the code to build your own conversational apps. If you build something cool, let us know on the Forum or check out some other Generative AI apps for inspiration. 🎈Previous: Work with LLMsNext: Build an LLM app using LangChainforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy" https://docs.streamlit.io/develop/api-reference/data/st.column_config/st.column_config.datecolumn#stcolumn_configdatecolumn,"DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceremovePAGE ELEMENTSWrite and magicaddText elementsaddData elementsremovest.dataframest.data_editorst.column_configremoveColumnText columnNumber columnCheckbox columnSelectbox columnDatetime columnDate columnTime columnList columnLink columnImage columnArea chart columnLine chart columnBar chart columnProgress columnst.tablest.metricst.jsonChart elementsaddInput widgetsaddMedia elementsaddLayouts and containersaddChat elementsaddStatus elementsaddThird-party componentsopen_in_newAPPLICATION LOGICNavigation and pagesaddExecution flowaddCaching and stateaddConnections and secretsaddCustom componentsaddUtilitiesaddConfigurationaddTOOLSApp testingaddCommand lineaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Develop/API reference/Data elements/st.column_config/Date columnst.column_config.DateColumnStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeConfigure a date column in st.dataframe or st.data_editor. This is the default column type for date values. This command needs to be used in the column_config parameter of st.dataframe or st.data_editor. When used with st.data_editor, editing will be enabled with a date picker widget. Function signature[source] st.column_config.DateColumn(label=None, *, width=None, help=None, disabled=None, required=None, default=None, format=None, min_value=None, max_value=None, step=None) Parameters label (str or None) The label shown at the top of the column. If None (default), the column name is used. width (""small"", ""medium"", ""large"", or None) The display width of the column. Can be one of ""small"", ""medium"", or ""large"". If None (default), the column will be sized to fit the cell contents. help (str or None) An optional tooltip that gets displayed when hovering over the column label. disabled (bool or None) Whether editing should be disabled for this column. Defaults to False. required (bool or None) Whether edited cells in the column need to have a value. If True, an edited cell can only be submitted if it has a value other than None. Defaults to False. default (datetime.date or None) Specifies the default value in this column when a new row is added by the user. format (str or None) A momentJS format string controlling how times are displayed. See momentJS docs for available formats. If None (default), uses YYYY-MM-DD. min_value (datetime.date or None) The minimum date that can be entered. If None (default), there will be no minimum. max_value (datetime.date or None) The maximum date that can be entered. If None (default), there will be no maximum. step (int or None) The stepping interval in days. If None (default), the step will be 1 day. Examples from datetime import date import pandas as pd import streamlit as st data_df = pd.DataFrame( { ""birthday"": [ date(1980, 1, 1), date(1990, 5, 3), date(1974, 5, 19), date(2001, 8, 17), ] } ) st.data_editor( data_df, column_config={ ""birthday"": st.column_config.DateColumn( ""Birthday"", min_value=date(1900, 1, 1), max_value=date(2005, 1, 1), format=""DD.MM.YYYY"", step=1, ), }, hide_index=True, ) Built with Streamlit 🎈Fullscreen open_in_new Previous: Datetime columnNext: Time columnforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy" https://docs.streamlit.io/knowledge-base/using-streamlit/streamlit-watch-changes-other-modules-importing-app#how-can-i-make-streamlit-watch-for-changes-in-other-modules-im-importing-in-my-app,"DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Knowledge base/FAQ/How can I make Streamlit watch for changes in other modules I'm importing in my app?How can I make Streamlit watch for changes in other modules I'm importing in my app? By default, Streamlit only watches modules contained in the current directory of the main app module. You can track other modules by adding the parent directory of each module to the PYTHONPATH. export PYTHONPATH=$PYTHONPATH:/path/to/module streamlit run your_script.py Previous: Sanity checksNext: What browsers does Streamlit support?forumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy" https://docs.streamlit.io/get-started/fundamentals/advanced-concepts,"DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsremoveBasic conceptsAdvanced conceptsAdditional featuresSummaryFirst stepsaddcodeDevelopConceptsaddAPI referenceaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Get started/Fundamentals/Advanced conceptsAdvanced concepts of Streamlit Now that you know how a Streamlit app runs and handles data, let's talk about being efficient. Caching allows you to save the output of a function so you can skip over it on rerun. Session State lets you save information for each user that is preserved between reruns. This not only allows you to avoid unecessary recalculation, but also allows you to create dynamic pages and handle progressive processes. Caching Caching allows your app to stay performant even when loading data from the web, manipulating large datasets, or performing expensive computations. The basic idea behind caching is to store the results of expensive function calls and return the cached result when the same inputs occur again. This avoids repeated execution of a function with the same input values. To cache a function in Streamlit, you need to apply a caching decorator to it. You have two choices: st.cache_data is the recommended way to cache computations that return data. Use st.cache_data when you use a function that returns a serializable data object (e.g. str, int, float, DataFrame, dict, list). It creates a new copy of the data at each function call, making it safe against mutations and race conditions. The behavior of st.cache_data is what you want in most cases – so if you're unsure, start with st.cache_data and see if it works! st.cache_resource is the recommended way to cache global resources like ML models or database connections. Use st.cache_resource when your function returns unserializable objects that you don’t want to load multiple times. It returns the cached object itself, which is shared across all reruns and sessions without copying or duplication. If you mutate an object that is cached using st.cache_resource, that mutation will exist across all reruns and sessions. Example: @st.cache_data def long_running_function(param1, param2): return … In the above example, long_running_function is decorated with @st.cache_data. As a result, Streamlit notes the following: The name of the function (""long_running_function""). The value of the inputs (param1, param2). The code within the function. Before running the code within long_running_function, Streamlit checks its cache for a previously saved result. If it finds a cached result for the given function and input values, it will return that cached result and not rerun function's code. Otherwise, Streamlit executes the function, saves the result in its cache, and proceeds with the script run. During development, the cache updates automatically as the function code changes, ensuring that the latest changes are reflected in the cache. Streamlit's two caching decorators and their use cases. For more information about the Streamlit caching decorators, their configuration parameters, and their limitations, see Caching. Session State Session State provides a dictionary-like interface where you can save information that is preserved between script reruns. Use st.session_state with key or attribute notation to store and recall values. For example, st.session_state[""my_key""] or st.session_state.my_key. Remember that widgets handle their statefulness all by themselves, so you won't always need to use Session State! What is a session? A session is a single instance of viewing an app. If you view an app from two different tabs in your browser, each tab will have its own session. So each viewer of an app will have a Session State tied to their specific view. Streamlit maintains this session as the user interacts with the app. If the user refreshes their browser page or reloads the URL to the app, their Session State resets and they begin again with a new session. Examples of using Session State Here's a simple app that counts the number of times the page has been run. Every time you click the button, the script will rerun. import streamlit as st if ""counter"" not in st.session_state: st.session_state.counter = 0 st.session_state.counter += 1 st.header(f""This page has run {st.session_state.counter} times."") st.button(""Run it again"") First run: The first time the app runs for each user, Session State is empty. Therefore, a key-value pair is created (""counter"":0). As the script continues, the counter is immediately incremented (""counter"":1) and the result is displayed: ""This page has run 1 times."" When the page has fully rendered, the script has finished and the Streamlit server waits for the user to do something. When that user clicks the button, a rerun begins. Second run: Since ""counter"" is already a key in Session State, it is not reinitialized. As the script continues, the counter is incremented (""counter"":2) and the result is displayed: ""This page has run 2 times."" There are a few common scenarios where Session State is helpful. As demonstrated above, Session State is used when you have a progressive process that you want to build upon from one rerun to the next. Session State can also be used to prevent recalculation, similar to caching. However, the differences are important: Caching associates stored values to specific functions and inputs. Cached values are accessible to all users across all sessions. Session State associates stored values to keys (strings). Values in session state are only available in the single session where it was saved. If you have random number generation in your app, you'd likely use Session State. Here's an example where data is generated randomly at the beginning of each session. By saving this random information in Session State, each user gets different random data when they open the app but it won't keep changing on them as they interact with it. If you select different colors with the picker you'll see that the data does not get re-randomized with each rerun. (If you open the app in a new tab to start a new session, you'll see different data!) import streamlit as st import pandas as pd import numpy as np if ""df"" not in st.session_state: st.session_state.df = pd.DataFrame(np.random.randn(20, 2), columns=[""x"", ""y""]) st.header(""Choose a datapoint color"") color = st.color_picker(""Color"", ""#FF0000"") st.divider() st.scatter_chart(st.session_state.df, x=""x"", y=""y"", color=color) If you are pulling the same data for all users, you'd likely cache a function that retrieves that data. On the other hand, if you pull data specific to a user, such as querying their personal information, you may want to save that in Session State. That way, the queried data is only available in that one session. As mentioned in Basic concepts, Session State is also related to widgets. Widgets are magical and handle statefulness quietly on their own. As an advanced feature however, you can manipulate the value of widgets within your code by assigning keys to them. Any key assigned to a widget becomes a key in Session State tied to the value of the widget. This can be used to manipulate the widget. After you finish understanding the basics of Streamlit, check out our guide on Widget behavior to dig in the details if you're interested. Connections As hinted above, you can use @st.cache_resource to cache connections. This is the most general solution which allows you to use almost any connection from any Python library. However, Streamlit also offers a convenient way to handle some of the most popular connections, like SQL! st.connection takes care of the caching for you so you can enjoy fewer lines of code. Getting data from your database can be as easy as: import streamlit as st conn = st.connection(""my_database"") df = conn.query(""select * from my_table"") st.dataframe(df) Of course, you may be wondering where your username and password go. Streamlit has a convenient mechanism for Secrets management. For now, let's just see how st.connection works very nicely with secrets. In your local project directory, you can save a .streamlit/secrets.toml file. You save your secrets in the toml file and st.connection just uses them! For example, if you have an app file streamlit_app.py your project directory may look like this: your-LOCAL-repository/ ├── .streamlit/ │ └── secrets.toml # Make sure to gitignore this! └── streamlit_app.py For the above SQL example, your secrets.toml file might look like the following: [connections.my_database] type=""sql"" dialect=""mysql"" username=""xxx"" password=""xxx"" host=""example.com"" # IP or URL port=3306 # Port number database=""mydb"" # Database name Since you don't want to commit your secrets.toml file to your repository, you'll need to learn how your host handles secrets when you're ready to publish your app. Each host platform may have a different way for you to pass your secrets. If you use Streamlit Community Cloud for example, each deployed app has a settings menu where you can load your secrets. After you've written an app and are ready to deploy, you can read all about how to Deploy your app on Community Cloud.Previous: Basic conceptsNext: Additional featuresforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy" https://docs.streamlit.io/develop/concepts/architecture/caching#behavior-1,"DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsremoveCOREArchitecture & executionremoveRunning your appStreamlit's architectureThe app chromeCachingSession StateFormsFragmentsWidget behaviorMultipage appsaddApp designaddADDITIONALConnections and secretsaddCustom componentsaddConfiguration and themingaddApp testingaddAPI referenceaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Develop/Concepts/Architecture & execution/Cachingpush_pinNoteDocumentation for the deprecated @st.cache decorator can be found in Optimize performance with st.cache. Caching overview Streamlit runs your script from top to bottom at every user interaction or code change. This execution model makes development super easy. But it comes with two major challenges: Long-running functions run again and again, which slows down your app. Objects get recreated again and again, which makes it hard to persist them across reruns or sessions. But don't worry! Streamlit lets you tackle both issues with its built-in caching mechanism. Caching stores the results of slow function calls, so they only need to run once. This makes your app much faster and helps with persisting objects across reruns. Table of contentsexpand_more Minimal example Basic usage Advanced usage Migrating from st.cache Minimal example To cache a function in Streamlit, you must decorate it with one of two decorators (st.cache_data or st.cache_resource): @st.cache_data def long_running_function(param1, param2): return … In this example, decorating long_running_function with @st.cache_data tells Streamlit that whenever the function is called, it checks two things: The values of the input parameters (in this case, param1 and param2). The code inside the function. If this is the first time Streamlit sees these parameter values and function code, it runs the function and stores the return value in a cache. The next time the function is called with the same parameters and code (e.g., when a user interacts with the app), Streamlit will skip executing the function altogether and return the cached value instead. During development, the cache updates automatically as the function code changes, ensuring that the latest changes are reflected in the cache. As mentioned, there are two caching decorators: st.cache_data is the recommended way to cache computations that return data: loading a DataFrame from CSV, transforming a NumPy array, querying an API, or any other function that returns a serializable data object (str, int, float, DataFrame, array, list, …). It creates a new copy of the data at each function call, making it safe against mutations and race conditions. The behavior of st.cache_data is what you want in most cases – so if you're unsure, start with st.cache_data and see if it works! st.cache_resource is the recommended way to cache global resources like ML models or database connections – unserializable objects that you don't want to load multiple times. Using it, you can share these resources across all reruns and sessions of an app without copying or duplication. Note that any mutations to the cached return value directly mutate the object in the cache (more details below). Streamlit's two caching decorators and their use cases. Basic usage st.cache_data st.cache_data is your go-to command for all functions that return data – whether DataFrames, NumPy arrays, str, int, float, or other serializable types. It's the right command for almost all use cases! Usage Let's look at an example of using st.cache_data. Suppose your app loads the Uber ride-sharing dataset – a CSV file of 50 MB – from the internet into a DataFrame: def load_data(url): df = pd.read_csv(url) # 👈 Download the data return df df = load_data(""https://github.com/plotly/datasets/raw/master/uber-rides-data1.csv"") st.dataframe(df) st.button(""Rerun"") Running the load_data function takes 2 to 30 seconds, depending on your internet connection. (Tip: if you are on a slow connection, use this 5 MB dataset instead). Without caching, the download is rerun each time the app is loaded or with user interaction. Try it yourself by clicking the button we added! Not a great experience… 😕 Now let's add the @st.cache_data decorator on load_data: @st.cache_data # 👈 Add the caching decorator def load_data(url): df = pd.read_csv(url) return df df = load_data(""https://github.com/plotly/datasets/raw/master/uber-rides-data1.csv"") st.dataframe(df) st.button(""Rerun"") Run the app again. You'll notice that the slow download only happens on the first run. Every subsequent rerun should be almost instant! 💨 Behavior How does this work? Let's go through the behavior of st.cache_data step by step: On the first run, Streamlit recognizes that it has never called the load_data function with the specified parameter value (the URL of the CSV file) So it runs the function and downloads the data. Now our caching mechanism becomes active: the returned DataFrame is serialized (converted to bytes) via pickle and stored in the cache (together with the value of the url parameter). On the next run, Streamlit checks the cache for an entry of load_data with the specific url. There is one! So it retrieves the cached object, deserializes it to a DataFrame, and returns it instead of re-running the function and downloading the data again. This process of serializing and deserializing the cached object creates a copy of our original DataFrame. While this copying behavior may seem unnecessary, it's what we want when caching data objects since it effectively prevents mutation and concurrency issues. Read the section “Mutation and concurrency issues"" below to understand this in more detail. priority_highWarningst.cache_data implicitly uses the pickle module, which is known to be insecure. Anything your cached function returns is pickled and stored, then unpickled on retrieval. Ensure your cached functions return trusted values because it is possible to construct malicious pickle data that will execute arbitrary code during unpickling. Never load data that could have come from an untrusted source in an unsafe mode or that could have been tampered with. Only load data you trust. Examples DataFrame transformations In the example above, we already showed how to cache loading a DataFrame. It can also be useful to cache DataFrame transformations such as df.filter, df.apply, or df.sort_values. Especially with large DataFrames, these operations can be slow. @st.cache_data def transform(df): df = df.filter(items=['one', 'three']) df = df.apply(np.sum, axis=0) return df Array computations Similarly, it can make sense to cache computations on NumPy arrays: @st.cache_data def add(arr1, arr2): return arr1 + arr2 Database queries You usually make SQL queries to load data into your app when working with databases. Repeatedly running these queries can be slow, cost money, and degrade the performance of your database. We strongly recommend caching any database queries in your app. See also our guides on connecting Streamlit to different databases for in-depth examples. connection = database.connect() @st.cache_data def query(): return pd.read_sql_query(""SELECT * from table"", connection) starTipYou should set a ttl (time to live) to get new results from your database. If you set st.cache_data(ttl=3600), Streamlit invalidates any cached values after 1 hour (3600 seconds) and runs the cached function again. See details in Controlling cache size and duration. API calls Similarly, it makes sense to cache API calls. Doing so also avoids rate limits. @st.cache_data def api_call(): response = requests.get('https://jsonplaceholder.typicode.com/posts/1') return response.json() Running ML models (inference) Running complex machine learning models can use significant time and memory. To avoid rerunning the same computations over and over, use caching. @st.cache_data def run_model(inputs): return model(inputs) st.cache_resource st.cache_resource is the right command to cache “resources"" that should be available globally across all users, sessions, and reruns. It has more limited use cases than st.cache_data, especially for caching database connections and ML models. Usage As an example for st.cache_resource, let's look at a typical machine learning app. As a first step, we need to load an ML model. We do this with Hugging Face's transformers library: from transformers import pipeline model = pipeline(""sentiment-analysis"") # 👈 Load the model If we put this code into a Streamlit app directly, the app will load the model at each rerun or user interaction. Repeatedly loading the model poses two problems: Loading the model takes time and slows down the app. Each session loads the model from scratch, which takes up a huge amount of memory. Instead, it would make much more sense to load the model once and use that same object across all users and sessions. That's exactly the use case for st.cache_resource! Let's add it to our app and process some text the user entered: from transformers import pipeline @st.cache_resource # 👈 Add the caching decorator def load_model(): return pipeline(""sentiment-analysis"") model = load_model() query = st.text_input(""Your query"", value=""I love Streamlit! 🎈"") if query: result = model(query)[0] # 👈 Classify the query text st.write(result) If you run this app, you'll see that the app calls load_model only once – right when the app starts. Subsequent runs will reuse that same model stored in the cache, saving time and memory! Behavior Using st.cache_resource is very similar to using st.cache_data. But there are a few important differences in behavior: st.cache_resource does not create a copy of the cached return value but instead stores the object itself in the cache. All mutations on the function's return value directly affect the object in the cache, so you must ensure that mutations from multiple sessions do not cause problems. In short, the return value must be thread-safe. priority_highWarningUsing st.cache_resource on objects that are not thread-safe might lead to crashes or corrupted data. Learn more below under Mutation and concurrency issues. Not creating a copy means there's just one global instance of the cached return object, which saves memory, e.g. when using a large ML model. In computer science terms, we create a singleton. Return values of functions do not need to be serializable. This behavior is great for types not serializable by nature, e.g., database connections, file handles, or threads. Caching these objects with st.cache_data is not possible. Examples Database connections st.cache_resource is useful for connecting to databases. Usually, you're creating a connection object that you want to reuse globally for every query. Creating a new connection object at each run would be inefficient and might lead to connection errors. That's exactly what st.cache_resource can do, e.g., for a Postgres database: @st.cache_resource def init_connection(): host = ""hh-pgsql-public.ebi.ac.uk"" database = ""pfmegrnargs"" user = ""reader"" password = ""NWDMCE5xdipIjRrp"" return psycopg2.connect(host=host, database=database, user=user, password=password) conn = init_connection() Of course, you can do the same for any other database. Have a look at our guides on how to connect Streamlit to databases for in-depth examples. Loading ML models Your app should always cache ML models, so they are not loaded into memory again for every new session. See the example above for how this works with 🤗 Hugging Face models. You can do the same thing for PyTorch, TensorFlow, etc. Here's an example for PyTorch: @st.cache_resource def load_model(): model = torchvision.models.resnet50(weights=ResNet50_Weights.DEFAULT) model.eval() return model model = load_model() Deciding which caching decorator to use The sections above showed many common examples for each caching decorator. But there are edge cases for which it's less trivial to decide which caching decorator to use. Eventually, it all comes down to the difference between “data"" and “resource"": Data are serializable objects (objects that can be converted to bytes via pickle) that you could easily save to disk. Imagine all the types you would usually store in a database or on a file system – basic types like str, int, and float, but also arrays, DataFrames, images, or combinations of these types (lists, tuples, dicts, and so on). Resources are unserializable objects that you usually would not save to disk or a database. They are often more complex, non-permanent objects like database connections, ML models, file handles, threads, etc. From the types listed above, it should be obvious that most objects in Python are “data."" That's also why st.cache_data is the correct command for almost all use cases. st.cache_resource is a more exotic command that you should only use in specific situations. Or if you're lazy and don't want to think too much, look up your use case or return type in the table below 😉: Use caseTypical return typesCaching decoratorReading a CSV file with pd.read_csvpandas.DataFramest.cache_dataReading a text filestr, list of strst.cache_dataTransforming pandas dataframespandas.DataFrame, pandas.Seriesst.cache_dataComputing with numpy arraysnumpy.ndarrayst.cache_dataSimple computations with basic typesstr, int, float, …st.cache_dataQuerying a databasepandas.DataFramest.cache_dataQuerying an APIpandas.DataFrame, str, dictst.cache_dataRunning an ML model (inference)pandas.DataFrame, str, int, dict, listst.cache_dataCreating or processing imagesPIL.Image.Image, numpy.ndarrayst.cache_dataCreating chartsmatplotlib.figure.Figure, plotly.graph_objects.Figure, altair.Chartst.cache_data (but some libraries require st.cache_resource, since the chart object is not serializable – make sure not to mutate the chart after creation!)Loading ML modelstransformers.Pipeline, torch.nn.Module, tensorflow.keras.Modelst.cache_resourceInitializing database connectionspyodbc.Connection, sqlalchemy.engine.base.Engine, psycopg2.connection, mysql.connector.MySQLConnection, sqlite3.Connectionst.cache_resourceOpening persistent file handles_io.TextIOWrapperst.cache_resourceOpening persistent threadsthreading.threadst.cache_resource Advanced usage Controlling cache size and duration If your app runs for a long time and constantly caches functions, you might run into two problems: The app runs out of memory because the cache is too large. Objects in the cache become stale, e.g. because you cached old data from a database. You can combat these problems with the ttl and max_entries parameters, which are available for both caching decorators. The ttl (time-to-live) parameter ttl sets a time to live on a cached function. If that time is up and you call the function again, the app will discard any old, cached values, and the function will be rerun. The newly computed value will then be stored in the cache. This behavior is useful for preventing stale data (problem 2) and the cache from growing too large (problem 1). Especially when pulling data from a database or API, you should always set a ttl so you are not using old data. Here's an example: @st.cache_data(ttl=3600) # 👈 Cache data for 1 hour (=3600 seconds) def get_api_data(): data = api.get(...) return data starTipYou can also set ttl values using timedelta, e.g., ttl=datetime.timedelta(hours=1). The max_entries parameter max_entries sets the maximum number of entries in the cache. An upper bound on the number of cache entries is useful for limiting memory (problem 1), especially when caching large objects. The oldest entry will be removed when a new entry is added to a full cache. Here's an example: @st.cache_data(max_entries=1000) # 👈 Maximum 1000 entries in the cache def get_large_array(seed): np.random.seed(seed) arr = np.random.rand(100000) return arr Customizing the spinner By default, Streamlit shows a small loading spinner in the app when a cached function is running. You can modify it easily with the show_spinner parameter, which is available for both caching decorators: @st.cache_data(show_spinner=False) # 👈 Disable the spinner def get_api_data(): data = api.get(...) return data @st.cache_data(show_spinner=""Fetching data from API..."") # 👈 Use custom text for spinner def get_api_data(): data = api.get(...) return data Excluding input parameters In a cached function, all input parameters must be hashable. Let's quickly explain why and what it means. When the function is called, Streamlit looks at its parameter values to determine if it was cached before. Therefore, it needs a reliable way to compare the parameter values across function calls. Trivial for a string or int – but complex for arbitrary objects! Streamlit uses hashing to solve that. It converts the parameter to a stable key and stores that key. At the next function call, it hashes the parameter again and compares it with the stored hash key. Unfortunately, not all parameters are hashable! E.g., you might pass an unhashable database connection or ML model to your cached function. In this case, you can exclude input parameters from caching. Simply prepend the parameter name with an underscore (e.g., _param1), and it will not be used for caching. Even if it changes, Streamlit will return a cached result if all the other parameters match up. Here's an example: @st.cache_data def fetch_data(_db_connection, num_rows): # 👈 Don't hash _db_connection data = _db_connection.fetch(num_rows) return data connection = init_connection() fetch_data(connection, 10) But what if you want to cache a function that takes an unhashable parameter? For example, you might want to cache a function that takes an ML model as input and returns the layer names of that model. Since the model is the only input parameter, you cannot exclude it from caching. In this case you can use the hash_funcs parameter to specify a custom hashing function for the model. The hash_funcs parameter As described above, Streamlit's caching decorators hash the input parameters and cached function's signature to determine whether the function has been run before and has a return value stored (""cache hit"") or needs to be run (""cache miss""). Input parameters that are not hashable by Streamlit's hashing implementation can be ignored by prepending an underscore to their name. But there two rare cases where this is undesirable. i.e. where you want to hash the parameter that Streamlit is unable to hash: When Streamlit's hashing mechanism fails to hash a parameter, resulting in a UnhashableParamError being raised. When you want to override Streamlit's default hashing mechanism for a parameter. Let's discuss each of these cases in turn with examples. Example 1: Hashing a custom class Streamlit does not know how to hash custom classes. If you pass a custom class to a cached function, Streamlit will raise a UnhashableParamError. For example, let's define a custom class MyCustomClass that accepts an initial integer score. Let's also define a cached function multiply_score that multiplies the score by a multiplier: import streamlit as st class MyCustomClass: def __init__(self, initial_score: int): self.my_score = initial_score @st.cache_data def multiply_score(obj: MyCustomClass, multiplier: int) -> int: return obj.my_score * multiplier initial_score = st.number_input(""Enter initial score"", value=15) score = MyCustomClass(initial_score) multiplier = 2 st.write(multiply_score(score, multiplier)) If you run this app, you'll see that Streamlit raises a UnhashableParamError since it does not know how to hash MyCustomClass: UnhashableParamError: Cannot hash argument 'obj' (of type __main__.MyCustomClass) in 'multiply_score'. To fix this, we can use the hash_funcs parameter to tell Streamlit how to hash MyCustomClass. We do this by passing a dictionary to hash_funcs that maps the name of the parameter to a hash function. The choice of hash function is up to the developer. In this case, let's define a custom hash function hash_func that takes the custom class as input and returns the score. We want the score to be the unique identifier of the object, so we can use it to deterministically hash the object: import streamlit as st class MyCustomClass: def __init__(self, initial_score: int): self.my_score = initial_score def hash_func(obj: MyCustomClass) -> int: return obj.my_score # or any other value that uniquely identifies the object @st.cache_data(hash_funcs={MyCustomClass: hash_func}) def multiply_score(obj: MyCustomClass, multiplier: int) -> int: return obj.my_score * multiplier initial_score = st.number_input(""Enter initial score"", value=15) score = MyCustomClass(initial_score) multiplier = 2 st.write(multiply_score(score, multiplier)) Now if you run the app, you'll see that Streamlit no longer raises a UnhashableParamError and the app runs as expected. Let's now consider the case where multiply_score is an attribute of MyCustomClass and we want to hash the entire object: import streamlit as st class MyCustomClass: def __init__(self, initial_score: int): self.my_score = initial_score @st.cache_data def multiply_score(self, multiplier: int) -> int: return self.my_score * multiplier initial_score = st.number_input(""Enter initial score"", value=15) score = MyCustomClass(initial_score) multiplier = 2 st.write(score.multiply_score(multiplier)) If you run this app, you'll see that Streamlit raises a UnhashableParamError since it cannot hash the argument 'self' (of type __main__.MyCustomClass) in 'multiply_score'. A simple fix here could be to use Python's hash() function to hash the object: import streamlit as st class MyCustomClass: def __init__(self, initial_score: int): self.my_score = initial_score @st.cache_data(hash_funcs={""__main__.MyCustomClass"": lambda x: hash(x.my_score)}) def multiply_score(self, multiplier: int) -> int: return self.my_score * multiplier initial_score = st.number_input(""Enter initial score"", value=15) score = MyCustomClass(initial_score) multiplier = 2 st.write(score.multiply_score(multiplier)) Above, the hash function is defined as lambda x: hash(x.my_score). This creates a hash based on the my_score attribute of the MyCustomClass instance. As long as my_score remains the same, the hash remains the same. Thus, the result of multiply_score can be retrieved from the cache without recomputation. As an astute Pythonista, you may have been tempted to use Python's id() function to hash the object like so: import streamlit as st class MyCustomClass: def __init__(self, initial_score: int): self.my_score = initial_score @st.cache_data(hash_funcs={""__main__.MyCustomClass"": id}) def multiply_score(self, multiplier: int) -> int: return self.my_score * multiplier initial_score = st.number_input(""Enter initial score"", value=15) score = MyCustomClass(initial_score) multiplier = 2 st.write(score.multiply_score(multiplier)) If you run the app, you'll notice that Streamlit recomputes multiply_score each time even if my_score hasn't changed! Puzzled? In Python, id() returns the identity of an object, which is unique and constant for the object during its lifetime. This means that even if the my_score value is the same between two instances of MyCustomClass, id() will return different values for these two instances, leading to different hash values. As a result, Streamlit considers these two different instances as needing separate cached values, thus it recomputes the multiply_score each time even if my_score hasn't changed. This is why we discourage using it as hash func, and instead encourage functions that return deterministic, true hash values. That said, if you know what you're doing, you can use id() as a hash function. Just be aware of the consequences. For example, id is often the correct hash func when you're passing the result of an @st.cache_resource function as the input param to another cached function. There's a whole class of object types that aren’t otherwise hashable. Example 2: Hashing a Pydantic model Let's consider another example where we want to hash a Pydantic model: import streamlit as st from pydantic import BaseModel class Person(BaseModel): name: str @st.cache_data def identity(person: Person): return person person = identity(Person(name=""Lee"")) st.write(f""The person is {person.name}"") Above, we define a custom class Person using Pydantic's BaseModel with a single attribute name. We also define an identity function which accepts an instance of Person as an arg and returns it without modification. This function is intended to cache the result, therefore, if called multiple times with the same Person instance, it won't recompute but return the cached instance. If you run the app, however, you'll run into a UnhashableParamError: Cannot hash argument 'person' (of type __main__.Person) in 'identity'. error. This is because Streamlit does not know how to hash the Person class. To fix this, we can use the hash_funcs kwarg to tell Streamlit how to hash Person. In the version below, we define a custom hash function hash_func that takes the Person instance as input and returns the name attribute. We want the name to be the unique identifier of the object, so we can use it to deterministically hash the object: import streamlit as st from pydantic import BaseModel class Person(BaseModel): name: str @st.cache_data(hash_funcs={Person: lambda p: p.name}) def identity(person: Person): return person person = identity(Person(name=""Lee"")) st.write(f""The person is {person.name}"") Example 3: Hashing a ML model There may be cases where you want to pass your favorite machine learning model to a cached function. For example, let's say you want to pass a TensorFlow model to a cached function, based on what model the user selects in the app. You might try something like this: import streamlit as st import tensorflow as tf @st.cache_resource def load_base_model(option): if option == 1: return tf.keras.applications.ResNet50(include_top=False, weights=""imagenet"") else: return tf.keras.applications.MobileNetV2(include_top=False, weights=""imagenet"") @st.cache_resource def load_layers(base_model): return [layer.name for layer in base_model.layers] option = st.radio(""Model 1 or 2"", [1, 2]) base_model = load_base_model(option) layers = load_layers(base_model) st.write(layers) In the above app, the user can select one of two models. Based on the selection, the app loads the corresponding model and passes it to load_layers. This function then returns the names of the layers in the model. If you run the app, you'll see that Streamlit raises a UnhashableParamError since it cannot hash the argument 'base_model' (of type keras.engine.functional.Functional) in 'load_layers'. If you disable hashing for base_model by prepending an underscore to its name, you'll observe that regardless of which base model is chosen, the layers displayed are same. This subtle bug is due to the fact that the load_layers function is not re-run when the base model changes. This is because Streamlit does not hash the base_model argument, so it does not know that the function needs to be re-run when the base model changes. To fix this, we can use the hash_funcs kwarg to tell Streamlit how to hash the base_model argument. In the version below, we define a custom hash function hash_func: Functional: lambda x: x.name. Our choice of hash func is informed by our knowledge that the name attribute of a Functional object or model uniquely identifies it. As long as the name attribute remains the same, the hash remains the same. Thus, the result of load_layers can be retrieved from the cache without recomputation. import streamlit as st import tensorflow as tf from keras.engine.functional import Functional @st.cache_resource def load_base_model(option): if option == 1: return tf.keras.applications.ResNet50(include_top=False, weights=""imagenet"") else: return tf.keras.applications.MobileNetV2(include_top=False, weights=""imagenet"") @st.cache_resource(hash_funcs={Functional: lambda x: x.name}) def load_layers(base_model): return [layer.name for layer in base_model.layers] option = st.radio(""Model 1 or 2"", [1, 2]) base_model = load_base_model(option) layers = load_layers(base_model) st.write(layers) In the above case, we could also have used hash_funcs={Functional: id} as the hash function. This is because id is often the correct hash func when you're passing the result of an @st.cache_resource function as the input param to another cached function. Example 4: Overriding Streamlit's default hashing mechanism Let's consider another example where we want to override Streamlit's default hashing mechanism for a pytz-localized datetime object: from datetime import datetime import pytz import streamlit as st tz = pytz.timezone(""Europe/Berlin"") @st.cache_data def load_data(dt): return dt now = datetime.now() st.text(load_data(dt=now)) now_tz = tz.localize(datetime.now()) st.text(load_data(dt=now_tz)) It may be surprising to see that although now and now_tz are of the same type, Streamlit does not how to hash now_tz and raises a UnhashableParamError. In this case, we can override Streamlit's default hashing mechanism for datetime objects by passing a custom hash function to the hash_funcs kwarg: from datetime import datetime import pytz import streamlit as st tz = pytz.timezone(""Europe/Berlin"") @st.cache_data(hash_funcs={datetime: lambda x: x.strftime(""%a %d %b %Y, %I:%M%p"")}) def load_data(dt): return dt now = datetime.now() st.text(load_data(dt=now)) now_tz = tz.localize(datetime.now()) st.text(load_data(dt=now_tz)) Let's now consider a case where we want to override Streamlit's default hashing mechanism for NumPy arrays. While Streamlit natively hashes Pandas and NumPy objects, there may be cases where you want to override Streamlit's default hashing mechanism for these objects. For example, let's say we create a cache-decorated show_data function that accepts a NumPy array and returns it without modification. In the bellow app, data = df[""str""].unique() (which is a NumPy array) is passed to the show_data function. import time import numpy as np import pandas as pd import streamlit as st @st.cache_data def get_data(): df = pd.DataFrame({""num"": [112, 112, 2, 3], ""str"": [""be"", ""a"", ""be"", ""c""]}) return df @st.cache_data def show_data(data): time.sleep(2) # This makes the function take 2s to run return data df = get_data() data = df[""str""].unique() st.dataframe(show_data(data)) st.button(""Re-run"") Since data is always the same, we expect the show_data function to return the cached value. However, if you run the app, and click the Re-run button, you'll notice that the show_data function is re-run each time. We can assume this behavior is a consequence of Streamlit's default hashing mechanism for NumPy arrays. To work around this, let's define a custom hash function hash_func that takes a NumPy array as input and returns a string representation of the array: import time import numpy as np import pandas as pd import streamlit as st @st.cache_data def get_data(): df = pd.DataFrame({""num"": [112, 112, 2, 3], ""str"": [""be"", ""a"", ""be"", ""c""]}) return df @st.cache_data(hash_funcs={np.ndarray: str}) def show_data(data): time.sleep(2) # This makes the function take 2s to run return data df = get_data() data = df[""str""].unique() st.dataframe(show_data(data)) st.button(""Re-run"") Now if you run the app, and click the Re-run button, you'll notice that the show_data function is no longer re-run each time. It's important to note here that our choice of hash function was very naive and not necessarily the best choice. For example, if the NumPy array is large, converting it to a string representation may be expensive. In such cases, it is up to you as the developer to define what a good hash function is for your use case. Static elements Since version 1.16.0, cached functions can contain Streamlit commands! For example, you can do this: @st.cache_data def get_api_data(): data = api.get(...) st.success(""Fetched data from API!"") # 👈 Show a success message return data As we know, Streamlit only runs this function if it hasn't been cached before. On this first run, the st.success message will appear in the app. But what happens on subsequent runs? It still shows up! Streamlit realizes that there is an st. command inside the cached function, saves it during the first run, and replays it on subsequent runs. Replaying static elements works for both caching decorators. You can also use this functionality to cache entire parts of your UI: @st.cache_data def show_data(): st.header(""Data analysis"") data = api.get(...) st.success(""Fetched data from API!"") st.write(""Here is a plot of the data:"") st.line_chart(data) st.write(""And here is the raw data:"") st.dataframe(data) Input widgets You can also use interactive input widgets like st.slider or st.text_input in cached functions. Widget replay is an experimental feature at the moment. To enable it, you need to set the experimental_allow_widgets parameter: @st.cache_data(experimental_allow_widgets=True) # 👈 Set the parameter def get_data(): num_rows = st.slider(""Number of rows to get"") # 👈 Add a slider data = api.get(..., num_rows) return data Streamlit treats the slider like an additional input parameter to the cached function. If you change the slider position, Streamlit will see if it has already cached the function for this slider value. If yes, it will return the cached value. If not, it will rerun the function using the new slider value. Using widgets in cached functions is extremely powerful because it lets you cache entire parts of your app. But it can be dangerous! Since Streamlit treats the widget value as an additional input parameter, it can easily lead to excessive memory usage. Imagine your cached function has five sliders and returns a 100 MB DataFrame. Then we'll add 100 MB to the cache for every permutation of these five slider values – even if the sliders do not influence the returned data! These additions can make your cache explode very quickly. Please be aware of this limitation if you use widgets in cached functions. We recommend using this feature only for isolated parts of your UI where the widgets directly influence the cached return value. priority_highWarningSupport for widgets in cached functions is experimental. We may change or remove it anytime without warning. Please use it with care! push_pinNoteTwo widgets are currently not supported in cached functions: st.file_uploader and st.camera_input. We may support them in the future. Feel free to open a GitHub issue if you need them! Dealing with large data As we explained, you should cache data objects with st.cache_data. But this can be slow for extremely large data, e.g., DataFrames or arrays with >100 million rows. That's because of the copying behavior of st.cache_data: on the first run, it serializes the return value to bytes and deserializes it on subsequent runs. Both operations take time. If you're dealing with extremely large data, it can make sense to use st.cache_resource instead. It does not create a copy of the return value via serialization/deserialization and is almost instant. But watch out: any mutation to the function's return value (such as dropping a column from a DataFrame or setting a value in an array) directly manipulates the object in the cache. You must ensure this doesn't corrupt your data or lead to crashes. See the section on Mutation and concurrency issues below. When benchmarking st.cache_data on pandas DataFrames with four columns, we found that it becomes slow when going beyond 100 million rows. The table shows runtimes for both caching decorators at different numbers of rows (all with four columns): 10M rows50M rows100M rows200M rowsst.cache_dataFirst run*0.4 s3 s14 s28 sSubsequent runs0.2 s1 s2 s7 sst.cache_resourceFirst run*0.01 s0.1 s0.2 s1 sSubsequent runs0 s0 s0 s0 s *For the first run, the table only shows the overhead time of using the caching decorator. It does not include the runtime of the cached function itself. Mutation and concurrency issues In the sections above, we talked a lot about issues when mutating return objects of cached functions. This topic is complicated! But it's central to understanding the behavior differences between st.cache_data and st.cache_resource. So let's dive in a bit deeper. First, we should clearly define what we mean by mutations and concurrency: By mutations, we mean any changes made to a cached function's return value after that function has been called. I.e. something like this: @st.cache_data def create_list(): l = [1, 2, 3] l = create_list() # 👈 Call the function l[0] = 2 # 👈 Mutate its return value By concurrency, we mean that multiple sessions can cause these mutations at the same time. Streamlit is a web framework that needs to handle many users and sessions connecting to an app. If two people view an app at the same time, they will both cause the Python script to rerun, which may manipulate cached return objects at the same time – concurrently. Mutating cached return objects can be dangerous. It can lead to exceptions in your app and even corrupt your data (which can be worse than a crashed app!). Below, we'll first explain the copying behavior of st.cache_data and show how it can avoid mutation issues. Then, we'll show how concurrent mutations can lead to data corruption and how to prevent it. Copying behavior st.cache_data creates a copy of the cached return value each time the function is called. This avoids most mutations and concurrency issues. To understand it in detail, let's go back to the Uber ridesharing example from the section on st.cache_data above. We are making two modifications to it: We are using st.cache_resource instead of st.cache_data. st.cache_resource does not create a copy of the cached object, so we can see what happens without the copying behavior. After loading the data, we manipulate the returned DataFrame (in place!) by dropping the column ""Lat"". Here's the code: @st.cache_resource # 👈 Turn off copying behavior def load_data(url): df = pd.read_csv(url) return df df = load_data(""https://raw.githubusercontent.com/plotly/datasets/master/uber-rides-data1.csv"") st.dataframe(df) df.drop(columns=['Lat'], inplace=True) # 👈 Mutate the dataframe inplace st.button(""Rerun"") Let's run it and see what happens! The first run should work fine. But in the second run, you see an exception: KeyError: ""['Lat'] not found in axis"". Why is that happening? Let's go step by step: On the first run, Streamlit runs load_data and stores the resulting DataFrame in the cache. Since we're using st.cache_resource, it does not create a copy but stores the original DataFrame. Then we drop the column ""Lat"" from the DataFrame. Note that this is dropping the column from the original DataFrame stored in the cache. We are manipulating it! On the second run, Streamlit returns that exact same manipulated DataFrame from the cache. It does not have the column ""Lat"" anymore! So our call to df.drop results in an exception. Pandas cannot drop a column that doesn't exist. The copying behavior of st.cache_data prevents this kind of mutation error. Mutations can only affect a specific copy and not the underlying object in the cache. The next rerun will get its own, unmutated copy of the DataFrame. You can try it yourself, just replace st.cache_resource with st.cache_data above, and you'll see that everything works. Because of this copying behavior, st.cache_data is the recommended way to cache data transforms and computations – anything that returns a serializable object. Concurrency issues Now let's look at what can happen when multiple users concurrently mutate an object in the cache. Let's say you have a function that returns a list. Again, we are using st.cache_resource to cache it so that we are not creating a copy: @st.cache_resource def create_list(): l = [1, 2, 3] return l l = create_list() first_list_value = l[0] l[0] = first_list_value + 1 st.write(""l[0] is:"", l[0]) Let's say user A runs the app. They will see the following output: l[0] is: 2 Let's say another user, B, visits the app right after. In contrast to user A, they will see the following output: l[0] is: 3 Now, user A reruns the app immediately after user B. They will see the following output: l[0] is: 4 What is happening here? Why are all outputs different? When user A visits the app, create_list() is called, and the list [1, 2, 3] is stored in the cache. This list is then returned to user A. The first value of the list, 1, is assigned to first_list_value , and l[0] is changed to 2. When user B visits the app, create_list() returns the mutated list from the cache: [2, 2, 3]. The first value of the list, 2, is assigned to first_list_value and l[0] is changed to 3. When user A reruns the app, create_list() returns the mutated list again: [3, 2, 3]. The first value of the list, 3, is assigned to first_list_value, and l[0] is changed to 4. If you think about it, this makes sense. Users A and B use the same list object (the one stored in the cache). And since the list object is mutated, user A's change to the list object is also reflected in user B's app. This is why you must be careful about mutating objects cached with st.cache_resource, especially when multiple users access the app concurrently. If we had used st.cache_data instead of st.cache_resource, the app would have copied the list object for each user, and the above example would have worked as expected – users A and B would have both seen: l[0] is: 2 push_pinNoteThis toy example might seem benign. But data corruption can be extremely dangerous! Imagine we had worked with the financial records of a large bank here. You surely don't want to wake up with less money on your account just because someone used the wrong caching decorator 😉 Migrating from st.cache We introduced the caching commands described above in Streamlit 1.18.0. Before that, we had one catch-all command st.cache. Using it was often confusing, resulted in weird exceptions, and was slow. That's why we replaced st.cache with the new commands in 1.18.0 (read more in this blog post). The new commands provide a more intuitive and efficient way to cache your data and resources and are intended to replace st.cache in all new development. If your app is still using st.cache, don't despair! Here are a few notes on migrating: Streamlit will show a deprecation warning if your app uses st.cache. We will not remove st.cache soon, so you don't need to worry about your 2-year-old app breaking. But we encourage you to try the new commands going forward – they will be way less annoying! Switching code to the new commands should be easy in most cases. To decide whether to use st.cache_data or st.cache_resource, read Deciding which caching decorator to use. Streamlit will also recognize common use cases and show hints right in the deprecation warnings. Most parameters from st.cache are also present in the new commands, with a few exceptions: allow_output_mutation does not exist anymore. You can safely delete it. Just make sure you use the right caching command for your use case. suppress_st_warning does not exist anymore. You can safely delete it. Cached functions can now contain Streamlit commands and will replay them. If you want to use widgets inside cached functions, set experimental_allow_widgets=True. See Input widgets for an example. If you have any questions or issues during the migration process, please contact us on the forum, and we will be happy to assist you. 🎈Previous: The app chromeNext: Optimize performance with st.cacheforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy" https://docs.streamlit.io/develop/api-reference/app-testing/testing-element-classes#buttonset_value,"DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceremovePAGE ELEMENTSWrite and magicaddText elementsaddData elementsaddChart elementsaddInput widgetsaddMedia elementsaddLayouts and containersaddChat elementsaddStatus elementsaddThird-party componentsopen_in_newAPPLICATION LOGICNavigation and pagesaddExecution flowaddCaching and stateaddConnections and secretsaddCustom componentsaddUtilitiesaddConfigurationaddTOOLSApp testingremovest.testing.v1.AppTestTesting element classesCommand lineaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Develop/API reference/App testing/Testing element classesTesting element classes st.testing.v1.element_tree.Block The Block class has the same methods and attributes as AppTest. A Block instance represents a container of elements just as AppTest represents the entire app. For example, Block.button will produce a WidgetList of Button in the same manner as AppTest.button. ChatMessage, Column, and Tab all inherit from Block. For all container classes, parameters of the original element can be obtained as properties. For example, ChatMessage.avatar and Tab.label. st.testing.v1.element_tree.ElementStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeElement base class for testing. This class's methods and attributes are universal for all elements implemented in testing. For example, Caption, Code, Text, and Title inherit from Element. All widget classes also inherit from Element, but have additional methods specific to each widget type. See the AppTest class for the full list of supported elements. For all element classes, parameters of the original element can be obtained as properties. For example, Button.label, Caption.help, and Toast.icon. Class description[source] st.testing.v1.element_tree.Element(proto, root) Methods run(*, timeout=None) Run the AppTest script which contains the element. Attributes value The value or contents of the element. st.testing.v1.element_tree.ButtonStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.button and st.form_submit_button. Class description[source] st.testing.v1.element_tree.Button(proto, root) Methods click() Set the value of the button to True. run(*, timeout=None) Run the AppTest script which contains the element. set_value(v) Set the value of the button. Attributes value The value of the button. (bool) st.testing.v1.element_tree.ChatInputStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.chat_input. Class description[source] st.testing.v1.element_tree.ChatInput(proto, root) Methods run(*, timeout=None) Run the AppTest script which contains the element. set_value(v) Set the value of the widget. Attributes value The value of the widget. (str) st.testing.v1.element_tree.CheckboxStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.checkbox. Class description[source] st.testing.v1.element_tree.Checkbox(proto, root) Methods check() Set the value of the widget to True. run(*, timeout=None) Run the AppTest script which contains the element. set_value(v) Set the value of the widget. uncheck() Set the value of the widget to False. Attributes value The value of the widget. (bool) st.testing.v1.element_tree.ColorPickerStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.color_picker. Class description[source] st.testing.v1.element_tree.ColorPicker(proto, root) Methods pick(v) Set the value of the widget as a hex string. May omit the ""#"" prefix. run(*, timeout=None) Run the AppTest script which contains the element. set_value(v) Set the value of the widget as a hex string. Attributes value The currently selected value as a hex string. (str) st.testing.v1.element_tree.DateInputStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.date_input. Class description[source] st.testing.v1.element_tree.DateInput(proto, root) Methods run(*, timeout=None) Run the AppTest script which contains the element. set_value(v) Set the value of the widget. Attributes value The value of the widget. (date or Tuple of date) st.testing.v1.element_tree.MultiselectStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.multiselect. Class description[source] st.testing.v1.element_tree.Multiselect(proto, root) Methods run(*, timeout=None) Run the AppTest script which contains the element. select(v) Add a selection to the widget. Do nothing if the value is already selected. If testing a multiselect widget with repeated options, use set_value instead. set_value(v) Set the value of the multiselect widget. (list) unselect(v) Remove a selection from the widget. Do nothing if the value is not already selected. If a value is selected multiple times, the first instance is removed. Attributes format_func The widget's formatting function for displaying options. (callable) indices The indices of the currently selected values from the options. (list) value The currently selected values from the options. (list) st.testing.v1.element_tree.NumberInputStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.number_input. Class description[source] st.testing.v1.element_tree.NumberInput(proto, root) Methods decrement() Decrement the st.number_input widget as if the user clicked ""-"". increment() Increment the st.number_input widget as if the user clicked ""+"". run(*, timeout=None) Run the AppTest script which contains the element. set_value(v) Set the value of the st.number_input widget. Attributes value Get the current value of the st.number_input widget. st.testing.v1.element_tree.RadioStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.radio. Class description[source] st.testing.v1.element_tree.Radio(proto, root) Methods run(*, timeout=None) Run the AppTest script which contains the element. set_value(v) Set the selection by value. Attributes format_func The widget's formatting function for displaying options. (callable) index The index of the current selection. (int) value The currently selected value from the options. (Any) st.testing.v1.element_tree.SelectSliderStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.select_slider. Class description[source] st.testing.v1.element_tree.SelectSlider(proto, root) Methods run(*, timeout=None) Run the AppTest script which contains the element. set_range(lower, upper) Set the ranged selection by values. set_value(v) Set the (single) selection by value. Attributes format_func The widget's formatting function for displaying options. (callable) value The currently selected value or range. (Any or Sequence of Any) st.testing.v1.element_tree.SelectboxStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.selectbox. Class description[source] st.testing.v1.element_tree.Selectbox(proto, root) Methods run(*, timeout=None) Run the AppTest script which contains the element. select(v) Set the selection by value. select_index(index) Set the selection by index. set_value(v) Set the selection by value. Attributes format_func The widget's formatting function for displaying options. (callable) index The index of the current selection. (int) value The currently selected value from the options. (Any) st.testing.v1.element_tree.SliderStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.slider. Class description[source] st.testing.v1.element_tree.Slider(proto, root) Methods run(*, timeout=None) Run the AppTest script which contains the element. set_range(lower, upper) Set the ranged value of the slider. set_value(v) Set the (single) value of the slider. Attributes value The currently selected value or range. (Any or Sequence of Any) st.testing.v1.element_tree.TextAreaStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.text_area. Class description[source] st.testing.v1.element_tree.TextArea(proto, root) Methods input(v) Set the value of the widget only if the value does not exceed the maximum allowed characters. run(*, timeout=None) Run the AppTest script which contains the element. set_value(v) Set the value of the widget. Attributes value The current value of the widget. (str) st.testing.v1.element_tree.TextInputStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.text_input. Class description[source] st.testing.v1.element_tree.TextInput(proto, root) Methods input(v) Set the value of the widget only if the value does not exceed the maximum allowed characters. run(*, timeout=None) Run the AppTest script which contains the element. set_value(v) Set the value of the widget. Attributes value The current value of the widget. (str) st.testing.v1.element_tree.TimeInputStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.time_input. Class description[source] st.testing.v1.element_tree.TimeInput(proto, root) Methods decrement() Select the previous available time. increment() Select the next available time. run(*, timeout=None) Run the AppTest script which contains the element. set_value(v) Set the value of the widget. Attributes value The current value of the widget. (time) st.testing.v1.element_tree.ToggleStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.toggle. Class description[source] st.testing.v1.element_tree.Toggle(proto, root) Methods run(*, timeout=None) Run the AppTest script which contains the element. set_value(v) Set the value of the widget. Attributes value The current value of the widget. (bool) Previous: st.testing.v1.AppTestNext: Command lineforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy" https://docs.streamlit.io/en/0.70.0/api.html#utilities-and-user-info,"DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceremovePAGE ELEMENTSWrite and magicaddText elementsaddData elementsaddChart elementsaddInput widgetsaddMedia elementsaddLayouts and containersaddChat elementsaddStatus elementsaddThird-party componentsopen_in_newAPPLICATION LOGICNavigation and pagesaddExecution flowaddCaching and stateaddConnections and secretsaddCustom componentsaddUtilitiesaddConfigurationaddTOOLSApp testingaddCommand lineaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Develop/API referenceAPI reference Streamlit makes it easy for you to visualize, mutate, and share data. The API reference is organized by activity type, like displaying data or optimizing performance. Each section includes methods associated with the activity type, including examples. Browse our API below and click to learn more about any of our available commands! 🎈 Display almost anything Write and magic st.writeWrite arguments to the app.st.write(""Hello **world**!"") st.write(my_data_frame) st.write(my_mpl_figure) st.write_streamWrite generators or streams to the app with a typewriter effect.st.write_stream(my_generator) st.write_stream(my_llm_stream) MagicAny time Streamlit sees either a variable or literal value on its own line, it automatically writes that to your app using st.write""Hello **world**!"" my_data_frame my_mpl_figure Text elements MarkdownDisplay string formatted as Markdown.st.markdown(""Hello **world**!"") TitleDisplay text in title formatting.st.title(""The app title"") HeaderDisplay text in header formatting.st.header(""This is a header"") SubheaderDisplay text in subheader formatting.st.subheader(""This is a subheader"") CaptionDisplay text in small font.st.caption(""This is written small caption text"") Code blockDisplay a code block with optional syntax highlighting.st.code(""a = 1234"") EchoDisplay some code in the app, then execute it. Useful for tutorials.with st.echo(): st.write('This code will be printed') LaTeXDisplay mathematical expressions formatted as LaTeX.st.latex(""\int a x^2 \,dx"") Preformatted textWrite fixed-width and preformatted text.st.text(""Hello world"") DividerDisplay a horizontal rule.st.divider() Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration! PreviousTagsAdd tags to your Streamlit apps. Created by @gagan3012.st_tags(label='# Enter Keywords:', text='Press enter to add more', value=['Zero', 'One', 'Two'], suggestions=['five', 'six', 'seven', 'eight', 'nine', 'three', 'eleven', 'ten', 'four'], maxtags = 4, key='1') NLUApply text mining on a dataframe. Created by @JohnSnowLabs.nlu.load('sentiment').predict('I love NLU! <3') Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.mention(label=""An awesome Streamlit App"", icon=""streamlit"", url=""https://extras.streamlit.app"",) Annotated textDisplay annotated text in Streamlit apps. Created by @tvst.annotated_text(""This "", (""is"", ""verb""), "" some "", (""annotated"", ""adj""), (""text"", ""noun""), "" for those of "", (""you"", ""pronoun""), "" who "", (""like"", ""verb""), "" this sort of "", (""thing"", ""noun""), ""."") Drawable CanvasProvides a sketching canvas using Fabric.js. Created by @andfanilo.st_canvas(fill_color=""rgba(255, 165, 0, 0.3)"", stroke_width=stroke_width, stroke_color=stroke_color, background_color=bg_color, background_image=Image.open(bg_image) if bg_image else None, update_streamlit=realtime_update, height=150, drawing_mode=drawing_mode, point_display_radius=point_display_radius if drawing_mode == 'point' else 0, key=""canvas"",) TagsAdd tags to your Streamlit apps. Created by @gagan3012.st_tags(label='# Enter Keywords:', text='Press enter to add more', value=['Zero', 'One', 'Two'], suggestions=['five', 'six', 'seven', 'eight', 'nine', 'three', 'eleven', 'ten', 'four'], maxtags = 4, key='1') NLUApply text mining on a dataframe. Created by @JohnSnowLabs.nlu.load('sentiment').predict('I love NLU! <3') Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.mention(label=""An awesome Streamlit App"", icon=""streamlit"", url=""https://extras.streamlit.app"",) Annotated textDisplay annotated text in Streamlit apps. Created by @tvst.annotated_text(""This "", (""is"", ""verb""), "" some "", (""annotated"", ""adj""), (""text"", ""noun""), "" for those of "", (""you"", ""pronoun""), "" who "", (""like"", ""verb""), "" this sort of "", (""thing"", ""noun""), ""."") Drawable CanvasProvides a sketching canvas using Fabric.js. Created by @andfanilo.st_canvas(fill_color=""rgba(255, 165, 0, 0.3)"", stroke_width=stroke_width, stroke_color=stroke_color, background_color=bg_color, background_image=Image.open(bg_image) if bg_image else None, update_streamlit=realtime_update, height=150, drawing_mode=drawing_mode, point_display_radius=point_display_radius if drawing_mode == 'point' else 0, key=""canvas"",) TagsAdd tags to your Streamlit apps. Created by @gagan3012.st_tags(label='# Enter Keywords:', text='Press enter to add more', value=['Zero', 'One', 'Two'], suggestions=['five', 'six', 'seven', 'eight', 'nine', 'three', 'eleven', 'ten', 'four'], maxtags = 4, key='1') NLUApply text mining on a dataframe. Created by @JohnSnowLabs.nlu.load('sentiment').predict('I love NLU! <3') Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.mention(label=""An awesome Streamlit App"", icon=""streamlit"", url=""https://extras.streamlit.app"",) Next Data elements DataframesDisplay a dataframe as an interactive table.st.dataframe(my_data_frame) Data editorDisplay a data editor widget.edited = st.data_editor(df, num_rows=""dynamic"") Column configurationConfigure the display and editing behavior of dataframes and data editors.st.column_config.NumberColumn(""Price (in USD)"", min_value=0, format=""$%d"") Static tablesDisplay a static table.st.table(my_data_frame) MetricsDisplay a metric in big bold font, with an optional indicator of how the metric changed.st.metric(""My metric"", 42, 2) Dicts and JSONDisplay object or string as a pretty-printed JSON string.st.json(my_dict) Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration! PreviousImage CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates value = streamlit_image_coordinates(""https://placekitten.com/200/300"") st.write(value) Plotly EventsMake Plotly charts interactive!. Created by @null-jones.from streamlit_plotly_events import plotly_events fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.metric_cards import style_metric_cards col3.metric(label=""No Change"", value=5000, delta=0) style_metric_cards() Streamlit AggridImplementation of Ag-Grid component for Streamlit. Created by @PablocFonseca.df = pd.DataFrame({'col1': [1, 2, 3], 'col2': [4, 5, 6]}) grid_return = AgGrid(df, editable=True) new_df = grid_return['data'] Streamlit FoliumStreamlit Component for rendering Folium maps. Created by @randyzwitch.m = folium.Map(location=[39.949610, -75.150282], zoom_start=16) folium.Marker([39.949610, -75.150282], popup=""Liberty Bell"", tooltip=""Liberty Bell"").add_to(m) st_data = st_folium(m, width=725) Pandas ProfilingPandas profiling component for Streamlit. Created by @okld.df = pd.read_csv(""https://storage.googleapis.com/tf-datasets/titanic/train.csv"") pr = df.profile_report() st_profile_report(pr) Image CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates value = streamlit_image_coordinates(""https://placekitten.com/200/300"") st.write(value) Plotly EventsMake Plotly charts interactive!. Created by @null-jones.from streamlit_plotly_events import plotly_events fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.metric_cards import style_metric_cards col3.metric(label=""No Change"", value=5000, delta=0) style_metric_cards() Streamlit AggridImplementation of Ag-Grid component for Streamlit. Created by @PablocFonseca.df = pd.DataFrame({'col1': [1, 2, 3], 'col2': [4, 5, 6]}) grid_return = AgGrid(df, editable=True) new_df = grid_return['data'] Streamlit FoliumStreamlit Component for rendering Folium maps. Created by @randyzwitch.m = folium.Map(location=[39.949610, -75.150282], zoom_start=16) folium.Marker([39.949610, -75.150282], popup=""Liberty Bell"", tooltip=""Liberty Bell"").add_to(m) st_data = st_folium(m, width=725) Pandas ProfilingPandas profiling component for Streamlit. Created by @okld.df = pd.read_csv(""https://storage.googleapis.com/tf-datasets/titanic/train.csv"") pr = df.profile_report() st_profile_report(pr) Image CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates value = streamlit_image_coordinates(""https://placekitten.com/200/300"") st.write(value) Plotly EventsMake Plotly charts interactive!. Created by @null-jones.from streamlit_plotly_events import plotly_events fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.metric_cards import style_metric_cards col3.metric(label=""No Change"", value=5000, delta=0) style_metric_cards() Next Chart elements Simple area chartsDisplay an area chart.st.area_chart(my_data_frame) Simple bar chartsDisplay a bar chart.st.bar_chart(my_data_frame) Simple line chartsDisplay a line chart.st.line_chart(my_data_frame) Simple scatter chartsDisplay a line chart.st.scatter_chart(my_data_frame) Scatterplots on mapsDisplay a map with points on it.st.map(my_data_frame) MatplotlibDisplay a matplotlib.pyplot figure.st.pyplot(my_mpl_figure) AltairDisplay a chart using the Altair library.st.altair_chart(my_altair_chart) Vega-LiteDisplay a chart using the Vega-Lite library.st.vega_lite_chart(my_vega_lite_chart) PlotlyDisplay an interactive Plotly chart.st.plotly_chart(my_plotly_chart) BokehDisplay an interactive Bokeh chart.st.bokeh_chart(my_bokeh_chart) PyDeckDisplay a chart using the PyDeck library.st.pydeck_chart(my_pydeck_chart) GraphVizDisplay a graph using the dagre-d3 library.st.graphviz_chart(my_graphviz_spec) Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration! PreviousStreamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl(""https://assets5.lottiefiles.com/packages/lf20_V9t630.json"") st_lottie(lottie_hello, key=""hello"") Plotly EventsMake Plotly charts interactive!. Created by @null-jones.fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.chart += get_annotations_chart(annotations=[(""Mar 01, 2008"", ""Pretty good day for GOOG""), (""Dec 01, 2007"", ""Something's going wrong for GOOG & AAPL""), (""Nov 01, 2008"", ""Market starts again thanks to...""), (""Dec 01, 2009"", ""Small crash for GOOG after...""),],) st.altair_chart(chart, use_container_width=True) PlostA deceptively simple plotting library for Streamlit. Created by @tvst.import plost plost.line_chart(my_dataframe, x='time', y='stock_value', color='stock_name',) HiPlotHigh dimensional Interactive Plotting. Created by @facebookresearch.data = [{'dropout':0.1, 'lr': 0.001, 'loss': 10.0, 'optimizer': 'SGD'}, {'dropout':0.15, 'lr': 0.01, 'loss': 3.5, 'optimizer': 'Adam'}, {'dropout':0.3, 'lr': 0.1, 'loss': 4.5, 'optimizer': 'Adam'}] hip.Experiment.from_iterable(data).display() EChartsHigh dimensional Interactive Plotting. Created by @andfanilo.from streamlit_echarts import st_echarts st_echarts(options=options) Streamlit FoliumStreamlit Component for rendering Folium maps. Created by @randyzwitch.m = folium.Map(location=[39.949610, -75.150282], zoom_start=16) st_data = st_folium(m, width=725) Spacy-StreamlitspaCy building blocks and visualizers for Streamlit apps. Created by @explosion.models = [""en_core_web_sm"", ""en_core_web_md""] spacy_streamlit.visualize(models, ""Sundar Pichai is the CEO of Google."") Streamlit AgraphA Streamlit Graph Vis, based on react-grah-vis. Created by @ChrisDelClea.from streamlit_agraph import agraph, Node, Edge, Config agraph(nodes=nodes, edges=edges, config=config) Streamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl(""https://assets5.lottiefiles.com/packages/lf20_V9t630.json"") st_lottie(lottie_hello, key=""hello"") Plotly EventsMake Plotly charts interactive!. Created by @null-jones.fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.chart += get_annotations_chart(annotations=[(""Mar 01, 2008"", ""Pretty good day for GOOG""), (""Dec 01, 2007"", ""Something's going wrong for GOOG & AAPL""), (""Nov 01, 2008"", ""Market starts again thanks to...""), (""Dec 01, 2009"", ""Small crash for GOOG after...""),],) st.altair_chart(chart, use_container_width=True) PlostA deceptively simple plotting library for Streamlit. Created by @tvst.import plost plost.line_chart(my_dataframe, x='time', y='stock_value', color='stock_name',) HiPlotHigh dimensional Interactive Plotting. Created by @facebookresearch.data = [{'dropout':0.1, 'lr': 0.001, 'loss': 10.0, 'optimizer': 'SGD'}, {'dropout':0.15, 'lr': 0.01, 'loss': 3.5, 'optimizer': 'Adam'}, {'dropout':0.3, 'lr': 0.1, 'loss': 4.5, 'optimizer': 'Adam'}] hip.Experiment.from_iterable(data).display() EChartsHigh dimensional Interactive Plotting. Created by @andfanilo.from streamlit_echarts import st_echarts st_echarts(options=options) Streamlit FoliumStreamlit Component for rendering Folium maps. Created by @randyzwitch.m = folium.Map(location=[39.949610, -75.150282], zoom_start=16) st_data = st_folium(m, width=725) Spacy-StreamlitspaCy building blocks and visualizers for Streamlit apps. Created by @explosion.models = [""en_core_web_sm"", ""en_core_web_md""] spacy_streamlit.visualize(models, ""Sundar Pichai is the CEO of Google."") Streamlit AgraphA Streamlit Graph Vis, based on react-grah-vis. Created by @ChrisDelClea.from streamlit_agraph import agraph, Node, Edge, Config agraph(nodes=nodes, edges=edges, config=config) Streamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl(""https://assets5.lottiefiles.com/packages/lf20_V9t630.json"") st_lottie(lottie_hello, key=""hello"") Plotly EventsMake Plotly charts interactive!. Created by @null-jones.fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.chart += get_annotations_chart(annotations=[(""Mar 01, 2008"", ""Pretty good day for GOOG""), (""Dec 01, 2007"", ""Something's going wrong for GOOG & AAPL""), (""Nov 01, 2008"", ""Market starts again thanks to...""), (""Dec 01, 2009"", ""Small crash for GOOG after...""),],) st.altair_chart(chart, use_container_width=True) Next Input widgets ButtonDisplay a button widget.clicked = st.button(""Click me"") Download buttonDisplay a download button widget.st.download_button(""Download file"", file) Form buttonDisplay a form submit button. For use with st.form.st.form_submit_button(""Sign up"") Link buttonDisplay a link button.st.link_button(""Go to gallery"", url) Page linkDisplay a link to another page in a multipage app.st.page_link(""app.py"", label=""Home"", icon=""🏠"") st.page_link(""pages/profile.py"", label=""My profile"") CheckboxDisplay a checkbox widget.selected = st.checkbox(""I agree"") Color pickerDisplay a color picker widget.color = st.color_picker(""Pick a color"") MultiselectDisplay a multiselect widget. The multiselect widget starts as empty.choices = st.multiselect(""Buy"", [""milk"", ""apples"", ""potatoes""]) RadioDisplay a radio button widget.choice = st.radio(""Pick one"", [""cats"", ""dogs""]) SelectboxDisplay a select widget.choice = st.selectbox(""Pick one"", [""cats"", ""dogs""]) Select-sliderDisplay a slider widget to select items from a list.size = st.select_slider(""Pick a size"", [""S"", ""M"", ""L""]) ToggleDisplay a toggle widget.activated = st.toggle(""Activate"") Number inputDisplay a numeric input widget.choice = st.number_input(""Pick a number"", 0, 10) SliderDisplay a slider widget.number = st.slider(""Pick a number"", 0, 100) Date inputDisplay a date input widget.date = st.date_input(""Your birthday"") Time inputDisplay a time input widget.time = st.time_input(""Meeting time"") Chat inputDisplay a chat input widget.prompt = st.chat_input(""Say something"") if prompt: st.write(f""The user has sent: {prompt}"") Text-areaDisplay a multi-line text input widget.text = st.text_area(""Text to translate"") Text inputDisplay a single-line text input widget.name = st.text_input(""First name"") Data editorDisplay a data editor widget.edited = st.experimental_data_editor(df, num_rows=""dynamic"") File UploaderDisplay a file uploader widget.data = st.file_uploader(""Upload a CSV"") Camera inputDisplay a widget that allows users to upload images directly from a camera.image = st.camera_input(""Take a picture"") Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration! PreviousStreamlit ChatStreamlit Component for a Chatbot UI. Created by @AI-Yash.from streamlit_chat import message message(""My message"") message(""Hello bot!"", is_user=True) # align's the message to the right Streamlit Option MenuSelect a single item from a list of options in a menu. Created by @victoryhb.from streamlit_option_menu import option_menu option_menu(""Main Menu"", [""Home"", 'Settings'], icons=['house', 'gear'], menu_icon=""cast"", default_index=1) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.stoggle import stoggle stoggle( ""Click me!"", """"""🥷 Surprise! Here's some additional content"""""",) Streamlit ElementsCreate a draggable and resizable dashboard in Streamlit. Created by @okls.from streamlit_elements import elements, mui, html with elements(""new_element""): mui.Typography(""Hello world"") TagsAdd tags to your Streamlit apps. Created by @gagan3012.from streamlit_tags import st_tags st_tags(label='# Enter Keywords:', text='Press enter to add more', value=['Zero', 'One', 'Two'], suggestions=['five', 'six', 'seven', 'eight', 'nine', 'three', 'eleven', 'ten', 'four'], maxtags = 4, key='1') StqdmThe simplest way to handle a progress bar in streamlit app. Created by @Wirg.from stqdm import stqdm for _ in stqdm(range(50)): sleep(0.5) TimelineDisplay a Timeline in Streamlit apps using TimelineJS. Created by @innerdoc.from streamlit_timeline import timeline with open('example.json', ""r"") as f: timeline(f.read(), height=800) Camera input liveAlternative for st.camera_input which returns the webcam images live. Created by @blackary.from camera_input_live import camera_input_live image = camera_input_live() st.image(value) Streamlit AceAce editor component for Streamlit. Created by @okld.from streamlit_ace import st_ace content = st_ace() content Streamlit ChatStreamlit Component for a Chatbot UI. Created by @AI-Yash.from streamlit_chat import message message(""My message"") message(""Hello bot!"", is_user=True) # align's the message to the right Streamlit Option MenuSelect a single item from a list of options in a menu. Created by @victoryhb.from streamlit_option_menu import option_menu option_menu(""Main Menu"", [""Home"", 'Settings'], icons=['house', 'gear'], menu_icon=""cast"", default_index=1) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.stoggle import stoggle stoggle( ""Click me!"", """"""🥷 Surprise! Here's some additional content"""""",) Streamlit ElementsCreate a draggable and resizable dashboard in Streamlit. Created by @okls.from streamlit_elements import elements, mui, html with elements(""new_element""): mui.Typography(""Hello world"") TagsAdd tags to your Streamlit apps. Created by @gagan3012.from streamlit_tags import st_tags st_tags(label='# Enter Keywords:', text='Press enter to add more', value=['Zero', 'One', 'Two'], suggestions=['five', 'six', 'seven', 'eight', 'nine', 'three', 'eleven', 'ten', 'four'], maxtags = 4, key='1') StqdmThe simplest way to handle a progress bar in streamlit app. Created by @Wirg.from stqdm import stqdm for _ in stqdm(range(50)): sleep(0.5) TimelineDisplay a Timeline in Streamlit apps using TimelineJS. Created by @innerdoc.from streamlit_timeline import timeline with open('example.json', ""r"") as f: timeline(f.read(), height=800) Camera input liveAlternative for st.camera_input which returns the webcam images live. Created by @blackary.from camera_input_live import camera_input_live image = camera_input_live() st.image(value) Streamlit AceAce editor component for Streamlit. Created by @okld.from streamlit_ace import st_ace content = st_ace() content Streamlit ChatStreamlit Component for a Chatbot UI. Created by @AI-Yash.from streamlit_chat import message message(""My message"") message(""Hello bot!"", is_user=True) # align's the message to the right Streamlit Option MenuSelect a single item from a list of options in a menu. Created by @victoryhb.from streamlit_option_menu import option_menu option_menu(""Main Menu"", [""Home"", 'Settings'], icons=['house', 'gear'], menu_icon=""cast"", default_index=1) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.stoggle import stoggle stoggle( ""Click me!"", """"""🥷 Surprise! Here's some additional content"""""",) Next Media elements ImageDisplay an image or list of images.st.image(numpy_array) st.image(image_bytes) st.image(file) st.image(""https://example.com/myimage.jpg"") AudioDisplay an audio player.st.audio(numpy_array) st.audio(audio_bytes) st.audio(file) st.audio(""https://example.com/myaudio.mp3"", format=""audio/mp3"") VideoDisplay a video player.st.video(numpy_array) st.video(video_bytes) st.video(file) st.video(""https://example.com/myvideo.mp4"", format=""video/mp4"") Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration! PreviousStreamlit CropperA simple image cropper for Streamlit. Created by @turner-anderson.from streamlit_cropper import st_cropper st_cropper(img, realtime_update=realtime_update, box_color=box_color, aspect_ratio=aspect_ratio) Image CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates streamlit_image_coordinates(""https://placekitten.com/200/300"") Streamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl(""https://assets5.lottiefiles.com/packages/lf20_V9t630.json"") st_lottie(lottie_hello, key=""hello"") Streamlit WebrtcHandling and transmitting real-time video/audio streams with Streamlit. Created by @whitphx.from streamlit_webrtc import webrtc_streamer webrtc_streamer(key=""sample"") Drawable CanvasProvides a sketching canvas using Fabric.js. Created by @andfanilo.from streamlit_drawable_canvas import st_canvas st_canvas(fill_color=""rgba(255, 165, 0, 0.3)"", stroke_width=stroke_width, stroke_color=stroke_color, background_color=bg_color, background_image=Image.open(bg_image) if bg_image else None, update_streamlit=realtime_update, height=150, drawing_mode=drawing_mode, point_display_radius=point_display_radius if drawing_mode == 'point' else 0, key=""canvas"",) Image ComparisonCompare images with a slider using JuxtaposeJS. Created by @fcakyon.from streamlit_image_comparison import image_comparison image_comparison(img1=""image1.jpg"", img2=""image2.jpg"",) Streamlit CropperA simple image cropper for Streamlit. Created by @turner-anderson.from streamlit_cropper import st_cropper st_cropper(img, realtime_update=realtime_update, box_color=box_color, aspect_ratio=aspect_ratio) Image CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates streamlit_image_coordinates(""https://placekitten.com/200/300"") Streamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl(""https://assets5.lottiefiles.com/packages/lf20_V9t630.json"") st_lottie(lottie_hello, key=""hello"") Streamlit WebrtcHandling and transmitting real-time video/audio streams with Streamlit. Created by @whitphx.from streamlit_webrtc import webrtc_streamer webrtc_streamer(key=""sample"") Drawable CanvasProvides a sketching canvas using Fabric.js. Created by @andfanilo.from streamlit_drawable_canvas import st_canvas st_canvas(fill_color=""rgba(255, 165, 0, 0.3)"", stroke_width=stroke_width, stroke_color=stroke_color, background_color=bg_color, background_image=Image.open(bg_image) if bg_image else None, update_streamlit=realtime_update, height=150, drawing_mode=drawing_mode, point_display_radius=point_display_radius if drawing_mode == 'point' else 0, key=""canvas"",) Image ComparisonCompare images with a slider using JuxtaposeJS. Created by @fcakyon.from streamlit_image_comparison import image_comparison image_comparison(img1=""image1.jpg"", img2=""image2.jpg"",) Streamlit CropperA simple image cropper for Streamlit. Created by @turner-anderson.from streamlit_cropper import st_cropper st_cropper(img, realtime_update=realtime_update, box_color=box_color, aspect_ratio=aspect_ratio) Image CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates streamlit_image_coordinates(""https://placekitten.com/200/300"") Streamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl(""https://assets5.lottiefiles.com/packages/lf20_V9t630.json"") st_lottie(lottie_hello, key=""hello"") Next Layouts and containers ColumnsInsert containers laid out as side-by-side columns.col1, col2 = st.columns(2) col1.write(""this is column 1"") col2.write(""this is column 2"") ContainerInsert a multi-element container.c = st.container() st.write(""This will show last"") c.write(""This will show first"") c.write(""This will show second"") Modal dialogsInsert a modal dialog that can rerun independently from the rest of the script.@st.experimental_dialog(""Sign up"") def email_form(): name = st.text_input(""Name"") email = st.text_input(""Email"") EmptyInsert a single-element container.c = st.empty() st.write(""This will show last"") c.write(""This will be replaced"") c.write(""This will show first"") ExpanderInsert a multi-element container that can be expanded/collapsed.with st.expander(""Open to see more""): st.write(""This is more content"") PopoverInsert a multi-element popover container that can be opened/closed.with st.popover(""Settings""): st.checkbox(""Show completed"") SidebarDisplay items in a sidebar.st.sidebar.write(""This lives in the sidebar"") st.sidebar.button(""Click me!"") TabsInsert containers separated into tabs.tab1, tab2 = st.tabs([""Tab 1"", ""Tab2""]) tab1.write(""this is tab 1"") tab2.write(""this is tab 2"") Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration!Streamlit ElementsCreate a draggable and resizable dashboard in Streamlit. Created by @okls.from streamlit_elements import elements, mui, html with elements(""new_element""): mui.Typography(""Hello world"") PydanticAuto-generate Streamlit UI from Pydantic Models and Dataclasses. Created by @lukasmasuch.import streamlit_pydantic as sp sp.pydantic_form(key=""my_form"", model=ExampleModel) Streamlit PagesAn experimental version of Streamlit Multi-Page Apps. Created by @blackary.from st_pages import Page, show_pages, add_page_title show_pages([ Page(""streamlit_app.py"", ""Home"", ""🏠""), Page(""other_pages/page2.py"", ""Page 2"", "":books:""), ]) Chat elements Streamlit provides a few commands to help you build conversational apps. These chat elements are designed to be used in conjunction with each other, but you can also use them separately. st.chat_message lets you insert a chat message container into the app so you can display messages from the user or the app. Chat containers can contain other Streamlit elements, including charts, tables, text, and more. st.chat_input lets you display a chat input widget so the user can type in a message. Chat inputDisplay a chat input widget.prompt = st.chat_input(""Say something"") if prompt: st.write(f""The user has sent: {prompt}"") Chat messageInsert a chat message container.import numpy as np with st.chat_message(""user""): st.write(""Hello 👋"") st.line_chart(np.random.randn(30, 3)) Status containerDisplay output of long-running tasks in a container.with st.status('Running'): do_something_slow() st.write_streamWrite generators or streams to the app with a typewriter effect.st.write_stream(my_generator) st.write_stream(my_llm_stream) Status elements Progress barDisplay a progress bar.for i in range(101): st.progress(i) do_something_slow() SpinnerTemporarily displays a message while executing a block of code.with st.spinner(""Please wait...""): do_something_slow() Status containerDisplay output of long-running tasks in a container.with st.status('Running'): do_something_slow() ToastBriefly displays a toast message in the bottom-right corner.st.toast('Butter!', icon='🧈') BalloonsDisplay celebratory balloons!do_something() # Celebrate when all done! st.balloons() SnowflakesDisplay celebratory snowflakes!do_something() # Celebrate when all done! st.snow() Success boxDisplay a success message.st.success(""Match found!"") Info boxDisplay an informational message.st.info(""Dataset is updated every day at midnight."") Warning boxDisplay warning message.st.warning(""Unable to fetch image. Skipping..."") Error boxDisplay error message.st.error(""We encountered an error"") Exception outputDisplay an exception.e = RuntimeError(""This is an exception of type RuntimeError"") st.exception(e) Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration!StqdmThe simplest way to handle a progress bar in streamlit app. Created by @Wirg.from stqdm import stqdm for _ in stqdm(range(50)): sleep(0.5) Custom notification boxA custom notification box with the ability to close it out. Created by @Socvest.from streamlit_custom_notification_box import custom_notification_box styles = {'material-icons':{'color': 'red'}, 'text-icon-link-close-container': {'box-shadow': '#3896de 0px 4px'}, 'notification-text': {'':''}, 'close-button':{'':''}, 'link':{'':''}} custom_notification_box(icon='info', textDisplay='We are almost done with your registration...', externalLink='more info', url='#', styles=styles, key=""foo"") Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.let_it_rain import rain rain(emoji=""🎈"", font_size=54, falling_speed=5, animation_length=""infinite"",) App logic and configuration Navigation and pages Switch pageProgrammatically navigates to a specified page.st.switch_page(""pages/my_page.py"") Page linkDisplay a link to another page in a multipage app.st.page_link(""app.py"", label=""Home"", icon=""🏠"") st.page_link(""pages/profile.py"", label=""My profile"") Execution flow Modal dialogsInsert a modal dialog that can rerun independently from the rest of the script.@st.experimental_dialog(""Sign up"") def email_form(): name = st.text_input(""Name"") email = st.text_input(""Email"") FormsCreate a form that batches elements together with a “Submit"" button.with st.form(key='my_form'): name = st.text_input(""Name"") email = st.text_input(""Email"") st.form_submit_button(""Sign up"") Partial rerunsDefine a fragment to rerun independently from the rest of the script.@st.experimental_fragment(run_every=""10s"") def fragment(): df = get_data() st.line_chart(df) Rerun scriptRerun the script immediately.st.rerun() Stop executionStops execution immediately.st.stop() Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration!AutorefreshForce a refresh without tying up a script. Created by @kmcgrady.from streamlit_autorefresh import st_autorefresh st_autorefresh(interval=2000, limit=100, key=""fizzbuzzcounter"") PydanticAuto-generate Streamlit UI from Pydantic Models and Dataclasses. Created by @lukasmasuch.import streamlit_pydantic as sp sp.pydantic_form(key=""my_form"", model=ExampleModel) Streamlit PagesAn experimental version of Streamlit Multi-Page Apps. Created by @blackary.from st_pages import Page, show_pages, add_page_title show_pages([ Page(""streamlit_app.py"", ""Home"", ""🏠""), Page(""other_pages/page2.py"", ""Page 2"", "":books:""), ]) Caching and state Cache dataFunction decorator to cache functions that return data (e.g. dataframe transforms, database queries, ML inference).@st.cache_data def long_function(param1, param2): # Perform expensive computation here or # fetch data from the web here return data Cache resourceFunction decorator to cache functions that return global resources (e.g. database connections, ML models).@st.cache_resource def init_model(): # Return a global resource here return pipeline( ""sentiment-analysis"", model=""distilbert-base-uncased-finetuned-sst-2-english"" ) Session stateSession state is a way to share variables between reruns, for each user session.st.session_state['key'] = value Query parametersGet, set, or clear the query parameters that are shown in the browser's URL bar.st.query_params[key] = value st.query_params.clear() Connections and databases Setup your connection Create a connectionConnect to a data source or APIconn = st.connection('pets_db', type='sql') pet_owners = conn.query('select * from pet_owners') st.dataframe(pet_owners) Built-in connections SnowflakeConnectionA connection to Snowflake.conn = st.connection('snowflake') SQLConnectionA connection to a SQL database using SQLAlchemy.conn = st.connection('sql') Build your own connections Connection base classBuild your own connection with BaseConnection.class MyConnection(BaseConnection[myconn.MyConnection]): def _connect(self, **kwargs) -> MyConnection: return myconn.connect(**self._secrets, **kwargs) def query(self, query): return self._instance.query(query) Secrets management Secrets singletonAccess secrets from a local TOML file.key = st.secrets[""OpenAI_key""] Secrets fileSave your secrets in a per-project or per-profile TOML file.OpenAI_key = """" Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration!AuthenticatorA secure authentication module to validate user credentials. Created by @mkhorasani.import streamlit_authenticator as stauth authenticator = stauth.Authenticate( config['credentials'], config['cookie']['name'], config['cookie']['key'], config['cookie']['expiry_days'], config['preauthorized']) WS localStorageA simple synchronous way of accessing localStorage from your app. Created by @gagangoku.from streamlit_ws_localstorage import injectWebsocketCode ret = conn.setLocalStorageVal(key='k1', val='v1') st.write('ret: ' + ret) Streamlit Auth0The fastest way to provide comprehensive login inside Streamlit. Created by @conradbez.from auth0_component import login_button user_info = login_button(clientId, domain = domain) st.write(user_info) Custom Components Declare a componentCreate and register a custom component.st.components.v1.declare_component( ""custom_slider"", ""/frontend"", ) HTMLDisplay an HTML string in an iframe.st.components.v1.html( ""

Foo bar.

"" ) iframeLoad a remote URL in an iframe.st.components.v1.iframe( ""docs.streamlit.io"" ) Utilities and user info User infost.experimental_user returns information about the logged-in user of private apps on Streamlit Community Cloud.if st.experimental_user.email == ""foo@corp.com"": st.write(""Welcome back, "", st.experimental_user.email) else: st.write(""You are not authorized to view this page."") Get helpDisplay object’s doc string, nicely formatted.st.help(st.write) st.help(pd.DataFrame) Render HTMLRenders HTML strings to your app.css = """""" """""" st.html(css) Configuration Configuration fileConfigures the default settings for your app.your-project/ ├── .streamlit/ │ └── config.toml └── your_app.py Set page title, favicon, and moreConfigures the default settings of the page.st.set_page_config( page_title=""My app"", page_icon="":shark:"", ) Developer tools App testing st.testing.v1.AppTestst.testing.v1.AppTest simulates a running Streamlit app for testing.from streamlit.testing.v1 import AppTest at = AppTest.from_file(""streamlit_app.py"") at.secrets[""WORD""] = ""Foobar"" at.run() assert not at.exception at.text_input(""word"").input(""Bazbat"").run() assert at.warning[0].value == ""Try again."" AppTest.from_filest.testing.v1.AppTest.from_file initializes a simulated app from a file.from streamlit.testing.v1 import AppTest at = AppTest.from_file(""streamlit_app.py"") at.run() AppTest.from_stringst.testing.v1.AppTest.from_string initializes a simulated app from a string.from streamlit.testing.v1 import AppTest at = AppTest.from_string(app_script_as_string) at.run() AppTest.from_functionst.testing.v1.AppTest.from_function initializes a simulated app from a function.from streamlit.testing.v1 import AppTest at = AppTest.from_function(app_script_as_callable) at.run() BlockA representation of container elements, including: st.chat_message st.columns st.sidebar st.tabs The main body of the app. # at.sidebar returns a Block at.sidebar.button[0].click().run() assert not at.exception ElementThe base class for representation of all elements, including: st.title st.header st.markdown st.dataframe # at.title returns a sequence of Title # Title inherits from Element assert at.title[0].value == ""My awesome app"" ButtonA representation of st.button and st.form_submit_button.at.button[0].click().run() ChatInputA representation of st.chat_input.at.chat_input[0].set_value(""What is Streamlit?"").run() CheckboxA representation of st.checkbox.at.checkbox[0].check().run() ColorPickerA representation of st.color_picker.at.color_picker[0].pick(""#FF4B4B"").run() DateInputA representation of st.date_input.release_date = datetime.date(2023, 10, 26) at.date_input[0].set_value(release_date).run() MultiselectA representation of st.multiselect.at.multiselect[0].select(""New York"").run() NumberInputA representation of st.number_input.at.number_input[0].increment().run() RadioA representation of st.radio.at.radio[0].set_value(""New York"").run() SelectSliderA representation of st.select_slider.at.select_slider[0].set_range(""A"",""C"").run() SelectboxA representation of st.selectbox.at.selectbox[0].select(""New York"").run() SliderA representation of st.slider.at.slider[0].set_range(2,5).run() TextAreaA representation of st.text_area.at.text_area[0].input(""Streamlit is awesome!"").run() TextInputA representation of st.text_input.at.text_input[0].input(""Streamlit"").run() TimeInputA representation of st.time_input.at.time_input[0].increment().run() ToggleA representation of st.toggle.at.toggle[0].set_value(""True"").run() Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration!Pandas ProfilingPandas profiling component for Streamlit. Created by @okld.df = pd.read_csv(""https://storage.googleapis.com/tf-datasets/titanic/train.csv"") pr = df.profile_report() st_profile_report(pr) Streamlit AceAce editor component for Streamlit. Created by @okld.from streamlit_ace import st_ace content = st_ace() content Streamlit AnalyticsTrack & visualize user interactions with your streamlit app. Created by @jrieke.import streamlit_analytics with streamlit_analytics.track(): st.text_input(""Write something"") Previous: ConceptsNext: Write and magicforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy" https://docs.streamlit.io/develop/concepts/configuration/https-support#https-support,"DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsremoveCOREArchitecture & executionaddMultipage appsaddApp designaddADDITIONALConnections and secretsaddCustom componentsaddConfiguration and themingremoveConfiguration optionsHTTPS supportServing static filesCustomize your themeApp testingaddAPI referenceaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Develop/Concepts/Configuration and theming/HTTPS supportHTTPS support Many apps need to be accessed with SSL / TLS protocol or https://. We recommend performing SSL termination in a reverse proxy or load balancer for self-hosted and production use cases, not directly in the app. Streamlit Community Cloud uses this approach, and every major cloud and app hosting platform should allow you to configure it and provide extensive documentation. You can find some of these platforms in our Deployment tutorials. To terminate SSL in your Streamlit app, you must configure server.sslCertFile and server.sslKeyFile. Learn how to set config options in Configuration. Details on usage The configuration value should be a local file path to a cert file and key file. These must be available at the time the app starts. Both server.sslCertFile and server.sslKeyFile must be specified. If only one is specified, your app will exit with an error. This feature will not work in Community Cloud. Community Cloud already serves your app with TLS. priority_highWarningIn a production environment, we recommend performing SSL termination by the load balancer or the reverse proxy, not using this option. The use of this option in Streamlit has not gone through extensive security audits or performance tests. Example usage # .streamlit/config.toml [server] sslCertFile = '/path/to/certchain.pem' sslKeyFile = '/path/to/private.key' Previous: Configuration optionsNext: Serving static filesforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy" https://docs.streamlit.io/develop/concepts/custom-components#making-your-own-component,"DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsremoveCOREArchitecture & executionaddMultipage appsaddApp designaddADDITIONALConnections and secretsaddCustom componentsremoveIntro to custom componentsCreate a ComponentPublish a ComponentLimitationsComponent galleryopen_in_newConfiguration and themingaddApp testingaddAPI referenceaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Develop/Concepts/Custom componentsCustom Components Components are third-party Python modules that extend what's possible with Streamlit. How to use a Component Components are super easy to use: Start by finding the Component you'd like to use. Two great resources for this are: The Component gallery This thread, by Fanilo A. from our forums. Install the Component using your favorite Python package manager. This step and all following steps are described in your component's instructions. For example, to use the fantastic AgGrid Component, you first install it with: pip install streamlit-aggrid In your Python code, import the Component as described in its instructions. For AgGrid, this step is: from st_aggrid import AgGrid ...now you're ready to use it! For AgGrid, that's: AgGrid(my_dataframe) Making your own Component If you're interested in making your own component, check out the following resources: Create a Component Publish a Component Components API Blog post for when we launched Components! Alternatively, if you prefer to learn using videos, our engineer Tim Conkling has put together some amazing tutorials: Video tutorial, part 1 Video tutorial, part 2 Previous: Connections and secretsNext: Intro to custom componentsforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy" https://docs.streamlit.io/develop/concepts/configuration/theming,"DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsremoveCOREArchitecture & executionaddMultipage appsaddApp designaddADDITIONALConnections and secretsaddCustom componentsaddConfiguration and themingremoveConfiguration optionsHTTPS supportServing static filesCustomize your themeApp testingaddAPI referenceaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Develop/Concepts/Configuration and theming/Customize your themeTheming In this guide, we provide examples of how Streamlit page elements are affected by the various theme config options. For a more high-level overview of Streamlit themes, see the Themes section of the main concepts documentation. Streamlit themes are defined using regular config options: a theme can be set via command line flag when starting your app using streamlit run or by defining it in the [theme] section of a .streamlit/config.toml file. For more information on setting config options, please refer to the Streamlit configuration documentation. The following config options show the default Streamlit Light theme recreated in the [theme] section of a .streamlit/config.toml file. [theme] primaryColor=""#F63366"" backgroundColor=""#FFFFFF"" secondaryBackgroundColor=""#F0F2F6"" textColor=""#262730"" font=""sans serif"" Let's go through each of these options, providing screenshots to demonstrate what parts of a Streamlit app they affect where needed. primaryColor primaryColor defines the accent color most often used throughout a Streamlit app. A few examples of Streamlit widgets that use primaryColor include st.checkbox, st.slider, and st.text_input (when focused). starTipAny CSS color can be used as the value for primaryColor and the other color options below. This means that theme colors can be specified in hex or with browser-supported color names like ""green"", ""yellow"", and ""chartreuse"". They can even be defined in the RGB and HSL formats! backgroundColor Defines the background color used in the main content area of your app. secondaryBackgroundColor This color is used where a second background color is needed for added contrast. Most notably, it is the sidebar's background color. It is also used as the background color for most interactive widgets. textColor This option controls the text color for most of your Streamlit app. font Selects the font used in your Streamlit app. Valid values are ""sans serif"", ""serif"", and ""monospace"". This option defaults to ""sans serif"" if unset or invalid. Note that code blocks are always rendered using the monospace font regardless of the font selected here. base An easy way to define custom themes that make small changes to one of the preset Streamlit themes is to use the base option. Using base, the Streamlit Light theme can be recreated as a custom theme by writing the following: [theme] base=""light"" The base option allows you to specify a preset Streamlit theme that your custom theme inherits from. Any theme config options not defined in your theme settings have their values set to those of the base theme. Valid values for base are ""light"" and ""dark"". For example, the following theme config defines a custom theme nearly identical to the Streamlit Dark theme, but with a new primaryColor. [theme] base=""dark"" primaryColor=""purple"" If base itself is omitted, it defaults to ""light"", so you can define a custom theme that changes the font of the Streamlit Light theme to serif with the following config [theme] font=""serif"" Previous: Serving static filesNext: App testingforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy" https://docs.streamlit.io/develop/api-reference/connections/st.connections.baseconnection#baseconnectionreset,"DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceremovePAGE ELEMENTSWrite and magicaddText elementsaddData elementsaddChart elementsaddInput widgetsaddMedia elementsaddLayouts and containersaddChat elementsaddStatus elementsaddThird-party componentsopen_in_newAPPLICATION LOGICNavigation and pagesaddExecution flowaddCaching and stateaddConnections and secretsremoveSECRETSst.secretssecrets.tomlCONNECTIONSst.connectionSnowflakeConnectionSQLConnectionBaseConnectionSnowparkConnectiondeleteCustom componentsaddUtilitiesaddConfigurationaddTOOLSApp testingaddCommand lineaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Develop/API reference/Connections and secrets/BaseConnectionstarTipThis page only contains information on the st.connections.BaseConnection class. For a deeper dive into creating and managing data connections within Streamlit apps, read Connecting to data. st.connections.BaseConnectionStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeThe abstract base class that all Streamlit Connections must inherit from. This base class provides connection authors with a standardized way to hook into the st.connection() factory function: connection authors are required to provide an implementation for the abstract method _connect in their subclasses. Additionally, it also provides a few methods/properties designed to make implementation of connections more convenient. See the docstrings for each of the methods of this class for more information Note While providing an implementation of _connect is technically all that's required to define a valid connection, connections should also provide the user with context-specific ways of interacting with the underlying connection object. For example, the first-party SQLConnection provides a query() method for reads and a session property for more complex operations. Class description[source] st.connections.BaseConnection(connection_name, **kwargs) Methods reset() Reset this connection so that it gets reinitialized the next time it's used. BaseConnection.resetStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeReset this connection so that it gets reinitialized the next time it's used. This method can be useful when a connection has become stale, an auth token has expired, or in similar scenarios where a broken connection might be fixed by reinitializing it. Note that some connection methods may already use reset() in their error handling code. Function signature[source] BaseConnection.reset() Example import streamlit as st conn = st.connection(""my_conn"") # Reset the connection before using it if it isn't healthy # Note: is_healthy() isn't a real method and is just shown for example here. if not conn.is_healthy(): conn.reset() # Do stuff with conn... Previous: SQLConnectionNext: st.experimental_connectionforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy" https://docs.streamlit.io/en/0.70.0/api.html#custom-components,"DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceremovePAGE ELEMENTSWrite and magicaddText elementsaddData elementsaddChart elementsaddInput widgetsaddMedia elementsaddLayouts and containersaddChat elementsaddStatus elementsaddThird-party componentsopen_in_newAPPLICATION LOGICNavigation and pagesaddExecution flowaddCaching and stateaddConnections and secretsaddCustom componentsaddUtilitiesaddConfigurationaddTOOLSApp testingaddCommand lineaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Develop/API referenceAPI reference Streamlit makes it easy for you to visualize, mutate, and share data. The API reference is organized by activity type, like displaying data or optimizing performance. Each section includes methods associated with the activity type, including examples. Browse our API below and click to learn more about any of our available commands! 🎈 Display almost anything Write and magic st.writeWrite arguments to the app.st.write(""Hello **world**!"") st.write(my_data_frame) st.write(my_mpl_figure) st.write_streamWrite generators or streams to the app with a typewriter effect.st.write_stream(my_generator) st.write_stream(my_llm_stream) MagicAny time Streamlit sees either a variable or literal value on its own line, it automatically writes that to your app using st.write""Hello **world**!"" my_data_frame my_mpl_figure Text elements MarkdownDisplay string formatted as Markdown.st.markdown(""Hello **world**!"") TitleDisplay text in title formatting.st.title(""The app title"") HeaderDisplay text in header formatting.st.header(""This is a header"") SubheaderDisplay text in subheader formatting.st.subheader(""This is a subheader"") CaptionDisplay text in small font.st.caption(""This is written small caption text"") Code blockDisplay a code block with optional syntax highlighting.st.code(""a = 1234"") EchoDisplay some code in the app, then execute it. Useful for tutorials.with st.echo(): st.write('This code will be printed') LaTeXDisplay mathematical expressions formatted as LaTeX.st.latex(""\int a x^2 \,dx"") Preformatted textWrite fixed-width and preformatted text.st.text(""Hello world"") DividerDisplay a horizontal rule.st.divider() Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration! PreviousTagsAdd tags to your Streamlit apps. Created by @gagan3012.st_tags(label='# Enter Keywords:', text='Press enter to add more', value=['Zero', 'One', 'Two'], suggestions=['five', 'six', 'seven', 'eight', 'nine', 'three', 'eleven', 'ten', 'four'], maxtags = 4, key='1') NLUApply text mining on a dataframe. Created by @JohnSnowLabs.nlu.load('sentiment').predict('I love NLU! <3') Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.mention(label=""An awesome Streamlit App"", icon=""streamlit"", url=""https://extras.streamlit.app"",) Annotated textDisplay annotated text in Streamlit apps. Created by @tvst.annotated_text(""This "", (""is"", ""verb""), "" some "", (""annotated"", ""adj""), (""text"", ""noun""), "" for those of "", (""you"", ""pronoun""), "" who "", (""like"", ""verb""), "" this sort of "", (""thing"", ""noun""), ""."") Drawable CanvasProvides a sketching canvas using Fabric.js. Created by @andfanilo.st_canvas(fill_color=""rgba(255, 165, 0, 0.3)"", stroke_width=stroke_width, stroke_color=stroke_color, background_color=bg_color, background_image=Image.open(bg_image) if bg_image else None, update_streamlit=realtime_update, height=150, drawing_mode=drawing_mode, point_display_radius=point_display_radius if drawing_mode == 'point' else 0, key=""canvas"",) TagsAdd tags to your Streamlit apps. Created by @gagan3012.st_tags(label='# Enter Keywords:', text='Press enter to add more', value=['Zero', 'One', 'Two'], suggestions=['five', 'six', 'seven', 'eight', 'nine', 'three', 'eleven', 'ten', 'four'], maxtags = 4, key='1') NLUApply text mining on a dataframe. Created by @JohnSnowLabs.nlu.load('sentiment').predict('I love NLU! <3') Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.mention(label=""An awesome Streamlit App"", icon=""streamlit"", url=""https://extras.streamlit.app"",) Annotated textDisplay annotated text in Streamlit apps. Created by @tvst.annotated_text(""This "", (""is"", ""verb""), "" some "", (""annotated"", ""adj""), (""text"", ""noun""), "" for those of "", (""you"", ""pronoun""), "" who "", (""like"", ""verb""), "" this sort of "", (""thing"", ""noun""), ""."") Drawable CanvasProvides a sketching canvas using Fabric.js. Created by @andfanilo.st_canvas(fill_color=""rgba(255, 165, 0, 0.3)"", stroke_width=stroke_width, stroke_color=stroke_color, background_color=bg_color, background_image=Image.open(bg_image) if bg_image else None, update_streamlit=realtime_update, height=150, drawing_mode=drawing_mode, point_display_radius=point_display_radius if drawing_mode == 'point' else 0, key=""canvas"",) TagsAdd tags to your Streamlit apps. Created by @gagan3012.st_tags(label='# Enter Keywords:', text='Press enter to add more', value=['Zero', 'One', 'Two'], suggestions=['five', 'six', 'seven', 'eight', 'nine', 'three', 'eleven', 'ten', 'four'], maxtags = 4, key='1') NLUApply text mining on a dataframe. Created by @JohnSnowLabs.nlu.load('sentiment').predict('I love NLU! <3') Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.mention(label=""An awesome Streamlit App"", icon=""streamlit"", url=""https://extras.streamlit.app"",) Next Data elements DataframesDisplay a dataframe as an interactive table.st.dataframe(my_data_frame) Data editorDisplay a data editor widget.edited = st.data_editor(df, num_rows=""dynamic"") Column configurationConfigure the display and editing behavior of dataframes and data editors.st.column_config.NumberColumn(""Price (in USD)"", min_value=0, format=""$%d"") Static tablesDisplay a static table.st.table(my_data_frame) MetricsDisplay a metric in big bold font, with an optional indicator of how the metric changed.st.metric(""My metric"", 42, 2) Dicts and JSONDisplay object or string as a pretty-printed JSON string.st.json(my_dict) Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration! PreviousImage CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates value = streamlit_image_coordinates(""https://placekitten.com/200/300"") st.write(value) Plotly EventsMake Plotly charts interactive!. Created by @null-jones.from streamlit_plotly_events import plotly_events fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.metric_cards import style_metric_cards col3.metric(label=""No Change"", value=5000, delta=0) style_metric_cards() Streamlit AggridImplementation of Ag-Grid component for Streamlit. Created by @PablocFonseca.df = pd.DataFrame({'col1': [1, 2, 3], 'col2': [4, 5, 6]}) grid_return = AgGrid(df, editable=True) new_df = grid_return['data'] Streamlit FoliumStreamlit Component for rendering Folium maps. Created by @randyzwitch.m = folium.Map(location=[39.949610, -75.150282], zoom_start=16) folium.Marker([39.949610, -75.150282], popup=""Liberty Bell"", tooltip=""Liberty Bell"").add_to(m) st_data = st_folium(m, width=725) Pandas ProfilingPandas profiling component for Streamlit. Created by @okld.df = pd.read_csv(""https://storage.googleapis.com/tf-datasets/titanic/train.csv"") pr = df.profile_report() st_profile_report(pr) Image CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates value = streamlit_image_coordinates(""https://placekitten.com/200/300"") st.write(value) Plotly EventsMake Plotly charts interactive!. Created by @null-jones.from streamlit_plotly_events import plotly_events fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.metric_cards import style_metric_cards col3.metric(label=""No Change"", value=5000, delta=0) style_metric_cards() Streamlit AggridImplementation of Ag-Grid component for Streamlit. Created by @PablocFonseca.df = pd.DataFrame({'col1': [1, 2, 3], 'col2': [4, 5, 6]}) grid_return = AgGrid(df, editable=True) new_df = grid_return['data'] Streamlit FoliumStreamlit Component for rendering Folium maps. Created by @randyzwitch.m = folium.Map(location=[39.949610, -75.150282], zoom_start=16) folium.Marker([39.949610, -75.150282], popup=""Liberty Bell"", tooltip=""Liberty Bell"").add_to(m) st_data = st_folium(m, width=725) Pandas ProfilingPandas profiling component for Streamlit. Created by @okld.df = pd.read_csv(""https://storage.googleapis.com/tf-datasets/titanic/train.csv"") pr = df.profile_report() st_profile_report(pr) Image CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates value = streamlit_image_coordinates(""https://placekitten.com/200/300"") st.write(value) Plotly EventsMake Plotly charts interactive!. Created by @null-jones.from streamlit_plotly_events import plotly_events fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.metric_cards import style_metric_cards col3.metric(label=""No Change"", value=5000, delta=0) style_metric_cards() Next Chart elements Simple area chartsDisplay an area chart.st.area_chart(my_data_frame) Simple bar chartsDisplay a bar chart.st.bar_chart(my_data_frame) Simple line chartsDisplay a line chart.st.line_chart(my_data_frame) Simple scatter chartsDisplay a line chart.st.scatter_chart(my_data_frame) Scatterplots on mapsDisplay a map with points on it.st.map(my_data_frame) MatplotlibDisplay a matplotlib.pyplot figure.st.pyplot(my_mpl_figure) AltairDisplay a chart using the Altair library.st.altair_chart(my_altair_chart) Vega-LiteDisplay a chart using the Vega-Lite library.st.vega_lite_chart(my_vega_lite_chart) PlotlyDisplay an interactive Plotly chart.st.plotly_chart(my_plotly_chart) BokehDisplay an interactive Bokeh chart.st.bokeh_chart(my_bokeh_chart) PyDeckDisplay a chart using the PyDeck library.st.pydeck_chart(my_pydeck_chart) GraphVizDisplay a graph using the dagre-d3 library.st.graphviz_chart(my_graphviz_spec) Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration! PreviousStreamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl(""https://assets5.lottiefiles.com/packages/lf20_V9t630.json"") st_lottie(lottie_hello, key=""hello"") Plotly EventsMake Plotly charts interactive!. Created by @null-jones.fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.chart += get_annotations_chart(annotations=[(""Mar 01, 2008"", ""Pretty good day for GOOG""), (""Dec 01, 2007"", ""Something's going wrong for GOOG & AAPL""), (""Nov 01, 2008"", ""Market starts again thanks to...""), (""Dec 01, 2009"", ""Small crash for GOOG after...""),],) st.altair_chart(chart, use_container_width=True) PlostA deceptively simple plotting library for Streamlit. Created by @tvst.import plost plost.line_chart(my_dataframe, x='time', y='stock_value', color='stock_name',) HiPlotHigh dimensional Interactive Plotting. Created by @facebookresearch.data = [{'dropout':0.1, 'lr': 0.001, 'loss': 10.0, 'optimizer': 'SGD'}, {'dropout':0.15, 'lr': 0.01, 'loss': 3.5, 'optimizer': 'Adam'}, {'dropout':0.3, 'lr': 0.1, 'loss': 4.5, 'optimizer': 'Adam'}] hip.Experiment.from_iterable(data).display() EChartsHigh dimensional Interactive Plotting. Created by @andfanilo.from streamlit_echarts import st_echarts st_echarts(options=options) Streamlit FoliumStreamlit Component for rendering Folium maps. Created by @randyzwitch.m = folium.Map(location=[39.949610, -75.150282], zoom_start=16) st_data = st_folium(m, width=725) Spacy-StreamlitspaCy building blocks and visualizers for Streamlit apps. Created by @explosion.models = [""en_core_web_sm"", ""en_core_web_md""] spacy_streamlit.visualize(models, ""Sundar Pichai is the CEO of Google."") Streamlit AgraphA Streamlit Graph Vis, based on react-grah-vis. Created by @ChrisDelClea.from streamlit_agraph import agraph, Node, Edge, Config agraph(nodes=nodes, edges=edges, config=config) Streamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl(""https://assets5.lottiefiles.com/packages/lf20_V9t630.json"") st_lottie(lottie_hello, key=""hello"") Plotly EventsMake Plotly charts interactive!. Created by @null-jones.fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.chart += get_annotations_chart(annotations=[(""Mar 01, 2008"", ""Pretty good day for GOOG""), (""Dec 01, 2007"", ""Something's going wrong for GOOG & AAPL""), (""Nov 01, 2008"", ""Market starts again thanks to...""), (""Dec 01, 2009"", ""Small crash for GOOG after...""),],) st.altair_chart(chart, use_container_width=True) PlostA deceptively simple plotting library for Streamlit. Created by @tvst.import plost plost.line_chart(my_dataframe, x='time', y='stock_value', color='stock_name',) HiPlotHigh dimensional Interactive Plotting. Created by @facebookresearch.data = [{'dropout':0.1, 'lr': 0.001, 'loss': 10.0, 'optimizer': 'SGD'}, {'dropout':0.15, 'lr': 0.01, 'loss': 3.5, 'optimizer': 'Adam'}, {'dropout':0.3, 'lr': 0.1, 'loss': 4.5, 'optimizer': 'Adam'}] hip.Experiment.from_iterable(data).display() EChartsHigh dimensional Interactive Plotting. Created by @andfanilo.from streamlit_echarts import st_echarts st_echarts(options=options) Streamlit FoliumStreamlit Component for rendering Folium maps. Created by @randyzwitch.m = folium.Map(location=[39.949610, -75.150282], zoom_start=16) st_data = st_folium(m, width=725) Spacy-StreamlitspaCy building blocks and visualizers for Streamlit apps. Created by @explosion.models = [""en_core_web_sm"", ""en_core_web_md""] spacy_streamlit.visualize(models, ""Sundar Pichai is the CEO of Google."") Streamlit AgraphA Streamlit Graph Vis, based on react-grah-vis. Created by @ChrisDelClea.from streamlit_agraph import agraph, Node, Edge, Config agraph(nodes=nodes, edges=edges, config=config) Streamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl(""https://assets5.lottiefiles.com/packages/lf20_V9t630.json"") st_lottie(lottie_hello, key=""hello"") Plotly EventsMake Plotly charts interactive!. Created by @null-jones.fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.chart += get_annotations_chart(annotations=[(""Mar 01, 2008"", ""Pretty good day for GOOG""), (""Dec 01, 2007"", ""Something's going wrong for GOOG & AAPL""), (""Nov 01, 2008"", ""Market starts again thanks to...""), (""Dec 01, 2009"", ""Small crash for GOOG after...""),],) st.altair_chart(chart, use_container_width=True) Next Input widgets ButtonDisplay a button widget.clicked = st.button(""Click me"") Download buttonDisplay a download button widget.st.download_button(""Download file"", file) Form buttonDisplay a form submit button. For use with st.form.st.form_submit_button(""Sign up"") Link buttonDisplay a link button.st.link_button(""Go to gallery"", url) Page linkDisplay a link to another page in a multipage app.st.page_link(""app.py"", label=""Home"", icon=""🏠"") st.page_link(""pages/profile.py"", label=""My profile"") CheckboxDisplay a checkbox widget.selected = st.checkbox(""I agree"") Color pickerDisplay a color picker widget.color = st.color_picker(""Pick a color"") MultiselectDisplay a multiselect widget. The multiselect widget starts as empty.choices = st.multiselect(""Buy"", [""milk"", ""apples"", ""potatoes""]) RadioDisplay a radio button widget.choice = st.radio(""Pick one"", [""cats"", ""dogs""]) SelectboxDisplay a select widget.choice = st.selectbox(""Pick one"", [""cats"", ""dogs""]) Select-sliderDisplay a slider widget to select items from a list.size = st.select_slider(""Pick a size"", [""S"", ""M"", ""L""]) ToggleDisplay a toggle widget.activated = st.toggle(""Activate"") Number inputDisplay a numeric input widget.choice = st.number_input(""Pick a number"", 0, 10) SliderDisplay a slider widget.number = st.slider(""Pick a number"", 0, 100) Date inputDisplay a date input widget.date = st.date_input(""Your birthday"") Time inputDisplay a time input widget.time = st.time_input(""Meeting time"") Chat inputDisplay a chat input widget.prompt = st.chat_input(""Say something"") if prompt: st.write(f""The user has sent: {prompt}"") Text-areaDisplay a multi-line text input widget.text = st.text_area(""Text to translate"") Text inputDisplay a single-line text input widget.name = st.text_input(""First name"") Data editorDisplay a data editor widget.edited = st.experimental_data_editor(df, num_rows=""dynamic"") File UploaderDisplay a file uploader widget.data = st.file_uploader(""Upload a CSV"") Camera inputDisplay a widget that allows users to upload images directly from a camera.image = st.camera_input(""Take a picture"") Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration! PreviousStreamlit ChatStreamlit Component for a Chatbot UI. Created by @AI-Yash.from streamlit_chat import message message(""My message"") message(""Hello bot!"", is_user=True) # align's the message to the right Streamlit Option MenuSelect a single item from a list of options in a menu. Created by @victoryhb.from streamlit_option_menu import option_menu option_menu(""Main Menu"", [""Home"", 'Settings'], icons=['house', 'gear'], menu_icon=""cast"", default_index=1) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.stoggle import stoggle stoggle( ""Click me!"", """"""🥷 Surprise! Here's some additional content"""""",) Streamlit ElementsCreate a draggable and resizable dashboard in Streamlit. Created by @okls.from streamlit_elements import elements, mui, html with elements(""new_element""): mui.Typography(""Hello world"") TagsAdd tags to your Streamlit apps. Created by @gagan3012.from streamlit_tags import st_tags st_tags(label='# Enter Keywords:', text='Press enter to add more', value=['Zero', 'One', 'Two'], suggestions=['five', 'six', 'seven', 'eight', 'nine', 'three', 'eleven', 'ten', 'four'], maxtags = 4, key='1') StqdmThe simplest way to handle a progress bar in streamlit app. Created by @Wirg.from stqdm import stqdm for _ in stqdm(range(50)): sleep(0.5) TimelineDisplay a Timeline in Streamlit apps using TimelineJS. Created by @innerdoc.from streamlit_timeline import timeline with open('example.json', ""r"") as f: timeline(f.read(), height=800) Camera input liveAlternative for st.camera_input which returns the webcam images live. Created by @blackary.from camera_input_live import camera_input_live image = camera_input_live() st.image(value) Streamlit AceAce editor component for Streamlit. Created by @okld.from streamlit_ace import st_ace content = st_ace() content Streamlit ChatStreamlit Component for a Chatbot UI. Created by @AI-Yash.from streamlit_chat import message message(""My message"") message(""Hello bot!"", is_user=True) # align's the message to the right Streamlit Option MenuSelect a single item from a list of options in a menu. Created by @victoryhb.from streamlit_option_menu import option_menu option_menu(""Main Menu"", [""Home"", 'Settings'], icons=['house', 'gear'], menu_icon=""cast"", default_index=1) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.stoggle import stoggle stoggle( ""Click me!"", """"""🥷 Surprise! Here's some additional content"""""",) Streamlit ElementsCreate a draggable and resizable dashboard in Streamlit. Created by @okls.from streamlit_elements import elements, mui, html with elements(""new_element""): mui.Typography(""Hello world"") TagsAdd tags to your Streamlit apps. Created by @gagan3012.from streamlit_tags import st_tags st_tags(label='# Enter Keywords:', text='Press enter to add more', value=['Zero', 'One', 'Two'], suggestions=['five', 'six', 'seven', 'eight', 'nine', 'three', 'eleven', 'ten', 'four'], maxtags = 4, key='1') StqdmThe simplest way to handle a progress bar in streamlit app. Created by @Wirg.from stqdm import stqdm for _ in stqdm(range(50)): sleep(0.5) TimelineDisplay a Timeline in Streamlit apps using TimelineJS. Created by @innerdoc.from streamlit_timeline import timeline with open('example.json', ""r"") as f: timeline(f.read(), height=800) Camera input liveAlternative for st.camera_input which returns the webcam images live. Created by @blackary.from camera_input_live import camera_input_live image = camera_input_live() st.image(value) Streamlit AceAce editor component for Streamlit. Created by @okld.from streamlit_ace import st_ace content = st_ace() content Streamlit ChatStreamlit Component for a Chatbot UI. Created by @AI-Yash.from streamlit_chat import message message(""My message"") message(""Hello bot!"", is_user=True) # align's the message to the right Streamlit Option MenuSelect a single item from a list of options in a menu. Created by @victoryhb.from streamlit_option_menu import option_menu option_menu(""Main Menu"", [""Home"", 'Settings'], icons=['house', 'gear'], menu_icon=""cast"", default_index=1) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.stoggle import stoggle stoggle( ""Click me!"", """"""🥷 Surprise! Here's some additional content"""""",) Next Media elements ImageDisplay an image or list of images.st.image(numpy_array) st.image(image_bytes) st.image(file) st.image(""https://example.com/myimage.jpg"") AudioDisplay an audio player.st.audio(numpy_array) st.audio(audio_bytes) st.audio(file) st.audio(""https://example.com/myaudio.mp3"", format=""audio/mp3"") VideoDisplay a video player.st.video(numpy_array) st.video(video_bytes) st.video(file) st.video(""https://example.com/myvideo.mp4"", format=""video/mp4"") Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration! PreviousStreamlit CropperA simple image cropper for Streamlit. Created by @turner-anderson.from streamlit_cropper import st_cropper st_cropper(img, realtime_update=realtime_update, box_color=box_color, aspect_ratio=aspect_ratio) Image CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates streamlit_image_coordinates(""https://placekitten.com/200/300"") Streamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl(""https://assets5.lottiefiles.com/packages/lf20_V9t630.json"") st_lottie(lottie_hello, key=""hello"") Streamlit WebrtcHandling and transmitting real-time video/audio streams with Streamlit. Created by @whitphx.from streamlit_webrtc import webrtc_streamer webrtc_streamer(key=""sample"") Drawable CanvasProvides a sketching canvas using Fabric.js. Created by @andfanilo.from streamlit_drawable_canvas import st_canvas st_canvas(fill_color=""rgba(255, 165, 0, 0.3)"", stroke_width=stroke_width, stroke_color=stroke_color, background_color=bg_color, background_image=Image.open(bg_image) if bg_image else None, update_streamlit=realtime_update, height=150, drawing_mode=drawing_mode, point_display_radius=point_display_radius if drawing_mode == 'point' else 0, key=""canvas"",) Image ComparisonCompare images with a slider using JuxtaposeJS. Created by @fcakyon.from streamlit_image_comparison import image_comparison image_comparison(img1=""image1.jpg"", img2=""image2.jpg"",) Streamlit CropperA simple image cropper for Streamlit. Created by @turner-anderson.from streamlit_cropper import st_cropper st_cropper(img, realtime_update=realtime_update, box_color=box_color, aspect_ratio=aspect_ratio) Image CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates streamlit_image_coordinates(""https://placekitten.com/200/300"") Streamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl(""https://assets5.lottiefiles.com/packages/lf20_V9t630.json"") st_lottie(lottie_hello, key=""hello"") Streamlit WebrtcHandling and transmitting real-time video/audio streams with Streamlit. Created by @whitphx.from streamlit_webrtc import webrtc_streamer webrtc_streamer(key=""sample"") Drawable CanvasProvides a sketching canvas using Fabric.js. Created by @andfanilo.from streamlit_drawable_canvas import st_canvas st_canvas(fill_color=""rgba(255, 165, 0, 0.3)"", stroke_width=stroke_width, stroke_color=stroke_color, background_color=bg_color, background_image=Image.open(bg_image) if bg_image else None, update_streamlit=realtime_update, height=150, drawing_mode=drawing_mode, point_display_radius=point_display_radius if drawing_mode == 'point' else 0, key=""canvas"",) Image ComparisonCompare images with a slider using JuxtaposeJS. Created by @fcakyon.from streamlit_image_comparison import image_comparison image_comparison(img1=""image1.jpg"", img2=""image2.jpg"",) Streamlit CropperA simple image cropper for Streamlit. Created by @turner-anderson.from streamlit_cropper import st_cropper st_cropper(img, realtime_update=realtime_update, box_color=box_color, aspect_ratio=aspect_ratio) Image CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates streamlit_image_coordinates(""https://placekitten.com/200/300"") Streamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl(""https://assets5.lottiefiles.com/packages/lf20_V9t630.json"") st_lottie(lottie_hello, key=""hello"") Next Layouts and containers ColumnsInsert containers laid out as side-by-side columns.col1, col2 = st.columns(2) col1.write(""this is column 1"") col2.write(""this is column 2"") ContainerInsert a multi-element container.c = st.container() st.write(""This will show last"") c.write(""This will show first"") c.write(""This will show second"") Modal dialogsInsert a modal dialog that can rerun independently from the rest of the script.@st.experimental_dialog(""Sign up"") def email_form(): name = st.text_input(""Name"") email = st.text_input(""Email"") EmptyInsert a single-element container.c = st.empty() st.write(""This will show last"") c.write(""This will be replaced"") c.write(""This will show first"") ExpanderInsert a multi-element container that can be expanded/collapsed.with st.expander(""Open to see more""): st.write(""This is more content"") PopoverInsert a multi-element popover container that can be opened/closed.with st.popover(""Settings""): st.checkbox(""Show completed"") SidebarDisplay items in a sidebar.st.sidebar.write(""This lives in the sidebar"") st.sidebar.button(""Click me!"") TabsInsert containers separated into tabs.tab1, tab2 = st.tabs([""Tab 1"", ""Tab2""]) tab1.write(""this is tab 1"") tab2.write(""this is tab 2"") Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration!Streamlit ElementsCreate a draggable and resizable dashboard in Streamlit. Created by @okls.from streamlit_elements import elements, mui, html with elements(""new_element""): mui.Typography(""Hello world"") PydanticAuto-generate Streamlit UI from Pydantic Models and Dataclasses. Created by @lukasmasuch.import streamlit_pydantic as sp sp.pydantic_form(key=""my_form"", model=ExampleModel) Streamlit PagesAn experimental version of Streamlit Multi-Page Apps. Created by @blackary.from st_pages import Page, show_pages, add_page_title show_pages([ Page(""streamlit_app.py"", ""Home"", ""🏠""), Page(""other_pages/page2.py"", ""Page 2"", "":books:""), ]) Chat elements Streamlit provides a few commands to help you build conversational apps. These chat elements are designed to be used in conjunction with each other, but you can also use them separately. st.chat_message lets you insert a chat message container into the app so you can display messages from the user or the app. Chat containers can contain other Streamlit elements, including charts, tables, text, and more. st.chat_input lets you display a chat input widget so the user can type in a message. Chat inputDisplay a chat input widget.prompt = st.chat_input(""Say something"") if prompt: st.write(f""The user has sent: {prompt}"") Chat messageInsert a chat message container.import numpy as np with st.chat_message(""user""): st.write(""Hello 👋"") st.line_chart(np.random.randn(30, 3)) Status containerDisplay output of long-running tasks in a container.with st.status('Running'): do_something_slow() st.write_streamWrite generators or streams to the app with a typewriter effect.st.write_stream(my_generator) st.write_stream(my_llm_stream) Status elements Progress barDisplay a progress bar.for i in range(101): st.progress(i) do_something_slow() SpinnerTemporarily displays a message while executing a block of code.with st.spinner(""Please wait...""): do_something_slow() Status containerDisplay output of long-running tasks in a container.with st.status('Running'): do_something_slow() ToastBriefly displays a toast message in the bottom-right corner.st.toast('Butter!', icon='🧈') BalloonsDisplay celebratory balloons!do_something() # Celebrate when all done! st.balloons() SnowflakesDisplay celebratory snowflakes!do_something() # Celebrate when all done! st.snow() Success boxDisplay a success message.st.success(""Match found!"") Info boxDisplay an informational message.st.info(""Dataset is updated every day at midnight."") Warning boxDisplay warning message.st.warning(""Unable to fetch image. Skipping..."") Error boxDisplay error message.st.error(""We encountered an error"") Exception outputDisplay an exception.e = RuntimeError(""This is an exception of type RuntimeError"") st.exception(e) Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration!StqdmThe simplest way to handle a progress bar in streamlit app. Created by @Wirg.from stqdm import stqdm for _ in stqdm(range(50)): sleep(0.5) Custom notification boxA custom notification box with the ability to close it out. Created by @Socvest.from streamlit_custom_notification_box import custom_notification_box styles = {'material-icons':{'color': 'red'}, 'text-icon-link-close-container': {'box-shadow': '#3896de 0px 4px'}, 'notification-text': {'':''}, 'close-button':{'':''}, 'link':{'':''}} custom_notification_box(icon='info', textDisplay='We are almost done with your registration...', externalLink='more info', url='#', styles=styles, key=""foo"") Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.let_it_rain import rain rain(emoji=""🎈"", font_size=54, falling_speed=5, animation_length=""infinite"",) App logic and configuration Navigation and pages Switch pageProgrammatically navigates to a specified page.st.switch_page(""pages/my_page.py"") Page linkDisplay a link to another page in a multipage app.st.page_link(""app.py"", label=""Home"", icon=""🏠"") st.page_link(""pages/profile.py"", label=""My profile"") Execution flow Modal dialogsInsert a modal dialog that can rerun independently from the rest of the script.@st.experimental_dialog(""Sign up"") def email_form(): name = st.text_input(""Name"") email = st.text_input(""Email"") FormsCreate a form that batches elements together with a “Submit"" button.with st.form(key='my_form'): name = st.text_input(""Name"") email = st.text_input(""Email"") st.form_submit_button(""Sign up"") Partial rerunsDefine a fragment to rerun independently from the rest of the script.@st.experimental_fragment(run_every=""10s"") def fragment(): df = get_data() st.line_chart(df) Rerun scriptRerun the script immediately.st.rerun() Stop executionStops execution immediately.st.stop() Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration!AutorefreshForce a refresh without tying up a script. Created by @kmcgrady.from streamlit_autorefresh import st_autorefresh st_autorefresh(interval=2000, limit=100, key=""fizzbuzzcounter"") PydanticAuto-generate Streamlit UI from Pydantic Models and Dataclasses. Created by @lukasmasuch.import streamlit_pydantic as sp sp.pydantic_form(key=""my_form"", model=ExampleModel) Streamlit PagesAn experimental version of Streamlit Multi-Page Apps. Created by @blackary.from st_pages import Page, show_pages, add_page_title show_pages([ Page(""streamlit_app.py"", ""Home"", ""🏠""), Page(""other_pages/page2.py"", ""Page 2"", "":books:""), ]) Caching and state Cache dataFunction decorator to cache functions that return data (e.g. dataframe transforms, database queries, ML inference).@st.cache_data def long_function(param1, param2): # Perform expensive computation here or # fetch data from the web here return data Cache resourceFunction decorator to cache functions that return global resources (e.g. database connections, ML models).@st.cache_resource def init_model(): # Return a global resource here return pipeline( ""sentiment-analysis"", model=""distilbert-base-uncased-finetuned-sst-2-english"" ) Session stateSession state is a way to share variables between reruns, for each user session.st.session_state['key'] = value Query parametersGet, set, or clear the query parameters that are shown in the browser's URL bar.st.query_params[key] = value st.query_params.clear() Connections and databases Setup your connection Create a connectionConnect to a data source or APIconn = st.connection('pets_db', type='sql') pet_owners = conn.query('select * from pet_owners') st.dataframe(pet_owners) Built-in connections SnowflakeConnectionA connection to Snowflake.conn = st.connection('snowflake') SQLConnectionA connection to a SQL database using SQLAlchemy.conn = st.connection('sql') Build your own connections Connection base classBuild your own connection with BaseConnection.class MyConnection(BaseConnection[myconn.MyConnection]): def _connect(self, **kwargs) -> MyConnection: return myconn.connect(**self._secrets, **kwargs) def query(self, query): return self._instance.query(query) Secrets management Secrets singletonAccess secrets from a local TOML file.key = st.secrets[""OpenAI_key""] Secrets fileSave your secrets in a per-project or per-profile TOML file.OpenAI_key = """" Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration!AuthenticatorA secure authentication module to validate user credentials. Created by @mkhorasani.import streamlit_authenticator as stauth authenticator = stauth.Authenticate( config['credentials'], config['cookie']['name'], config['cookie']['key'], config['cookie']['expiry_days'], config['preauthorized']) WS localStorageA simple synchronous way of accessing localStorage from your app. Created by @gagangoku.from streamlit_ws_localstorage import injectWebsocketCode ret = conn.setLocalStorageVal(key='k1', val='v1') st.write('ret: ' + ret) Streamlit Auth0The fastest way to provide comprehensive login inside Streamlit. Created by @conradbez.from auth0_component import login_button user_info = login_button(clientId, domain = domain) st.write(user_info) Custom Components Declare a componentCreate and register a custom component.st.components.v1.declare_component( ""custom_slider"", ""/frontend"", ) HTMLDisplay an HTML string in an iframe.st.components.v1.html( ""

Foo bar.

"" ) iframeLoad a remote URL in an iframe.st.components.v1.iframe( ""docs.streamlit.io"" ) Utilities and user info User infost.experimental_user returns information about the logged-in user of private apps on Streamlit Community Cloud.if st.experimental_user.email == ""foo@corp.com"": st.write(""Welcome back, "", st.experimental_user.email) else: st.write(""You are not authorized to view this page."") Get helpDisplay object’s doc string, nicely formatted.st.help(st.write) st.help(pd.DataFrame) Render HTMLRenders HTML strings to your app.css = """""" """""" st.html(css) Configuration Configuration fileConfigures the default settings for your app.your-project/ ├── .streamlit/ │ └── config.toml └── your_app.py Set page title, favicon, and moreConfigures the default settings of the page.st.set_page_config( page_title=""My app"", page_icon="":shark:"", ) Developer tools App testing st.testing.v1.AppTestst.testing.v1.AppTest simulates a running Streamlit app for testing.from streamlit.testing.v1 import AppTest at = AppTest.from_file(""streamlit_app.py"") at.secrets[""WORD""] = ""Foobar"" at.run() assert not at.exception at.text_input(""word"").input(""Bazbat"").run() assert at.warning[0].value == ""Try again."" AppTest.from_filest.testing.v1.AppTest.from_file initializes a simulated app from a file.from streamlit.testing.v1 import AppTest at = AppTest.from_file(""streamlit_app.py"") at.run() AppTest.from_stringst.testing.v1.AppTest.from_string initializes a simulated app from a string.from streamlit.testing.v1 import AppTest at = AppTest.from_string(app_script_as_string) at.run() AppTest.from_functionst.testing.v1.AppTest.from_function initializes a simulated app from a function.from streamlit.testing.v1 import AppTest at = AppTest.from_function(app_script_as_callable) at.run() BlockA representation of container elements, including: st.chat_message st.columns st.sidebar st.tabs The main body of the app. # at.sidebar returns a Block at.sidebar.button[0].click().run() assert not at.exception ElementThe base class for representation of all elements, including: st.title st.header st.markdown st.dataframe # at.title returns a sequence of Title # Title inherits from Element assert at.title[0].value == ""My awesome app"" ButtonA representation of st.button and st.form_submit_button.at.button[0].click().run() ChatInputA representation of st.chat_input.at.chat_input[0].set_value(""What is Streamlit?"").run() CheckboxA representation of st.checkbox.at.checkbox[0].check().run() ColorPickerA representation of st.color_picker.at.color_picker[0].pick(""#FF4B4B"").run() DateInputA representation of st.date_input.release_date = datetime.date(2023, 10, 26) at.date_input[0].set_value(release_date).run() MultiselectA representation of st.multiselect.at.multiselect[0].select(""New York"").run() NumberInputA representation of st.number_input.at.number_input[0].increment().run() RadioA representation of st.radio.at.radio[0].set_value(""New York"").run() SelectSliderA representation of st.select_slider.at.select_slider[0].set_range(""A"",""C"").run() SelectboxA representation of st.selectbox.at.selectbox[0].select(""New York"").run() SliderA representation of st.slider.at.slider[0].set_range(2,5).run() TextAreaA representation of st.text_area.at.text_area[0].input(""Streamlit is awesome!"").run() TextInputA representation of st.text_input.at.text_input[0].input(""Streamlit"").run() TimeInputA representation of st.time_input.at.time_input[0].increment().run() ToggleA representation of st.toggle.at.toggle[0].set_value(""True"").run() Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration!Pandas ProfilingPandas profiling component for Streamlit. Created by @okld.df = pd.read_csv(""https://storage.googleapis.com/tf-datasets/titanic/train.csv"") pr = df.profile_report() st_profile_report(pr) Streamlit AceAce editor component for Streamlit. Created by @okld.from streamlit_ace import st_ace content = st_ace() content Streamlit AnalyticsTrack & visualize user interactions with your streamlit app. Created by @jrieke.import streamlit_analytics with streamlit_analytics.track(): st.text_input(""Write something"") Previous: ConceptsNext: Write and magicforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy" https://docs.streamlit.io/develop/concepts/architecture/fragments#defining-and-calling-a-fragment,"DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsremoveCOREArchitecture & executionremoveRunning your appStreamlit's architectureThe app chromeCachingSession StateFormsFragmentsWidget behaviorMultipage appsaddApp designaddADDITIONALConnections and secretsaddCustom componentsaddConfiguration and themingaddApp testingaddAPI referenceaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Develop/Concepts/Architecture & execution/FragmentsWorking with fragments and partial reruns Reruns are a central part of every Streamlit app. When users interact with widgets, your script reruns from top to bottom, and your app's frontend is updated. Streamlit provides several features to help you develop your app within this execution model. Streamlit version 1.33.0 introduced fragments to allow rerunning a portion of your code instead of your full script. As your app grows larger and more complex, these partial reruns help your app be efficient and performant. Fragments give you finer, easy-to-understand control over your app's execution flow. Before you read about fragments, we recommend having a basic understanding of caching, Session State, and forms. Use cases for fragments Fragments are versatile and applicable to a wide variety of circumstances. Here are just a few, common scenarios where fragments are useful: Your app has multiple visualizations and each one takes time to load, but you have a filter input that only updates one of them. You have a dynamic form that doesn't need to update the rest of your app (until the form is complete). You want to automatically update a single component or group of components to stream data. Defining and calling a fragment Streamlit provides a decorator (st.experimental_fragment) to turn any function into a fragment function. When you call a fragment function that contains a widget function, a user triggers a partial rerun instead of a full rerun when they interact with that fragment's widget. During a partial rerun, your fragment function is re-executed. Anything within the main body of your fragment is updated on the frontend, while the rest of your app remains the same. We'll describe fragments written across multiple containers later on. Here is a basic example of defining and calling a fragment function. Just like with caching, remember to call your function after defining it. import streamlit as st @st.experimental_fragment def fragment_function(): if st.button(""Hi!""): st.write(""Hi back!"") fragment_function() If you want the main body of your fragment to appear in the sidebar or another container, call your fragment function inside a context manager. with st.sidebar: fragment_function() Partial rerun execution flow Consider the following code with the explanation and diagram below. import streamlit as st st.title(""My Awesome App"") @st.experimental_fragment() def toggle_and_text(): cols = st.columns(2) cols[0].toggle(""Toggle"") cols[1].text_area(""Enter text"") @st.experimental_fragment() def filter_and_file(): cols = st.columns(2) cols[0].checkbox(""Filter"") cols[1].file_uploader(""Upload image"") toggle_and_text() cols = st.columns(2) cols[0].selectbox(""Select"", [1,2,3], None) cols[1].button(""Update"") filter_and_file() When a user interacts with an input widget inside a fragment, only the fragment reruns instead of the full script. When a user interacts with an input widget outside a fragment, the full script reruns as usual. If you run the code above, the full script will run top to bottom on your app's initial load. If you flip the toggle button in your running app, the first fragment (toggle_and_text()) will rerun, redrawing the toggle and text area while leaving everything else unchanged. If you click the checkbox, the second fragment (filter_and_file()) will rerun and consequently redraw the checkbox and file uploader. Everything else remains unchanged. Finally, if you click the update button, the full script will rerun, and Streamlit will redraw everything. Fragment return values and interacting with the rest of your app Streamlit ignores fragment return values during fragment reruns, so defining return values for your fragment functions is not recommended. Instead, if your fragment needs to share data with the rest of your app, use Session State. Fragments are just functions in your script, so they can access Session State, imported modules, and other Streamlit elements like containers. If your fragment writes to any container created outside of itself, note the following difference in behavior: Elements drawn in the main body of your fragment are cleared and redrawn in place during a fragment rerun. Repeated fragment reruns will not cause additional elements to appear. Elements drawn to containers outside the main body of fragment will not be cleared with each fragment rerun. Instead, Streamlit will draw them additively and these elements will accumulate until the next full-script rerun. To prevent elements from accumulating in outside containers, use st.empty containers. For a related tutorial, see Create a fragment across multiple containers. If you need to trigger a full-script rerun from inside a fragment, call st.rerun. For a related tutorial, see Trigger a full-script rerun from inside a fragment. Automate fragment reruns st.experimental_fragment includes a convenient run_every parameter that causes the fragment to rerun automatically at the specified time interval. These reruns are in addition to any reruns (fragment or full-script) triggered by your user. The automatic fragment reruns will continue even if your user is not interacting with your app. This is a great way to show a live data stream or status on a running background job, efficiently updating your rendered data and only your rendered data. @st.experimental_fragment(run_every=""10s"") def auto_function(): # This will update every 10 seconds! df = get_latest_updates() st.line_chart(df) auto_function() For a related tutorial, see Start and stop a streaming fragment. Compare fragments to other Streamlit features Fragments vs forms Here is a comparison between fragments and forms: Forms allow users to interact with widgets without rerunning your app. Streamlit does not send user actions within a form to your app's Python backend until the form is submitted. Widgets within a form can not dynamically update other widgets (in or out of the form) in real-time. Fragments run independently from the rest of your code. As your users interact with fragment widgets, their actions are immediately processed by your app's Python backend and your fragment code is rerun. Widgets within a fragment can dynamically update other widgets within the same fragment in real-time. A form batches user input without interaction between any widgets. A fragment immediately processes user input but limits the scope of the rerun. Fragments vs callbacks Here is a comparison between fragments and callbacks: Callbacks allow you to execute a function at the beginning of a script rerun. A callback is a single prefix to your script rerun. Fragments allow you to rerun a portion of your script. A fragment is a repeatable postfix to your script, running each time a user interacts with a fragment widget, or automatically in sequence when run_every is set. When callbacks render elements to your page, they are rendered before the rest of your page elements. When fragments render elements to your page, they are updated with each fragment rerun (unless they are written to containers outside of the fragment, in which case they accumulate there). Fragments vs custom components Here is a comparison between fragments and custom components: Components are custom frontend code that can interact with the Python code, native elements, and widgets in your Streamlit app. Custom components extend what’s possible with Streamlit. They follow the normal Streamlit execution flow. Fragments are parts of your app that can rerun independently of the full app. Fragments can be composed of multiple Streamlit elements, widgets, or any Python code. A fragment can include one or more custom components. A custom component could not easily include a fragment! Fragments vs caching Here is a comparison between fragments and caching: Caching: allows you to skip over a function and return a previously computed value. When you use caching, you execute everything except the cached function (if you've already run it before). Fragments: allow you to freeze most of your app and just execute the fragment. When you use fragments, you execute only the fragment (when triggering a fragment rerun). Caching saves you from unnecessarily running a piece of your app while the rest runs. Fragments save you from running your full app when you only want to run one piece. Limitations and unsupported behavior Fragments can't detect a change in input values. It is best to use Session State for dynamic input and output for fragment functions. Calling fragments within fragments is unsupported. Using caching and fragments on the same function is unsupported. Previous: FormsNext: Widget behaviorforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy" https://docs.streamlit.io/knowledge-base/tutorials/build-conversational-apps#stchat_message,"DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceaddTutorialsremoveExecution flowaddConnect to data sourcesaddMultipage appsaddWork with LLMsremoveBuild a basic LLM chat appBuild an LLM app using LangChainQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Develop/Tutorials/Work with LLMs/Build a basic LLM chat appBuild a basic LLM chat app Introduction The advent of large language models like GPT has revolutionized the ease of developing chat-based applications. Streamlit offers several Chat elements, enabling you to build Graphical User Interfaces (GUIs) for conversational agents or chatbots. Leveraging session state along with these elements allows you to construct anything from a basic chatbot to a more advanced, ChatGPT-like experience using purely Python code. In this tutorial, we'll start by walking through Streamlit's chat elements, st.chat_message and st.chat_input. Then we'll proceed to construct three distinct applications, each showcasing an increasing level of complexity and functionality: First, we'll Build a bot that mirrors your input to get a feel for the chat elements and how they work. We'll also introduce session state and how it can be used to store the chat history. This section will serve as a foundation for the rest of the tutorial. Next, you'll learn how to Build a simple chatbot GUI with streaming. Finally, we'll Build a ChatGPT-like app that leverages session state to remember conversational context, all within less than 50 lines of code. Here's a sneak peek of the LLM-powered chatbot GUI with streaming we'll build in this tutorial: Built with Streamlit 🎈Fullscreen open_in_new Play around with the above demo to get a feel for what we'll build in this tutorial. A few things to note: There's a chat input at the bottom of the screen that's always visible. It contains some placeholder text. You can type in a message and press Enter or click the run button to send it. When you enter a message, it appears as a chat message in the container above. The container is scrollable, so you can scroll up to see previous messages. A default avatar is displayed to your messages' left. The assistant's responses are streamed to the frontend and are displayed with a different default avatar. Before we start building, let's take a closer look at the chat elements we'll use. Chat elements Streamlit offers several commands to help you build conversational apps. These chat elements are designed to be used in conjunction with each other, but you can also use them separately. st.chat_message lets you insert a chat message container into the app so you can display messages from the user or the app. Chat containers can contain other Streamlit elements, including charts, tables, text, and more. st.chat_input lets you display a chat input widget so the user can type in a message. For an overview of the API, check out this video tutorial by Chanin Nantasenamat (@dataprofessor), a Senior Developer Advocate at Streamlit. st.chat_message st.chat_message lets you insert a multi-element chat message container into your app. The returned container can contain any Streamlit element, including charts, tables, text, and more. To add elements to the returned container, you can use with notation. st.chat_message's first parameter is the name of the message author, which can be either ""user"" or ""assistant"" to enable preset styling and avatars, like in the demo above. You can also pass in a custom string to use as the author name. Currently, the name is not shown in the UI but is only set as an accessibility label. For accessibility reasons, you should not use an empty string. Here's an minimal example of how to use st.chat_message to display a welcome message: import streamlit as st with st.chat_message(""user""): st.write(""Hello 👋"") Notice the message is displayed with a default avatar and styling since we passed in ""user"" as the author name. You can also pass in ""assistant"" as the author name to use a different default avatar and styling, or pass in a custom name and avatar. See the API reference for more details. import streamlit as st import numpy as np with st.chat_message(""assistant""): st.write(""Hello human"") st.bar_chart(np.random.randn(30, 3)) Built with Streamlit 🎈Fullscreen open_in_new While we've used the preferred with notation in the above examples, you can also just call methods directly in the returned objects. The below example is equivalent to the one above: import streamlit as st import numpy as np message = st.chat_message(""assistant"") message.write(""Hello human"") message.bar_chart(np.random.randn(30, 3)) So far, we've displayed predefined messages. But what if we want to display messages based on user input? st.chat_input st.chat_input lets you display a chat input widget so the user can type in a message. The returned value is the user's input, which is None if the user hasn't sent a message yet. You can also pass in a default prompt to display in the input widget. Here's an example of how to use st.chat_input to display a chat input widget and show the user's input: import streamlit as st prompt = st.chat_input(""Say something"") if prompt: st.write(f""User has sent the following prompt: {prompt}"") Built with Streamlit 🎈Fullscreen open_in_new Pretty straightforward, right? Now let's combine st.chat_message and st.chat_input to build a bot the mirrors or echoes your input. Build a bot that mirrors your input In this section, we'll build a bot that mirrors or echoes your input. More specifically, the bot will respond to your input with the same message. We'll use st.chat_message to display the user's input and st.chat_input to accept user input. We'll also use session state to store the chat history so we can display it in the chat message container. First, let's think about the different components we'll need to build our bot: Two chat message containers to display messages from the user and the bot, respectively. A chat input widget so the user can type in a message. A way to store the chat history so we can display it in the chat message containers. We can use a list to store the messages, and append to it every time the user or bot sends a message. Each entry in the list will be a dictionary with the following keys: role (the author of the message), and content (the message content). import streamlit as st st.title(""Echo Bot"") # Initialize chat history if ""messages"" not in st.session_state: st.session_state.messages = [] # Display chat messages from history on app rerun for message in st.session_state.messages: with st.chat_message(message[""role""]): st.markdown(message[""content""]) In the above snippet, we've added a title to our app and a for loop to iterate through the chat history and display each message in the chat message container (with the author role and message content). We've also added a check to see if the messages key is in st.session_state. If it's not, we initialize it to an empty list. This is because we'll be adding messages to the list later on, and we don't want to overwrite the list every time the app reruns. Now let's accept user input with st.chat_input, display the user's message in the chat message container, and add it to the chat history. # React to user input if prompt := st.chat_input(""What is up?""): # Display user message in chat message container with st.chat_message(""user""): st.markdown(prompt) # Add user message to chat history st.session_state.messages.append({""role"": ""user"", ""content"": prompt}) We used the := operator to assign the user's input to the prompt variable and checked if it's not None in the same line. If the user has sent a message, we display the message in the chat message container and append it to the chat history. All that's left to do is add the chatbot's responses within the if block. We'll use the same logic as before to display the bot's response (which is just the user's prompt) in the chat message container and add it to the history. response = f""Echo: {prompt}"" # Display assistant response in chat message container with st.chat_message(""assistant""): st.markdown(response) # Add assistant response to chat history st.session_state.messages.append({""role"": ""assistant"", ""content"": response}) Putting it all together, here's the full code for our simple chatbot GUI and the result: View full codeexpand_moreimport streamlit as st st.title(""Echo Bot"") # Initialize chat history if ""messages"" not in st.session_state: st.session_state.messages = [] # Display chat messages from history on app rerun for message in st.session_state.messages: with st.chat_message(message[""role""]): st.markdown(message[""content""]) # React to user input if prompt := st.chat_input(""What is up?""): # Display user message in chat message container st.chat_message(""user"").markdown(prompt) # Add user message to chat history st.session_state.messages.append({""role"": ""user"", ""content"": prompt}) response = f""Echo: {prompt}"" # Display assistant response in chat message container with st.chat_message(""assistant""): st.markdown(response) # Add assistant response to chat history st.session_state.messages.append({""role"": ""assistant"", ""content"": response}) Built with Streamlit 🎈Fullscreen open_in_new While the above example is very simple, it's a good starting point for building more complex conversational apps. Notice how the bot responds instantly to your input. In the next section, we'll add a delay to simulate the bot ""thinking"" before responding. Build a simple chatbot GUI with streaming In this section, we'll build a simple chatbot GUI that responds to user input with a random message from a list of pre-determind responses. In the next section, we'll convert this simple toy example into a ChatGPT-like experience using OpenAI. Just like previously, we still require the same components to build our chatbot. Two chat message containers to display messages from the user and the bot, respectively. A chat input widget so the user can type in a message. And a way to store the chat history so we can display it in the chat message containers. Let's just copy the code from the previous section and add a few tweaks to it. import streamlit as st import random import time st.title(""Simple chat"") # Initialize chat history if ""messages"" not in st.session_state: st.session_state.messages = [] # Display chat messages from history on app rerun for message in st.session_state.messages: with st.chat_message(message[""role""]): st.markdown(message[""content""]) # Accept user input if prompt := st.chat_input(""What is up?""): # Display user message in chat message container with st.chat_message(""user""): st.markdown(prompt) # Add user message to chat history st.session_state.messages.append({""role"": ""user"", ""content"": prompt}) The only difference so far is we've changed the title of our app and added imports for random and time. We'll use random to randomly select a response from a list of responses and time to add a delay to simulate the chatbot ""thinking"" before responding. All that's left to do is add the chatbot's responses within the if block. We'll use a list of responses and randomly select one to display. We'll also add a delay to simulate the chatbot ""thinking"" before responding (or stream its response). Let's make a helper function for this and insert it at the top of our app. # Streamed response emulator def response_generator(): response = random.choice( [ ""Hello there! How can I assist you today?"", ""Hi, human! Is there anything I can help you with?"", ""Do you need help?"", ] ) for word in response.split(): yield word + "" "" time.sleep(0.05) Back to writing the response in our chat interface, we'll use st.write_stream to write out the streamed response with a typewriter effect. # Display assistant response in chat message container with st.chat_message(""assistant""): response = st.write_stream(response_generator()) # Add assistant response to chat history st.session_state.messages.append({""role"": ""assistant"", ""content"": response}) Above, we've added a placeholder to display the chatbot's response. We've also added a for loop to iterate through the response and display it one word at a time. We've added a delay of 0.05 seconds between each word to simulate the chatbot ""thinking"" before responding. Finally, we append the chatbot's response to the chat history. As you've probably guessed, this is a naive implementation of streaming. We'll see how to implement streaming with OpenAI in the next section. Putting it all together, here's the full code for our simple chatbot GUI and the result: View full codeexpand_moreimport streamlit as st import random import time # Streamed response emulator def response_generator(): response = random.choice( [ ""Hello there! How can I assist you today?"", ""Hi, human! Is there anything I can help you with?"", ""Do you need help?"", ] ) for word in response.split(): yield word + "" "" time.sleep(0.05) st.title(""Simple chat"") # Initialize chat history if ""messages"" not in st.session_state: st.session_state.messages = [] # Display chat messages from history on app rerun for message in st.session_state.messages: with st.chat_message(message[""role""]): st.markdown(message[""content""]) # Accept user input if prompt := st.chat_input(""What is up?""): # Add user message to chat history st.session_state.messages.append({""role"": ""user"", ""content"": prompt}) # Display user message in chat message container with st.chat_message(""user""): st.markdown(prompt) # Display assistant response in chat message container with st.chat_message(""assistant""): response = st.write_stream(response_generator()) # Add assistant response to chat history st.session_state.messages.append({""role"": ""assistant"", ""content"": response}) Built with Streamlit 🎈Fullscreen open_in_new Play around with the above demo to get a feel for what we've built. It's a very simple chatbot GUI, but it has all the components of a more sophisticated chatbot. In the next section, we'll see how to build a ChatGPT-like app using OpenAI. Build a ChatGPT-like app Now that you've understood the basics of Streamlit's chat elements, let's make a few tweaks to it to build our own ChatGPT-like app. You'll need to install the OpenAI Python library and get an API key to follow along. Install dependencies First let's install the dependencies we'll need for this section: pip install openai streamlit Add OpenAI API key to Streamlit secrets Next, let's add our OpenAI API key to Streamlit secrets. We do this by creating .streamlit/secrets.toml file in our project directory and adding the following lines to it: # .streamlit/secrets.toml OPENAI_API_KEY = ""YOUR_API_KEY"" Write the app Now let's write the app. We'll use the same code as before, but we'll replace the list of responses with a call to the OpenAI API. We'll also add a few more tweaks to make the app more ChatGPT-like. import streamlit as st from openai import OpenAI st.title(""ChatGPT-like clone"") # Set OpenAI API key from Streamlit secrets client = OpenAI(api_key=st.secrets[""OPENAI_API_KEY""]) # Set a default model if ""openai_model"" not in st.session_state: st.session_state[""openai_model""] = ""gpt-3.5-turbo"" # Initialize chat history if ""messages"" not in st.session_state: st.session_state.messages = [] # Display chat messages from history on app rerun for message in st.session_state.messages: with st.chat_message(message[""role""]): st.markdown(message[""content""]) # Accept user input if prompt := st.chat_input(""What is up?""): # Add user message to chat history st.session_state.messages.append({""role"": ""user"", ""content"": prompt}) # Display user message in chat message container with st.chat_message(""user""): st.markdown(prompt) All that's changed is that we've added a default model to st.session_state and set our OpenAI API key from Streamlit secrets. Here's where it gets interesting. We can replace our emulated stream with the model's responses from OpenAI: # Display assistant response in chat message container with st.chat_message(""assistant""): stream = client.chat.completions.create( model=st.session_state[""openai_model""], messages=[ {""role"": m[""role""], ""content"": m[""content""]} for m in st.session_state.messages ], stream=True, ) response = st.write_stream(stream) st.session_state.messages.append({""role"": ""assistant"", ""content"": response}) Above, we've replaced the list of responses with a call to OpenAI().chat.completions.create. We've set stream=True to stream the responses to the frontend. In the API call, we pass the model name we hardcoded in session state and pass the chat history as a list of messages. We also pass the role and content of each message in the chat history. Finally, OpenAI returns a stream of responses (split into chunks of tokens), which we iterate through and display each chunk. Putting it all together, here's the full code for our ChatGPT-like app and the result: View full codeexpand_morefrom openai import OpenAI import streamlit as st st.title(""ChatGPT-like clone"") client = OpenAI(api_key=st.secrets[""OPENAI_API_KEY""]) if ""openai_model"" not in st.session_state: st.session_state[""openai_model""] = ""gpt-3.5-turbo"" if ""messages"" not in st.session_state: st.session_state.messages = [] for message in st.session_state.messages: with st.chat_message(message[""role""]): st.markdown(message[""content""]) if prompt := st.chat_input(""What is up?""): st.session_state.messages.append({""role"": ""user"", ""content"": prompt}) with st.chat_message(""user""): st.markdown(prompt) with st.chat_message(""assistant""): stream = client.chat.completions.create( model=st.session_state[""openai_model""], messages=[ {""role"": m[""role""], ""content"": m[""content""]} for m in st.session_state.messages ], stream=True, ) response = st.write_stream(stream) st.session_state.messages.append({""role"": ""assistant"", ""content"": response}) Built with Streamlit 🎈Fullscreen open_in_new Congratulations! You've built your own ChatGPT-like app in less than 50 lines of code. We're very excited to see what you'll build with Streamlit's chat elements. Experiment with different models and tweak the code to build your own conversational apps. If you build something cool, let us know on the Forum or check out some other Generative AI apps for inspiration. 🎈Previous: Work with LLMsNext: Build an LLM app using LangChainforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy" https://docs.streamlit.io/knowledge-base,"DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Knowledge baseKnowledge base The knowledge base is a self-serve library of tips, step-by-step tutorials, and articles that answer your questions about creating and deploying Streamlit apps. quizFAQ Here are some frequently asked questions about using Streamlit.downloadingInstalling dependencies. If you run into problems installing dependencies for your Streamlit apps, we've got you covered.reportDeployment issues. Have questions about deploying Streamlit apps to the cloud? This section covers deployment-related issues.Previous: DeployNext: FAQforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy" https://docs.streamlit.io/develop/tutorials/multipage/st.page_link-nav#build-the-example,"DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceaddTutorialsremoveExecution flowaddConnect to data sourcesaddMultipage appsremoveBuild navigation with st.page_linkWork with LLMsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Develop/Tutorials/Multipage apps/Build navigation with st.page_linkBuild a custom navigation menu with st.page_link Streamlit lets you build custom navigation menus and elements with st.page_link. Introduced in Streamlit version 1.31.0, st.page_link can link to other pages in your multipage app or to external sites. When linked to another page in your app, st.page_link will show a highlight effect to indicate the current page. When combined with the client.showSidebarNavigation configuration option, you can build sleek, dynamic navigation in your app. Prerequisites Create a new working directory in your development environment. We'll call this directory your-repository. Summary In this example, we'll build a dynamic navigation menu for a multipage app that depends on the current user's role. We've abstracted away the use of username and creditials to simplify the example. Instead, we'll use a selectbox on the main page of the app to switch between roles. Session State will carry this selection between pages. The app will have a main page (app.py) which serves as the abstracted log-in page. There will be three additional pages which will be hidden or accessible, depending on the current role. The file structure will be as follows: your-repository/ ├── .streamlit/ │ └── config.toml ├── pages/ │ ├── admin.py │ ├── super-admin.py │ └── user.py ├── menu.py └── app.py Here's a look at what we'll build: Built with Streamlit 🎈Fullscreen open_in_new Build the example Hide the default sidebar navigation When creating a custom navigation menu, you need to hide the default sidebar navigation using client.showSidebarNavigation. Add the following .streamlit/config.toml file to your working directory: [client] showSidebarNavigation = false Create a menu function You can write different menu logic for different pages or you can create a single menu function to call on multiple pages. In this example, we'll use the same menu logic on all pages, including a redirect to the main page when a user isn't logged in. We'll build a few helper functions to do this. menu_with_redirect() checks if a user is logged in, then either redirects them to the main page or renders the menu. menu() will call the correct helper function to render the menu based on whether the user is logged in or not. authenticated_menu() will display a menu based on an authenticated user's role. unauthenticated_menu() will display a menu for unauthenticated users. We'll call menu() on the main page and call menu_with_redirect() on the other pages. st.session_state.role will store the current selected role. If this value does not exist or is set to None, then the user is not logged in. Otherwise, it will hold the user's role as a string: ""user"", ""admin"", or ""super-admin"". Add the following menu.py file to your working directory. (We'll describe the functions in more detail below.) import streamlit as st def authenticated_menu(): # Show a navigation menu for authenticated users st.sidebar.page_link(""app.py"", label=""Switch accounts"") st.sidebar.page_link(""pages/user.py"", label=""Your profile"") if st.session_state.role in [""admin"", ""super-admin""]: st.sidebar.page_link(""pages/admin.py"", label=""Manage users"") st.sidebar.page_link( ""pages/super-admin.py"", label=""Manage admin access"", disabled=st.session_state.role != ""super-admin"", ) def unauthenticated_menu(): # Show a navigation menu for unauthenticated users st.sidebar.page_link(""app.py"", label=""Log in"") def menu(): # Determine if a user is logged in or not, then show the correct # navigation menu if ""role"" not in st.session_state or st.session_state.role is None: unauthenticated_menu() return authenticated_menu() def menu_with_redirect(): # Redirect users to the main page if not logged in, otherwise continue to # render the navigation menu if ""role"" not in st.session_state or st.session_state.role is None: st.switch_page(""app.py"") menu() Let's take a closer look at authenticated_menu(). When this function is called, st.session_state.role exists and has a value other than None. def authenticated_menu(): # Show a navigation menu for authenticated users The first two pages in the navigation menu are available to all users. Since we know a user is logged in when this function is called, we'll use the label ""Switch accounts"" for the main page. (If you don't use the label parameter, the page name will be derived from the file name like it is with the default sidebar navigation.) st.sidebar.page_link(""app.py"", label=""Switch accounts"") st.sidebar.page_link(""pages/user.py"", label=""Your profile"") We only want to show the next two pages to admins. Furthermore, we've chosen to disable—but not hide—the super-admin page when the admin user is not a super-admin. We do this using the disabled parameter. (disabled=True when the role is not ""super-admin"".) if st.session_state.role in [""admin"", ""super-admin""]: st.sidebar.page_link(""pages/admin.py"", label=""Manage users"") st.sidebar.page_link( ""pages/super-admin.py"", label=""Manage admin access"", disabled=st.session_state.role != ""super-admin"", ) It's that simple! unauthenticated_menu() will only show a link to the main page of the app with the label ""Log in."" menu() does a simple inspection of st.session_state.role to switch between the two menu-rendering functions. Finally, menu_with_redirect() extends menu() to redirect users to app.py if they aren't logged in. starTipIf you want to include emojis in your page labels, you can use the icon parameter. There's no need to include emojis in your file name or the label parameter. Create the main file of your app The main app.py file will serve as a pseudo-login page. The user can choose a role from the st.selectbox widget. A few bits of logic will save that role into Session State to preserve it while navigating between pages—even when returning to app.py. Add the following app.py file to your working directory: import streamlit as st from menu import menu # Initialize st.session_state.role to None if ""role"" not in st.session_state: st.session_state.role = None # Retrieve the role from Session State to initialize the widget st.session_state._role = st.session_state.role def set_role(): # Callback function to save the role selection to Session State st.session_state.role = st.session_state._role # Selectbox to choose role st.selectbox( ""Select your role:"", [None, ""user"", ""admin"", ""super-admin""], key=""_role"", on_change=set_role, ) menu() # Render the dynamic menu! Add other pages to your app Add the following pages/user.py file: import streamlit as st from menu import menu_with_redirect # Redirect to app.py if not logged in, otherwise show the navigation menu menu_with_redirect() st.title(""This page is available to all users"") st.markdown(f""You are currently logged with the role of {st.session_state.role}."") Session State resets if a user manually navigates to a page by URL. Therefore, if a user tries to access an admin page in this example, Session State will be cleared, and they will be redirected to the main page as an unauthenicated user. However, it's still good practice to include a check of the role at the top of each restricted page. You can use st.stop to halt an app if a role is not whitelisted. pages/admin.py: import streamlit as st from menu import menu_with_redirect # Redirect to app.py if not logged in, otherwise show the navigation menu menu_with_redirect() # Verify the user's role if st.session_state.role not in [""admin"", ""super-admin""]: st.warning(""You do not have permission to view this page."") st.stop() st.title(""This page is available to all admins"") st.markdown(f""You are currently logged with the role of {st.session_state.role}."") pages/super-admin.py: import streamlit as st from menu import menu_with_redirect # Redirect to app.py if not logged in, otherwise show the navigation menu menu_with_redirect() # Verify the user's role if st.session_state.role not in [""super-admin""]: st.warning(""You do not have permission to view this page."") st.stop() st.title(""This page is available to super-admins"") st.markdown(f""You are currently logged with the role of {st.session_state.role}."") As noted above, the redirect in menu_with_redirect() will prevent a user from ever seeing the warning messages on the admin pages. If you want to see the warning, just add another st.page_link(""pages/admin.py"") button at the bottom of app.py so you can navigate to the admin page after selecting the ""user"" role. 😉Previous: Multipage appsNext: Work with LLMsforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy" https://docs.streamlit.io/develop/concepts/design/custom-classes#understanding-how-python-defines-and-compares-classes,"DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsremoveCOREArchitecture & executionaddMultipage appsaddApp designremoveAnimate & update elementsButton behavior and examplesDataframesUsing custom classesWorking with timezonesADDITIONALConnections and secretsaddCustom componentsaddConfiguration and themingaddApp testingaddAPI referenceaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Develop/Concepts/App design/Using custom classesUsing custom Python classes in your Streamlit app If you are building a complex Streamlit app or working with existing code, you may have custom Python classes defined in your script. Common examples include the following: Defining a @dataclass to store related data within your app. Defining an Enum class to represent a fixed set of options or values. Defining custom interfaces to external services or databases not covered by st.connection. Because Streamlit reruns your script after every user interaction, custom classes may be redefined multiple times within the same Streamlit session. This may result in unwanted effects, especially with class and instance comparisons. Read on to understand this common pitfall and how to avoid it. We begin by covering some general-purpose patterns you can use for different types of custom classes, and follow with a few more technical details explaining why this matters. Finally, we go into more detail about Using Enum classes specifically, and describe a configuration option which can make them more convenient. Patterns to define your custom classes Pattern 1: Define your class in a separate module This is the recommended, general solution. If possible, move class definitions into their own module file and import them into your app script. As long as you are not editing the file where your class is defined, Streamlit will not re-import it with each rerun. Therefore, if a class is defined in an external file and imported into your script, the class will not be redefined during the session. Example: Move your class definition Try running the following Streamlit app where MyClass is defined within the page's script. isinstance() will return True on the first script run then return False on each rerun thereafter. # app.py import streamlit as st # MyClass gets redefined every time app.py reruns class MyClass: def __init__(self, var1, var2): self.var1 = var1 self.var2 = var2 if ""my_instance"" not in st.session_state: st.session_state.my_instance = MyClass(""foo"", ""bar"") # Displays True on the first run then False on every rerun st.write(isinstance(st.session_state.my_instance, MyClass)) st.button(""Rerun"") If you move the class definition out of app.py into another file, you can make isinstance() consistently return True. Consider the following file structure: myproject/ ├── my_class.py └── app.py # my_class.py class MyClass: def __init__(self, var1, var2): self.var1 = var1 self.var2 = var2 # app.py import streamlit as st from my_class import MyClass # MyClass doesn't get redefined with each rerun if ""my_instance"" not in st.session_state: st.session_state.my_instance = MyClass(""foo"", ""bar"") # Displays True on every rerun st.write(isinstance(st.session_state.my_instance, MyClass)) st.button(""Rerun"") Streamlit only reloads code in imported modules when it detects the code has changed. Thus, if you are actively editing the file where your class is defined, you may need to stop and restart your Streamlit server to avoid an undesirable class redefinition mid-session. Pattern 2: Force your class to compare internal values For classes that store data (like dataclasses), you may be more interested in comparing the internally stored values rather than the class itself. If you define a custom __eq__ method, you can force comparisons to be made on the internally stored values. Example: Define __eq__ Try running the following Streamlit app and observe how the comparison is True on the first run then False on every rerun thereafter. import streamlit as st from dataclasses import dataclass @dataclass class MyDataclass: var1: int var2: float if ""my_dataclass"" not in st.session_state: st.session_state.my_dataclass = MyDataclass(1, 5.5) # Displays True on the first run the False on every rerun st.session_state.my_dataclass == MyDataclass(1, 5.5) st.button(""Rerun"") Since MyDataclass gets redefined with each rerun, the instance stored in Session State will not be equal to any instance defined in a later script run. You can fix this by forcing a comparison of internal values as follows: import streamlit as st from dataclasses import dataclass @dataclass class MyDataclass: var1: int var2: float def __eq__(self, other): # An instance of MyDataclass is equal to another object if the object # contains the same fields with the same values return (self.var1, self.var2) == (other.var1, other.var2) if ""my_dataclass"" not in st.session_state: st.session_state.my_dataclass = MyDataclass(1, 5.5) # Displays True on every rerun st.session_state.my_dataclass == MyDataclass(1, 5.5) st.button(""Rerun"") The default Python __eq__ implementation for a regular class or @dataclass depends on the in-memory ID of the class or class instance. To avoid problems in Streamlit, your custom __eq__ method should not depend the type() of self and other. Pattern 3: Store your class as serialized data Another option for classes that store data is to define serialization and deserialization methods like to_str and from_str for your class. You can use these to store class instance data in st.session_state rather than storing the class instance itself. Similar to pattern 2, this is a way to force comparison of the internal data and bypass the changing in-memory IDs. Example: Save your class instance as a string Using the same example from pattern 2, this can be done as follows: import streamlit as st from dataclasses import dataclass @dataclass class MyDataclass: var1: int var2: float def to_str(self): return f""{self.var1},{self.var2}"" @classmethod def from_str(cls, serial_str): values = serial_str.split("","") var1 = int(values[0]) var2 = float(values[1]) return cls(var1, var2) if ""my_dataclass"" not in st.session_state: st.session_state.my_dataclass = MyDataclass(1, 5.5).to_str() # Displays True on every rerun MyDataclass.from_str(st.session_state.my_dataclass) == MyDataclass(1, 5.5) st.button(""Rerun"") Pattern 4: Use caching to preserve your class For classes that are used as resources (database connections, state managers, APIs), consider using the cached singleton pattern. Use @st.cache_resource to decorate a @staticmethod of your class to generate a single, cached instance of the class. For example: import streamlit as st class MyResource: def __init__(self, api_url: str): self._url = api_url @st.cache_resource(ttl=300) @staticmethod def get_resource_manager(api_url: str): return MyResource(api_url) # This is cached until Session State is cleared or 5 minutes has elapsed. resource_manager = MyResource.get_resource_manager(""http://example.com/api/"") When you use one of Streamlit's caching decorators on a function, Streamlit doesn't use the function object to look up cached values. Instead, Streamlit's caching decorators index return values using the function's qualified name and module. So, even though Streamlit redefines MyResource with each script run, st.cache_resource is unaffected by this. get_resource_manager() will return its cached value with each rerun, until the value expires. Understanding how Python defines and compares classes So what's really happening here? We'll consider a simple example to illustrate why this is a pitfall. Feel free to skip this section if you don't want to deal more details. You can jump ahead to learn about Using Enum classes. Example: What happens when you define the same class twice? Set aside Streamlit for a moment and think about this simple Python script: from dataclasses import dataclass @dataclass class Student: student_id: int name: str Marshall_A = Student(1, ""Marshall"") Marshall_B = Student(1, ""Marshall"") # This is True (because a dataclass will compare two of its instances by value) Marshall_A == Marshall_B # Redefine the class @dataclass class Student: student_id: int name: str Marshall_C = Student(1, ""Marshall"") # This is False Marshall_A == Marshall_C In this example, the dataclass Student is defined twice. All three Marshalls have the same internal values. If you compare Marshall_A and Marshall_B they will be equal because they were both created from the first definition of Student. However, if you compare Marshall_A and Marshall_C they will not be equal because Marshall_C was created from the second definition of Student. Even though both Student dataclasses are defined exactly the same, they have differnt in-memory IDs and are therefore different. What's happening in Streamlit? In Streamlit, you probably don't have the same class written twice in your page script. However, the rerun logic of Streamlit creates the same effect. Let's use the above example for an analogy. If you define a class in one script run and save an instance in Session State, then a later rerun will redefine the class and you may end up comparing a Mashall_C in your rerun to a Marshall_A in Session State. Since widgets rely on Session State under the hood, this is where things can get confusing. How Streamlit widgets store options Several Streamlit UI elements, such as st.selectbox or st.radio, accept multiple-choice options via an options argument. The user of your application can typically select one or more of these options. The selected value is returned by the widget function. For example: number = st.selectbox(""Pick a number, any number"", options=[1, 2, 3]) # number == whatever value the user has selected from the UI. When you call a function like st.selectbox and pass an Iterable to options, the Iterable and current selection are saved into a hidden portion of Session State called the Widget Metadata. When the user of your application interacts with the st.selectbox widget, the broswer sends the index of their selection to your Streamlit server. This index is used to determine which values from the original options list, saved in the Widget Metadata from the previous page execution, are returned to your application. The key detail is that the value returned by st.selectbox (or similar widget function) is from an Iterable saved in Session State during a previous execution of the page, NOT the values passed to options on the current execution. There are a number of architectural reasons why Streamlit is designed this way, which we won't go into here. However, this is how we end up comparing instances of different classes when we think we are comparing instances of the same class. A pathological example The above explanation might be a bit confusing, so here's a pathological example to illustrate the idea. import streamlit as st from dataclasses import dataclass @dataclass class Student: student_id: int name: str Marshall_A = Student(1, ""Marshall"") if ""B"" not in st.session_state: st.session_state.B = Student(1, ""Marshall"") Marshall_B = st.session_state.B options = [Marshall_A,Marshall_B] selected = st.selectbox(""Pick"", options) # This comparison does not return expected results: selected == Marshall_A # This comparison evaluates as expected: selected == Marshall_B As a final note, we used @dataclass in the example for this section to illustrate a point, but in fact it is possible to encounter these same problems with classes, in general. Any class which checks class identity inside of a comparison operator—such as __eq__ or __gt__—can exhibit these issues. Using Enum classes in Streamlit The Enum class from the Python standard library is a powerful way to define custom symbolic names that can be used as options for st.multiselect or st.selectbox in place of str values. For example, you might add the following to your streamlit page: from enum import Enum import streamlit as st # class syntax class Color(Enum): RED = 1 GREEN = 2 BLUE = 3 selected_colors = set(st.multiselect(""Pick colors"", options=Color)) if selected_colors == {Color.RED, Color.GREEN}: st.write(""Hooray, you found the color YELLOW!"") If you're using the latest version of Streamlit, this Streamlit page will work as it appears it should. When a user picks both Color.RED and Color.GREEN, they are shown the special message. However, if you've read the rest of this page you might notice something tricky going on. Specifically, the Enum class Color gets redefined every time this script is run. In Python, if you define two Enum classes with the same class name, members, and values, the classes and their members are still considered unique from each other. This should cause the above if condition to always evaluate to False. In any script rerun, the Color values returned by st.multiselect would be of a different class than the Color defined in that script run. If you run the snippet above with Streamlit version 1.28.0 or less, you will not be able see the special message. Thankfully, as of version 1.29.0, Streamlit introduced a configuration option to greatly simplify the problem. That's where the enabled-by-default enumCoercion configuration option comes in. Understanding the enumCoercion configuration option When enumCoercion is enabled, Streamlit tries to recognize when you are using an element like st.multiselect or st.selectbox with a set of Enum members as options. If Streamlit detects this, it will convert the widget's returned values to members of the Enum class defined in the latest script run. This is something we call automatic Enum coercion. This behavior is configurable via the enumCoercion setting in your Streamlit config.toml file. It is enabled by default, and may be disabled or set to a stricter set of matching criteria. If you find that you still encounter issues with enumCoercion enabled, consider using the custom class patterns described above, such as moving your Enum class definition to a separate module file.Previous: DataframesNext: Working with timezonesforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy" https://docs.streamlit.io/knowledge-base/deploy/custom-subdomains#deploy-your-app-1,"DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudremoveGet startedaddDeploy your appremoveApp dependenciesSecrets managementManage your appaddShare your appaddManage your accountaddTroubleshootingStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Deploy/Streamlit Community Cloud/Deploy your appDeploy your app Streamlit Community Cloud lets you deploy your apps in just one click, and most apps will deploy in only a few minutes. If you don't have an app ready to deploy, fork or clone one from our App gallery — you can find apps for machine learning, data visualization, data exploration, A/B testing and more. You can also fork and deploy samples straight from the New app button. Once you've deployed your app, check out how you can Edit your app with GitHub Codespaces. push_pinNoteIf you want to deploy your app on a different cloud service, check out the Deploy Streamlit apps article in our Knowledge Base. Add your app to GitHub Streamlit Community Cloud launches apps directly from your GitHub repo, so your app code and dependencies need to be on GitHub before you try to deploy your app. For more information on how to specify dependencies, see App dependencies. Your directory structure should look similar to this: your-repository/ ├── your_app.py └── requirements.txt If you are including any custom Configuration or Theming, make sure your config file is saved relative to the root of your repo. Within your repo, your config file should be named .streamlit/config.toml. your-repository/ ├── .streamlit/ │ └── config.toml ├── your_app.py └── requirements.txt priority_highImportantAlthough you can deploy multiple apps from the same repository, there can be only one configuration file. Deploy your app From your workspace at share.streamlit.io, click ""New app"" from the upper-right corner of your workspace. Fill in your repo, branch, and file path. As a shortcut, you can also click ""Paste GitHub URL"" to paste a link directly to your_app.py on GitHub. An app URL with a random hash is prefilled but you can change this to a custom subdomain instead. In the example below, the app would be deployed to https://red-balloon.streamlit.app/. You can always change your subdomain later. See more about Custom subdomains at the end of this page. Advanced settings for deployment push_pinNoteStreamlit Community Cloud supports all released versions of Python that are still receiving security updates. Streamlit Community Cloud defaults to version 3.9. You can select a version of your choice from the ""Python version"" dropdown in the ""Advanced settings"" modal. If an app is running a version of Python that becomes unsupported, it will be forcibly upgraded to the oldest, supported version of Python and may break. (Optional) If you are connecting to a data source or want to specify the Python version for your app, you can do that by clicking ""Advanced settings"" before you deploy the app. Learn more about Secrets management. Watch your app launch Your app is now deploying and you can watch while it launches. Most apps take only a couple of minutes to deploy, but if your app has a lot of dependencies it may take longer to deploy the first time. After the initial deployment, any change that does not touch your dependencies should show up immediately. push_pinNoteThe Streamlit Community Cloud logs on the right hand side of your app are only viewable to users with developer access to your repository. These logs help you debug any issues with the app. Learn more about Streamlit Community Cloud logs. Your app URL That's it — you're done! Your app now has a unique subdomain URL that you can share with others. Read more about how to Share your app with viewers. Unique subdomains If the ""Custom subdomain (optional)"" field is blank when you deploy your app, a URL is assigned following a structure based on your GitHub repo. The URL begins with your GitHub username or organization owning your repo, followed by your repo name, app path, and a short hash. If you deploy from a branch other than main or master, the URL also includes the branch name. https://[GitHub username or organization]-[repo name]-[app path]-[branch name]-[short hash].streamlit.app For example, this is an app deployed from the streamlit organization. The repo is demo-self-driving and the app name is streamlit_app.py in the root directory. The branch name is master and therefore not included. https://streamlit-demo-self-driving-streamlit-app-8jya0g.streamlit.app Custom subdomains Setting a custom subdomain makes it much easier to share your app since you can choose something memorable. Whether you set a custom subdomain during deployment or later, your app's URL will appear as: https://.streamlit.app To view or customize your app subdomain from the dashboard: Click the overflow icon (more_vert) to the app's right and select ""Settings"". View the ""General"" tab in the App settings modal. Your app's unique subdomain will appear here. Pick a custom subdomain between 6 and 63 characters in length for your app's URL and hit ""Save"". It's that simple! You can then access your app by visiting your customized URL 🎉. If a custom subdomain is not available (e.g. because it's already taken), you'll see an error message like this: Previous: Get startedNext: App dependenciesforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy" https://docs.streamlit.io/en/0.76.0/api.html#data-elements,"DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceremovePAGE ELEMENTSWrite and magicaddText elementsaddData elementsaddChart elementsaddInput widgetsaddMedia elementsaddLayouts and containersaddChat elementsaddStatus elementsaddThird-party componentsopen_in_newAPPLICATION LOGICNavigation and pagesaddExecution flowaddCaching and stateaddConnections and secretsaddCustom componentsaddUtilitiesaddConfigurationaddTOOLSApp testingaddCommand lineaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Develop/API referenceAPI reference Streamlit makes it easy for you to visualize, mutate, and share data. The API reference is organized by activity type, like displaying data or optimizing performance. Each section includes methods associated with the activity type, including examples. Browse our API below and click to learn more about any of our available commands! 🎈 Display almost anything Write and magic st.writeWrite arguments to the app.st.write(""Hello **world**!"") st.write(my_data_frame) st.write(my_mpl_figure) st.write_streamWrite generators or streams to the app with a typewriter effect.st.write_stream(my_generator) st.write_stream(my_llm_stream) MagicAny time Streamlit sees either a variable or literal value on its own line, it automatically writes that to your app using st.write""Hello **world**!"" my_data_frame my_mpl_figure Text elements MarkdownDisplay string formatted as Markdown.st.markdown(""Hello **world**!"") TitleDisplay text in title formatting.st.title(""The app title"") HeaderDisplay text in header formatting.st.header(""This is a header"") SubheaderDisplay text in subheader formatting.st.subheader(""This is a subheader"") CaptionDisplay text in small font.st.caption(""This is written small caption text"") Code blockDisplay a code block with optional syntax highlighting.st.code(""a = 1234"") EchoDisplay some code in the app, then execute it. Useful for tutorials.with st.echo(): st.write('This code will be printed') LaTeXDisplay mathematical expressions formatted as LaTeX.st.latex(""\int a x^2 \,dx"") Preformatted textWrite fixed-width and preformatted text.st.text(""Hello world"") DividerDisplay a horizontal rule.st.divider() Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration! PreviousTagsAdd tags to your Streamlit apps. Created by @gagan3012.st_tags(label='# Enter Keywords:', text='Press enter to add more', value=['Zero', 'One', 'Two'], suggestions=['five', 'six', 'seven', 'eight', 'nine', 'three', 'eleven', 'ten', 'four'], maxtags = 4, key='1') NLUApply text mining on a dataframe. Created by @JohnSnowLabs.nlu.load('sentiment').predict('I love NLU! <3') Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.mention(label=""An awesome Streamlit App"", icon=""streamlit"", url=""https://extras.streamlit.app"",) Annotated textDisplay annotated text in Streamlit apps. Created by @tvst.annotated_text(""This "", (""is"", ""verb""), "" some "", (""annotated"", ""adj""), (""text"", ""noun""), "" for those of "", (""you"", ""pronoun""), "" who "", (""like"", ""verb""), "" this sort of "", (""thing"", ""noun""), ""."") Drawable CanvasProvides a sketching canvas using Fabric.js. Created by @andfanilo.st_canvas(fill_color=""rgba(255, 165, 0, 0.3)"", stroke_width=stroke_width, stroke_color=stroke_color, background_color=bg_color, background_image=Image.open(bg_image) if bg_image else None, update_streamlit=realtime_update, height=150, drawing_mode=drawing_mode, point_display_radius=point_display_radius if drawing_mode == 'point' else 0, key=""canvas"",) TagsAdd tags to your Streamlit apps. Created by @gagan3012.st_tags(label='# Enter Keywords:', text='Press enter to add more', value=['Zero', 'One', 'Two'], suggestions=['five', 'six', 'seven', 'eight', 'nine', 'three', 'eleven', 'ten', 'four'], maxtags = 4, key='1') NLUApply text mining on a dataframe. Created by @JohnSnowLabs.nlu.load('sentiment').predict('I love NLU! <3') Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.mention(label=""An awesome Streamlit App"", icon=""streamlit"", url=""https://extras.streamlit.app"",) Annotated textDisplay annotated text in Streamlit apps. Created by @tvst.annotated_text(""This "", (""is"", ""verb""), "" some "", (""annotated"", ""adj""), (""text"", ""noun""), "" for those of "", (""you"", ""pronoun""), "" who "", (""like"", ""verb""), "" this sort of "", (""thing"", ""noun""), ""."") Drawable CanvasProvides a sketching canvas using Fabric.js. Created by @andfanilo.st_canvas(fill_color=""rgba(255, 165, 0, 0.3)"", stroke_width=stroke_width, stroke_color=stroke_color, background_color=bg_color, background_image=Image.open(bg_image) if bg_image else None, update_streamlit=realtime_update, height=150, drawing_mode=drawing_mode, point_display_radius=point_display_radius if drawing_mode == 'point' else 0, key=""canvas"",) TagsAdd tags to your Streamlit apps. Created by @gagan3012.st_tags(label='# Enter Keywords:', text='Press enter to add more', value=['Zero', 'One', 'Two'], suggestions=['five', 'six', 'seven', 'eight', 'nine', 'three', 'eleven', 'ten', 'four'], maxtags = 4, key='1') NLUApply text mining on a dataframe. Created by @JohnSnowLabs.nlu.load('sentiment').predict('I love NLU! <3') Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.mention(label=""An awesome Streamlit App"", icon=""streamlit"", url=""https://extras.streamlit.app"",) Next Data elements DataframesDisplay a dataframe as an interactive table.st.dataframe(my_data_frame) Data editorDisplay a data editor widget.edited = st.data_editor(df, num_rows=""dynamic"") Column configurationConfigure the display and editing behavior of dataframes and data editors.st.column_config.NumberColumn(""Price (in USD)"", min_value=0, format=""$%d"") Static tablesDisplay a static table.st.table(my_data_frame) MetricsDisplay a metric in big bold font, with an optional indicator of how the metric changed.st.metric(""My metric"", 42, 2) Dicts and JSONDisplay object or string as a pretty-printed JSON string.st.json(my_dict) Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration! PreviousImage CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates value = streamlit_image_coordinates(""https://placekitten.com/200/300"") st.write(value) Plotly EventsMake Plotly charts interactive!. Created by @null-jones.from streamlit_plotly_events import plotly_events fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.metric_cards import style_metric_cards col3.metric(label=""No Change"", value=5000, delta=0) style_metric_cards() Streamlit AggridImplementation of Ag-Grid component for Streamlit. Created by @PablocFonseca.df = pd.DataFrame({'col1': [1, 2, 3], 'col2': [4, 5, 6]}) grid_return = AgGrid(df, editable=True) new_df = grid_return['data'] Streamlit FoliumStreamlit Component for rendering Folium maps. Created by @randyzwitch.m = folium.Map(location=[39.949610, -75.150282], zoom_start=16) folium.Marker([39.949610, -75.150282], popup=""Liberty Bell"", tooltip=""Liberty Bell"").add_to(m) st_data = st_folium(m, width=725) Pandas ProfilingPandas profiling component for Streamlit. Created by @okld.df = pd.read_csv(""https://storage.googleapis.com/tf-datasets/titanic/train.csv"") pr = df.profile_report() st_profile_report(pr) Image CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates value = streamlit_image_coordinates(""https://placekitten.com/200/300"") st.write(value) Plotly EventsMake Plotly charts interactive!. Created by @null-jones.from streamlit_plotly_events import plotly_events fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.metric_cards import style_metric_cards col3.metric(label=""No Change"", value=5000, delta=0) style_metric_cards() Streamlit AggridImplementation of Ag-Grid component for Streamlit. Created by @PablocFonseca.df = pd.DataFrame({'col1': [1, 2, 3], 'col2': [4, 5, 6]}) grid_return = AgGrid(df, editable=True) new_df = grid_return['data'] Streamlit FoliumStreamlit Component for rendering Folium maps. Created by @randyzwitch.m = folium.Map(location=[39.949610, -75.150282], zoom_start=16) folium.Marker([39.949610, -75.150282], popup=""Liberty Bell"", tooltip=""Liberty Bell"").add_to(m) st_data = st_folium(m, width=725) Pandas ProfilingPandas profiling component for Streamlit. Created by @okld.df = pd.read_csv(""https://storage.googleapis.com/tf-datasets/titanic/train.csv"") pr = df.profile_report() st_profile_report(pr) Image CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates value = streamlit_image_coordinates(""https://placekitten.com/200/300"") st.write(value) Plotly EventsMake Plotly charts interactive!. Created by @null-jones.from streamlit_plotly_events import plotly_events fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.metric_cards import style_metric_cards col3.metric(label=""No Change"", value=5000, delta=0) style_metric_cards() Next Chart elements Simple area chartsDisplay an area chart.st.area_chart(my_data_frame) Simple bar chartsDisplay a bar chart.st.bar_chart(my_data_frame) Simple line chartsDisplay a line chart.st.line_chart(my_data_frame) Simple scatter chartsDisplay a line chart.st.scatter_chart(my_data_frame) Scatterplots on mapsDisplay a map with points on it.st.map(my_data_frame) MatplotlibDisplay a matplotlib.pyplot figure.st.pyplot(my_mpl_figure) AltairDisplay a chart using the Altair library.st.altair_chart(my_altair_chart) Vega-LiteDisplay a chart using the Vega-Lite library.st.vega_lite_chart(my_vega_lite_chart) PlotlyDisplay an interactive Plotly chart.st.plotly_chart(my_plotly_chart) BokehDisplay an interactive Bokeh chart.st.bokeh_chart(my_bokeh_chart) PyDeckDisplay a chart using the PyDeck library.st.pydeck_chart(my_pydeck_chart) GraphVizDisplay a graph using the dagre-d3 library.st.graphviz_chart(my_graphviz_spec) Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration! PreviousStreamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl(""https://assets5.lottiefiles.com/packages/lf20_V9t630.json"") st_lottie(lottie_hello, key=""hello"") Plotly EventsMake Plotly charts interactive!. Created by @null-jones.fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.chart += get_annotations_chart(annotations=[(""Mar 01, 2008"", ""Pretty good day for GOOG""), (""Dec 01, 2007"", ""Something's going wrong for GOOG & AAPL""), (""Nov 01, 2008"", ""Market starts again thanks to...""), (""Dec 01, 2009"", ""Small crash for GOOG after...""),],) st.altair_chart(chart, use_container_width=True) PlostA deceptively simple plotting library for Streamlit. Created by @tvst.import plost plost.line_chart(my_dataframe, x='time', y='stock_value', color='stock_name',) HiPlotHigh dimensional Interactive Plotting. Created by @facebookresearch.data = [{'dropout':0.1, 'lr': 0.001, 'loss': 10.0, 'optimizer': 'SGD'}, {'dropout':0.15, 'lr': 0.01, 'loss': 3.5, 'optimizer': 'Adam'}, {'dropout':0.3, 'lr': 0.1, 'loss': 4.5, 'optimizer': 'Adam'}] hip.Experiment.from_iterable(data).display() EChartsHigh dimensional Interactive Plotting. Created by @andfanilo.from streamlit_echarts import st_echarts st_echarts(options=options) Streamlit FoliumStreamlit Component for rendering Folium maps. Created by @randyzwitch.m = folium.Map(location=[39.949610, -75.150282], zoom_start=16) st_data = st_folium(m, width=725) Spacy-StreamlitspaCy building blocks and visualizers for Streamlit apps. Created by @explosion.models = [""en_core_web_sm"", ""en_core_web_md""] spacy_streamlit.visualize(models, ""Sundar Pichai is the CEO of Google."") Streamlit AgraphA Streamlit Graph Vis, based on react-grah-vis. Created by @ChrisDelClea.from streamlit_agraph import agraph, Node, Edge, Config agraph(nodes=nodes, edges=edges, config=config) Streamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl(""https://assets5.lottiefiles.com/packages/lf20_V9t630.json"") st_lottie(lottie_hello, key=""hello"") Plotly EventsMake Plotly charts interactive!. Created by @null-jones.fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.chart += get_annotations_chart(annotations=[(""Mar 01, 2008"", ""Pretty good day for GOOG""), (""Dec 01, 2007"", ""Something's going wrong for GOOG & AAPL""), (""Nov 01, 2008"", ""Market starts again thanks to...""), (""Dec 01, 2009"", ""Small crash for GOOG after...""),],) st.altair_chart(chart, use_container_width=True) PlostA deceptively simple plotting library for Streamlit. Created by @tvst.import plost plost.line_chart(my_dataframe, x='time', y='stock_value', color='stock_name',) HiPlotHigh dimensional Interactive Plotting. Created by @facebookresearch.data = [{'dropout':0.1, 'lr': 0.001, 'loss': 10.0, 'optimizer': 'SGD'}, {'dropout':0.15, 'lr': 0.01, 'loss': 3.5, 'optimizer': 'Adam'}, {'dropout':0.3, 'lr': 0.1, 'loss': 4.5, 'optimizer': 'Adam'}] hip.Experiment.from_iterable(data).display() EChartsHigh dimensional Interactive Plotting. Created by @andfanilo.from streamlit_echarts import st_echarts st_echarts(options=options) Streamlit FoliumStreamlit Component for rendering Folium maps. Created by @randyzwitch.m = folium.Map(location=[39.949610, -75.150282], zoom_start=16) st_data = st_folium(m, width=725) Spacy-StreamlitspaCy building blocks and visualizers for Streamlit apps. Created by @explosion.models = [""en_core_web_sm"", ""en_core_web_md""] spacy_streamlit.visualize(models, ""Sundar Pichai is the CEO of Google."") Streamlit AgraphA Streamlit Graph Vis, based on react-grah-vis. Created by @ChrisDelClea.from streamlit_agraph import agraph, Node, Edge, Config agraph(nodes=nodes, edges=edges, config=config) Streamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl(""https://assets5.lottiefiles.com/packages/lf20_V9t630.json"") st_lottie(lottie_hello, key=""hello"") Plotly EventsMake Plotly charts interactive!. Created by @null-jones.fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.chart += get_annotations_chart(annotations=[(""Mar 01, 2008"", ""Pretty good day for GOOG""), (""Dec 01, 2007"", ""Something's going wrong for GOOG & AAPL""), (""Nov 01, 2008"", ""Market starts again thanks to...""), (""Dec 01, 2009"", ""Small crash for GOOG after...""),],) st.altair_chart(chart, use_container_width=True) Next Input widgets ButtonDisplay a button widget.clicked = st.button(""Click me"") Download buttonDisplay a download button widget.st.download_button(""Download file"", file) Form buttonDisplay a form submit button. For use with st.form.st.form_submit_button(""Sign up"") Link buttonDisplay a link button.st.link_button(""Go to gallery"", url) Page linkDisplay a link to another page in a multipage app.st.page_link(""app.py"", label=""Home"", icon=""🏠"") st.page_link(""pages/profile.py"", label=""My profile"") CheckboxDisplay a checkbox widget.selected = st.checkbox(""I agree"") Color pickerDisplay a color picker widget.color = st.color_picker(""Pick a color"") MultiselectDisplay a multiselect widget. The multiselect widget starts as empty.choices = st.multiselect(""Buy"", [""milk"", ""apples"", ""potatoes""]) RadioDisplay a radio button widget.choice = st.radio(""Pick one"", [""cats"", ""dogs""]) SelectboxDisplay a select widget.choice = st.selectbox(""Pick one"", [""cats"", ""dogs""]) Select-sliderDisplay a slider widget to select items from a list.size = st.select_slider(""Pick a size"", [""S"", ""M"", ""L""]) ToggleDisplay a toggle widget.activated = st.toggle(""Activate"") Number inputDisplay a numeric input widget.choice = st.number_input(""Pick a number"", 0, 10) SliderDisplay a slider widget.number = st.slider(""Pick a number"", 0, 100) Date inputDisplay a date input widget.date = st.date_input(""Your birthday"") Time inputDisplay a time input widget.time = st.time_input(""Meeting time"") Chat inputDisplay a chat input widget.prompt = st.chat_input(""Say something"") if prompt: st.write(f""The user has sent: {prompt}"") Text-areaDisplay a multi-line text input widget.text = st.text_area(""Text to translate"") Text inputDisplay a single-line text input widget.name = st.text_input(""First name"") Data editorDisplay a data editor widget.edited = st.experimental_data_editor(df, num_rows=""dynamic"") File UploaderDisplay a file uploader widget.data = st.file_uploader(""Upload a CSV"") Camera inputDisplay a widget that allows users to upload images directly from a camera.image = st.camera_input(""Take a picture"") Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration! PreviousStreamlit ChatStreamlit Component for a Chatbot UI. Created by @AI-Yash.from streamlit_chat import message message(""My message"") message(""Hello bot!"", is_user=True) # align's the message to the right Streamlit Option MenuSelect a single item from a list of options in a menu. Created by @victoryhb.from streamlit_option_menu import option_menu option_menu(""Main Menu"", [""Home"", 'Settings'], icons=['house', 'gear'], menu_icon=""cast"", default_index=1) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.stoggle import stoggle stoggle( ""Click me!"", """"""🥷 Surprise! Here's some additional content"""""",) Streamlit ElementsCreate a draggable and resizable dashboard in Streamlit. Created by @okls.from streamlit_elements import elements, mui, html with elements(""new_element""): mui.Typography(""Hello world"") TagsAdd tags to your Streamlit apps. Created by @gagan3012.from streamlit_tags import st_tags st_tags(label='# Enter Keywords:', text='Press enter to add more', value=['Zero', 'One', 'Two'], suggestions=['five', 'six', 'seven', 'eight', 'nine', 'three', 'eleven', 'ten', 'four'], maxtags = 4, key='1') StqdmThe simplest way to handle a progress bar in streamlit app. Created by @Wirg.from stqdm import stqdm for _ in stqdm(range(50)): sleep(0.5) TimelineDisplay a Timeline in Streamlit apps using TimelineJS. Created by @innerdoc.from streamlit_timeline import timeline with open('example.json', ""r"") as f: timeline(f.read(), height=800) Camera input liveAlternative for st.camera_input which returns the webcam images live. Created by @blackary.from camera_input_live import camera_input_live image = camera_input_live() st.image(value) Streamlit AceAce editor component for Streamlit. Created by @okld.from streamlit_ace import st_ace content = st_ace() content Streamlit ChatStreamlit Component for a Chatbot UI. Created by @AI-Yash.from streamlit_chat import message message(""My message"") message(""Hello bot!"", is_user=True) # align's the message to the right Streamlit Option MenuSelect a single item from a list of options in a menu. Created by @victoryhb.from streamlit_option_menu import option_menu option_menu(""Main Menu"", [""Home"", 'Settings'], icons=['house', 'gear'], menu_icon=""cast"", default_index=1) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.stoggle import stoggle stoggle( ""Click me!"", """"""🥷 Surprise! Here's some additional content"""""",) Streamlit ElementsCreate a draggable and resizable dashboard in Streamlit. Created by @okls.from streamlit_elements import elements, mui, html with elements(""new_element""): mui.Typography(""Hello world"") TagsAdd tags to your Streamlit apps. Created by @gagan3012.from streamlit_tags import st_tags st_tags(label='# Enter Keywords:', text='Press enter to add more', value=['Zero', 'One', 'Two'], suggestions=['five', 'six', 'seven', 'eight', 'nine', 'three', 'eleven', 'ten', 'four'], maxtags = 4, key='1') StqdmThe simplest way to handle a progress bar in streamlit app. Created by @Wirg.from stqdm import stqdm for _ in stqdm(range(50)): sleep(0.5) TimelineDisplay a Timeline in Streamlit apps using TimelineJS. Created by @innerdoc.from streamlit_timeline import timeline with open('example.json', ""r"") as f: timeline(f.read(), height=800) Camera input liveAlternative for st.camera_input which returns the webcam images live. Created by @blackary.from camera_input_live import camera_input_live image = camera_input_live() st.image(value) Streamlit AceAce editor component for Streamlit. Created by @okld.from streamlit_ace import st_ace content = st_ace() content Streamlit ChatStreamlit Component for a Chatbot UI. Created by @AI-Yash.from streamlit_chat import message message(""My message"") message(""Hello bot!"", is_user=True) # align's the message to the right Streamlit Option MenuSelect a single item from a list of options in a menu. Created by @victoryhb.from streamlit_option_menu import option_menu option_menu(""Main Menu"", [""Home"", 'Settings'], icons=['house', 'gear'], menu_icon=""cast"", default_index=1) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.stoggle import stoggle stoggle( ""Click me!"", """"""🥷 Surprise! Here's some additional content"""""",) Next Media elements ImageDisplay an image or list of images.st.image(numpy_array) st.image(image_bytes) st.image(file) st.image(""https://example.com/myimage.jpg"") AudioDisplay an audio player.st.audio(numpy_array) st.audio(audio_bytes) st.audio(file) st.audio(""https://example.com/myaudio.mp3"", format=""audio/mp3"") VideoDisplay a video player.st.video(numpy_array) st.video(video_bytes) st.video(file) st.video(""https://example.com/myvideo.mp4"", format=""video/mp4"") Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration! PreviousStreamlit CropperA simple image cropper for Streamlit. Created by @turner-anderson.from streamlit_cropper import st_cropper st_cropper(img, realtime_update=realtime_update, box_color=box_color, aspect_ratio=aspect_ratio) Image CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates streamlit_image_coordinates(""https://placekitten.com/200/300"") Streamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl(""https://assets5.lottiefiles.com/packages/lf20_V9t630.json"") st_lottie(lottie_hello, key=""hello"") Streamlit WebrtcHandling and transmitting real-time video/audio streams with Streamlit. Created by @whitphx.from streamlit_webrtc import webrtc_streamer webrtc_streamer(key=""sample"") Drawable CanvasProvides a sketching canvas using Fabric.js. Created by @andfanilo.from streamlit_drawable_canvas import st_canvas st_canvas(fill_color=""rgba(255, 165, 0, 0.3)"", stroke_width=stroke_width, stroke_color=stroke_color, background_color=bg_color, background_image=Image.open(bg_image) if bg_image else None, update_streamlit=realtime_update, height=150, drawing_mode=drawing_mode, point_display_radius=point_display_radius if drawing_mode == 'point' else 0, key=""canvas"",) Image ComparisonCompare images with a slider using JuxtaposeJS. Created by @fcakyon.from streamlit_image_comparison import image_comparison image_comparison(img1=""image1.jpg"", img2=""image2.jpg"",) Streamlit CropperA simple image cropper for Streamlit. Created by @turner-anderson.from streamlit_cropper import st_cropper st_cropper(img, realtime_update=realtime_update, box_color=box_color, aspect_ratio=aspect_ratio) Image CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates streamlit_image_coordinates(""https://placekitten.com/200/300"") Streamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl(""https://assets5.lottiefiles.com/packages/lf20_V9t630.json"") st_lottie(lottie_hello, key=""hello"") Streamlit WebrtcHandling and transmitting real-time video/audio streams with Streamlit. Created by @whitphx.from streamlit_webrtc import webrtc_streamer webrtc_streamer(key=""sample"") Drawable CanvasProvides a sketching canvas using Fabric.js. Created by @andfanilo.from streamlit_drawable_canvas import st_canvas st_canvas(fill_color=""rgba(255, 165, 0, 0.3)"", stroke_width=stroke_width, stroke_color=stroke_color, background_color=bg_color, background_image=Image.open(bg_image) if bg_image else None, update_streamlit=realtime_update, height=150, drawing_mode=drawing_mode, point_display_radius=point_display_radius if drawing_mode == 'point' else 0, key=""canvas"",) Image ComparisonCompare images with a slider using JuxtaposeJS. Created by @fcakyon.from streamlit_image_comparison import image_comparison image_comparison(img1=""image1.jpg"", img2=""image2.jpg"",) Streamlit CropperA simple image cropper for Streamlit. Created by @turner-anderson.from streamlit_cropper import st_cropper st_cropper(img, realtime_update=realtime_update, box_color=box_color, aspect_ratio=aspect_ratio) Image CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates streamlit_image_coordinates(""https://placekitten.com/200/300"") Streamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl(""https://assets5.lottiefiles.com/packages/lf20_V9t630.json"") st_lottie(lottie_hello, key=""hello"") Next Layouts and containers ColumnsInsert containers laid out as side-by-side columns.col1, col2 = st.columns(2) col1.write(""this is column 1"") col2.write(""this is column 2"") ContainerInsert a multi-element container.c = st.container() st.write(""This will show last"") c.write(""This will show first"") c.write(""This will show second"") Modal dialogsInsert a modal dialog that can rerun independently from the rest of the script.@st.experimental_dialog(""Sign up"") def email_form(): name = st.text_input(""Name"") email = st.text_input(""Email"") EmptyInsert a single-element container.c = st.empty() st.write(""This will show last"") c.write(""This will be replaced"") c.write(""This will show first"") ExpanderInsert a multi-element container that can be expanded/collapsed.with st.expander(""Open to see more""): st.write(""This is more content"") PopoverInsert a multi-element popover container that can be opened/closed.with st.popover(""Settings""): st.checkbox(""Show completed"") SidebarDisplay items in a sidebar.st.sidebar.write(""This lives in the sidebar"") st.sidebar.button(""Click me!"") TabsInsert containers separated into tabs.tab1, tab2 = st.tabs([""Tab 1"", ""Tab2""]) tab1.write(""this is tab 1"") tab2.write(""this is tab 2"") Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration!Streamlit ElementsCreate a draggable and resizable dashboard in Streamlit. Created by @okls.from streamlit_elements import elements, mui, html with elements(""new_element""): mui.Typography(""Hello world"") PydanticAuto-generate Streamlit UI from Pydantic Models and Dataclasses. Created by @lukasmasuch.import streamlit_pydantic as sp sp.pydantic_form(key=""my_form"", model=ExampleModel) Streamlit PagesAn experimental version of Streamlit Multi-Page Apps. Created by @blackary.from st_pages import Page, show_pages, add_page_title show_pages([ Page(""streamlit_app.py"", ""Home"", ""🏠""), Page(""other_pages/page2.py"", ""Page 2"", "":books:""), ]) Chat elements Streamlit provides a few commands to help you build conversational apps. These chat elements are designed to be used in conjunction with each other, but you can also use them separately. st.chat_message lets you insert a chat message container into the app so you can display messages from the user or the app. Chat containers can contain other Streamlit elements, including charts, tables, text, and more. st.chat_input lets you display a chat input widget so the user can type in a message. Chat inputDisplay a chat input widget.prompt = st.chat_input(""Say something"") if prompt: st.write(f""The user has sent: {prompt}"") Chat messageInsert a chat message container.import numpy as np with st.chat_message(""user""): st.write(""Hello 👋"") st.line_chart(np.random.randn(30, 3)) Status containerDisplay output of long-running tasks in a container.with st.status('Running'): do_something_slow() st.write_streamWrite generators or streams to the app with a typewriter effect.st.write_stream(my_generator) st.write_stream(my_llm_stream) Status elements Progress barDisplay a progress bar.for i in range(101): st.progress(i) do_something_slow() SpinnerTemporarily displays a message while executing a block of code.with st.spinner(""Please wait...""): do_something_slow() Status containerDisplay output of long-running tasks in a container.with st.status('Running'): do_something_slow() ToastBriefly displays a toast message in the bottom-right corner.st.toast('Butter!', icon='🧈') BalloonsDisplay celebratory balloons!do_something() # Celebrate when all done! st.balloons() SnowflakesDisplay celebratory snowflakes!do_something() # Celebrate when all done! st.snow() Success boxDisplay a success message.st.success(""Match found!"") Info boxDisplay an informational message.st.info(""Dataset is updated every day at midnight."") Warning boxDisplay warning message.st.warning(""Unable to fetch image. Skipping..."") Error boxDisplay error message.st.error(""We encountered an error"") Exception outputDisplay an exception.e = RuntimeError(""This is an exception of type RuntimeError"") st.exception(e) Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration!StqdmThe simplest way to handle a progress bar in streamlit app. Created by @Wirg.from stqdm import stqdm for _ in stqdm(range(50)): sleep(0.5) Custom notification boxA custom notification box with the ability to close it out. Created by @Socvest.from streamlit_custom_notification_box import custom_notification_box styles = {'material-icons':{'color': 'red'}, 'text-icon-link-close-container': {'box-shadow': '#3896de 0px 4px'}, 'notification-text': {'':''}, 'close-button':{'':''}, 'link':{'':''}} custom_notification_box(icon='info', textDisplay='We are almost done with your registration...', externalLink='more info', url='#', styles=styles, key=""foo"") Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.let_it_rain import rain rain(emoji=""🎈"", font_size=54, falling_speed=5, animation_length=""infinite"",) App logic and configuration Navigation and pages Switch pageProgrammatically navigates to a specified page.st.switch_page(""pages/my_page.py"") Page linkDisplay a link to another page in a multipage app.st.page_link(""app.py"", label=""Home"", icon=""🏠"") st.page_link(""pages/profile.py"", label=""My profile"") Execution flow Modal dialogsInsert a modal dialog that can rerun independently from the rest of the script.@st.experimental_dialog(""Sign up"") def email_form(): name = st.text_input(""Name"") email = st.text_input(""Email"") FormsCreate a form that batches elements together with a “Submit"" button.with st.form(key='my_form'): name = st.text_input(""Name"") email = st.text_input(""Email"") st.form_submit_button(""Sign up"") Partial rerunsDefine a fragment to rerun independently from the rest of the script.@st.experimental_fragment(run_every=""10s"") def fragment(): df = get_data() st.line_chart(df) Rerun scriptRerun the script immediately.st.rerun() Stop executionStops execution immediately.st.stop() Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration!AutorefreshForce a refresh without tying up a script. Created by @kmcgrady.from streamlit_autorefresh import st_autorefresh st_autorefresh(interval=2000, limit=100, key=""fizzbuzzcounter"") PydanticAuto-generate Streamlit UI from Pydantic Models and Dataclasses. Created by @lukasmasuch.import streamlit_pydantic as sp sp.pydantic_form(key=""my_form"", model=ExampleModel) Streamlit PagesAn experimental version of Streamlit Multi-Page Apps. Created by @blackary.from st_pages import Page, show_pages, add_page_title show_pages([ Page(""streamlit_app.py"", ""Home"", ""🏠""), Page(""other_pages/page2.py"", ""Page 2"", "":books:""), ]) Caching and state Cache dataFunction decorator to cache functions that return data (e.g. dataframe transforms, database queries, ML inference).@st.cache_data def long_function(param1, param2): # Perform expensive computation here or # fetch data from the web here return data Cache resourceFunction decorator to cache functions that return global resources (e.g. database connections, ML models).@st.cache_resource def init_model(): # Return a global resource here return pipeline( ""sentiment-analysis"", model=""distilbert-base-uncased-finetuned-sst-2-english"" ) Session stateSession state is a way to share variables between reruns, for each user session.st.session_state['key'] = value Query parametersGet, set, or clear the query parameters that are shown in the browser's URL bar.st.query_params[key] = value st.query_params.clear() Connections and databases Setup your connection Create a connectionConnect to a data source or APIconn = st.connection('pets_db', type='sql') pet_owners = conn.query('select * from pet_owners') st.dataframe(pet_owners) Built-in connections SnowflakeConnectionA connection to Snowflake.conn = st.connection('snowflake') SQLConnectionA connection to a SQL database using SQLAlchemy.conn = st.connection('sql') Build your own connections Connection base classBuild your own connection with BaseConnection.class MyConnection(BaseConnection[myconn.MyConnection]): def _connect(self, **kwargs) -> MyConnection: return myconn.connect(**self._secrets, **kwargs) def query(self, query): return self._instance.query(query) Secrets management Secrets singletonAccess secrets from a local TOML file.key = st.secrets[""OpenAI_key""] Secrets fileSave your secrets in a per-project or per-profile TOML file.OpenAI_key = """" Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration!AuthenticatorA secure authentication module to validate user credentials. Created by @mkhorasani.import streamlit_authenticator as stauth authenticator = stauth.Authenticate( config['credentials'], config['cookie']['name'], config['cookie']['key'], config['cookie']['expiry_days'], config['preauthorized']) WS localStorageA simple synchronous way of accessing localStorage from your app. Created by @gagangoku.from streamlit_ws_localstorage import injectWebsocketCode ret = conn.setLocalStorageVal(key='k1', val='v1') st.write('ret: ' + ret) Streamlit Auth0The fastest way to provide comprehensive login inside Streamlit. Created by @conradbez.from auth0_component import login_button user_info = login_button(clientId, domain = domain) st.write(user_info) Custom Components Declare a componentCreate and register a custom component.st.components.v1.declare_component( ""custom_slider"", ""/frontend"", ) HTMLDisplay an HTML string in an iframe.st.components.v1.html( ""

Foo bar.

"" ) iframeLoad a remote URL in an iframe.st.components.v1.iframe( ""docs.streamlit.io"" ) Utilities and user info User infost.experimental_user returns information about the logged-in user of private apps on Streamlit Community Cloud.if st.experimental_user.email == ""foo@corp.com"": st.write(""Welcome back, "", st.experimental_user.email) else: st.write(""You are not authorized to view this page."") Get helpDisplay object’s doc string, nicely formatted.st.help(st.write) st.help(pd.DataFrame) Render HTMLRenders HTML strings to your app.css = """""" """""" st.html(css) Configuration Configuration fileConfigures the default settings for your app.your-project/ ├── .streamlit/ │ └── config.toml └── your_app.py Set page title, favicon, and moreConfigures the default settings of the page.st.set_page_config( page_title=""My app"", page_icon="":shark:"", ) Developer tools App testing st.testing.v1.AppTestst.testing.v1.AppTest simulates a running Streamlit app for testing.from streamlit.testing.v1 import AppTest at = AppTest.from_file(""streamlit_app.py"") at.secrets[""WORD""] = ""Foobar"" at.run() assert not at.exception at.text_input(""word"").input(""Bazbat"").run() assert at.warning[0].value == ""Try again."" AppTest.from_filest.testing.v1.AppTest.from_file initializes a simulated app from a file.from streamlit.testing.v1 import AppTest at = AppTest.from_file(""streamlit_app.py"") at.run() AppTest.from_stringst.testing.v1.AppTest.from_string initializes a simulated app from a string.from streamlit.testing.v1 import AppTest at = AppTest.from_string(app_script_as_string) at.run() AppTest.from_functionst.testing.v1.AppTest.from_function initializes a simulated app from a function.from streamlit.testing.v1 import AppTest at = AppTest.from_function(app_script_as_callable) at.run() BlockA representation of container elements, including: st.chat_message st.columns st.sidebar st.tabs The main body of the app. # at.sidebar returns a Block at.sidebar.button[0].click().run() assert not at.exception ElementThe base class for representation of all elements, including: st.title st.header st.markdown st.dataframe # at.title returns a sequence of Title # Title inherits from Element assert at.title[0].value == ""My awesome app"" ButtonA representation of st.button and st.form_submit_button.at.button[0].click().run() ChatInputA representation of st.chat_input.at.chat_input[0].set_value(""What is Streamlit?"").run() CheckboxA representation of st.checkbox.at.checkbox[0].check().run() ColorPickerA representation of st.color_picker.at.color_picker[0].pick(""#FF4B4B"").run() DateInputA representation of st.date_input.release_date = datetime.date(2023, 10, 26) at.date_input[0].set_value(release_date).run() MultiselectA representation of st.multiselect.at.multiselect[0].select(""New York"").run() NumberInputA representation of st.number_input.at.number_input[0].increment().run() RadioA representation of st.radio.at.radio[0].set_value(""New York"").run() SelectSliderA representation of st.select_slider.at.select_slider[0].set_range(""A"",""C"").run() SelectboxA representation of st.selectbox.at.selectbox[0].select(""New York"").run() SliderA representation of st.slider.at.slider[0].set_range(2,5).run() TextAreaA representation of st.text_area.at.text_area[0].input(""Streamlit is awesome!"").run() TextInputA representation of st.text_input.at.text_input[0].input(""Streamlit"").run() TimeInputA representation of st.time_input.at.time_input[0].increment().run() ToggleA representation of st.toggle.at.toggle[0].set_value(""True"").run() Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration!Pandas ProfilingPandas profiling component for Streamlit. Created by @okld.df = pd.read_csv(""https://storage.googleapis.com/tf-datasets/titanic/train.csv"") pr = df.profile_report() st_profile_report(pr) Streamlit AceAce editor component for Streamlit. Created by @okld.from streamlit_ace import st_ace content = st_ace() content Streamlit AnalyticsTrack & visualize user interactions with your streamlit app. Created by @jrieke.import streamlit_analytics with streamlit_analytics.track(): st.text_input(""Write something"") Previous: ConceptsNext: Write and magicforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy" https://docs.streamlit.io/develop/api-reference/layout/st.expander#stexpander,"DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceremovePAGE ELEMENTSWrite and magicaddText elementsaddData elementsaddChart elementsaddInput widgetsaddMedia elementsaddLayouts and containersremovest.columnsst.containerst.dialoglinkst.emptyst.expanderst.formlinkst.popoverst.sidebarst.tabsChat elementsaddStatus elementsaddThird-party componentsopen_in_newAPPLICATION LOGICNavigation and pagesaddExecution flowaddCaching and stateaddConnections and secretsaddCustom componentsaddUtilitiesaddConfigurationaddTOOLSApp testingaddCommand lineaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Develop/API reference/Layouts and containers/st.expanderst.expanderStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeInsert a multi-element container that can be expanded/collapsed. Inserts a container into your app that can be used to hold multiple elements and can be expanded or collapsed by the user. When collapsed, all that is visible is the provided label. To add elements to the returned container, you can use the with notation (preferred) or just call methods directly on the returned object. See examples below. Warning Currently, you may not put expanders inside another expander. Function signature[source] st.expander(label, expanded=False) Parameters label (str) A string to use as the header for the expander. The label can optionally contain Markdown and supports the following elements: Bold, Italics, Strikethroughs, Inline Code, Emojis, and Links. This also supports: Emoji shortcodes, such as :+1: and :sunglasses:. For a list of all supported codes, see https://share.streamlit.io/streamlit/emoji-shortcodes. LaTeX expressions, by wrapping them in ""$"" or ""$$"" (the ""$$"" must be on their own lines). Supported LaTeX functions are listed at https://katex.org/docs/supported.html. Colored text and background colors for text, using the syntax :color[text to be colored] and :color-background[text to be colored], respectively. color must be replaced with any of the following supported colors: blue, green, orange, red, violet, gray/grey, rainbow. For example, you can use :orange[your text here] or :blue-background[your text here]. Unsupported elements are unwrapped so only their children (text contents) render. Display unsupported elements as literal characters by backslash-escaping them. E.g. 1\. Not an ordered list. expanded (bool) If True, initializes the expander in ""expanded"" state. Defaults to False (collapsed). Examples You can use the with notation to insert any element into an expander import streamlit as st st.bar_chart({""data"": [1, 5, 2, 6, 2, 1]}) with st.expander(""See explanation""): st.write(''' The chart above shows some numbers I picked for you. I rolled actual dice for these, so they're *guaranteed* to be random. ''') st.image(""https://static.streamlit.io/examples/dice.jpg"") Built with Streamlit 🎈Fullscreen open_in_new Or you can just call methods directly on the returned objects: import streamlit as st st.bar_chart({""data"": [1, 5, 2, 6, 2, 1]}) expander = st.expander(""See explanation"") expander.write(''' The chart above shows some numbers I picked for you. I rolled actual dice for these, so they're *guaranteed* to be random. ''') expander.image(""https://static.streamlit.io/examples/dice.jpg"") Built with Streamlit 🎈Fullscreen open_in_new Previous: st.emptyNext: st.formforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy" https://docs.streamlit.io/en/latest/api.html#magic,"DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceremovePAGE ELEMENTSWrite and magicaddText elementsaddData elementsaddChart elementsaddInput widgetsaddMedia elementsaddLayouts and containersaddChat elementsaddStatus elementsaddThird-party componentsopen_in_newAPPLICATION LOGICNavigation and pagesaddExecution flowaddCaching and stateaddConnections and secretsaddCustom componentsaddUtilitiesaddConfigurationaddTOOLSApp testingaddCommand lineaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Develop/API referenceAPI reference Streamlit makes it easy for you to visualize, mutate, and share data. The API reference is organized by activity type, like displaying data or optimizing performance. Each section includes methods associated with the activity type, including examples. Browse our API below and click to learn more about any of our available commands! 🎈 Display almost anything Write and magic st.writeWrite arguments to the app.st.write(""Hello **world**!"") st.write(my_data_frame) st.write(my_mpl_figure) st.write_streamWrite generators or streams to the app with a typewriter effect.st.write_stream(my_generator) st.write_stream(my_llm_stream) MagicAny time Streamlit sees either a variable or literal value on its own line, it automatically writes that to your app using st.write""Hello **world**!"" my_data_frame my_mpl_figure Text elements MarkdownDisplay string formatted as Markdown.st.markdown(""Hello **world**!"") TitleDisplay text in title formatting.st.title(""The app title"") HeaderDisplay text in header formatting.st.header(""This is a header"") SubheaderDisplay text in subheader formatting.st.subheader(""This is a subheader"") CaptionDisplay text in small font.st.caption(""This is written small caption text"") Code blockDisplay a code block with optional syntax highlighting.st.code(""a = 1234"") EchoDisplay some code in the app, then execute it. Useful for tutorials.with st.echo(): st.write('This code will be printed') LaTeXDisplay mathematical expressions formatted as LaTeX.st.latex(""\int a x^2 \,dx"") Preformatted textWrite fixed-width and preformatted text.st.text(""Hello world"") DividerDisplay a horizontal rule.st.divider() Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration! PreviousTagsAdd tags to your Streamlit apps. Created by @gagan3012.st_tags(label='# Enter Keywords:', text='Press enter to add more', value=['Zero', 'One', 'Two'], suggestions=['five', 'six', 'seven', 'eight', 'nine', 'three', 'eleven', 'ten', 'four'], maxtags = 4, key='1') NLUApply text mining on a dataframe. Created by @JohnSnowLabs.nlu.load('sentiment').predict('I love NLU! <3') Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.mention(label=""An awesome Streamlit App"", icon=""streamlit"", url=""https://extras.streamlit.app"",) Annotated textDisplay annotated text in Streamlit apps. Created by @tvst.annotated_text(""This "", (""is"", ""verb""), "" some "", (""annotated"", ""adj""), (""text"", ""noun""), "" for those of "", (""you"", ""pronoun""), "" who "", (""like"", ""verb""), "" this sort of "", (""thing"", ""noun""), ""."") Drawable CanvasProvides a sketching canvas using Fabric.js. Created by @andfanilo.st_canvas(fill_color=""rgba(255, 165, 0, 0.3)"", stroke_width=stroke_width, stroke_color=stroke_color, background_color=bg_color, background_image=Image.open(bg_image) if bg_image else None, update_streamlit=realtime_update, height=150, drawing_mode=drawing_mode, point_display_radius=point_display_radius if drawing_mode == 'point' else 0, key=""canvas"",) TagsAdd tags to your Streamlit apps. Created by @gagan3012.st_tags(label='# Enter Keywords:', text='Press enter to add more', value=['Zero', 'One', 'Two'], suggestions=['five', 'six', 'seven', 'eight', 'nine', 'three', 'eleven', 'ten', 'four'], maxtags = 4, key='1') NLUApply text mining on a dataframe. Created by @JohnSnowLabs.nlu.load('sentiment').predict('I love NLU! <3') Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.mention(label=""An awesome Streamlit App"", icon=""streamlit"", url=""https://extras.streamlit.app"",) Annotated textDisplay annotated text in Streamlit apps. Created by @tvst.annotated_text(""This "", (""is"", ""verb""), "" some "", (""annotated"", ""adj""), (""text"", ""noun""), "" for those of "", (""you"", ""pronoun""), "" who "", (""like"", ""verb""), "" this sort of "", (""thing"", ""noun""), ""."") Drawable CanvasProvides a sketching canvas using Fabric.js. Created by @andfanilo.st_canvas(fill_color=""rgba(255, 165, 0, 0.3)"", stroke_width=stroke_width, stroke_color=stroke_color, background_color=bg_color, background_image=Image.open(bg_image) if bg_image else None, update_streamlit=realtime_update, height=150, drawing_mode=drawing_mode, point_display_radius=point_display_radius if drawing_mode == 'point' else 0, key=""canvas"",) TagsAdd tags to your Streamlit apps. Created by @gagan3012.st_tags(label='# Enter Keywords:', text='Press enter to add more', value=['Zero', 'One', 'Two'], suggestions=['five', 'six', 'seven', 'eight', 'nine', 'three', 'eleven', 'ten', 'four'], maxtags = 4, key='1') NLUApply text mining on a dataframe. Created by @JohnSnowLabs.nlu.load('sentiment').predict('I love NLU! <3') Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.mention(label=""An awesome Streamlit App"", icon=""streamlit"", url=""https://extras.streamlit.app"",) Next Data elements DataframesDisplay a dataframe as an interactive table.st.dataframe(my_data_frame) Data editorDisplay a data editor widget.edited = st.data_editor(df, num_rows=""dynamic"") Column configurationConfigure the display and editing behavior of dataframes and data editors.st.column_config.NumberColumn(""Price (in USD)"", min_value=0, format=""$%d"") Static tablesDisplay a static table.st.table(my_data_frame) MetricsDisplay a metric in big bold font, with an optional indicator of how the metric changed.st.metric(""My metric"", 42, 2) Dicts and JSONDisplay object or string as a pretty-printed JSON string.st.json(my_dict) Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration! PreviousImage CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates value = streamlit_image_coordinates(""https://placekitten.com/200/300"") st.write(value) Plotly EventsMake Plotly charts interactive!. Created by @null-jones.from streamlit_plotly_events import plotly_events fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.metric_cards import style_metric_cards col3.metric(label=""No Change"", value=5000, delta=0) style_metric_cards() Streamlit AggridImplementation of Ag-Grid component for Streamlit. Created by @PablocFonseca.df = pd.DataFrame({'col1': [1, 2, 3], 'col2': [4, 5, 6]}) grid_return = AgGrid(df, editable=True) new_df = grid_return['data'] Streamlit FoliumStreamlit Component for rendering Folium maps. Created by @randyzwitch.m = folium.Map(location=[39.949610, -75.150282], zoom_start=16) folium.Marker([39.949610, -75.150282], popup=""Liberty Bell"", tooltip=""Liberty Bell"").add_to(m) st_data = st_folium(m, width=725) Pandas ProfilingPandas profiling component for Streamlit. Created by @okld.df = pd.read_csv(""https://storage.googleapis.com/tf-datasets/titanic/train.csv"") pr = df.profile_report() st_profile_report(pr) Image CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates value = streamlit_image_coordinates(""https://placekitten.com/200/300"") st.write(value) Plotly EventsMake Plotly charts interactive!. Created by @null-jones.from streamlit_plotly_events import plotly_events fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.metric_cards import style_metric_cards col3.metric(label=""No Change"", value=5000, delta=0) style_metric_cards() Streamlit AggridImplementation of Ag-Grid component for Streamlit. Created by @PablocFonseca.df = pd.DataFrame({'col1': [1, 2, 3], 'col2': [4, 5, 6]}) grid_return = AgGrid(df, editable=True) new_df = grid_return['data'] Streamlit FoliumStreamlit Component for rendering Folium maps. Created by @randyzwitch.m = folium.Map(location=[39.949610, -75.150282], zoom_start=16) folium.Marker([39.949610, -75.150282], popup=""Liberty Bell"", tooltip=""Liberty Bell"").add_to(m) st_data = st_folium(m, width=725) Pandas ProfilingPandas profiling component for Streamlit. Created by @okld.df = pd.read_csv(""https://storage.googleapis.com/tf-datasets/titanic/train.csv"") pr = df.profile_report() st_profile_report(pr) Image CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates value = streamlit_image_coordinates(""https://placekitten.com/200/300"") st.write(value) Plotly EventsMake Plotly charts interactive!. Created by @null-jones.from streamlit_plotly_events import plotly_events fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.metric_cards import style_metric_cards col3.metric(label=""No Change"", value=5000, delta=0) style_metric_cards() Next Chart elements Simple area chartsDisplay an area chart.st.area_chart(my_data_frame) Simple bar chartsDisplay a bar chart.st.bar_chart(my_data_frame) Simple line chartsDisplay a line chart.st.line_chart(my_data_frame) Simple scatter chartsDisplay a line chart.st.scatter_chart(my_data_frame) Scatterplots on mapsDisplay a map with points on it.st.map(my_data_frame) MatplotlibDisplay a matplotlib.pyplot figure.st.pyplot(my_mpl_figure) AltairDisplay a chart using the Altair library.st.altair_chart(my_altair_chart) Vega-LiteDisplay a chart using the Vega-Lite library.st.vega_lite_chart(my_vega_lite_chart) PlotlyDisplay an interactive Plotly chart.st.plotly_chart(my_plotly_chart) BokehDisplay an interactive Bokeh chart.st.bokeh_chart(my_bokeh_chart) PyDeckDisplay a chart using the PyDeck library.st.pydeck_chart(my_pydeck_chart) GraphVizDisplay a graph using the dagre-d3 library.st.graphviz_chart(my_graphviz_spec) Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration! PreviousStreamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl(""https://assets5.lottiefiles.com/packages/lf20_V9t630.json"") st_lottie(lottie_hello, key=""hello"") Plotly EventsMake Plotly charts interactive!. Created by @null-jones.fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.chart += get_annotations_chart(annotations=[(""Mar 01, 2008"", ""Pretty good day for GOOG""), (""Dec 01, 2007"", ""Something's going wrong for GOOG & AAPL""), (""Nov 01, 2008"", ""Market starts again thanks to...""), (""Dec 01, 2009"", ""Small crash for GOOG after...""),],) st.altair_chart(chart, use_container_width=True) PlostA deceptively simple plotting library for Streamlit. Created by @tvst.import plost plost.line_chart(my_dataframe, x='time', y='stock_value', color='stock_name',) HiPlotHigh dimensional Interactive Plotting. Created by @facebookresearch.data = [{'dropout':0.1, 'lr': 0.001, 'loss': 10.0, 'optimizer': 'SGD'}, {'dropout':0.15, 'lr': 0.01, 'loss': 3.5, 'optimizer': 'Adam'}, {'dropout':0.3, 'lr': 0.1, 'loss': 4.5, 'optimizer': 'Adam'}] hip.Experiment.from_iterable(data).display() EChartsHigh dimensional Interactive Plotting. Created by @andfanilo.from streamlit_echarts import st_echarts st_echarts(options=options) Streamlit FoliumStreamlit Component for rendering Folium maps. Created by @randyzwitch.m = folium.Map(location=[39.949610, -75.150282], zoom_start=16) st_data = st_folium(m, width=725) Spacy-StreamlitspaCy building blocks and visualizers for Streamlit apps. Created by @explosion.models = [""en_core_web_sm"", ""en_core_web_md""] spacy_streamlit.visualize(models, ""Sundar Pichai is the CEO of Google."") Streamlit AgraphA Streamlit Graph Vis, based on react-grah-vis. Created by @ChrisDelClea.from streamlit_agraph import agraph, Node, Edge, Config agraph(nodes=nodes, edges=edges, config=config) Streamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl(""https://assets5.lottiefiles.com/packages/lf20_V9t630.json"") st_lottie(lottie_hello, key=""hello"") Plotly EventsMake Plotly charts interactive!. Created by @null-jones.fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.chart += get_annotations_chart(annotations=[(""Mar 01, 2008"", ""Pretty good day for GOOG""), (""Dec 01, 2007"", ""Something's going wrong for GOOG & AAPL""), (""Nov 01, 2008"", ""Market starts again thanks to...""), (""Dec 01, 2009"", ""Small crash for GOOG after...""),],) st.altair_chart(chart, use_container_width=True) PlostA deceptively simple plotting library for Streamlit. Created by @tvst.import plost plost.line_chart(my_dataframe, x='time', y='stock_value', color='stock_name',) HiPlotHigh dimensional Interactive Plotting. Created by @facebookresearch.data = [{'dropout':0.1, 'lr': 0.001, 'loss': 10.0, 'optimizer': 'SGD'}, {'dropout':0.15, 'lr': 0.01, 'loss': 3.5, 'optimizer': 'Adam'}, {'dropout':0.3, 'lr': 0.1, 'loss': 4.5, 'optimizer': 'Adam'}] hip.Experiment.from_iterable(data).display() EChartsHigh dimensional Interactive Plotting. Created by @andfanilo.from streamlit_echarts import st_echarts st_echarts(options=options) Streamlit FoliumStreamlit Component for rendering Folium maps. Created by @randyzwitch.m = folium.Map(location=[39.949610, -75.150282], zoom_start=16) st_data = st_folium(m, width=725) Spacy-StreamlitspaCy building blocks and visualizers for Streamlit apps. Created by @explosion.models = [""en_core_web_sm"", ""en_core_web_md""] spacy_streamlit.visualize(models, ""Sundar Pichai is the CEO of Google."") Streamlit AgraphA Streamlit Graph Vis, based on react-grah-vis. Created by @ChrisDelClea.from streamlit_agraph import agraph, Node, Edge, Config agraph(nodes=nodes, edges=edges, config=config) Streamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl(""https://assets5.lottiefiles.com/packages/lf20_V9t630.json"") st_lottie(lottie_hello, key=""hello"") Plotly EventsMake Plotly charts interactive!. Created by @null-jones.fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.chart += get_annotations_chart(annotations=[(""Mar 01, 2008"", ""Pretty good day for GOOG""), (""Dec 01, 2007"", ""Something's going wrong for GOOG & AAPL""), (""Nov 01, 2008"", ""Market starts again thanks to...""), (""Dec 01, 2009"", ""Small crash for GOOG after...""),],) st.altair_chart(chart, use_container_width=True) Next Input widgets ButtonDisplay a button widget.clicked = st.button(""Click me"") Download buttonDisplay a download button widget.st.download_button(""Download file"", file) Form buttonDisplay a form submit button. For use with st.form.st.form_submit_button(""Sign up"") Link buttonDisplay a link button.st.link_button(""Go to gallery"", url) Page linkDisplay a link to another page in a multipage app.st.page_link(""app.py"", label=""Home"", icon=""🏠"") st.page_link(""pages/profile.py"", label=""My profile"") CheckboxDisplay a checkbox widget.selected = st.checkbox(""I agree"") Color pickerDisplay a color picker widget.color = st.color_picker(""Pick a color"") MultiselectDisplay a multiselect widget. The multiselect widget starts as empty.choices = st.multiselect(""Buy"", [""milk"", ""apples"", ""potatoes""]) RadioDisplay a radio button widget.choice = st.radio(""Pick one"", [""cats"", ""dogs""]) SelectboxDisplay a select widget.choice = st.selectbox(""Pick one"", [""cats"", ""dogs""]) Select-sliderDisplay a slider widget to select items from a list.size = st.select_slider(""Pick a size"", [""S"", ""M"", ""L""]) ToggleDisplay a toggle widget.activated = st.toggle(""Activate"") Number inputDisplay a numeric input widget.choice = st.number_input(""Pick a number"", 0, 10) SliderDisplay a slider widget.number = st.slider(""Pick a number"", 0, 100) Date inputDisplay a date input widget.date = st.date_input(""Your birthday"") Time inputDisplay a time input widget.time = st.time_input(""Meeting time"") Chat inputDisplay a chat input widget.prompt = st.chat_input(""Say something"") if prompt: st.write(f""The user has sent: {prompt}"") Text-areaDisplay a multi-line text input widget.text = st.text_area(""Text to translate"") Text inputDisplay a single-line text input widget.name = st.text_input(""First name"") Data editorDisplay a data editor widget.edited = st.experimental_data_editor(df, num_rows=""dynamic"") File UploaderDisplay a file uploader widget.data = st.file_uploader(""Upload a CSV"") Camera inputDisplay a widget that allows users to upload images directly from a camera.image = st.camera_input(""Take a picture"") Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration! PreviousStreamlit ChatStreamlit Component for a Chatbot UI. Created by @AI-Yash.from streamlit_chat import message message(""My message"") message(""Hello bot!"", is_user=True) # align's the message to the right Streamlit Option MenuSelect a single item from a list of options in a menu. Created by @victoryhb.from streamlit_option_menu import option_menu option_menu(""Main Menu"", [""Home"", 'Settings'], icons=['house', 'gear'], menu_icon=""cast"", default_index=1) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.stoggle import stoggle stoggle( ""Click me!"", """"""🥷 Surprise! Here's some additional content"""""",) Streamlit ElementsCreate a draggable and resizable dashboard in Streamlit. Created by @okls.from streamlit_elements import elements, mui, html with elements(""new_element""): mui.Typography(""Hello world"") TagsAdd tags to your Streamlit apps. Created by @gagan3012.from streamlit_tags import st_tags st_tags(label='# Enter Keywords:', text='Press enter to add more', value=['Zero', 'One', 'Two'], suggestions=['five', 'six', 'seven', 'eight', 'nine', 'three', 'eleven', 'ten', 'four'], maxtags = 4, key='1') StqdmThe simplest way to handle a progress bar in streamlit app. Created by @Wirg.from stqdm import stqdm for _ in stqdm(range(50)): sleep(0.5) TimelineDisplay a Timeline in Streamlit apps using TimelineJS. Created by @innerdoc.from streamlit_timeline import timeline with open('example.json', ""r"") as f: timeline(f.read(), height=800) Camera input liveAlternative for st.camera_input which returns the webcam images live. Created by @blackary.from camera_input_live import camera_input_live image = camera_input_live() st.image(value) Streamlit AceAce editor component for Streamlit. Created by @okld.from streamlit_ace import st_ace content = st_ace() content Streamlit ChatStreamlit Component for a Chatbot UI. Created by @AI-Yash.from streamlit_chat import message message(""My message"") message(""Hello bot!"", is_user=True) # align's the message to the right Streamlit Option MenuSelect a single item from a list of options in a menu. Created by @victoryhb.from streamlit_option_menu import option_menu option_menu(""Main Menu"", [""Home"", 'Settings'], icons=['house', 'gear'], menu_icon=""cast"", default_index=1) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.stoggle import stoggle stoggle( ""Click me!"", """"""🥷 Surprise! Here's some additional content"""""",) Streamlit ElementsCreate a draggable and resizable dashboard in Streamlit. Created by @okls.from streamlit_elements import elements, mui, html with elements(""new_element""): mui.Typography(""Hello world"") TagsAdd tags to your Streamlit apps. Created by @gagan3012.from streamlit_tags import st_tags st_tags(label='# Enter Keywords:', text='Press enter to add more', value=['Zero', 'One', 'Two'], suggestions=['five', 'six', 'seven', 'eight', 'nine', 'three', 'eleven', 'ten', 'four'], maxtags = 4, key='1') StqdmThe simplest way to handle a progress bar in streamlit app. Created by @Wirg.from stqdm import stqdm for _ in stqdm(range(50)): sleep(0.5) TimelineDisplay a Timeline in Streamlit apps using TimelineJS. Created by @innerdoc.from streamlit_timeline import timeline with open('example.json', ""r"") as f: timeline(f.read(), height=800) Camera input liveAlternative for st.camera_input which returns the webcam images live. Created by @blackary.from camera_input_live import camera_input_live image = camera_input_live() st.image(value) Streamlit AceAce editor component for Streamlit. Created by @okld.from streamlit_ace import st_ace content = st_ace() content Streamlit ChatStreamlit Component for a Chatbot UI. Created by @AI-Yash.from streamlit_chat import message message(""My message"") message(""Hello bot!"", is_user=True) # align's the message to the right Streamlit Option MenuSelect a single item from a list of options in a menu. Created by @victoryhb.from streamlit_option_menu import option_menu option_menu(""Main Menu"", [""Home"", 'Settings'], icons=['house', 'gear'], menu_icon=""cast"", default_index=1) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.stoggle import stoggle stoggle( ""Click me!"", """"""🥷 Surprise! Here's some additional content"""""",) Next Media elements ImageDisplay an image or list of images.st.image(numpy_array) st.image(image_bytes) st.image(file) st.image(""https://example.com/myimage.jpg"") AudioDisplay an audio player.st.audio(numpy_array) st.audio(audio_bytes) st.audio(file) st.audio(""https://example.com/myaudio.mp3"", format=""audio/mp3"") VideoDisplay a video player.st.video(numpy_array) st.video(video_bytes) st.video(file) st.video(""https://example.com/myvideo.mp4"", format=""video/mp4"") Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration! PreviousStreamlit CropperA simple image cropper for Streamlit. Created by @turner-anderson.from streamlit_cropper import st_cropper st_cropper(img, realtime_update=realtime_update, box_color=box_color, aspect_ratio=aspect_ratio) Image CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates streamlit_image_coordinates(""https://placekitten.com/200/300"") Streamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl(""https://assets5.lottiefiles.com/packages/lf20_V9t630.json"") st_lottie(lottie_hello, key=""hello"") Streamlit WebrtcHandling and transmitting real-time video/audio streams with Streamlit. Created by @whitphx.from streamlit_webrtc import webrtc_streamer webrtc_streamer(key=""sample"") Drawable CanvasProvides a sketching canvas using Fabric.js. Created by @andfanilo.from streamlit_drawable_canvas import st_canvas st_canvas(fill_color=""rgba(255, 165, 0, 0.3)"", stroke_width=stroke_width, stroke_color=stroke_color, background_color=bg_color, background_image=Image.open(bg_image) if bg_image else None, update_streamlit=realtime_update, height=150, drawing_mode=drawing_mode, point_display_radius=point_display_radius if drawing_mode == 'point' else 0, key=""canvas"",) Image ComparisonCompare images with a slider using JuxtaposeJS. Created by @fcakyon.from streamlit_image_comparison import image_comparison image_comparison(img1=""image1.jpg"", img2=""image2.jpg"",) Streamlit CropperA simple image cropper for Streamlit. Created by @turner-anderson.from streamlit_cropper import st_cropper st_cropper(img, realtime_update=realtime_update, box_color=box_color, aspect_ratio=aspect_ratio) Image CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates streamlit_image_coordinates(""https://placekitten.com/200/300"") Streamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl(""https://assets5.lottiefiles.com/packages/lf20_V9t630.json"") st_lottie(lottie_hello, key=""hello"") Streamlit WebrtcHandling and transmitting real-time video/audio streams with Streamlit. Created by @whitphx.from streamlit_webrtc import webrtc_streamer webrtc_streamer(key=""sample"") Drawable CanvasProvides a sketching canvas using Fabric.js. Created by @andfanilo.from streamlit_drawable_canvas import st_canvas st_canvas(fill_color=""rgba(255, 165, 0, 0.3)"", stroke_width=stroke_width, stroke_color=stroke_color, background_color=bg_color, background_image=Image.open(bg_image) if bg_image else None, update_streamlit=realtime_update, height=150, drawing_mode=drawing_mode, point_display_radius=point_display_radius if drawing_mode == 'point' else 0, key=""canvas"",) Image ComparisonCompare images with a slider using JuxtaposeJS. Created by @fcakyon.from streamlit_image_comparison import image_comparison image_comparison(img1=""image1.jpg"", img2=""image2.jpg"",) Streamlit CropperA simple image cropper for Streamlit. Created by @turner-anderson.from streamlit_cropper import st_cropper st_cropper(img, realtime_update=realtime_update, box_color=box_color, aspect_ratio=aspect_ratio) Image CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates streamlit_image_coordinates(""https://placekitten.com/200/300"") Streamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl(""https://assets5.lottiefiles.com/packages/lf20_V9t630.json"") st_lottie(lottie_hello, key=""hello"") Next Layouts and containers ColumnsInsert containers laid out as side-by-side columns.col1, col2 = st.columns(2) col1.write(""this is column 1"") col2.write(""this is column 2"") ContainerInsert a multi-element container.c = st.container() st.write(""This will show last"") c.write(""This will show first"") c.write(""This will show second"") Modal dialogsInsert a modal dialog that can rerun independently from the rest of the script.@st.experimental_dialog(""Sign up"") def email_form(): name = st.text_input(""Name"") email = st.text_input(""Email"") EmptyInsert a single-element container.c = st.empty() st.write(""This will show last"") c.write(""This will be replaced"") c.write(""This will show first"") ExpanderInsert a multi-element container that can be expanded/collapsed.with st.expander(""Open to see more""): st.write(""This is more content"") PopoverInsert a multi-element popover container that can be opened/closed.with st.popover(""Settings""): st.checkbox(""Show completed"") SidebarDisplay items in a sidebar.st.sidebar.write(""This lives in the sidebar"") st.sidebar.button(""Click me!"") TabsInsert containers separated into tabs.tab1, tab2 = st.tabs([""Tab 1"", ""Tab2""]) tab1.write(""this is tab 1"") tab2.write(""this is tab 2"") Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration!Streamlit ElementsCreate a draggable and resizable dashboard in Streamlit. Created by @okls.from streamlit_elements import elements, mui, html with elements(""new_element""): mui.Typography(""Hello world"") PydanticAuto-generate Streamlit UI from Pydantic Models and Dataclasses. Created by @lukasmasuch.import streamlit_pydantic as sp sp.pydantic_form(key=""my_form"", model=ExampleModel) Streamlit PagesAn experimental version of Streamlit Multi-Page Apps. Created by @blackary.from st_pages import Page, show_pages, add_page_title show_pages([ Page(""streamlit_app.py"", ""Home"", ""🏠""), Page(""other_pages/page2.py"", ""Page 2"", "":books:""), ]) Chat elements Streamlit provides a few commands to help you build conversational apps. These chat elements are designed to be used in conjunction with each other, but you can also use them separately. st.chat_message lets you insert a chat message container into the app so you can display messages from the user or the app. Chat containers can contain other Streamlit elements, including charts, tables, text, and more. st.chat_input lets you display a chat input widget so the user can type in a message. Chat inputDisplay a chat input widget.prompt = st.chat_input(""Say something"") if prompt: st.write(f""The user has sent: {prompt}"") Chat messageInsert a chat message container.import numpy as np with st.chat_message(""user""): st.write(""Hello 👋"") st.line_chart(np.random.randn(30, 3)) Status containerDisplay output of long-running tasks in a container.with st.status('Running'): do_something_slow() st.write_streamWrite generators or streams to the app with a typewriter effect.st.write_stream(my_generator) st.write_stream(my_llm_stream) Status elements Progress barDisplay a progress bar.for i in range(101): st.progress(i) do_something_slow() SpinnerTemporarily displays a message while executing a block of code.with st.spinner(""Please wait...""): do_something_slow() Status containerDisplay output of long-running tasks in a container.with st.status('Running'): do_something_slow() ToastBriefly displays a toast message in the bottom-right corner.st.toast('Butter!', icon='🧈') BalloonsDisplay celebratory balloons!do_something() # Celebrate when all done! st.balloons() SnowflakesDisplay celebratory snowflakes!do_something() # Celebrate when all done! st.snow() Success boxDisplay a success message.st.success(""Match found!"") Info boxDisplay an informational message.st.info(""Dataset is updated every day at midnight."") Warning boxDisplay warning message.st.warning(""Unable to fetch image. Skipping..."") Error boxDisplay error message.st.error(""We encountered an error"") Exception outputDisplay an exception.e = RuntimeError(""This is an exception of type RuntimeError"") st.exception(e) Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration!StqdmThe simplest way to handle a progress bar in streamlit app. Created by @Wirg.from stqdm import stqdm for _ in stqdm(range(50)): sleep(0.5) Custom notification boxA custom notification box with the ability to close it out. Created by @Socvest.from streamlit_custom_notification_box import custom_notification_box styles = {'material-icons':{'color': 'red'}, 'text-icon-link-close-container': {'box-shadow': '#3896de 0px 4px'}, 'notification-text': {'':''}, 'close-button':{'':''}, 'link':{'':''}} custom_notification_box(icon='info', textDisplay='We are almost done with your registration...', externalLink='more info', url='#', styles=styles, key=""foo"") Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.let_it_rain import rain rain(emoji=""🎈"", font_size=54, falling_speed=5, animation_length=""infinite"",) App logic and configuration Navigation and pages Switch pageProgrammatically navigates to a specified page.st.switch_page(""pages/my_page.py"") Page linkDisplay a link to another page in a multipage app.st.page_link(""app.py"", label=""Home"", icon=""🏠"") st.page_link(""pages/profile.py"", label=""My profile"") Execution flow Modal dialogsInsert a modal dialog that can rerun independently from the rest of the script.@st.experimental_dialog(""Sign up"") def email_form(): name = st.text_input(""Name"") email = st.text_input(""Email"") FormsCreate a form that batches elements together with a “Submit"" button.with st.form(key='my_form'): name = st.text_input(""Name"") email = st.text_input(""Email"") st.form_submit_button(""Sign up"") Partial rerunsDefine a fragment to rerun independently from the rest of the script.@st.experimental_fragment(run_every=""10s"") def fragment(): df = get_data() st.line_chart(df) Rerun scriptRerun the script immediately.st.rerun() Stop executionStops execution immediately.st.stop() Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration!AutorefreshForce a refresh without tying up a script. Created by @kmcgrady.from streamlit_autorefresh import st_autorefresh st_autorefresh(interval=2000, limit=100, key=""fizzbuzzcounter"") PydanticAuto-generate Streamlit UI from Pydantic Models and Dataclasses. Created by @lukasmasuch.import streamlit_pydantic as sp sp.pydantic_form(key=""my_form"", model=ExampleModel) Streamlit PagesAn experimental version of Streamlit Multi-Page Apps. Created by @blackary.from st_pages import Page, show_pages, add_page_title show_pages([ Page(""streamlit_app.py"", ""Home"", ""🏠""), Page(""other_pages/page2.py"", ""Page 2"", "":books:""), ]) Caching and state Cache dataFunction decorator to cache functions that return data (e.g. dataframe transforms, database queries, ML inference).@st.cache_data def long_function(param1, param2): # Perform expensive computation here or # fetch data from the web here return data Cache resourceFunction decorator to cache functions that return global resources (e.g. database connections, ML models).@st.cache_resource def init_model(): # Return a global resource here return pipeline( ""sentiment-analysis"", model=""distilbert-base-uncased-finetuned-sst-2-english"" ) Session stateSession state is a way to share variables between reruns, for each user session.st.session_state['key'] = value Query parametersGet, set, or clear the query parameters that are shown in the browser's URL bar.st.query_params[key] = value st.query_params.clear() Connections and databases Setup your connection Create a connectionConnect to a data source or APIconn = st.connection('pets_db', type='sql') pet_owners = conn.query('select * from pet_owners') st.dataframe(pet_owners) Built-in connections SnowflakeConnectionA connection to Snowflake.conn = st.connection('snowflake') SQLConnectionA connection to a SQL database using SQLAlchemy.conn = st.connection('sql') Build your own connections Connection base classBuild your own connection with BaseConnection.class MyConnection(BaseConnection[myconn.MyConnection]): def _connect(self, **kwargs) -> MyConnection: return myconn.connect(**self._secrets, **kwargs) def query(self, query): return self._instance.query(query) Secrets management Secrets singletonAccess secrets from a local TOML file.key = st.secrets[""OpenAI_key""] Secrets fileSave your secrets in a per-project or per-profile TOML file.OpenAI_key = """" Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration!AuthenticatorA secure authentication module to validate user credentials. Created by @mkhorasani.import streamlit_authenticator as stauth authenticator = stauth.Authenticate( config['credentials'], config['cookie']['name'], config['cookie']['key'], config['cookie']['expiry_days'], config['preauthorized']) WS localStorageA simple synchronous way of accessing localStorage from your app. Created by @gagangoku.from streamlit_ws_localstorage import injectWebsocketCode ret = conn.setLocalStorageVal(key='k1', val='v1') st.write('ret: ' + ret) Streamlit Auth0The fastest way to provide comprehensive login inside Streamlit. Created by @conradbez.from auth0_component import login_button user_info = login_button(clientId, domain = domain) st.write(user_info) Custom Components Declare a componentCreate and register a custom component.st.components.v1.declare_component( ""custom_slider"", ""/frontend"", ) HTMLDisplay an HTML string in an iframe.st.components.v1.html( ""

Foo bar.

"" ) iframeLoad a remote URL in an iframe.st.components.v1.iframe( ""docs.streamlit.io"" ) Utilities and user info User infost.experimental_user returns information about the logged-in user of private apps on Streamlit Community Cloud.if st.experimental_user.email == ""foo@corp.com"": st.write(""Welcome back, "", st.experimental_user.email) else: st.write(""You are not authorized to view this page."") Get helpDisplay object’s doc string, nicely formatted.st.help(st.write) st.help(pd.DataFrame) Render HTMLRenders HTML strings to your app.css = """""" """""" st.html(css) Configuration Configuration fileConfigures the default settings for your app.your-project/ ├── .streamlit/ │ └── config.toml └── your_app.py Set page title, favicon, and moreConfigures the default settings of the page.st.set_page_config( page_title=""My app"", page_icon="":shark:"", ) Developer tools App testing st.testing.v1.AppTestst.testing.v1.AppTest simulates a running Streamlit app for testing.from streamlit.testing.v1 import AppTest at = AppTest.from_file(""streamlit_app.py"") at.secrets[""WORD""] = ""Foobar"" at.run() assert not at.exception at.text_input(""word"").input(""Bazbat"").run() assert at.warning[0].value == ""Try again."" AppTest.from_filest.testing.v1.AppTest.from_file initializes a simulated app from a file.from streamlit.testing.v1 import AppTest at = AppTest.from_file(""streamlit_app.py"") at.run() AppTest.from_stringst.testing.v1.AppTest.from_string initializes a simulated app from a string.from streamlit.testing.v1 import AppTest at = AppTest.from_string(app_script_as_string) at.run() AppTest.from_functionst.testing.v1.AppTest.from_function initializes a simulated app from a function.from streamlit.testing.v1 import AppTest at = AppTest.from_function(app_script_as_callable) at.run() BlockA representation of container elements, including: st.chat_message st.columns st.sidebar st.tabs The main body of the app. # at.sidebar returns a Block at.sidebar.button[0].click().run() assert not at.exception ElementThe base class for representation of all elements, including: st.title st.header st.markdown st.dataframe # at.title returns a sequence of Title # Title inherits from Element assert at.title[0].value == ""My awesome app"" ButtonA representation of st.button and st.form_submit_button.at.button[0].click().run() ChatInputA representation of st.chat_input.at.chat_input[0].set_value(""What is Streamlit?"").run() CheckboxA representation of st.checkbox.at.checkbox[0].check().run() ColorPickerA representation of st.color_picker.at.color_picker[0].pick(""#FF4B4B"").run() DateInputA representation of st.date_input.release_date = datetime.date(2023, 10, 26) at.date_input[0].set_value(release_date).run() MultiselectA representation of st.multiselect.at.multiselect[0].select(""New York"").run() NumberInputA representation of st.number_input.at.number_input[0].increment().run() RadioA representation of st.radio.at.radio[0].set_value(""New York"").run() SelectSliderA representation of st.select_slider.at.select_slider[0].set_range(""A"",""C"").run() SelectboxA representation of st.selectbox.at.selectbox[0].select(""New York"").run() SliderA representation of st.slider.at.slider[0].set_range(2,5).run() TextAreaA representation of st.text_area.at.text_area[0].input(""Streamlit is awesome!"").run() TextInputA representation of st.text_input.at.text_input[0].input(""Streamlit"").run() TimeInputA representation of st.time_input.at.time_input[0].increment().run() ToggleA representation of st.toggle.at.toggle[0].set_value(""True"").run() Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration!Pandas ProfilingPandas profiling component for Streamlit. Created by @okld.df = pd.read_csv(""https://storage.googleapis.com/tf-datasets/titanic/train.csv"") pr = df.profile_report() st_profile_report(pr) Streamlit AceAce editor component for Streamlit. Created by @okld.from streamlit_ace import st_ace content = st_ace() content Streamlit AnalyticsTrack & visualize user interactions with your streamlit app. Created by @jrieke.import streamlit_analytics with streamlit_analytics.track(): st.text_input(""Write something"") Previous: ConceptsNext: Write and magicforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy" https://docs.streamlit.io/develop/concepts/custom-components/intro#python--frontend,"DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsremoveCOREArchitecture & executionaddMultipage appsaddApp designaddADDITIONALConnections and secretsaddCustom componentsremoveIntro to custom componentsCreate a ComponentPublish a ComponentLimitationsComponent galleryopen_in_newConfiguration and themingaddApp testingaddAPI referenceaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Develop/Concepts/Custom components/Intro to custom componentsIntro to custom components The first step in developing a Streamlit Component is deciding whether to create a static component (i.e. rendered once, controlled by Python) or to create a bi-directional component that can communicate from Python to JavaScript and back. Create a static component If your goal in creating a Streamlit Component is solely to display HTML code or render a chart from a Python visualization library, Streamlit provides two methods that greatly simplify the process: components.html() and components.iframe(). If you are unsure whether you need bi-directional communication, start here first! Render an HTML string While st.text, st.markdown and st.write make it easy to write text to a Streamlit app, sometimes you'd rather implement a custom piece of HTML. Similarly, while Streamlit natively supports many charting libraries, you may want to implement a specific HTML/JavaScript template for a new charting library. components.html works by giving you the ability to embed an iframe inside of a Streamlit app that contains your desired output. Example import streamlit as st import streamlit.components.v1 as components # bootstrap 4 collapse example components.html( """"""
Collapsible Group Item #1 content
Collapsible Group Item #2 content
"""""", height=600, ) Render an iframe URL components.iframe is similar in features to components.html, with the difference being that components.iframe takes a URL as its input. This is used for situations where you want to include an entire page within a Streamlit app. Example import streamlit as st import streamlit.components.v1 as components # embed streamlit docs in a streamlit app components.iframe(""https://example.com"", height=500) Create a bi-directional component A bi-directional Streamlit Component has two parts: A frontend, which is built out of HTML and any other web tech you like (JavaScript, React, Vue, etc.), and gets rendered in Streamlit apps via an iframe tag. A Python API, which Streamlit apps use to instantiate and talk to that frontend To make the process of creating bi-directional Streamlit Components easier, we've created a React template and a TypeScript-only template in the Streamlit Component-template GitHub repo. We also provide some example Components in the same repo. Development Environment Setup To build a Streamlit Component, you need the following installed in your development environment: Python 3.8 - Python 3.12 Streamlit 1.11.1 or higher nodejs npm or yarn Clone the component-template GitHub repo, then decide whether you want to use the React.js (""template"") or plain TypeScript (""template-reactless"") template. Initialize and build the component template frontend from the terminal: # React template template/my_component/frontend npm install # Initialize the project and install npm dependencies npm run start # Start the Webpack dev server # or # TypeScript-only template template-reactless/my_component/frontend npm install # Initialize the project and install npm dependencies npm run start # Start the Webpack dev server From a separate terminal, run the Streamlit app (Python) that declares and uses the component: # React template cd template . venv/bin/activate # or similar to activate the venv/conda environment where Streamlit is installed pip install -e . # install template as editable package streamlit run my_component/example.py # run the example # or # TypeScript-only template cd template-reactless . venv/bin/activate # or similar to activate the venv/conda environment where Streamlit is installed pip install -e . # install template as editable package streamlit run my_component/example.py # run the example After running the steps above, you should see a Streamlit app in your browser that looks like this: The example app from the template shows how bi-directional communication is implemented. The Streamlit Component displays a button (Python → JavaScript), and the end-user can click the button. Each time the button is clicked, the JavaScript front-end increments the counter value and passes it back to Python (JavaScript → Python), which is then displayed by Streamlit (Python → JavaScript). Frontend Because each Streamlit Component is its own webpage that gets rendered into an iframe, you can use just about any web tech you'd like to create that web page. We provide two templates to get started with in the Streamlit Components-template GitHub repo; one of those templates uses React and the other does not. push_pinNoteEven if you're not already familiar with React, you may still want to check out the React-based template. It handles most of the boilerplate required to send and receive data from Streamlit, and you can learn the bits of React you need as you go.If you'd rather not use React, please read this section anyway! It explains the fundamentals of Streamlit ↔ Component communication. React The React-based template is in template/my_component/frontend/src/MyComponent.tsx. MyComponent.render() is called automatically when the component needs to be re-rendered (just like in any React app) Arguments passed from the Python script are available via the this.props.args dictionary: # Send arguments in Python: result = my_component(greeting=""Hello"", name=""Streamlit"") // Receive arguments in frontend: let greeting = this.props.args[""greeting""]; // greeting = ""Hello"" let name = this.props.args[""name""]; // name = ""Streamlit"" Use Streamlit.setComponentValue() to return data from the component to the Python script: // Set value in frontend: Streamlit.setComponentValue(3.14); # Access value in Python: result = my_component(greeting=""Hello"", name=""Streamlit"") st.write(""result = "", result) # result = 3.14 When you call Streamlit.setComponentValue(new_value), that new value is sent to Streamlit, which then re-executes the Python script from top to bottom. When the script is re-executed, the call to my_component(...) will return the new value. From a code flow perspective, it appears that you're transmitting data synchronously with the frontend: Python sends the arguments to JavaScript, and JavaScript returns a value to Python, all in a single function call! But in reality this is all happening asynchronously, and it's the re-execution of the Python script that achieves the sleight of hand. Use Streamlit.setFrameHeight() to control the height of your component. By default, the React template calls this automatically (see StreamlitComponentBase.componentDidUpdate()). You can override this behavior if you need more control. There's a tiny bit of magic in the last line of the file: export default withStreamlitConnection(MyComponent) - this does some handshaking with Streamlit, and sets up the mechanisms for bi-directional data communication. TypeScript-only The TypeScript-only template is in template-reactless/my_component/frontend/src/MyComponent.tsx. This template has much more code than its React sibling, in that all the mechanics of handshaking, setting up event listeners, and updating the component's frame height are done manually. The React version of the template handles most of these details automatically. Towards the bottom of the source file, the template calls Streamlit.setComponentReady() to tell Streamlit it's ready to start receiving data. (You'll generally want to do this after creating and loading everything that the Component relies on.) It subscribes to Streamlit.RENDER_EVENT to be notified of when to redraw. (This event won't be fired until setComponentReady is called) Within its onRender event handler, it accesses the arguments passed in the Python script via event.detail.args It sends data back to the Python script in the same way that the React template does—clicking on the ""Click Me!"" button calls Streamlit.setComponentValue() It informs Streamlit when its height may have changed via Streamlit.setFrameHeight() Working with Themes push_pinNoteCustom component theme support requires streamlit-component-lib version 1.2.0 or higher. Along with sending an args object to your component, Streamlit also sends a theme object defining the active theme so that your component can adjust its styling in a compatible way. This object is sent in the same message as args, so it can be accessed via this.props.theme (when using the React template) or event.detail.theme (when using the plain TypeScript template). The theme object has the following shape: { ""base"": ""lightORdark"", ""primaryColor"": ""someColor1"", ""backgroundColor"": ""someColor2"", ""secondaryBackgroundColor"": ""someColor3"", ""textColor"": ""someColor4"", ""font"": ""someFont"" } The base option allows you to specify a preset Streamlit theme that your custom theme inherits from. Any theme config options not defined in your theme settings have their values set to those of the base theme. Valid values for base are ""light"" and ""dark"". Note that the theme object has fields with the same names and semantics as the options in the ""theme"" section of the config options printed with the command streamlit config show. When using the React template, the following CSS variables are also set automatically. --base --primary-color --background-color --secondary-background-color --text-color --font If you're not familiar with CSS variables, the TLDR version is that you can use them like this: .mySelector { color: var(--text-color); } These variables match the fields defined in the theme object above, and whether to use CSS variables or the theme object in your component is a matter of personal preference. Other frontend details Because you're hosting your component from a dev server (via npm run start), any changes you make should be automatically reflected in the Streamlit app when you save. If you want to add more packages to your component, run npm add to add them from within your component's frontend/ directory. npm add baseui To build a static version of your component, run npm run export. See Prepare your Component for more information Python API components.declare_component() is all that's required to create your Component's Python API: import streamlit.components.v1 as components my_component = components.declare_component( ""my_component"", url=""http://localhost:3001"" ) You can then use the returned my_component function to send and receive data with your frontend code: # Send data to the frontend using named arguments. return_value = my_component(name=""Blackbeard"", ship=""Queen Anne's Revenge"") # `my_component`'s return value is the data returned from the frontend. st.write(""Value = "", return_value) While the above is all you need to define from the Python side to have a working Component, we recommend creating a ""wrapper"" function with named arguments and default values, input validation and so on. This will make it easier for end-users to understand what data values your function accepts and allows for defining helpful docstrings. Please see this example from the Components-template for an example of creating a wrapper function. Data serialization Python → Frontend You send data from Python to the frontend by passing keyword args to your Component's invoke function (that is, the function returned from declare_component). You can send the following types of data from Python to the frontend: Any JSON-serializable data numpy.array pandas.DataFrame Any JSON-serializable data gets serialized to a JSON string, and deserialized to its JavaScript equivalent. numpy.array and pandas.DataFrame get serialized using Apache Arrow and are deserialized as instances of ArrowTable, which is a custom type that wraps Arrow structures and provides a convenient API on top of them. Check out the CustomDataframe and SelectableDataTable Component example code for more context on how to use ArrowTable. Frontend → Python You send data from the frontend to Python via the Streamlit.setComponentValue() API (which is part of the template code). Unlike arg-passing from Python → frontend, this API takes a single value. If you want to return multiple values, you'll need to wrap them in an Array or Object. Custom Components can send JSON-serializable data from the frontend to Python, as well as Apache Arrow ArrowTables to represent dataframes.Previous: Custom componentsNext: Create a ComponentforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy" https://docs.streamlit.io/develop/api-reference/configuration/config.toml#theme,"DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceremovePAGE ELEMENTSWrite and magicaddText elementsaddData elementsaddChart elementsaddInput widgetsaddMedia elementsaddLayouts and containersaddChat elementsaddStatus elementsaddThird-party componentsopen_in_newAPPLICATION LOGICNavigation and pagesaddExecution flowaddCaching and stateaddConnections and secretsaddCustom componentsaddUtilitiesaddConfigurationremoveconfig.tomlst.set_page_configTOOLSApp testingaddCommand lineaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Develop/API reference/Configuration/config.tomlconfig.toml config.toml is an optional file you can define for your working directory or global development environment. When config.toml is defined both globally and in your working directory, Streamlit combines the configuration options and gives precendence to the working-directory configuration. Additionally, you can use environment variables and command-line options to override additional configuration options. For more information, see Configuration options. File location To define your configuration locally or per-project, add .streamlit/config.toml to your working directory. Your working directory is wherever you call streamlit run. If you haven't previously created the .streamlit directory, you will need to add it. To define your configuration globally, you must first locate your global .streamlit directory. Streamlit adds this hidden directory to your OS user profile during installation. For MacOS/Linx, this will be ~/.streamlit/config.toml. For Windows, this will be %userprofile%/.streamlit/config.toml. File format config.toml is a TOML file. Example [client] showErrorDetails = false [theme] primaryColor = ""#F63366"" backgroundColor = ""black"" Available configuration options Below are all the sections and options you can have in your .streamlit/config.toml file. To see all configurations, use the following command in your terminal or CLI: streamlit config show Global [global] # ***DEPRECATED*** # global.disableWatchdogWarning has been deprecated has been deprecated and # will be removed in a future version. This option will be removed on or after # 2024-01-20. # **************** # By default, Streamlit checks if the Python watchdog module is available # and, if not, prints a warning asking for you to install it. The watchdog # module is not required, but highly recommended. It improves Streamlit's # ability to detect changes to files in your filesystem. # If you'd like to turn off this warning, set this to True. # Default: false disableWatchdogWarning = false # By default, Streamlit displays a warning when a user sets both a widget # default value in the function defining the widget and a widget value via # the widget's key in `st.session_state`. # If you'd like to turn off this warning, set this to True. # Default: false disableWidgetStateDuplicationWarning = false # If True, will show a warning when you run a Streamlit-enabled script # via ""python my_script.py"". # Default: true showWarningOnDirectExecution = true Logger [logger] # Level of logging: 'error', 'warning', 'info', or 'debug'. # Default: 'info' level = ""info"" # String format for logging messages. If logger.datetimeFormat is set, # logger messages will default to `%(asctime)s.%(msecs)03d %(message)s`. See # Python's documentation for available attributes: # https://docs.python.org/2.6/develop/logging.html#formatter-objects # Default: ""%(asctime)s %(message)s"" messageFormat = ""%(asctime)s %(message)s"" Client [client] # ***DEPRECATED*** # client.caching has been deprecated and is not required anymore for our new # caching commands. This option will be removed on or after 2024-01-20. # **************** # Whether to enable st.cache. This does not affect st.cache_data or # st.cache_resource. # Default: true caching = true # ***DEPRECATED*** # client.displayEnabled has been deprecated and will be removed in a future # version. This option will be removed on or after 2024-01-20. # **************** # If false, makes your Streamlit script not draw to a Streamlit app. # Default: true displayEnabled = true # Controls whether uncaught app exceptions and deprecation warnings # are displayed in the browser. By default, this is set to True and # Streamlit displays app exceptions and associated tracebacks, and # deprecation warnings, in the browser. # # If set to False, deprecation warnings and full exception messages # will print to the console only. Exceptions will still display in the # browser with a generic error message. For now, the exception type and # traceback show in the browser also, but they will be removed in the # future. # Default: true showErrorDetails = true # Change the visibility of items in the toolbar, options menu, # and settings dialog (top right of the app). # Allowed values: # * ""auto"" : Show the developer options if the app is accessed through # localhost or through Streamlit Community Cloud as a developer. # Hide them otherwise. # * ""developer"" : Show the developer options. # * ""viewer"" : Hide the developer options. # * ""minimal"" : Show only options set externally (e.g. through # Streamlit Community Cloud) or through st.set_page_config. # If there are no options left, hide the menu. # Default: ""auto"" toolbarMode = ""auto"" # Controls whether the default sidebar page navigation in a multipage app is # displayed. # Default: true showSidebarNavigation = true Runner [runner] # Allows you to type a variable or string by itself in a single line of # Python code to write it to the app. # Default: true magicEnabled = true # ***DEPRECATED*** # runner.installTracer has been deprecated and will be removed in a future # version. This option will be removed on or after 2024-01-20. # **************** # Install a Python tracer to allow you to stop or pause your script at # any point and introspect it. As a side-effect, this slows down your # script's execution. # Default: false installTracer = false # ***DEPRECATED*** # runner.fixMatplotlib has been deprecated and will be removed in a future # version. This option will be removed on or after 2024-01-20. # **************** # Sets the MPLBACKEND environment variable to Agg inside Streamlit to # prevent Python crashing. # Default: true fixMatplotlib = true # Handle script rerun requests immediately, rather than waiting for script # execution to reach a yield point. This makes Streamlit much more # responsive to user interaction, but it can lead to race conditions in # apps that mutate session_state data outside of explicit session_state # assignment statements. # Default: true fastReruns = true # Raise an exception after adding unserializable data to Session State. # Some execution environments may require serializing all data in Session # State, so it may be useful to detect incompatibility during development, # or when the execution environment will stop supporting it in the future. # Default: false enforceSerializableSessionState = false # Adjust how certain 'options' widgets like radio, selectbox, and # multiselect coerce Enum members when the Enum class gets # re-defined during a script re-run. For more information, check out the docs: # https://docs.streamlit.io/develop/concepts/design/custom-classes#enums # # Allowed values: # * ""off"" : Disables Enum coercion. # * ""nameOnly"" : Enum classes can be coerced if their member names match. # * ""nameAndValue"" : Enum classes can be coerced if their member names AND # member values match. # Default: ""nameOnly"" enumCoercion = ""nameOnly"" Server [server] # List of folders that should not be watched for changes. This # impacts both ""Run on Save"" and @st.cache. # Relative paths will be taken as relative to the current working directory. # Example: ['/home/user1/env', 'relative/path/to/folder'] # Default: [] folderWatchBlacklist = [] # Change the type of file watcher used by Streamlit, or turn it off # completely. # Allowed values: # * ""auto"" : Streamlit will attempt to use the watchdog module, and # falls back to polling if watchdog is not available. # * ""watchdog"" : Force Streamlit to use the watchdog module. # * ""poll"" : Force Streamlit to always use polling. # * ""none"" : Streamlit will not watch files. # Default: ""auto"" fileWatcherType = ""auto"" # Symmetric key used to produce signed cookies. If deploying on multiple # replicas, this should be set to the same value across all replicas to ensure # they all share the same secret. # Default: randomly generated secret key. cookieSecret = ""a-random-key-appears-here"" # If false, will attempt to open a browser window on start. # Default: false unless (1) we are on a Linux box where DISPLAY is unset, or # (2) we are running in the Streamlit Atom plugin. headless = false # Automatically rerun script when the file is modified on disk. # Default: false runOnSave = false # The address where the server will listen for client and browser # connections. Use this if you want to bind the server to a specific address. # If set, the server will only be accessible from this address, and not from # any aliases (like localhost). # Default: (unset) address = # The port where the server will listen for browser connections. # Don't use port 3000 which is reserved for internal development. # Default: 8501 port = 8501 # The base path for the URL where Streamlit should be served from. # Default: """" baseUrlPath = """" # Enables support for Cross-Origin Resource Sharing (CORS) protection, for # added security. # Due to conflicts between CORS and XSRF, if `server.enableXsrfProtection` is # on and `server.enableCORS` is off at the same time, we will prioritize # `server.enableXsrfProtection`. # Default: true enableCORS = true # Enables support for Cross-Site Request Forgery (XSRF) protection, for added # security. # Due to conflicts between CORS and XSRF, if `server.enableXsrfProtection` is # on and `server.enableCORS` is off at the same time, we will prioritize # `server.enableXsrfProtection`. # Default: true enableXsrfProtection = true # Max size, in megabytes, for files uploaded with the file_uploader. # Default: 200 maxUploadSize = 200 # Max size, in megabytes, of messages that can be sent via the WebSocket # connection. # Default: 200 maxMessageSize = 200 # Enables support for websocket compression. # Default: false enableWebsocketCompression = false # Enable serving files from a `static` directory in the running app's # directory. # Default: false enableStaticServing = false # Server certificate file for connecting via HTTPS. # Must be set at the same time as ""server.sslKeyFile"". # ['DO NOT USE THIS OPTION IN A PRODUCTION ENVIRONMENT. It has not gone through # security audits or performance tests. For the production environment, we # recommend performing SSL termination by the load balancer or the reverse # proxy.'] # sslCertFile = # Cryptographic key file for connecting via HTTPS. # Must be set at the same time as ""server.sslCertFile"". # ['DO NOT USE THIS OPTION IN A PRODUCTION ENVIRONMENT. It has not gone through # security audits or performance tests. For the production environment, we # recommend performing SSL termination by the load balancer or the reverse # proxy.'] # sslKeyFile = Browser [browser] # Internet address where users should point their browsers in order to # connect to the app. Can be IP address or DNS name and path. # This is used to: # - Set the correct URL for CORS and XSRF protection purposes. # - Show the URL on the terminal # - Open the browser # Default: ""localhost"" serverAddress = ""localhost"" # Whether to send usage statistics to Streamlit. # Default: true gatherUsageStats = true # Port where users should point their browsers in order to connect to the # app. # This is used to: # - Set the correct URL for XSRF protection purposes. # - Show the URL on the terminal (part of `streamlit run`). # - Open the browser automatically (part of `streamlit run`). # This option is for advanced use cases. To change the port of your app, use # `server.Port` instead. Don't use port 3000 which is reserved for internal # development. # Default: whatever value is set in server.port. serverPort = 8501 Mapbox [mapbox] # Configure Streamlit to use a custom Mapbox # token for elements like st.pydeck_chart and st.map. # To get a token for yourself, create an account at # https://mapbox.com. It's free (for moderate usage levels)! # Default: """" token = """" Deprecation [deprecation] # Set to false to disable the deprecation warning for using the global pyplot # instance. # Default: true showPyplotGlobalUse = true Theme [theme] # The preset Streamlit theme that your custom theme inherits from. # One of ""light"" or ""dark"". # base = # Primary accent color for interactive elements. # primaryColor = # Background color for the main content area. # backgroundColor = # Background color used for the sidebar and most interactive widgets. # secondaryBackgroundColor = # Color used for almost all text. # textColor = # Font family for all text in the app, except code blocks. One of ""sans serif"", # ""serif"", or ""monospace"". # font = Previous: ConfigurationNext: st.set_page_configforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy" https://docs.streamlit.io/knowledge-base/deploy/increase-file-uploader-limit-streamlit-cloud#how-do-i-increase-the-upload-limit-of-stfile_uploader-on-streamlit-community-cloud,"DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Knowledge base/Deployment issues/How do I increase the upload limit of st.file_uploader on Streamlit Community Cloud?How do I increase the upload limit of st.file_uploader on Streamlit Community Cloud? Overview By default, files uploaded using st.file_uploader() are limited to 200MB. You can configure this using the server.maxUploadSize config option. Streamlit provides four different ways to set configuration options: In a global config file at ~/.streamlit/config.toml for macOS/Linux or %userprofile%/.streamlit/config.toml for Windows: [server] maxUploadSize = 200 In a per-project config file at $CWD/.streamlit/config.toml, where $CWD is the folder you're running Streamlit from. Through STREAMLIT_* environment variables, such as: export STREAMLIT_SERVER_MAX_UPLOAD_SIZE=200 As flags on the command line when running streamlit run: streamlit run your_script.py --server.maxUploadSize 200 Which of the four options should you choose for an app deployed to Streamlit Community Cloud? 🤔 Solution When deploying your app to Streamlit Community Cloud, you should use option 1. Namely, set the maxUploadSize config option in a global config file (.streamlit/config.toml) uploaded to your app's GitHub repo. 🎈 For example, to increase the upload limit to 400MB, upload a .streamlit/config.toml file containing the following lines to your app's GitHub repo: [server] maxUploadSize = 400 Relevant resources Streamlit drag and drop capping at 200MB, need workaround File uploader widget API How to set Streamlit configuration options Previous: Does Streamlit support the WSGI Protocol? (aka Can I deploy Streamlit with gunicorn?)Next: Invoking a Python subprocess in a deployed Streamlit appforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy" https://docs.streamlit.io/en/0.71.0/api.html#secrets-management,"DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceremovePAGE ELEMENTSWrite and magicaddText elementsaddData elementsaddChart elementsaddInput widgetsaddMedia elementsaddLayouts and containersaddChat elementsaddStatus elementsaddThird-party componentsopen_in_newAPPLICATION LOGICNavigation and pagesaddExecution flowaddCaching and stateaddConnections and secretsaddCustom componentsaddUtilitiesaddConfigurationaddTOOLSApp testingaddCommand lineaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Develop/API referenceAPI reference Streamlit makes it easy for you to visualize, mutate, and share data. The API reference is organized by activity type, like displaying data or optimizing performance. Each section includes methods associated with the activity type, including examples. Browse our API below and click to learn more about any of our available commands! 🎈 Display almost anything Write and magic st.writeWrite arguments to the app.st.write(""Hello **world**!"") st.write(my_data_frame) st.write(my_mpl_figure) st.write_streamWrite generators or streams to the app with a typewriter effect.st.write_stream(my_generator) st.write_stream(my_llm_stream) MagicAny time Streamlit sees either a variable or literal value on its own line, it automatically writes that to your app using st.write""Hello **world**!"" my_data_frame my_mpl_figure Text elements MarkdownDisplay string formatted as Markdown.st.markdown(""Hello **world**!"") TitleDisplay text in title formatting.st.title(""The app title"") HeaderDisplay text in header formatting.st.header(""This is a header"") SubheaderDisplay text in subheader formatting.st.subheader(""This is a subheader"") CaptionDisplay text in small font.st.caption(""This is written small caption text"") Code blockDisplay a code block with optional syntax highlighting.st.code(""a = 1234"") EchoDisplay some code in the app, then execute it. Useful for tutorials.with st.echo(): st.write('This code will be printed') LaTeXDisplay mathematical expressions formatted as LaTeX.st.latex(""\int a x^2 \,dx"") Preformatted textWrite fixed-width and preformatted text.st.text(""Hello world"") DividerDisplay a horizontal rule.st.divider() Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration! PreviousTagsAdd tags to your Streamlit apps. Created by @gagan3012.st_tags(label='# Enter Keywords:', text='Press enter to add more', value=['Zero', 'One', 'Two'], suggestions=['five', 'six', 'seven', 'eight', 'nine', 'three', 'eleven', 'ten', 'four'], maxtags = 4, key='1') NLUApply text mining on a dataframe. Created by @JohnSnowLabs.nlu.load('sentiment').predict('I love NLU! <3') Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.mention(label=""An awesome Streamlit App"", icon=""streamlit"", url=""https://extras.streamlit.app"",) Annotated textDisplay annotated text in Streamlit apps. Created by @tvst.annotated_text(""This "", (""is"", ""verb""), "" some "", (""annotated"", ""adj""), (""text"", ""noun""), "" for those of "", (""you"", ""pronoun""), "" who "", (""like"", ""verb""), "" this sort of "", (""thing"", ""noun""), ""."") Drawable CanvasProvides a sketching canvas using Fabric.js. Created by @andfanilo.st_canvas(fill_color=""rgba(255, 165, 0, 0.3)"", stroke_width=stroke_width, stroke_color=stroke_color, background_color=bg_color, background_image=Image.open(bg_image) if bg_image else None, update_streamlit=realtime_update, height=150, drawing_mode=drawing_mode, point_display_radius=point_display_radius if drawing_mode == 'point' else 0, key=""canvas"",) TagsAdd tags to your Streamlit apps. Created by @gagan3012.st_tags(label='# Enter Keywords:', text='Press enter to add more', value=['Zero', 'One', 'Two'], suggestions=['five', 'six', 'seven', 'eight', 'nine', 'three', 'eleven', 'ten', 'four'], maxtags = 4, key='1') NLUApply text mining on a dataframe. Created by @JohnSnowLabs.nlu.load('sentiment').predict('I love NLU! <3') Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.mention(label=""An awesome Streamlit App"", icon=""streamlit"", url=""https://extras.streamlit.app"",) Annotated textDisplay annotated text in Streamlit apps. Created by @tvst.annotated_text(""This "", (""is"", ""verb""), "" some "", (""annotated"", ""adj""), (""text"", ""noun""), "" for those of "", (""you"", ""pronoun""), "" who "", (""like"", ""verb""), "" this sort of "", (""thing"", ""noun""), ""."") Drawable CanvasProvides a sketching canvas using Fabric.js. Created by @andfanilo.st_canvas(fill_color=""rgba(255, 165, 0, 0.3)"", stroke_width=stroke_width, stroke_color=stroke_color, background_color=bg_color, background_image=Image.open(bg_image) if bg_image else None, update_streamlit=realtime_update, height=150, drawing_mode=drawing_mode, point_display_radius=point_display_radius if drawing_mode == 'point' else 0, key=""canvas"",) TagsAdd tags to your Streamlit apps. Created by @gagan3012.st_tags(label='# Enter Keywords:', text='Press enter to add more', value=['Zero', 'One', 'Two'], suggestions=['five', 'six', 'seven', 'eight', 'nine', 'three', 'eleven', 'ten', 'four'], maxtags = 4, key='1') NLUApply text mining on a dataframe. Created by @JohnSnowLabs.nlu.load('sentiment').predict('I love NLU! <3') Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.mention(label=""An awesome Streamlit App"", icon=""streamlit"", url=""https://extras.streamlit.app"",) Next Data elements DataframesDisplay a dataframe as an interactive table.st.dataframe(my_data_frame) Data editorDisplay a data editor widget.edited = st.data_editor(df, num_rows=""dynamic"") Column configurationConfigure the display and editing behavior of dataframes and data editors.st.column_config.NumberColumn(""Price (in USD)"", min_value=0, format=""$%d"") Static tablesDisplay a static table.st.table(my_data_frame) MetricsDisplay a metric in big bold font, with an optional indicator of how the metric changed.st.metric(""My metric"", 42, 2) Dicts and JSONDisplay object or string as a pretty-printed JSON string.st.json(my_dict) Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration! PreviousImage CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates value = streamlit_image_coordinates(""https://placekitten.com/200/300"") st.write(value) Plotly EventsMake Plotly charts interactive!. Created by @null-jones.from streamlit_plotly_events import plotly_events fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.metric_cards import style_metric_cards col3.metric(label=""No Change"", value=5000, delta=0) style_metric_cards() Streamlit AggridImplementation of Ag-Grid component for Streamlit. Created by @PablocFonseca.df = pd.DataFrame({'col1': [1, 2, 3], 'col2': [4, 5, 6]}) grid_return = AgGrid(df, editable=True) new_df = grid_return['data'] Streamlit FoliumStreamlit Component for rendering Folium maps. Created by @randyzwitch.m = folium.Map(location=[39.949610, -75.150282], zoom_start=16) folium.Marker([39.949610, -75.150282], popup=""Liberty Bell"", tooltip=""Liberty Bell"").add_to(m) st_data = st_folium(m, width=725) Pandas ProfilingPandas profiling component for Streamlit. Created by @okld.df = pd.read_csv(""https://storage.googleapis.com/tf-datasets/titanic/train.csv"") pr = df.profile_report() st_profile_report(pr) Image CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates value = streamlit_image_coordinates(""https://placekitten.com/200/300"") st.write(value) Plotly EventsMake Plotly charts interactive!. Created by @null-jones.from streamlit_plotly_events import plotly_events fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.metric_cards import style_metric_cards col3.metric(label=""No Change"", value=5000, delta=0) style_metric_cards() Streamlit AggridImplementation of Ag-Grid component for Streamlit. Created by @PablocFonseca.df = pd.DataFrame({'col1': [1, 2, 3], 'col2': [4, 5, 6]}) grid_return = AgGrid(df, editable=True) new_df = grid_return['data'] Streamlit FoliumStreamlit Component for rendering Folium maps. Created by @randyzwitch.m = folium.Map(location=[39.949610, -75.150282], zoom_start=16) folium.Marker([39.949610, -75.150282], popup=""Liberty Bell"", tooltip=""Liberty Bell"").add_to(m) st_data = st_folium(m, width=725) Pandas ProfilingPandas profiling component for Streamlit. Created by @okld.df = pd.read_csv(""https://storage.googleapis.com/tf-datasets/titanic/train.csv"") pr = df.profile_report() st_profile_report(pr) Image CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates value = streamlit_image_coordinates(""https://placekitten.com/200/300"") st.write(value) Plotly EventsMake Plotly charts interactive!. Created by @null-jones.from streamlit_plotly_events import plotly_events fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.metric_cards import style_metric_cards col3.metric(label=""No Change"", value=5000, delta=0) style_metric_cards() Next Chart elements Simple area chartsDisplay an area chart.st.area_chart(my_data_frame) Simple bar chartsDisplay a bar chart.st.bar_chart(my_data_frame) Simple line chartsDisplay a line chart.st.line_chart(my_data_frame) Simple scatter chartsDisplay a line chart.st.scatter_chart(my_data_frame) Scatterplots on mapsDisplay a map with points on it.st.map(my_data_frame) MatplotlibDisplay a matplotlib.pyplot figure.st.pyplot(my_mpl_figure) AltairDisplay a chart using the Altair library.st.altair_chart(my_altair_chart) Vega-LiteDisplay a chart using the Vega-Lite library.st.vega_lite_chart(my_vega_lite_chart) PlotlyDisplay an interactive Plotly chart.st.plotly_chart(my_plotly_chart) BokehDisplay an interactive Bokeh chart.st.bokeh_chart(my_bokeh_chart) PyDeckDisplay a chart using the PyDeck library.st.pydeck_chart(my_pydeck_chart) GraphVizDisplay a graph using the dagre-d3 library.st.graphviz_chart(my_graphviz_spec) Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration! PreviousStreamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl(""https://assets5.lottiefiles.com/packages/lf20_V9t630.json"") st_lottie(lottie_hello, key=""hello"") Plotly EventsMake Plotly charts interactive!. Created by @null-jones.fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.chart += get_annotations_chart(annotations=[(""Mar 01, 2008"", ""Pretty good day for GOOG""), (""Dec 01, 2007"", ""Something's going wrong for GOOG & AAPL""), (""Nov 01, 2008"", ""Market starts again thanks to...""), (""Dec 01, 2009"", ""Small crash for GOOG after...""),],) st.altair_chart(chart, use_container_width=True) PlostA deceptively simple plotting library for Streamlit. Created by @tvst.import plost plost.line_chart(my_dataframe, x='time', y='stock_value', color='stock_name',) HiPlotHigh dimensional Interactive Plotting. Created by @facebookresearch.data = [{'dropout':0.1, 'lr': 0.001, 'loss': 10.0, 'optimizer': 'SGD'}, {'dropout':0.15, 'lr': 0.01, 'loss': 3.5, 'optimizer': 'Adam'}, {'dropout':0.3, 'lr': 0.1, 'loss': 4.5, 'optimizer': 'Adam'}] hip.Experiment.from_iterable(data).display() EChartsHigh dimensional Interactive Plotting. Created by @andfanilo.from streamlit_echarts import st_echarts st_echarts(options=options) Streamlit FoliumStreamlit Component for rendering Folium maps. Created by @randyzwitch.m = folium.Map(location=[39.949610, -75.150282], zoom_start=16) st_data = st_folium(m, width=725) Spacy-StreamlitspaCy building blocks and visualizers for Streamlit apps. Created by @explosion.models = [""en_core_web_sm"", ""en_core_web_md""] spacy_streamlit.visualize(models, ""Sundar Pichai is the CEO of Google."") Streamlit AgraphA Streamlit Graph Vis, based on react-grah-vis. Created by @ChrisDelClea.from streamlit_agraph import agraph, Node, Edge, Config agraph(nodes=nodes, edges=edges, config=config) Streamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl(""https://assets5.lottiefiles.com/packages/lf20_V9t630.json"") st_lottie(lottie_hello, key=""hello"") Plotly EventsMake Plotly charts interactive!. Created by @null-jones.fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.chart += get_annotations_chart(annotations=[(""Mar 01, 2008"", ""Pretty good day for GOOG""), (""Dec 01, 2007"", ""Something's going wrong for GOOG & AAPL""), (""Nov 01, 2008"", ""Market starts again thanks to...""), (""Dec 01, 2009"", ""Small crash for GOOG after...""),],) st.altair_chart(chart, use_container_width=True) PlostA deceptively simple plotting library for Streamlit. Created by @tvst.import plost plost.line_chart(my_dataframe, x='time', y='stock_value', color='stock_name',) HiPlotHigh dimensional Interactive Plotting. Created by @facebookresearch.data = [{'dropout':0.1, 'lr': 0.001, 'loss': 10.0, 'optimizer': 'SGD'}, {'dropout':0.15, 'lr': 0.01, 'loss': 3.5, 'optimizer': 'Adam'}, {'dropout':0.3, 'lr': 0.1, 'loss': 4.5, 'optimizer': 'Adam'}] hip.Experiment.from_iterable(data).display() EChartsHigh dimensional Interactive Plotting. Created by @andfanilo.from streamlit_echarts import st_echarts st_echarts(options=options) Streamlit FoliumStreamlit Component for rendering Folium maps. Created by @randyzwitch.m = folium.Map(location=[39.949610, -75.150282], zoom_start=16) st_data = st_folium(m, width=725) Spacy-StreamlitspaCy building blocks and visualizers for Streamlit apps. Created by @explosion.models = [""en_core_web_sm"", ""en_core_web_md""] spacy_streamlit.visualize(models, ""Sundar Pichai is the CEO of Google."") Streamlit AgraphA Streamlit Graph Vis, based on react-grah-vis. Created by @ChrisDelClea.from streamlit_agraph import agraph, Node, Edge, Config agraph(nodes=nodes, edges=edges, config=config) Streamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl(""https://assets5.lottiefiles.com/packages/lf20_V9t630.json"") st_lottie(lottie_hello, key=""hello"") Plotly EventsMake Plotly charts interactive!. Created by @null-jones.fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.chart += get_annotations_chart(annotations=[(""Mar 01, 2008"", ""Pretty good day for GOOG""), (""Dec 01, 2007"", ""Something's going wrong for GOOG & AAPL""), (""Nov 01, 2008"", ""Market starts again thanks to...""), (""Dec 01, 2009"", ""Small crash for GOOG after...""),],) st.altair_chart(chart, use_container_width=True) Next Input widgets ButtonDisplay a button widget.clicked = st.button(""Click me"") Download buttonDisplay a download button widget.st.download_button(""Download file"", file) Form buttonDisplay a form submit button. For use with st.form.st.form_submit_button(""Sign up"") Link buttonDisplay a link button.st.link_button(""Go to gallery"", url) Page linkDisplay a link to another page in a multipage app.st.page_link(""app.py"", label=""Home"", icon=""🏠"") st.page_link(""pages/profile.py"", label=""My profile"") CheckboxDisplay a checkbox widget.selected = st.checkbox(""I agree"") Color pickerDisplay a color picker widget.color = st.color_picker(""Pick a color"") MultiselectDisplay a multiselect widget. The multiselect widget starts as empty.choices = st.multiselect(""Buy"", [""milk"", ""apples"", ""potatoes""]) RadioDisplay a radio button widget.choice = st.radio(""Pick one"", [""cats"", ""dogs""]) SelectboxDisplay a select widget.choice = st.selectbox(""Pick one"", [""cats"", ""dogs""]) Select-sliderDisplay a slider widget to select items from a list.size = st.select_slider(""Pick a size"", [""S"", ""M"", ""L""]) ToggleDisplay a toggle widget.activated = st.toggle(""Activate"") Number inputDisplay a numeric input widget.choice = st.number_input(""Pick a number"", 0, 10) SliderDisplay a slider widget.number = st.slider(""Pick a number"", 0, 100) Date inputDisplay a date input widget.date = st.date_input(""Your birthday"") Time inputDisplay a time input widget.time = st.time_input(""Meeting time"") Chat inputDisplay a chat input widget.prompt = st.chat_input(""Say something"") if prompt: st.write(f""The user has sent: {prompt}"") Text-areaDisplay a multi-line text input widget.text = st.text_area(""Text to translate"") Text inputDisplay a single-line text input widget.name = st.text_input(""First name"") Data editorDisplay a data editor widget.edited = st.experimental_data_editor(df, num_rows=""dynamic"") File UploaderDisplay a file uploader widget.data = st.file_uploader(""Upload a CSV"") Camera inputDisplay a widget that allows users to upload images directly from a camera.image = st.camera_input(""Take a picture"") Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration! PreviousStreamlit ChatStreamlit Component for a Chatbot UI. Created by @AI-Yash.from streamlit_chat import message message(""My message"") message(""Hello bot!"", is_user=True) # align's the message to the right Streamlit Option MenuSelect a single item from a list of options in a menu. Created by @victoryhb.from streamlit_option_menu import option_menu option_menu(""Main Menu"", [""Home"", 'Settings'], icons=['house', 'gear'], menu_icon=""cast"", default_index=1) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.stoggle import stoggle stoggle( ""Click me!"", """"""🥷 Surprise! Here's some additional content"""""",) Streamlit ElementsCreate a draggable and resizable dashboard in Streamlit. Created by @okls.from streamlit_elements import elements, mui, html with elements(""new_element""): mui.Typography(""Hello world"") TagsAdd tags to your Streamlit apps. Created by @gagan3012.from streamlit_tags import st_tags st_tags(label='# Enter Keywords:', text='Press enter to add more', value=['Zero', 'One', 'Two'], suggestions=['five', 'six', 'seven', 'eight', 'nine', 'three', 'eleven', 'ten', 'four'], maxtags = 4, key='1') StqdmThe simplest way to handle a progress bar in streamlit app. Created by @Wirg.from stqdm import stqdm for _ in stqdm(range(50)): sleep(0.5) TimelineDisplay a Timeline in Streamlit apps using TimelineJS. Created by @innerdoc.from streamlit_timeline import timeline with open('example.json', ""r"") as f: timeline(f.read(), height=800) Camera input liveAlternative for st.camera_input which returns the webcam images live. Created by @blackary.from camera_input_live import camera_input_live image = camera_input_live() st.image(value) Streamlit AceAce editor component for Streamlit. Created by @okld.from streamlit_ace import st_ace content = st_ace() content Streamlit ChatStreamlit Component for a Chatbot UI. Created by @AI-Yash.from streamlit_chat import message message(""My message"") message(""Hello bot!"", is_user=True) # align's the message to the right Streamlit Option MenuSelect a single item from a list of options in a menu. Created by @victoryhb.from streamlit_option_menu import option_menu option_menu(""Main Menu"", [""Home"", 'Settings'], icons=['house', 'gear'], menu_icon=""cast"", default_index=1) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.stoggle import stoggle stoggle( ""Click me!"", """"""🥷 Surprise! Here's some additional content"""""",) Streamlit ElementsCreate a draggable and resizable dashboard in Streamlit. Created by @okls.from streamlit_elements import elements, mui, html with elements(""new_element""): mui.Typography(""Hello world"") TagsAdd tags to your Streamlit apps. Created by @gagan3012.from streamlit_tags import st_tags st_tags(label='# Enter Keywords:', text='Press enter to add more', value=['Zero', 'One', 'Two'], suggestions=['five', 'six', 'seven', 'eight', 'nine', 'three', 'eleven', 'ten', 'four'], maxtags = 4, key='1') StqdmThe simplest way to handle a progress bar in streamlit app. Created by @Wirg.from stqdm import stqdm for _ in stqdm(range(50)): sleep(0.5) TimelineDisplay a Timeline in Streamlit apps using TimelineJS. Created by @innerdoc.from streamlit_timeline import timeline with open('example.json', ""r"") as f: timeline(f.read(), height=800) Camera input liveAlternative for st.camera_input which returns the webcam images live. Created by @blackary.from camera_input_live import camera_input_live image = camera_input_live() st.image(value) Streamlit AceAce editor component for Streamlit. Created by @okld.from streamlit_ace import st_ace content = st_ace() content Streamlit ChatStreamlit Component for a Chatbot UI. Created by @AI-Yash.from streamlit_chat import message message(""My message"") message(""Hello bot!"", is_user=True) # align's the message to the right Streamlit Option MenuSelect a single item from a list of options in a menu. Created by @victoryhb.from streamlit_option_menu import option_menu option_menu(""Main Menu"", [""Home"", 'Settings'], icons=['house', 'gear'], menu_icon=""cast"", default_index=1) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.stoggle import stoggle stoggle( ""Click me!"", """"""🥷 Surprise! Here's some additional content"""""",) Next Media elements ImageDisplay an image or list of images.st.image(numpy_array) st.image(image_bytes) st.image(file) st.image(""https://example.com/myimage.jpg"") AudioDisplay an audio player.st.audio(numpy_array) st.audio(audio_bytes) st.audio(file) st.audio(""https://example.com/myaudio.mp3"", format=""audio/mp3"") VideoDisplay a video player.st.video(numpy_array) st.video(video_bytes) st.video(file) st.video(""https://example.com/myvideo.mp4"", format=""video/mp4"") Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration! PreviousStreamlit CropperA simple image cropper for Streamlit. Created by @turner-anderson.from streamlit_cropper import st_cropper st_cropper(img, realtime_update=realtime_update, box_color=box_color, aspect_ratio=aspect_ratio) Image CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates streamlit_image_coordinates(""https://placekitten.com/200/300"") Streamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl(""https://assets5.lottiefiles.com/packages/lf20_V9t630.json"") st_lottie(lottie_hello, key=""hello"") Streamlit WebrtcHandling and transmitting real-time video/audio streams with Streamlit. Created by @whitphx.from streamlit_webrtc import webrtc_streamer webrtc_streamer(key=""sample"") Drawable CanvasProvides a sketching canvas using Fabric.js. Created by @andfanilo.from streamlit_drawable_canvas import st_canvas st_canvas(fill_color=""rgba(255, 165, 0, 0.3)"", stroke_width=stroke_width, stroke_color=stroke_color, background_color=bg_color, background_image=Image.open(bg_image) if bg_image else None, update_streamlit=realtime_update, height=150, drawing_mode=drawing_mode, point_display_radius=point_display_radius if drawing_mode == 'point' else 0, key=""canvas"",) Image ComparisonCompare images with a slider using JuxtaposeJS. Created by @fcakyon.from streamlit_image_comparison import image_comparison image_comparison(img1=""image1.jpg"", img2=""image2.jpg"",) Streamlit CropperA simple image cropper for Streamlit. Created by @turner-anderson.from streamlit_cropper import st_cropper st_cropper(img, realtime_update=realtime_update, box_color=box_color, aspect_ratio=aspect_ratio) Image CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates streamlit_image_coordinates(""https://placekitten.com/200/300"") Streamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl(""https://assets5.lottiefiles.com/packages/lf20_V9t630.json"") st_lottie(lottie_hello, key=""hello"") Streamlit WebrtcHandling and transmitting real-time video/audio streams with Streamlit. Created by @whitphx.from streamlit_webrtc import webrtc_streamer webrtc_streamer(key=""sample"") Drawable CanvasProvides a sketching canvas using Fabric.js. Created by @andfanilo.from streamlit_drawable_canvas import st_canvas st_canvas(fill_color=""rgba(255, 165, 0, 0.3)"", stroke_width=stroke_width, stroke_color=stroke_color, background_color=bg_color, background_image=Image.open(bg_image) if bg_image else None, update_streamlit=realtime_update, height=150, drawing_mode=drawing_mode, point_display_radius=point_display_radius if drawing_mode == 'point' else 0, key=""canvas"",) Image ComparisonCompare images with a slider using JuxtaposeJS. Created by @fcakyon.from streamlit_image_comparison import image_comparison image_comparison(img1=""image1.jpg"", img2=""image2.jpg"",) Streamlit CropperA simple image cropper for Streamlit. Created by @turner-anderson.from streamlit_cropper import st_cropper st_cropper(img, realtime_update=realtime_update, box_color=box_color, aspect_ratio=aspect_ratio) Image CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates streamlit_image_coordinates(""https://placekitten.com/200/300"") Streamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl(""https://assets5.lottiefiles.com/packages/lf20_V9t630.json"") st_lottie(lottie_hello, key=""hello"") Next Layouts and containers ColumnsInsert containers laid out as side-by-side columns.col1, col2 = st.columns(2) col1.write(""this is column 1"") col2.write(""this is column 2"") ContainerInsert a multi-element container.c = st.container() st.write(""This will show last"") c.write(""This will show first"") c.write(""This will show second"") Modal dialogsInsert a modal dialog that can rerun independently from the rest of the script.@st.experimental_dialog(""Sign up"") def email_form(): name = st.text_input(""Name"") email = st.text_input(""Email"") EmptyInsert a single-element container.c = st.empty() st.write(""This will show last"") c.write(""This will be replaced"") c.write(""This will show first"") ExpanderInsert a multi-element container that can be expanded/collapsed.with st.expander(""Open to see more""): st.write(""This is more content"") PopoverInsert a multi-element popover container that can be opened/closed.with st.popover(""Settings""): st.checkbox(""Show completed"") SidebarDisplay items in a sidebar.st.sidebar.write(""This lives in the sidebar"") st.sidebar.button(""Click me!"") TabsInsert containers separated into tabs.tab1, tab2 = st.tabs([""Tab 1"", ""Tab2""]) tab1.write(""this is tab 1"") tab2.write(""this is tab 2"") Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration!Streamlit ElementsCreate a draggable and resizable dashboard in Streamlit. Created by @okls.from streamlit_elements import elements, mui, html with elements(""new_element""): mui.Typography(""Hello world"") PydanticAuto-generate Streamlit UI from Pydantic Models and Dataclasses. Created by @lukasmasuch.import streamlit_pydantic as sp sp.pydantic_form(key=""my_form"", model=ExampleModel) Streamlit PagesAn experimental version of Streamlit Multi-Page Apps. Created by @blackary.from st_pages import Page, show_pages, add_page_title show_pages([ Page(""streamlit_app.py"", ""Home"", ""🏠""), Page(""other_pages/page2.py"", ""Page 2"", "":books:""), ]) Chat elements Streamlit provides a few commands to help you build conversational apps. These chat elements are designed to be used in conjunction with each other, but you can also use them separately. st.chat_message lets you insert a chat message container into the app so you can display messages from the user or the app. Chat containers can contain other Streamlit elements, including charts, tables, text, and more. st.chat_input lets you display a chat input widget so the user can type in a message. Chat inputDisplay a chat input widget.prompt = st.chat_input(""Say something"") if prompt: st.write(f""The user has sent: {prompt}"") Chat messageInsert a chat message container.import numpy as np with st.chat_message(""user""): st.write(""Hello 👋"") st.line_chart(np.random.randn(30, 3)) Status containerDisplay output of long-running tasks in a container.with st.status('Running'): do_something_slow() st.write_streamWrite generators or streams to the app with a typewriter effect.st.write_stream(my_generator) st.write_stream(my_llm_stream) Status elements Progress barDisplay a progress bar.for i in range(101): st.progress(i) do_something_slow() SpinnerTemporarily displays a message while executing a block of code.with st.spinner(""Please wait...""): do_something_slow() Status containerDisplay output of long-running tasks in a container.with st.status('Running'): do_something_slow() ToastBriefly displays a toast message in the bottom-right corner.st.toast('Butter!', icon='🧈') BalloonsDisplay celebratory balloons!do_something() # Celebrate when all done! st.balloons() SnowflakesDisplay celebratory snowflakes!do_something() # Celebrate when all done! st.snow() Success boxDisplay a success message.st.success(""Match found!"") Info boxDisplay an informational message.st.info(""Dataset is updated every day at midnight."") Warning boxDisplay warning message.st.warning(""Unable to fetch image. Skipping..."") Error boxDisplay error message.st.error(""We encountered an error"") Exception outputDisplay an exception.e = RuntimeError(""This is an exception of type RuntimeError"") st.exception(e) Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration!StqdmThe simplest way to handle a progress bar in streamlit app. Created by @Wirg.from stqdm import stqdm for _ in stqdm(range(50)): sleep(0.5) Custom notification boxA custom notification box with the ability to close it out. Created by @Socvest.from streamlit_custom_notification_box import custom_notification_box styles = {'material-icons':{'color': 'red'}, 'text-icon-link-close-container': {'box-shadow': '#3896de 0px 4px'}, 'notification-text': {'':''}, 'close-button':{'':''}, 'link':{'':''}} custom_notification_box(icon='info', textDisplay='We are almost done with your registration...', externalLink='more info', url='#', styles=styles, key=""foo"") Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.let_it_rain import rain rain(emoji=""🎈"", font_size=54, falling_speed=5, animation_length=""infinite"",) App logic and configuration Navigation and pages Switch pageProgrammatically navigates to a specified page.st.switch_page(""pages/my_page.py"") Page linkDisplay a link to another page in a multipage app.st.page_link(""app.py"", label=""Home"", icon=""🏠"") st.page_link(""pages/profile.py"", label=""My profile"") Execution flow Modal dialogsInsert a modal dialog that can rerun independently from the rest of the script.@st.experimental_dialog(""Sign up"") def email_form(): name = st.text_input(""Name"") email = st.text_input(""Email"") FormsCreate a form that batches elements together with a “Submit"" button.with st.form(key='my_form'): name = st.text_input(""Name"") email = st.text_input(""Email"") st.form_submit_button(""Sign up"") Partial rerunsDefine a fragment to rerun independently from the rest of the script.@st.experimental_fragment(run_every=""10s"") def fragment(): df = get_data() st.line_chart(df) Rerun scriptRerun the script immediately.st.rerun() Stop executionStops execution immediately.st.stop() Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration!AutorefreshForce a refresh without tying up a script. Created by @kmcgrady.from streamlit_autorefresh import st_autorefresh st_autorefresh(interval=2000, limit=100, key=""fizzbuzzcounter"") PydanticAuto-generate Streamlit UI from Pydantic Models and Dataclasses. Created by @lukasmasuch.import streamlit_pydantic as sp sp.pydantic_form(key=""my_form"", model=ExampleModel) Streamlit PagesAn experimental version of Streamlit Multi-Page Apps. Created by @blackary.from st_pages import Page, show_pages, add_page_title show_pages([ Page(""streamlit_app.py"", ""Home"", ""🏠""), Page(""other_pages/page2.py"", ""Page 2"", "":books:""), ]) Caching and state Cache dataFunction decorator to cache functions that return data (e.g. dataframe transforms, database queries, ML inference).@st.cache_data def long_function(param1, param2): # Perform expensive computation here or # fetch data from the web here return data Cache resourceFunction decorator to cache functions that return global resources (e.g. database connections, ML models).@st.cache_resource def init_model(): # Return a global resource here return pipeline( ""sentiment-analysis"", model=""distilbert-base-uncased-finetuned-sst-2-english"" ) Session stateSession state is a way to share variables between reruns, for each user session.st.session_state['key'] = value Query parametersGet, set, or clear the query parameters that are shown in the browser's URL bar.st.query_params[key] = value st.query_params.clear() Connections and databases Setup your connection Create a connectionConnect to a data source or APIconn = st.connection('pets_db', type='sql') pet_owners = conn.query('select * from pet_owners') st.dataframe(pet_owners) Built-in connections SnowflakeConnectionA connection to Snowflake.conn = st.connection('snowflake') SQLConnectionA connection to a SQL database using SQLAlchemy.conn = st.connection('sql') Build your own connections Connection base classBuild your own connection with BaseConnection.class MyConnection(BaseConnection[myconn.MyConnection]): def _connect(self, **kwargs) -> MyConnection: return myconn.connect(**self._secrets, **kwargs) def query(self, query): return self._instance.query(query) Secrets management Secrets singletonAccess secrets from a local TOML file.key = st.secrets[""OpenAI_key""] Secrets fileSave your secrets in a per-project or per-profile TOML file.OpenAI_key = """" Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration!AuthenticatorA secure authentication module to validate user credentials. Created by @mkhorasani.import streamlit_authenticator as stauth authenticator = stauth.Authenticate( config['credentials'], config['cookie']['name'], config['cookie']['key'], config['cookie']['expiry_days'], config['preauthorized']) WS localStorageA simple synchronous way of accessing localStorage from your app. Created by @gagangoku.from streamlit_ws_localstorage import injectWebsocketCode ret = conn.setLocalStorageVal(key='k1', val='v1') st.write('ret: ' + ret) Streamlit Auth0The fastest way to provide comprehensive login inside Streamlit. Created by @conradbez.from auth0_component import login_button user_info = login_button(clientId, domain = domain) st.write(user_info) Custom Components Declare a componentCreate and register a custom component.st.components.v1.declare_component( ""custom_slider"", ""/frontend"", ) HTMLDisplay an HTML string in an iframe.st.components.v1.html( ""

Foo bar.

"" ) iframeLoad a remote URL in an iframe.st.components.v1.iframe( ""docs.streamlit.io"" ) Utilities and user info User infost.experimental_user returns information about the logged-in user of private apps on Streamlit Community Cloud.if st.experimental_user.email == ""foo@corp.com"": st.write(""Welcome back, "", st.experimental_user.email) else: st.write(""You are not authorized to view this page."") Get helpDisplay object’s doc string, nicely formatted.st.help(st.write) st.help(pd.DataFrame) Render HTMLRenders HTML strings to your app.css = """""" """""" st.html(css) Configuration Configuration fileConfigures the default settings for your app.your-project/ ├── .streamlit/ │ └── config.toml └── your_app.py Set page title, favicon, and moreConfigures the default settings of the page.st.set_page_config( page_title=""My app"", page_icon="":shark:"", ) Developer tools App testing st.testing.v1.AppTestst.testing.v1.AppTest simulates a running Streamlit app for testing.from streamlit.testing.v1 import AppTest at = AppTest.from_file(""streamlit_app.py"") at.secrets[""WORD""] = ""Foobar"" at.run() assert not at.exception at.text_input(""word"").input(""Bazbat"").run() assert at.warning[0].value == ""Try again."" AppTest.from_filest.testing.v1.AppTest.from_file initializes a simulated app from a file.from streamlit.testing.v1 import AppTest at = AppTest.from_file(""streamlit_app.py"") at.run() AppTest.from_stringst.testing.v1.AppTest.from_string initializes a simulated app from a string.from streamlit.testing.v1 import AppTest at = AppTest.from_string(app_script_as_string) at.run() AppTest.from_functionst.testing.v1.AppTest.from_function initializes a simulated app from a function.from streamlit.testing.v1 import AppTest at = AppTest.from_function(app_script_as_callable) at.run() BlockA representation of container elements, including: st.chat_message st.columns st.sidebar st.tabs The main body of the app. # at.sidebar returns a Block at.sidebar.button[0].click().run() assert not at.exception ElementThe base class for representation of all elements, including: st.title st.header st.markdown st.dataframe # at.title returns a sequence of Title # Title inherits from Element assert at.title[0].value == ""My awesome app"" ButtonA representation of st.button and st.form_submit_button.at.button[0].click().run() ChatInputA representation of st.chat_input.at.chat_input[0].set_value(""What is Streamlit?"").run() CheckboxA representation of st.checkbox.at.checkbox[0].check().run() ColorPickerA representation of st.color_picker.at.color_picker[0].pick(""#FF4B4B"").run() DateInputA representation of st.date_input.release_date = datetime.date(2023, 10, 26) at.date_input[0].set_value(release_date).run() MultiselectA representation of st.multiselect.at.multiselect[0].select(""New York"").run() NumberInputA representation of st.number_input.at.number_input[0].increment().run() RadioA representation of st.radio.at.radio[0].set_value(""New York"").run() SelectSliderA representation of st.select_slider.at.select_slider[0].set_range(""A"",""C"").run() SelectboxA representation of st.selectbox.at.selectbox[0].select(""New York"").run() SliderA representation of st.slider.at.slider[0].set_range(2,5).run() TextAreaA representation of st.text_area.at.text_area[0].input(""Streamlit is awesome!"").run() TextInputA representation of st.text_input.at.text_input[0].input(""Streamlit"").run() TimeInputA representation of st.time_input.at.time_input[0].increment().run() ToggleA representation of st.toggle.at.toggle[0].set_value(""True"").run() Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration!Pandas ProfilingPandas profiling component for Streamlit. Created by @okld.df = pd.read_csv(""https://storage.googleapis.com/tf-datasets/titanic/train.csv"") pr = df.profile_report() st_profile_report(pr) Streamlit AceAce editor component for Streamlit. Created by @okld.from streamlit_ace import st_ace content = st_ace() content Streamlit AnalyticsTrack & visualize user interactions with your streamlit app. Created by @jrieke.import streamlit_analytics with streamlit_analytics.track(): st.text_input(""Write something"") Previous: ConceptsNext: Write and magicforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy" https://docs.streamlit.io/develop/api-reference/caching-and-state/st.query_params#stquery_paramsfrom_dict,"DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceremovePAGE ELEMENTSWrite and magicaddText elementsaddData elementsaddChart elementsaddInput widgetsaddMedia elementsaddLayouts and containersaddChat elementsaddStatus elementsaddThird-party componentsopen_in_newAPPLICATION LOGICNavigation and pagesaddExecution flowaddCaching and stateremovest.cache_datast.cache_resourcest.cachedeletest.session_statest.query_paramsst.experimental_get_query_paramsdeletest.experimental_set_query_paramsdeleteConnections and secretsaddCustom componentsaddUtilitiesaddConfigurationaddTOOLSApp testingaddCommand lineaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Develop/API reference/Caching and state/st.query_paramsst.query_params st.query_params provides a dictionary-like interface to access query parameters in your app's URL and is available as of Streamlit 1.30.0. It behaves similarly to st.session_state with the notable exception that keys may be repeated in an app's URL. Handling of repeated keys requires special consideration as explained below. st.query_params can be used with both key and attribute notation. For example, st.query_params.my_key and st.query_params[""my_key""]. All keys and values will be set and returned as strings. When you write to st.query_params, key-value pair prefixed with ? is added to the end of your app's URL. Each additional pair is prefixed with & instead of ?. Query parameters are cleared when navigating between pages in a multipage app. For example, consider the following URL: https://your_app.streamlit.app/?first_key=1&second_key=two&third_key=true The parameters in the URL above will be accessible in st.query_params as: { ""first_key"" : ""1"", ""second_key"" : ""two"", ""third_key"" : ""true"" } This means you can use those parameters in your app like this: # You can read query params using key notation if st.query_params[""first_key""] == ""1"": do_something() # ...or using attribute notation if st.query_params.second_key == ""two"": do_something_else() # And you can change a param by just writing to it st.query_params.first_key = 2 # This gets converted to str automatically Repeated keys When a key is repeated in your app's URL (?a=1&a=2&a=3), dict-like methods will return only the last value. In this example, st.query_params[""a""] returns ""3"". To get all keys as a list, use the .get_all() method shown below. To set the value of a repeated key, assign the values as a list. For example, st.query_params.a = [""1"", ""2"", ""3""] produces the repeated key given at the beginning of this paragraph. Limitation st.query_params can't get or set embedding settings as described in Embed your app. st.query_params.embed and st.query_params.embed_options will raise an AttributeError or StreamlitAPIException when trying to get or set their values, respectively. st.query_params.clearStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeClear all query parameters from the URL of the app. Function signature[source] st.query_params.clear() Returns(None) No description st.query_params.from_dictStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSet all of the query parameters from a dictionary or dictionary-like object. This method primarily exists for advanced users who want to control multiple query parameters in a single update. To set individual query parameters, use key or attribute notation instead. This method inherits limitations from st.query_params and can't be used to set embedding options as described in Embed your app. To handle repeated keys, the value in a key-value pair should be a list. Note .from_dict() is not a direct inverse of .to_dict() if you are working with repeated keys. A true inverse operation is {key: st.query_params.get_all(key) for key st.query_params}. Function signature[source] st.query_params.from_dict(params) Parameters params (dict) A dictionary used to replace the current query parameters. Example import streamlit as st st.query_params.from_dict({""foo"": ""bar"", ""baz"": [1, ""two""]}) st.query_params.get_allStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeGet a list of all query parameter values associated to a given key. When a key is repeated as a query parameter within the URL, this method allows all values to be obtained. In contrast, dict-like methods only retrieve the last value when a key is repeated in the URL. Function signature[source] st.query_params.get_all(key) Parameters key (str) The label of the query parameter in the URL. Returns(List[str]) A list of values associated to the given key. May return zero, one, or multiple values. st.query_params.to_dictStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeGet all query parameters as a dictionary. This method primarily exists for internal use and is not needed for most cases. st.query_params returns an object that inherits from dict by default. When a key is repeated as a query parameter within the URL, this method will return only the last value of each unique key. Function signature[source] st.query_params.to_dict() Returns(Dict[str,str]) A dictionary of the current query paramters in the app's URL. Previous: st.session_stateNext: st.experimental_get_query_paramsforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy" https://docs.streamlit.io/develop/concepts/custom-components/limitations#how-do-streamlit-components-differ-from-functionality-provided-in-the-base-streamlit-package,"DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsremoveCOREArchitecture & executionaddMultipage appsaddApp designaddADDITIONALConnections and secretsaddCustom componentsremoveIntro to custom componentsCreate a ComponentPublish a ComponentLimitationsComponent galleryopen_in_newConfiguration and themingaddApp testingaddAPI referenceaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Develop/Concepts/Custom components/LimitationsLimitations of custom components How do Streamlit Components differ from functionality provided in the base Streamlit package? Streamlit Components are wrapped up in an iframe, which gives you the ability to do whatever you want (within the iframe) using any web technology you like. What types of things aren't possible with Streamlit Components? Because each Streamlit Component gets mounted into its own sandboxed iframe, this implies a few limitations on what is possible with Components: Can't communicate with other Components: Components can’t contain (or otherwise communicate with) other components, so Components cannot be used to build something like a grid layout. Can't modify CSS: A Component can’t modify the CSS that the rest of the Streamlit app uses, so you can't create something to put the app in dark mode, for example. Can't add/remove elements: A Component can’t add or remove other elements of a Streamlit app, so you couldn't make something to remove the app menu, for example. My Component seems to be blinking/stuttering...how do I fix that? Currently, no automatic debouncing of Component updates is performed within Streamlit. The Component creator themselves can decide to rate-limit the updates they send back to Streamlit.Previous: Publish a ComponentNext: Component galleryforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy" https://docs.streamlit.io/deploy/streamlit-community-cloud/troubleshooting#billing-and-administration,"DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudremoveGet startedaddDeploy your appaddManage your appaddShare your appaddManage your accountaddTroubleshootingStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Deploy/Streamlit Community Cloud/TroubleshootingTroubleshooting Sorry to hear you're having issues! Please take a look at some frequently asked questions and issues below. If you cannot find an answer to your issue, please post on our Community forum so that our engineers or community members can help you. Table of contents General help Deploying apps Sharing and accessing apps Data and app security GitHub integration Limitations and known issues General help How can I get help with my app? If you have any questions, feedback, run into any issues, or need to reach us, you can ask on our Community forum. This is best suited for any questions related to the open source library and Community Cloud - debugging code, deployment, resource limits, etc. Deploying apps My repo isn't showing on the Deploy page It's possible it just isn't showing up even though it is already there. Try typing it in. If we don't recognize it, you'll see the message below with a link to click and give access. If for some reason that doesn't work, please try logging out and back in again to make sure the change took effect. And if that doesn't work - please let us know and we'll get you sorted! It won't let me deploy the app To deploy an app for the first time you must have admin-level access to the repo in GitHub. Please check with your administrator to make sure you have that access. If not, please ask them to deploy for the first time (we need this in order to establish webhooks for continuous integration) and from there you can then push updates to the app. I need to set a specific Python version for my app When deploying an app, under advanced settings, you can choose which version of Python you wish your app to use. How do I store files locally? If you want to store your data locally as opposed to in a database, you can store the file in your GitHub repository. Streamlit is just python, so you can read the file using: pandas.read_csv(""data.csv"") or open(""data.csv"") starTipIf you have really big or binary data that you change frequently, and git is feeling slow, you might want to check out Git Large File Store (LFS) as a better way to store large files in GitHub. You don't need to make any changes to your app to start using it. If your GitHub repo uses LFS, it will now just work with Streamlit. My app is running into issues while deploying Check your Cloud logs by clicking on the ""Manage app"" expander in the bottom right corner of your screen. Often the trouble is due to a dependency not being declared. See here for more information on dependency management. If that's not the issue, then please send the logs and warning you are seeing to our Community forum and we'll help get you sorted! My app is hitting resource limits / my app is running very slowly If your app is running slowly or you're hitting the 'Argh' page, we first highly recommend going through and implementing the suggestions in the following blog posts to prevent your app from hitting the resource limits and to detect if your Streamlit app leaks memory: Common app problems: Resource limits 3 steps to fix app memory leaks If you're still having issues, click here to learn more about resource limits. Can I get a custom URL for my app? Yes! You can find instructions for setting a custom subdomain here. Sharing and accessing apps Don't have SSO? No problem! You can sign in to Streamlit with your email address. Click here for step-by-step instructions on how to sign in with email. */} How do I add viewers to my Streamlit apps? Viewer auth allows you to restrict the viewers of your private app. To access your app, users have to authenticate using an email-based passwordless login or Google OAuth. To learn more about how to share your public and private apps with viewers, click here. Do viewers need access to the GitHub repo? Nope! You only need access to the GitHub repo if you want to push changes to the app. What will unauthorized/logged out viewers see when they view my app? A 404 error is displayed to unauthorized viewers to avoid providing any unnecessary information about your app to unintended viewers. Users who satisfy any of the following conditions will see a 404 error when attempting to view your app after you have configured viewer auth: User is not logged in with their primary identity. User is not included in the list of allowed viewers provided in the app settings. User lacks read access to your app's GitHub repo. User has read access to your app's GitHub repo but is not enrolled in Streamlit Community Cloud. I've added someone to the viewer list but they still see a 404 error when attempting to view the app If a user is still seeing a 404 error after their email address has been added to the viewer list, we recommend that you: Check that the user did not log into a different Google account via Single Sign-On (if you have added their work email address to the viewer list, ask the user to check that they are not logged into their personal Google account, and vice versa). Check that the user has navigated to the correct URL. Check that the user's email address has been entered correctly in the viewer list. Reach out on our Community forum and we will be happy to help. Data and app security How will Streamlit secure my data? Streamlit takes a number of industry best-practice measures to ensure your code, data, and apps are all secure. Read more in our Trust and Security memo. How do I set up SSO for my organization? Community Cloud uses Google OAuth, by default. If you use Google for authentication you're all set. Billing and administration The Community Cloud is a free service. You don't have to worry about setting up billing or being charged. GitHub integration Why does Streamlit require additional OAuth scope? In order to deploy your app, Streamlit requires access to your app's source code in GitHub and also the ability to manage the public keys associated with the repositories. The default GitHub OAuth scopes are sufficient to work with apps in public GitHub repositories. However, in order to work with apps in private GitHub repositories, Streamlit requires the additional repo OAuth scope from GitHub. We recognize that this scope provides Streamlit with extra permissions that we do not really need, and which, as people who prize security, we'd rather not even be granted. Alas, we need to work with the APIs we are provided by GitHub. After deploying my private-repo app, I received an email from GitHub saying a new public key was added to my repo. Is this expected? This is the expected behavior. When you try to deploy an app that lives in a private repo, Streamlit Community Cloud needs to get access to that repo somehow. For this, we create a read-only GitHub Deploy Key then access your repo using a public SSH key. When we set this up, GitHub notifies admins of the repo that the key was created as a security measure. What happens when a user's permissions change on GitHub? Once a user is added to a repository on GitHub, it will take at most 15 minutes before they can deploy the app on Cloud. If a user is removed from a repository on GitHub, it will take at most 15 minutes before their permissions to manage the app from that repository are revoked. Limitations and known issues Here are some limitations and known issues that we're actively working to resolve. When you print something to the Cloud logs, you may need to do a sys.stdout.flush() before it shows up. Matplotlib doesn't work well with threads. So if you're using Matplotlib you should wrap your code with locks as shown in the snippet below. This Matplotlib bug is more prominent when you share your app apps since you're more likely to get more concurrent users then. from matplotlib.backends.backend_agg import RendererAgg _lock = RendererAgg.lock with _lock: fig.title('This is a figure)') fig.plot([1,20,3,40]) st.pyplot(fig) All apps are hosted in the United States. This is currently not configurable. Previous: Manage your accountNext: Streamlit in SnowflakeforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy" https://docs.streamlit.io/deploy/concepts/dependencies,"DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceaddTutorialsaddQuick referenceaddweb_assetDeployConceptsremoveDependenciesSecretsStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Deploy/Concepts/DependenciesManaging dependencies when deploying your app Before you began developing your app, you set up and configured your development environment by installing Python and Streamlit. When you deploy your app, you need to set up and configure your deployment environment in the same way. When you deploy your app to a cloud service, your app's Python server will be running on a remote machine. This remote machine will not have access all the files and programs on your personal computer. All Streamlit apps have at least two dependencies: Python and Streamlit. Your app may have additional dependencies in the form of Python packages or software that must be installed to properly execute your script. If you are using a service like Streamlit Community Cloud which is designed for Streamlit apps, we'll take care of Python and Streamlit for you! Install Python and other software If you are using Streamlit Community Cloud, Python is already installed. You can just pick the version in the deployment dialog. If you need to install Python yourself or you have other non-Python software to install, follow your platform's instructions to install additional software. You will commonly use a package management tool to do this. For example, Streamlit Community Cloud uses Advanced Package Tool (apt) for Debian-based Linux systems. For more information about installing non-Python depencies on Streamlit Community Cloud, see apt-get dependencies. Install Python packages Once you have Python installed in your deployment environment, you'll need to install all the necessary Python packages, including Streamlit! With each import of an installed package, you add a Python dependency to your script. You need to install those dependencies in your deployment environment through a Python package manager. If you are using Streamlit Community Cloud, you'll have the latest version of Streamlit and all of its dependencies installed by default. So, if you're making a simple app and don't need additional dependencies, you won't have to do anything at all! pip and requirements.txt Since pip comes by default with Python, the most common way to configure your Python environment is with a requirements.txt file. Each line of a requirements.txt file is a package to pip install. You should not include built-in Python libraries like math or random in your requirements.txt file. These are a part of Python and aren't installed separately. If you have a script like the following, you would only need to install Streamlit. No extra dependencies would be needed since pandas and numpy are installed as direct dependencies of streamlit. Similarly, math and random are built into Python. import streamlit as st import pandas as pd import numpy as np import math import random st.write('Hi!') However, it's a best practice accurately record packages you use, so the recommended requirements.txt file would be: streamlit pandas numpy If you needed to specify certain versions, another valid example would be: streamlit==1.24.1 pandas>2.0 numpy<=1.25.1 A requirements.txt file is commonly saved in the root of your repository or file directory. If you are using Streamlit Community Cloud, see Add Python dependencies for more information. Otherwise, check your platform's documentation.Previous: ConceptsNext: SecretsforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy" https://docs.streamlit.io/develop/api-reference/charts/st.graphviz_chart#stgraphviz_chart,"DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceremovePAGE ELEMENTSWrite and magicaddText elementsaddData elementsaddChart elementsremoveSIMPLEst.area_chartst.bar_chartst.line_chartst.mapst.scatter_chartADVANCEDst.altair_chartst.bokeh_chartst.graphviz_chartst.plotly_chartst.pydeck_chartst.pyplotst.vega_lite_chartInput widgetsaddMedia elementsaddLayouts and containersaddChat elementsaddStatus elementsaddThird-party componentsopen_in_newAPPLICATION LOGICNavigation and pagesaddExecution flowaddCaching and stateaddConnections and secretsaddCustom componentsaddUtilitiesaddConfigurationaddTOOLSApp testingaddCommand lineaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Develop/API reference/Chart elements/st.graphviz_chartst.graphviz_chartStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeDisplay a graph using the dagre-d3 library. Function signature[source] st.graphviz_chart(figure_or_dot, use_container_width=False) Parameters figure_or_dot (graphviz.dot.Graph, graphviz.dot.Digraph, str) The Graphlib graph object or dot string to display use_container_width (bool) If True, set the chart width to the column width. This takes precedence over the figure's native width value. Example import streamlit as st import graphviz # Create a graphlib graph object graph = graphviz.Digraph() graph.edge('run', 'intr') graph.edge('intr', 'runbl') graph.edge('runbl', 'run') graph.edge('run', 'kernel') graph.edge('kernel', 'zombie') graph.edge('kernel', 'sleep') graph.edge('kernel', 'runmem') graph.edge('sleep', 'swap') graph.edge('swap', 'runswap') graph.edge('runswap', 'new') graph.edge('runswap', 'runmem') graph.edge('new', 'runmem') graph.edge('sleep', 'runmem') st.graphviz_chart(graph) Or you can render the chart from the graph using GraphViz's Dot language: st.graphviz_chart(''' digraph { run -> intr intr -> runbl runbl -> run run -> kernel kernel -> zombie kernel -> sleep kernel -> runmem sleep -> swap swap -> runswap runswap -> new runswap -> runmem new -> runmem sleep -> runmem } ''') Built with Streamlit 🎈Fullscreen open_in_new Previous: st.bokeh_chartNext: st.plotly_chartforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy" https://docs.streamlit.io/knowledge-base/deploy/deploy-streamlit-domain-port-80#how-do-i-deploy-streamlit-on-a-domain-so-it-appears-to-run-on-a-regular-port-ie-port-80,"DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Knowledge base/Deployment issues/How do I deploy Streamlit on a domain so it appears to run on a regular port (i.e. port 80)?How do I deploy Streamlit on a domain so it appears to run on a regular port (i.e. port 80)? Problem You want to deploy a Streamlit app on a domain so it appears to run on port 80. Solution You should use a reverse proxy to forward requests from a webserver like Apache or Nginx to the port where your Streamlit app is running. You can accomplish this in several different ways. The simplest way is to forward all requests sent to your domain so that your Streamlit app appears as the content of your website. Another approach is to configure your webserver to forward requests to designated subfolders (e.g. http://awesomestuff.net/streamlitapp) to different Streamlit apps on the same domain, as in this example config for Nginx submitted by a Streamlit community member. Related forum posts: https://discuss.streamlit.io/t/permission-denied-in-ec2-port-80/798/3 https://discuss.streamlit.io/t/how-to-use-streamlit-with-nginx/378/7 Previous: How can I deploy multiple Streamlit apps on different subdomains?Next: Does Streamlit support the WSGI Protocol? (aka Can I deploy Streamlit with gunicorn?)forumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy" https://docs.streamlit.io/knowledge-base/deploy/invoking-python-subprocess-deployed-streamlit-app#solution,"DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Knowledge base/Deployment issues/Invoking a Python subprocess in a deployed Streamlit appInvoking a Python subprocess in a deployed Streamlit app Problem Let's suppose you want to invoke a subprocess to run a Python script script.py in your deployed Streamlit app streamlit_app.py. For example, the machine learning library Ludwig is run using a command-line interface, or maybe you want to run a bash script or similar type of process from Python. You have tried the following, but run into dependency issues for script.py, even though you have specified your Python dependencies in a requirements file: # streamlit_app.py import streamlit as st import subprocess subprocess.run([""python"", ""script.py""]) Solution When you run the above code block, you will get the version of Python that is on the system path—not necessarily the Python executable installed in the virtual environment that the Streamlit code is running under. The solution is to detect the Python executable directly with sys.executable: # streamlit_app.py import streamlit as st import subprocess import sys subprocess.run([f""{sys.executable}"", ""script.py""]) This ensures that script.py is running under the same Python executable as your Streamlit code—where your Python dependencies are installed. Relevant links https://stackoverflow.com/questions/69947867/run-portion-of-python-code-in-parallel-from-a-streamlit-app/69948545#69948545 https://discuss.streamlit.io/t/modulenotfounderror-no-module-named-cv2-streamlit/18319/3?u=snehankekre https://docs.python.org/3/library/sys.html#sys.executable Previous: How do I increase the upload limit of st.file_uploader on Streamlit Community Cloud?Next: Organizing your apps with workspaces on Streamlit Community CloudforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy" https://docs.streamlit.io/knowledge-base/deploy/deploy-multiple-streamlit-apps-different-subdomains,"DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Knowledge base/Deployment issues/How can I deploy multiple Streamlit apps on different subdomains?How can I deploy multiple Streamlit apps on different subdomains? Problem You want to deploy multiple Streamlit apps on different subdomains. Solution Like running your Streamlit app on more common ports such as 80, subdomains are handled by a web server like Apache or Nginx: Set up a web server on a machine with a public IP address, then use a DNS server to point all desired subdomains to your webserver's IP address Configure your web server to route requests for each subdomain to the different ports that your Streamlit apps are running on For example, let’s say you had two Streamlit apps called Calvin and Hobbes. App Calvin is running on port 8501. You set up app Hobbes to run on port 8502. Your webserver would then be set up to ""listen"" for requests on subdomains calvin.somedomain.com and hobbes.subdomain.com, and route requests to port 8501 and 8502, respectively. Check out these two tutorials for Apache2 and Nginx that deal with setting up a webserver to redirect subdomains to different ports: Apache2 subdomains NGinx subdomains Previous: Authentication without SSONext: How do I deploy Streamlit on a domain so it appears to run on a regular port (i.e. port 80)?forumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy" https://docs.streamlit.io/deploy/streamlit-community-cloud/manage-your-app#manage-your-app-from-your-workspace,"DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudremoveGet startedaddDeploy your appaddManage your appremoveApp analyticsApp settingsDelete your appEdit your appFavorite your appReboot your appShare your appaddManage your accountaddTroubleshootingStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Deploy/Streamlit Community Cloud/Manage your appManage your app You can manage your deployed app from your workspace at share.streamlit.io or directly from .streamlit.app. You can view, deploy, delete, reboot, or favorite an app. Manage your app from your workspace Streamlit Community Cloud is organized into workspaces, which automatically group your apps according to the corresponding GitHub repository's owner. Your workspace is indicated in the upper-right corner. You will have one workspace that matches your GitHub username and additional workspaces for any GitHub organization or user who has granted you access. Additionally, if you have view-only access to an app, you will be able to see that app's workspace. When you do not have developer access to an app, your management options for that app will be restricted as shown in the following sections. To deploy or manage any app, always switch to the workspace matching the repository's owner first. At the top of your workspace, ""Analytics"" is a shortcut to App analytics and ""Settings"" links to your Workspace settings (not to be confused with App settings for each of your apps). App overflow menus Each app has a menu accessible from the overflow icon (more_vert) to the right. Copy URL — See Copy your app's URL Edit — See Edit your app with GitHub Codespaces Favorite — See Favorite your app Analytics — See App analytics Reboot — See Reboot your app Delete — See Delete your app Settings — See App settings If you have view-only access to an app, options will be restricted in that app's menu. Manage your app directly from your app You can manage your deployed app directly from the app itself! Just make sure you are signed in to Streamlit Community Cloud then visit your app. Streamlit Community Cloud logs From your app at .streamlit.app, click ""Manage app"" in the lower-right corner. Once you've clicked on ""Manage app"", you will be able to view your app's logs. This is your primary place to troubleshoot any issues with your app. You can access more developer options by clicking the overflow icon (more_vert) at the bottom of your Cloud logs. To conveniently download your logs, click ""Download log"". Other options accessible from Cloud logs are: Analytics — See App analytics. Reboot app — See Reboot your app. Delete app — See Delete your app. Settings — See App settings. Your apps — Takes you to your app workspace. Documentation — Takes you to our documentation. Support — Takes you to our forums! App menus From your app at .streamlit.app, you can always access your app's menu just like you can when developing locally. The option to deploy your app is removed, but you can still clear your cache from here. Manage your app in GitHub Update your app Your GitHub repository is the source for the app, so that means that any time you push an update to your repo you'll see it reflected in the app in almost real time. Try it out! Streamlit also smartly detects whether you touched your dependencies, in which case it will automatically do a full redeploy for you—which will take a little more time. But since most updates don't involve dependency changes, you should usually see your app update in real time. Add or remove dependencies You can add/remove dependencies at any point by updating requirements.txt (Python dependenciess) or packages.txt (Linux dependencies) and committing the changes to your repository on GitHub. This will cause Streamlit Community Cloud to detect there was a change in your dependencies and automatically trigger (re)installation. It is best practice to pin your Streamlit version in requirements.txt. Otherwise, the version may be auto-upgraded at any point without your knowledge, which could lead to undesired results (e.g. when we deprecate a feature in Streamlit). App resources and limits Resource limits All Streamlit Community Cloud users have access to the same resources and are subject to the same limits. These limits may change at any time without notice. If your app meets or exceeds its limits, it may slow down from throttling or become nonfunctional. The limits as of February 2024 are approximately as follows: CPU: 0.078 cores minimum, 2 cores maximum Memory: 690MB minimum, 2.7GBs maximum Storage: No minimum, 50GB maximum Symptoms that your app is running out of resources include the following: Your app is running slowly. Your app displays ""🤯 This app has gone over its resource limits."" Your app displays ""😦 Oh no."" Good for the world Streamlit offers increased resources for apps with good-for-the-world use cases. Generally, these apps are used by an educational institution or nonprofit organization, are part of an open-source project, or benefit the world in some way. If your app is not primarily used by a for-profit company you can apply for increased resources. If you are an educator or student looking to deploy additional private apps, please apply to our education program instead. Optimizing your app If your app is running slow or showing the error pages mentioned above, we first highly recommend going through and implementing the suggestions in the following blog posts to prevent your app from hitting the resource limits and to detect if your Streamlit app leaks memory: Common app problems: Resource limits 3 steps to fix app memory leaks If your app exceeds its resource limits, developers and viewers alike will see ""😦 Oh no."" If see ""😦 Oh no."" when viewing your app, first check your Cloud logs for any specific errors. If there are no errors in your Cloud logs you are likely dealing with a resource issue. Developer view If you are logged into a developer account for an app over its limits, you can access ""Manage app"" from the lower-right corner of the app to reboot it and clear its memory. ""Manage app"" will be red and have a warning icon (error). App hibernation All apps without traffic for 7 consecutive days will automatically go to sleep. This is done to alleviate resources and allow the best communal use of the platform! If you would like to keep your app awake, simply visit the app to create traffic or commit your app's repository, even if it's an empty commit! If left alone your app will go to sleep at the 7 day mark. When someone visits the app after this, they will see the sleeping page: To wake the app up, click ""Yes, get this app back up!"" This can be done by anyone who has access to view the app, not just the app developer! You can see which of your apps are asleep from your workspace. Sleeping apps have a moon icon (bedtime) to the right. Previous: Deploy your appNext: App analyticsforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy" https://docs.streamlit.io/develop/api-reference/connections/st.connections.snowparkconnection#snowparkconnectionsession,"DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceremovePAGE ELEMENTSWrite and magicaddText elementsaddData elementsaddChart elementsaddInput widgetsaddMedia elementsaddLayouts and containersaddChat elementsaddStatus elementsaddThird-party componentsopen_in_newAPPLICATION LOGICNavigation and pagesaddExecution flowaddCaching and stateaddConnections and secretsremoveSECRETSst.secretssecrets.tomlCONNECTIONSst.connectionSnowflakeConnectionSQLConnectionBaseConnectionSnowparkConnectiondeleteCustom componentsaddUtilitiesaddConfigurationaddTOOLSApp testingaddCommand lineaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Develop/API reference/Connections and secrets/SnowparkConnectionpriority_highImportantThis is an experimental feature. Experimental features and their APIs may change or be removed at any time. To learn more, click here. starTipThis page only contains the st.connections.SnowparkConnection class. For a deeper dive into creating and managing data connections within Streamlit apps, read Connecting to data. st.connections.SnowparkConnectionStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakedeleteDeprecation noticest.connections.SnowParkConnection was deprecated in version 1.28.0. Use st.connections.SnowflakeConnection instead.A connection to Snowpark using snowflake.snowpark.session.Session. Initialize using st.connection("""", type=""snowpark""). In addition to providing access to the Snowpark Session, SnowparkConnection supports direct SQL querying using query(""..."") and thread safe access using with conn.safe_session():. See methods below for more information. SnowparkConnections should always be created using st.connection(), not initialized directly. Note We don't expect this iteration of SnowparkConnection to be able to scale well in apps with many concurrent users due to the lock contention that will occur over the single underlying Session object under high load. Class description[source] st.connections.SnowparkConnection(connection_name, **kwargs) Methods query(sql, ttl=None) Run a read-only SQL query. reset() Reset this connection so that it gets reinitialized the next time it's used. safe_session() Grab the underlying Snowpark session in a thread-safe manner. Attributes session Access the underlying Snowpark session. SnowparkConnection.queryStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeRun a read-only SQL query. This method implements both query result caching (with caching behavior identical to that of using @st.cache_data) as well as simple error handling/retries. Note Queries that are run without a specified ttl are cached indefinitely. Function signature[source] SnowparkConnection.query(sql, ttl=None) Parameters sql (str) The read-only SQL query to execute. ttl (float, int, timedelta or None) The maximum number of seconds to keep results in the cache, or None if cached results should not expire. The default is None. Returns(pandas.DataFrame) The result of running the query, formatted as a pandas DataFrame. Example import streamlit as st conn = st.connection(""snowpark"") df = conn.query(""select * from pet_owners"") st.dataframe(df) SnowparkConnection.resetStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeReset this connection so that it gets reinitialized the next time it's used. This method can be useful when a connection has become stale, an auth token has expired, or in similar scenarios where a broken connection might be fixed by reinitializing it. Note that some connection methods may already use reset() in their error handling code. Function signature[source] SnowparkConnection.reset() Example import streamlit as st conn = st.connection(""my_conn"") # Reset the connection before using it if it isn't healthy # Note: is_healthy() isn't a real method and is just shown for example here. if not conn.is_healthy(): conn.reset() # Do stuff with conn... SnowparkConnection.safe_sessionStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeGrab the underlying Snowpark session in a thread-safe manner. As operations on a Snowpark session are not thread safe, we need to take care when using a session in the context of a Streamlit app where each script run occurs in its own thread. Using the contextmanager pattern to do this ensures that access on this connection's underlying Session is done in a thread-safe manner. Information on how to use Snowpark sessions can be found in the Snowpark documentation. Function signature[source] SnowparkConnection.safe_session() Example import streamlit as st conn = st.connection(""snowpark"") with conn.safe_session() as session: df = session.table(""mytable"").limit(10).to_pandas() st.dataframe(df) SnowparkConnection.sessionStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeAccess the underlying Snowpark session. Note Snowpark sessions are not thread safe. Users of this method are responsible for ensuring that access to the session returned by this method is done in a thread-safe manner. For most users, we recommend using the thread-safe safe_session() method and a with block. Information on how to use Snowpark sessions can be found in the Snowpark documentation. Function signature[source] SnowparkConnection.session Example import streamlit as st session = st.connection(""snowpark"").session df = session.table(""mytable"").limit(10).to_pandas() st.dataframe(df) Previous: st.experimental_connectionNext: ExperimentalBaseConnectionforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy" https://docs.streamlit.io/develop/concepts/architecture/widget-behavior#save-widget-values-in-session-state-to-preserve-them-between-pages,"DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsremoveCOREArchitecture & executionremoveRunning your appStreamlit's architectureThe app chromeCachingSession StateFormsFragmentsWidget behaviorMultipage appsaddApp designaddADDITIONALConnections and secretsaddCustom componentsaddConfiguration and themingaddApp testingaddAPI referenceaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Develop/Concepts/Architecture & execution/Widget behaviorUnderstanding widget behavior Widgets (like st.button, st.selectbox, and st.text_input) are at the heart of Streamlit apps. They are the interactive elements of Streamlit that pass information from your users into your Python code. Widgets are magical and often work how you want, but they can have surprising behavior in some situations. Understanding the different parts of a widget and the precise order in which events occur helps you achieve your desired results. This guide covers advanced concepts about widgets. Generally, it begins with simpler concepts and increases in complexity. For most beginning users, these details won't be important to know right away. When you want to dynamically change widgets or preserve widget information between pages, these concepts will be important to understand. We recommend having a basic understanding of Session State before reading this guide. 🎈 TL;DRexpand_more The actions of one user do not affect the widgets of any other user. A widget function call returns the widget's current value, which is a simple Python type. (e.g. st.button returns a boolean value.) Widgets return their default values on their first call before a user interacts with them. A widget's identity depends on the arguments passed to the widget function. Changing a widget's label, min or max value, default value, placeholder text, help text, or key will cause it to reset. If you don't call a widget function in a script run, Streamlit will delete the widget's information—including its key-value pair in Session State. If you call the same widget function later, Streamlit treats it as a new widget. The last two points (widget identity and widget deletion) are the most relevant when dynamically changing widgets or working with multi-page applications. This is covered in detail later in this guide: Statefulness of widgets and Widget life cycle. Anatomy of a widget There are four parts to keep in mind when using widgets: The frontend component as seen by the user. The backend value or value as seen through st.session_state. The key of the widget used to access its value via st.session_state. The return value given by the widget's function. Widgets are session dependent Widget states are dependent on a particular session (browser connection). The actions of one user do not affect the widgets of any other user. Furthermore, if a user opens up multiple tabs to access an app, each tab will be a unique session. Changing a widget in one tab will not affect the same widget in another tab. Widgets return simple Python data types The value of a widget as seen through st.session_state and returned by the widget function are of simple Python types. For example, st.button returns a boolean value and will have the same boolean value saved in st.session_state if using a key. The first time a widget function is called (before a user interacts with it), it will return its default value. (e.g. st.selectbox returns the first option by default.) Default values are configurable for all widgets with a few special exceptions like st.button and st.file_uploader. Keys help distinguish widgets and access their values Widget keys serve two purposes: Distinguishing two otherwise identical widgets. Creating a means to access and manipulate the widget's value through st.session_state. Whenever possible, Streamlit updates widgets incrementally on the frontend instead of rebuilding them with each rerun. This means Streamlit assigns an ID to each widget from the arguments passed to the widget function. A widget's ID is based on parameters such as label, min or max value, default value, placeholder text, help text, and key. The page where the widget appears also factors into a widget's ID. If you have two widgets of the same type with the same arguments on the same page, you will get a DuplicateWidgetID error. In this case, assign unique keys to the two widgets. Streamlit can't understand two identical widgets on the same page # This will cause a DuplicateWidgetID error. st.button(""OK"") st.button(""OK"") Use keys to distinguish otherwise identical widgets st.button(""OK"", key=""privacy"") st.button(""OK"", key=""terms"") Order of operations When a user interacts with a widget, the order of logic is: Its value in st.session_state is updated. The callback function (if any) is executed. The page reruns with the widget function returning its new value. If the callback function writes anything to the screen, that content will appear above the rest of the page. A callback function runs as a prefix to the script rerunning. Consequently, that means anything written via a callback function will disappear as soon as the user performs their next action. Other widgets should generally not be created within a callback function. push_pinNoteIf a callback function is passed any args or kwargs, those arguments will be established when the widget is rendered. In particular, if you want to use a widget's new value in its own callback function, you cannot pass that value to the callback function via the args parameter; you will have to assign a key to the widget and look up its new value using a call to st.session_state within the callback function. Using callback functions with forms Using a callback function with a form requires consideration of this order of operations. import streamlit as st if ""attendance"" not in st.session_state: st.session_state.attendance = set() def take_attendance(): if st.session_state.name in st.session_state.attendance: st.info(f""{st.session_state.name} has already been counted."") else: st.session_state.attendance.add(st.session_state.name) with st.form(key=""my_form""): st.text_input(""Name"", key=""name"") st.form_submit_button(""I'm here!"", on_click=take_attendance) Built with Streamlit 🎈Fullscreen open_in_new Statefulness of widgets As long as the defining parameters of a widget remain the same and that widget is continuously rendered on the frontend, then it will be stateful and remember user input. Changing parameters of a widget will reset it If any of the defining parameters of a widget change, Streamlit will see it as a new widget and it will reset. The use of manually assigned keys and default values is particularly important in this case. Note that callback functions, callback args and kwargs, label visibility, and disabling a widget do not affect a widget's identity. In this example, we have a slider whose min and max values are changed. Try interacting with each slider to change its value then change the min or max setting to see what happens. import streamlit as st cols = st.columns([2, 1, 2]) minimum = cols[0].number_input(""Minimum"", 1, 5) maximum = cols[2].number_input(""Maximum"", 6, 10, 10) st.slider(""No default, no key"", minimum, maximum) st.slider(""No default, with key"", minimum, maximum, key=""a"") st.slider(""With default, no key"", minimum, maximum, value=5) st.slider(""With default, with key"", minimum, maximum, value=5, key=""b"") Built with Streamlit 🎈Fullscreen open_in_new Updating a slider with no default value For the first two sliders above, as soon as the min or max value is changed, the sliders reset to the min value. The changing of the min or max value makes them ""new"" widgets from Streamlit's perspective and so they are recreated from scratch when the app reruns with the changed parameters. Since no default value is defined, each widget will reset to its min value. This is the same with or without a key since it's seen as a new widget either way. There is a subtle point to understand about pre-existing keys connecting to widgets. This will be explained further down in Widget life cycle. Updating a slider with a default value For the last two sliders above, a change to the min or max value will result in the widgets being seen as ""new"" and thus recreated like before. Since a default value of 5 is defined, each widget will reset to 5 whenever the min or max is changed. This is again the same (with or without a key). A solution to Retain statefulness when changing a widget's parameters is provided further on. Widgets do not persist when not continually rendered If a widget's function is not called during a script run, then none of its parts will be retained, including its value in st.session_state. If a widget has a key and you navigate away from that widget, its key and associated value in st.session_state will be deleted. Even temporarily hiding a widget will cause it to reset when it reappears; Streamlit will treat it like a new widget. You can either interrupt the Widget clean-up process (described at the end of this page) or save the value to another key. Save widget values in Session State to preserve them between pages If you want to navigate away from a widget and return to it while keeping its value, use a separate key in st.session_state to save the information independently from the widget. In this example, a temporary key is used with a widget. The temporary key uses an underscore prefix. Hence, ""_my_key"" is used as the widget key, but the data is copied to ""my_key"" to preserve it between pages. import streamlit as st def store_value(): # Copy the value to the permanent key st.session_state[""my_key""] = st.session_state[""_my_key""] # Copy the saved value to the temporary key st.session_state[""_my_key""] = st.session_state[""my_key""] st.number_input(""Number of filters"", key=""_my_key"", on_change=store_value) If this is functionalized to work with multiple widgets, it could look something like this: import streamlit as st def store_value(key): st.session_state[key] = st.session_state[""_""+key] def load_value(key): st.session_state[""_""+key] = st.session_state[key] load_value(""my_key"") st.number_input(""Number of filters"", key=""_my_key"", on_change=store_value, args=[""my_key""]) Widget life cycle When a widget function is called, Streamlit will check if it already has a widget with the same parameters. Streamlit will reconnect if it thinks the widget already exists. Otherwise, it will make a new one. As mentioned earlier, Streamlit determines a widget's ID based on parameters such as label, min or max value, default value, placeholder text, help text, and key. The page name also factors into a widget's ID. On the other hand, callback functions, callback args and kwargs, label visibility, and disabling a widget do not affect a widget's identity. Calling a widget function when the widget doesn't already exist If your script rerun calls a widget function with changed parameters or calls a widget function that wasn't used on the last script run: Streamlit will build the frontend and backend parts of the widget. If the widget has been assigned a key, Streamlit will check if that key already exists in Session State. a. If it exists and is not currently associated with another widget, Streamlit will attach to that key and take on its value for the widget. b. Otherwise, it will assign the default value to the key in st.session_state (creating a new key-value pair or overwriting an existing one). If there are args or kwargs for a callback function, they are computed and saved at this point in time. The default value is then returned by the function. Step 2 can be tricky. If you have a widget: st.number_input(""Alpha"",key=""A"") and you change it on a page rerun to: st.number_input(""Beta"",key=""A"") Streamlit will see that as a new widget because of the label change. The key ""A"" will be considered part of the widget labeled ""Alpha"" and will not be attached as-is to the new widget labeled ""Beta"". Streamlit will destroy st.session_state.A and recreate it with the default value. If a widget attaches to a pre-existing key when created and is also manually assigned a default value, you will get a warning if there is a disparity. If you want to control a widget's value through st.session_state, initialize the widget's value through st.session_state and avoid the default value argument to prevent conflict. Calling a widget function when the widget already exists When rerunning a script without changing a widget's parameters: Streamlit will connect to the existing frontend and backend parts. If the widget has a key that was deleted from st.session_state, then Streamlit will recreate the key using the current frontend value. (e.g Deleting a key will not revert the widget to a default value.) It will return the current value of the widget. Widget clean-up process When Streamlit gets to the end of a script run, it will delete the data for any widgets it has in memory that were not rendered on the screen. Most importantly, that means Streamlit will delete all key-value pairs in st.session_state associated with a widget not currently on screen. Additional examples As promised, let's address how to retain the statefulness of widgets when changing pages or modifying their parameters. There are two ways to do this. Use dummy keys to duplicate widget values in st.session_state and protect the data from being deleted along with the widget. Interrupt the widget clean-up process. The first method was shown above in Save widget values in Session State to preserve them between pages Interrupting the widget clean-up process To retain information for a widget with key=""my_key"", just add this to the top of every page: st.session_state.my_key = st.session_state.my_key When you manually save data to a key in st.session_state, it will become detached from any widget as far as the clean-up process is concerned. If you navigate away from a widget with some key ""my_key"" and save data to st.session_state.my_key on the new page, you will interrupt the widget clean-up process and prevent the key-value pair from being deleted or overwritten if another widget with the same key exists. Retain statefulness when changing a widget's parameters Here is a solution to our earlier example of changing a slider's min and max values. This solution interrupts the clean-up process as described above. import streamlit as st # Set default value if ""a"" not in st.session_state: st.session_state.a = 5 cols = st.columns(2) minimum = cols[0].number_input(""Min"", 1, 5, key=""min"") maximum = cols[1].number_input(""Max"", 6, 10, 10, key=""max"") def update_value(): # Helper function to ensure consistency between widget parameters and value st.session_state.a = min(st.session_state.a, maximum) st.session_state.a = max(st.session_state.a, minimum) # Validate the slider value before rendering update_value() st.slider(""A"", minimum, maximum, key=""a"") Built with Streamlit 🎈Fullscreen open_in_new The update_value() helper function is actually doing two things. On the surface, it's making sure there are no inconsistent changes to the parameters values as described. Importantly, it's also interrupting the widget clean-up process. When the min or max value of the widget changes, Streamlit sees it as a new widget on rerun. Without saving a value to st.session_state.a, the value would be thrown out and replaced by the ""new"" widget's default value.Previous: FragmentsNext: Multipage appsforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy" https://docs.streamlit.io/develop/tutorials/databases/private-gsheet#connecting-to-a-google-sheet-from-community-cloud,"DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceaddTutorialsremoveExecution flowaddConnect to data sourcesremoveAWS S3BigQueryDeta BaseFirestoreopen_in_newGoogle Cloud StorageMicrosoft SQL ServerMongoDBMySQLNeonPostgreSQLPrivate Google SheetPublic Google SheetSnowflakeSupabaseTableauTiDBTigerGraphMultipage appsaddWork with LLMsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Develop/Tutorials/Connect to data sources/Private Google SheetConnect Streamlit to a private Google Sheet Introduction This guide explains how to securely access a private Google Sheet from Streamlit Community Cloud. It uses st.connection, Streamlit GSheetsConnection, and Streamlit's Secrets management. If you are fine with enabling link sharing for your Google Sheet (i.e. everyone with the link can view it), the guide Connect Streamlit to a public Google Sheet shows a simpler method of doing this. If your Sheet contains sensitive information and you cannot enable link sharing, keep on reading. Prerequisites This tutorial requires streamlit>=1.28 and st-gsheets-connection in your Python environment. Create a Google Sheet If you already have a Sheet that you want to use, feel free to skip to the next step. Create a spreadsheet with this example data. namepetMarydogJohncatRobertbird Enable the Sheets API Programmatic access to Google Sheets is controlled through Google Cloud Platform. Create an account or sign in and head over to the APIs & Services dashboard (select or create a project if asked). As shown below, search for the Sheets API and enable it: Create a service account & key file To use the Sheets API from Streamlit Community Cloud, you need a Google Cloud Platform service account (a special account type for programmatic data access). Go to the Service Accounts page and create an account with the Viewer permission (this will let the account access data but not change it): push_pinNoteThe button ""CREATE SERVICE ACCOUNT"" is gray, you don't have the correct permissions. Ask the admin of your Google Cloud project for help. After clicking ""DONE"", you should be back on the service accounts overview. First, note down the email address of the account you just created (important for next step!). Then, create a JSON key file for the new account and download it: Share the Google Sheet with the service account By default, the service account you just created cannot access your Google Sheet. To give it access, click on the ""Share"" button in the Google Sheet, add the email of the service account (noted down in step 2), and choose the correct permission (if you just want to read the data, ""Viewer"" is enough): Add the key file to your local app secrets Your local Streamlit app will read secrets from a file .streamlit/secrets.toml in your app's root directory. Create this file if it doesn't exist yet and add the URL of your Google Sheet plus the content of the key file you downloaded to it as shown below: # .streamlit/secrets.toml [connections.gsheets] spreadsheet = ""https://docs.google.com/spreadsheets/d/xxxxxxx/edit#gid=0"" # From your JSON key file type = ""service_account"" project_id = ""xxx"" private_key_id = ""xxx"" private_key = ""xxx"" client_email = ""xxx"" client_id = ""xxx"" auth_uri = ""https://accounts.google.com/o/oauth2/auth"" token_uri = ""https://oauth2.googleapis.com/token"" auth_provider_x509_cert_url = ""https://www.googleapis.com/oauth2/v1/certs"" client_x509_cert_url = ""xxx"" priority_highImportantAdd this file to .gitignore and don't commit it to your GitHub repo! Write your Streamlit app Copy the code below to your Streamlit app and run it. # streamlit_app.py import streamlit as st from streamlit_gsheets import GSheetsConnection # Create a connection object. conn = st.connection(""gsheets"", type=GSheetsConnection) df = conn.read() # Print results. for row in df.itertuples(): st.write(f""{row.name} has a :{row.pet}:"") See st.connection above? This handles secrets retrieval, setup, query caching and retries. By default, .read() results are cached without expiring. You can pass optional parameters to .read() to customize your connection. For example, you can specify the name of a worksheet, cache expiration time, or pass-through parameters for pandas.read_csv like this: df = conn.read( worksheet=""Sheet1"", ttl=""10m"", usecols=[0, 1], nrows=3, ) In this case, we set ttl=""10m"" to ensure the query result is cached for no longer than 10 minutes. You can also set ttl=0 to disable caching. Learn more in Caching. We've declared optional parameters usecols=[0,1] and nrows=3 for pandas to use under the hood. If everything worked out (and you used the example table we created above), your app should look like this: Connecting to a Google Sheet from Community Cloud This tutorial assumes a local Streamlit app, however you can also connect to Google Sheets from apps hosted in Community Cloud. The main additional steps are: Include information about dependencies using a requirements.txt file with st-gsheets-connection and any other dependencies. Add your secrets to your Community Cloud app. Previous: PostgreSQLNext: Public Google SheetforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy" https://docs.streamlit.io/develop/concepts/app-testing/cheat-sheet#data-elements,"DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsremoveCOREArchitecture & executionaddMultipage appsaddApp designaddADDITIONALConnections and secretsaddCustom componentsaddConfiguration and themingaddApp testingremoveGet startedBeyond the basicsAutomate your testsExampleCheat sheetAPI referenceaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Develop/Concepts/App testing/Cheat sheetApp testing cheat sheet Text elements from streamlit.testing.v1 import AppTest at = AppTest.from_file(""cheatsheet_app.py"") # Headers assert ""My app"" in at.title[0].value assert ""New topic"" in at.header[0].value assert ""Interesting sub-topic"" in at.subheader[0].value assert len(at.divider) == 2 # Body / code assert ""Hello, world!"" in at.markdown[0].value assert ""import streamlit as st"" in at.code[0].value assert ""A cool diagram"" in at.caption[0].value assert ""Hello again, world!"" in at.text[0].value assert ""\int a x^2 \,dx"" in at.latex[0].value Input widgets from streamlit.testing.v1 import AppTest at = AppTest.from_file(""cheatsheet_app.py"") # button assert at.button[0].value == False at.button[0].click().run() assert at.button[0].value == True # checkbox assert at.checkbox[0].value == False at.checkbox[0].check().run() # uncheck() is also supported assert at.checkbox[0].value == True # color_picker assert at.color_picker[0].value == ""#FFFFFF"" at.color_picker[0].pick(""#000000"").run() # date_input assert at.date_input[0].value == datetime.date(2019, 7, 6) at.date_input[0].set_value(datetime.date(2022, 12, 21)).run() # form_submit_button - shows up just like a button assert at.button[0].value == False at.button[0].click().run() assert at.button[0].value == True # multiselect assert at.multiselect[0].value == [""foo"", ""bar""] at.multiselect[0].select(""baz"").unselect(""foo"").run() # number_input assert at.number_input[0].value == 5 at.number_input[0].increment().run() # radio assert at.radio[0].value == ""Bar"" assert at.radio[0].index == 3 at.radio[0].set_value(""Foo"").run() # selectbox assert at.selectbox[0].value == ""Bar"" assert at.selectbox[0].index == 3 at.selectbox[0].set_value(""Foo"").run() # select_slider assert at.select_slider[0].value == ""Feb"" at.select_slider[0].set_value(""Mar"").run() at.select_slider[0].set_range(""Apr"", ""Jun"").run() # slider assert at.slider[0].value == 2 at.slider[0].set_value(3).run() at.slider[0].set_range(4, 6).run() # text_area assert at.text_area[0].value == ""Hello, world!"" at.text_area[0].set_value(""Hello, yourself!"").run() # text_input assert at.text_input[0].value == ""Hello, world!"") at.text_input[0].set_value(""Hello, yourself!"").run() # time_input assert at.time_input[0].value == datetime.time(8, 45) at.time_input[0].set_value(datetime.time(12, 30)) # toggle assert at.toggle[0].value == False assert at.toggle[0].label == ""Debug mode"" at.toggle[0].set_value(True).run() assert at.toggle[0].value == True Data elements from streamlit.testing.v1 import AppTest at = AppTest.from_file(""cheatsheet_app.py"") # dataframe expected_df = pd.DataFrame([1, 2, 3]) assert at.dataframe[0].value.equals(expected_df) # metric assert at.metric[0].value == ""9500"" assert at.metric[0].delta == ""1000"" # json assert at.json[0].value == '[""hi"", {""foo"": ""bar""}]' # table table_df = pd.DataFrame([1, 2, 3]) assert at.table[0].value.equals(table_df) Layouts and containers from streamlit.testing.v1 import AppTest at = AppTest.from_file(""cheatsheet_app.py"") # sidebar at.sidebar.text_input[0].set_value(""Jane Doe"") # columns at.columns[1].markdown[0].value == ""Hello, world!"" # tabs at.tabs[2].markdown[0].value == ""Hello, yourself!"" Chat elements from streamlit.testing.v1 import AppTest at = AppTest.from_file(""cheatsheet_app.py"") # chat_input at.chat_input[0].set_value(""Do you know any jokes?"").run() # Note: chat_input value clears after every re-run (like in a real app) # chat_message assert at.chat_message[0].markdown[0].value == ""Do you know any jokes?"" assert at.chat_message[0].avatar == ""user"" Status elements from streamlit.testing.v1 import AppTest at = AppTest.from_file(""cheatsheet_app.py"") # exception assert len(at.exception) == 1 assert ""TypeError"" in at.exception[0].value # Other in-line alerts: success, info, warning, error assert at.success[0].value == ""Great job!"" assert at.info[0].value == ""Please enter an API key to continue"" assert at.warning[0].value == ""Sorry, the passwords didn't match"" assert at.error[0].value == ""Something went wrong :("" # toast assert at.toast[0].value == ""That was lit!"" and at.toast[0].icon == ""🔥"" Limitations As of Streamlit 1.28, the following Streamlit features are not natively supported by AppTest. However, workarounds are possible for many of them by inspecting the underlying proto directly using AppTest.get(). We plan to regularly add support for missing elements until all features are supported. Chart elements (st.bar_chart, st.line_chart, etc) Media elements (st.image, st.video, st.audio) st.file_uploader st.data_editor st.expander st.status st.camera_input st.download_button st.link_button Previous: ExampleNext: API referenceforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy" https://docs.streamlit.io/develop/api-reference/caching-and-state/st.experimental_memo#stexperimental_memo,"DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceremovePAGE ELEMENTSWrite and magicaddText elementsaddData elementsaddChart elementsaddInput widgetsaddMedia elementsaddLayouts and containersaddChat elementsaddStatus elementsaddThird-party componentsopen_in_newAPPLICATION LOGICNavigation and pagesaddExecution flowaddCaching and stateremovest.cache_datast.cache_resourcest.cachedeletest.session_statest.query_paramsst.experimental_get_query_paramsdeletest.experimental_set_query_paramsdeleteConnections and secretsaddCustom componentsaddUtilitiesaddConfigurationaddTOOLSApp testingaddCommand lineaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Develop/API reference/Caching and state/st.experimental_memopriority_highImportantThis is an experimental feature. Experimental features and their APIs may change or be removed at any time. To learn more, click here. st.experimental_memoStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakedeleteDeprecation noticest.experimental_memo was deprecated in version 1.18.0. Use st.cache_data instead. Learn more in Caching.Decorator to cache functions that return data (e.g. dataframe transforms, database queries, ML inference). Cached objects are stored in ""pickled"" form, which means that the return value of a cached function must be pickleable. Each caller of the cached function gets its own copy of the cached data. You can clear a function's cache with func.clear() or clear the entire cache with st.cache_data.clear(). To cache global resources, use st.cache_resource instead. Learn more about caching at https://docs.streamlit.io/library/advanced-features/caching. Function signature[source] st.experimental_memo(func=None, *, ttl, max_entries, show_spinner, persist, experimental_allow_widgets, hash_funcs=None) Parameters func (callable) The function to cache. Streamlit hashes the function's source code. ttl (float, timedelta, str, or None) The maximum time to keep an entry in the cache. Can be one of: None if cache entries should never expire (default). A number specifying the time in seconds. A string specifying the time in a format supported by Pandas's Timedelta constructor, e.g. ""1d"", ""1.5 days"", or ""1h23s"". A timedelta object from Python's built-in datetime library, e.g. timedelta(days=1). Note that ttl will be ignored if persist=""disk"" or persist=True. max_entries (int or None) The maximum number of entries to keep in the cache, or None for an unbounded cache. When a new entry is added to a full cache, the oldest cached entry will be removed. Defaults to None. show_spinner (bool or str) Enable the spinner. Default is True to show a spinner when there is a ""cache miss"" and the cached data is being created. If string, value of show_spinner param will be used for spinner text. persist (""disk"", bool, or None) Optional location to persist cached data to. Passing ""disk"" (or True) will persist the cached data to the local disk. None (or False) will disable persistence. The default is None. experimental_allow_widgets (bool) Allow widgets to be used in the cached function. Defaults to False. Support for widgets in cached functions is currently experimental. Setting this parameter to True may lead to excessive memory use since the widget value is treated as an additional input parameter to the cache. We may remove support for this option at any time without notice. hash_funcs (dict or None) Mapping of types or fully qualified names to hash functions. This is used to override the behavior of the hasher inside Streamlit's caching mechanism: when the hasher encounters an object, it will first check to see if its type matches a key in this dict and, if so, will use the provided function to generate a hash for it. See below for an example of how this can be used. Example import streamlit as st @st.cache_data def fetch_and_clean_data(url): # Fetch data from URL here, and then clean it up. return data d1 = fetch_and_clean_data(DATA_URL_1) # Actually executes the function, since this is the first time it was # encountered. d2 = fetch_and_clean_data(DATA_URL_1) # Does not execute the function. Instead, returns its previously computed # value. This means that now the data in d1 is the same as in d2. d3 = fetch_and_clean_data(DATA_URL_2) # This is a different URL, so the function executes. To set the persist parameter, use this command as follows: import streamlit as st @st.cache_data(persist=""disk"") def fetch_and_clean_data(url): # Fetch data from URL here, and then clean it up. return data By default, all parameters to a cached function must be hashable. Any parameter whose name begins with _ will not be hashed. You can use this as an ""escape hatch"" for parameters that are not hashable: import streamlit as st @st.cache_data def fetch_and_clean_data(_db_connection, num_rows): # Fetch data from _db_connection here, and then clean it up. return data connection = make_database_connection() d1 = fetch_and_clean_data(connection, num_rows=10) # Actually executes the function, since this is the first time it was # encountered. another_connection = make_database_connection() d2 = fetch_and_clean_data(another_connection, num_rows=10) # Does not execute the function. Instead, returns its previously computed # value - even though the _database_connection parameter was different # in both calls. A cached function's cache can be procedurally cleared: import streamlit as st @st.cache_data def fetch_and_clean_data(_db_connection, num_rows): # Fetch data from _db_connection here, and then clean it up. return data fetch_and_clean_data.clear(_db_connection, 50) # Clear the cached entry for the arguments provided. fetch_and_clean_data.clear() # Clear all cached entries for this function. To override the default hashing behavior, pass a custom hash function. You can do that by mapping a type (e.g. datetime.datetime) to a hash function (lambda dt: dt.isoformat()) like this: import streamlit as st import datetime @st.cache_data(hash_funcs={datetime.datetime: lambda dt: dt.isoformat()}) def convert_to_utc(dt: datetime.datetime): return dt.astimezone(datetime.timezone.utc) Alternatively, you can map the type's fully-qualified name (e.g. ""datetime.datetime"") to the hash function instead: import streamlit as st import datetime @st.cache_data(hash_funcs={""datetime.datetime"": lambda dt: dt.isoformat()}) def convert_to_utc(dt: datetime.datetime): return dt.astimezone(datetime.timezone.utc) Persistent memo caches currently don't support TTL. ttl will be ignored if persist is specified: import streamlit as st @st.experimental_memo(ttl=60, persist=""disk"") def load_data(): return 42 st.write(load_data()) And a warning will be logged to your terminal: streamlit run app.py You can now view your Streamlit app in your browser. Local URL: http://localhost:8501 Network URL: http://192.168.1.1:8501 2022-09-22 13:35:41.587 The memoized function 'load_data' has a TTL that will be ignored. Persistent memo caches currently don't support TTL. st.experimental_memo.clearStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakedeleteDeprecation noticest.experimental_memo.clear was deprecated in version 1.18.0. Use st.cache_data.clear instead. Learn more in Caching.Clear all in-memory and on-disk data caches. Function signature[source] st.experimental_memo.clear() Example In the example below, pressing the ""Clear All"" button will clear memoized values from all functions decorated with @st.experimental_memo. import streamlit as st @st.experimental_memo def square(x): return x**2 @st.experimental_memo def cube(x): return x**3 if st.button(""Clear All""): # Clear values from *all* memoized functions: # i.e. clear values from both square and cube st.experimental_memo.clear() Replay static st elements in cache-decorated functions Functions decorated with @st.experimental_memo can contain static st elements. When a cache-decorated function is executed, we record the element and block messages produced, so the elements will appear in the app even when execution of the function is skipped because the result was cached. In the example below, the @st.experimental_memo decorator is used to cache the execution of the load_data function, that returns a pandas DataFrame. Notice the cached function also contains a st.area_chart command, which will be replayed when the function is skipped because the result was cached. import numpy as np import pandas as pd import streamlit as st @st.experimental_memo def load_data(rows): chart_data = pd.DataFrame( np.random.randn(rows, 10), columns=[""a"", ""b"", ""c"", ""d"", ""e"", ""f"", ""g"", ""h"", ""i"", ""j""], ) # Contains a static element st.area_chart st.area_chart(chart_data) # This will be recorded and displayed even when the function is skipped return chart_data df = load_data(20) st.dataframe(df) Supported static st elements in cache-decorated functions include: st.alert st.altair_chart st.area_chart st.audio st.bar_chart st.ballons st.bokeh_chart st.caption st.code st.components.v1.html st.components.v1.iframe st.container st.dataframe st.echo st.empty st.error st.exception st.expander st.experimental_get_query_params st.experimental_set_query_params st.form st.form_submit_button st.graphviz_chart st.help st.image st.info st.json st.latex st.line_chart st.markdown st.metric st.plotly_chart st.progress st.pydeck_chart st.snow st.spinner st.success st.table st.text st.vega_lite_chart st.video st.warning Replay input widgets in cache-decorated functions In addition to static elements, functions decorated with @st.experimental_memo can also contain input widgets! Replaying input widgets is disabled by default. To enable it, you can set the experimental_allow_widgets parameter for @st.experimental_memo to True. The example below enables widget replaying, and shows the use of a checkbox widget within a cache-decorated function. import streamlit as st # Enable widget replay @st.experimental_memo(experimental_allow_widgets=True) def func(): # Contains an input widget st.checkbox(""Works!"") func() If the cache decorated function contains input widgets, but experimental_allow_widgets is set to False or unset, Streamlit will throw a CachedStFunctionWarning, like the one below: import streamlit as st # Widget replay is disabled by default @st.experimental_memo def func(): # Streamlit will throw a CachedStFunctionWarning st.checkbox(""Doesn't work"") func() How widget replay works Let's demystify how widget replay in cache-decorated functions works and gain a conceptual understanding. Widget values are treated as additional inputs to the function, and are used to determine whether the function should be executed or not. Consider the following example: import streamlit as st @st.experimental_memo(experimental_allow_widgets=True) def plus_one(x): y = x + 1 if st.checkbox(""Nuke the value 💥""): st.write(""Value was nuked, returning 0"") y = 0 return y st.write(plus_one(2)) The plus_one function takes an integer x as input, and returns x + 1. The function also contains a checkbox widget, which is used to ""nuke"" the value of x. i.e. the return value of plus_one depends on the state of the checkbox: if it is checked, the function returns 0, otherwise it returns 3. In order to know which value the cache should return (in case of a cache hit), Streamlit treats the checkbox state (checked / unchecked) as an additional input to the function plus_one (just like x). If the user checks the checkbox (thereby changing its state), we look up the cache for the same value of x (2) and the same checkbox state (checked). If the cache contains a value for this combination of inputs, we return it. Otherwise, we execute the function and store the result in the cache. Let's now understand how enabling and disabling widget replay changes the behavior of the function. Widget replay disabled Widgets in cached functions throw a CachedStFunctionWarning and are ignored. Other static elements in cached functions replay as expected. Widget replay enabled Widgets in cached functions don't lead to a warning, and are replayed as expected. Interacting with a widget in a cached function will cause the function to be executed again, and the cache to be updated. Widgets in cached functions retain their state across reruns. Each unique combination of widget values is treated as a separate input to the function, and is used to determine whether the function should be executed or not. i.e. Each unique combination of widget values has its own cache entry; the cached function runs the first time and the saved value is used afterwards. Calling a cached function multiple times in one script run with the same arguments triggers a DuplicateWidgetID error. If the arguments to a cached function change, widgets from that function that render again retain their state. Changing the source code of a cached function invalidates the cache. Both st.experimental_memo and st.experimental_singleton support widget replay. Fundamentally, the behavior of a function with (supported) widgets in it doesn't change when it is decorated with @st.experimental_memo or @st.experimental_singleton. The only difference is that the function is only executed when we detect a cache ""miss"". Supported widgets All input widgets are supported in cache-decorated functions. The following is an exhaustive list of supported widgets: st.button st.camera_input st.checkbox st.color_picker st.date_input st.download_button st.file_uploader st.multiselect st.number_input st.radio st.selectbox st.select_slider st.slider st.text_area st.text_input st.time_input Previous: st.cacheNext: st.experimental_singletonforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy" https://docs.streamlit.io/develop/api-reference/charts/st.scatter_chart#elementadd_rows,"DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceremovePAGE ELEMENTSWrite and magicaddText elementsaddData elementsaddChart elementsremoveSIMPLEst.area_chartst.bar_chartst.line_chartst.mapst.scatter_chartADVANCEDst.altair_chartst.bokeh_chartst.graphviz_chartst.plotly_chartst.pydeck_chartst.pyplotst.vega_lite_chartInput widgetsaddMedia elementsaddLayouts and containersaddChat elementsaddStatus elementsaddThird-party componentsopen_in_newAPPLICATION LOGICNavigation and pagesaddExecution flowaddCaching and stateaddConnections and secretsaddCustom componentsaddUtilitiesaddConfigurationaddTOOLSApp testingaddCommand lineaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Develop/API reference/Chart elements/st.scatter_chartst.scatter_chartStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeDisplay a scatterplot chart. This is syntax-sugar around st.altair_chart. The main difference is this command uses the data's own column and indices to figure out the chart's spec. As a result this is easier to use for many ""just plot this"" scenarios, while being less customizable. If st.scatter_chart does not guess the data specification correctly, try specifying your desired chart using st.altair_chart. Function signature[source] st.scatter_chart(data=None, *, x=None, y=None, color=None, size=None, width=0, height=0, use_container_width=True) Parameters data (pandas.DataFrame, pandas.Styler, pyarrow.Table, numpy.ndarray, pyspark.sql.DataFrame, snowflake.snowpark.dataframe.DataFrame, snowflake.snowpark.table.Table, Iterable, dict or None) Data to be plotted. x (str or None) Column name to use for the x-axis. If None, uses the data index for the x-axis. y (str, Sequence of str, or None) Column name(s) to use for the y-axis. If a Sequence of strings, draws several series on the same chart by melting your wide-format table into a long-format table behind the scenes. If None, draws the data of all remaining columns as data series. color (str, tuple, Sequence of str, Sequence of tuple, or None) The color of the circles representing each datapoint. This can be: None, to use the default color. A hex string like ""#ffaa00"" or ""#ffaa0088"". An RGB or RGBA tuple with the red, green, blue, and alpha components specified as ints from 0 to 255 or floats from 0.0 to 1.0. The name of a column in the dataset where the color of that datapoint will come from. If the values in this column are in one of the color formats above (hex string or color tuple), then that color will be used. Otherwise, the color will be automatically picked from the default palette. For example: if the dataset has 1000 rows, but this column only contains the values ""adult"", ""child"", and ""baby"", then those 1000 datapoints be shown using three colors from the default palette. But if this column only contains floats or ints, then those 1000 datapoints will be shown using a colors from a continuous color gradient. Finally, if this column only contains the values ""#ffaa00"", ""#f0f"", ""#0000ff"", then then each of those 1000 datapoints will be assigned ""#ffaa00"", ""#f0f"", or ""#0000ff"" as appropriate. If the dataframe is in wide format (that is, y is a Sequence of columns), this can also be: A list of string colors or color tuples to be used for each of the series in the chart. This list should have the same length as the number of y values (e.g. color=[""#fd0"", ""#f0f"", ""#04f""] for three series). size (str, float, int, or None) The size of the circles representing each point. This can be: A number like 100, to specify a single size to use for all datapoints. The name of the column to use for the size. This allows each datapoint to be represented by a circle of a different size. width (int) The chart width in pixels. If 0, selects the width automatically. height (int) The chart height in pixels. If 0, selects the height automatically. use_container_width (bool) If True, set the chart width to the column width. This takes precedence over the width argument. Examples import streamlit as st import pandas as pd import numpy as np chart_data = pd.DataFrame(np.random.randn(20, 3), columns=[""a"", ""b"", ""c""]) st.scatter_chart(chart_data) Built with Streamlit 🎈Fullscreen open_in_new You can also choose different columns to use for x and y, as well as set the color dynamically based on a 3rd column (assuming your dataframe is in long format): import streamlit as st import pandas as pd import numpy as np chart_data = pd.DataFrame(np.random.randn(20, 3), columns=[""col1"", ""col2"", ""col3""]) chart_data['col4'] = np.random.choice(['A','B','C'], 20) st.scatter_chart( chart_data, x='col1', y='col2', color='col4', size='col3', ) Built with Streamlit 🎈Fullscreen open_in_new Finally, if your dataframe is in wide format, you can group multiple columns under the y argument to show multiple series with different colors: import streamlit as st import pandas as pd import numpy as np chart_data = pd.DataFrame(np.random.randn(20, 4), columns=[""col1"", ""col2"", ""col3"", ""col4""]) st.scatter_chart( chart_data, x='col1', y=['col2', 'col3'], size='col4', color=['#FF0000', '#0000FF'], # Optional ) Built with Streamlit 🎈Fullscreen open_in_new element.add_rowsStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeConcatenate a dataframe to the bottom of the current one. Function signature[source] element.add_rows(data=None, **kwargs) Parameters data (pandas.DataFrame, pandas.Styler, pyarrow.Table, numpy.ndarray, pyspark.sql.DataFrame, snowflake.snowpark.dataframe.DataFrame, Iterable, dict, or None) Table to concat. Optional. **kwargs (pandas.DataFrame, numpy.ndarray, Iterable, dict, or None) The named dataset to concat. Optional. You can only pass in 1 dataset (including the one in the data parameter). Example import streamlit as st import pandas as pd import numpy as np df1 = pd.DataFrame(np.random.randn(50, 20), columns=(""col %d"" % i for i in range(20))) my_table = st.table(df1) df2 = pd.DataFrame(np.random.randn(50, 20), columns=(""col %d"" % i for i in range(20))) my_table.add_rows(df2) # Now the table shown in the Streamlit app contains the data for # df1 followed by the data for df2. You can do the same thing with plots. For example, if you want to add more data to a line chart: # Assuming df1 and df2 from the example above still exist... my_chart = st.line_chart(df1) my_chart.add_rows(df2) # Now the chart shown in the Streamlit app contains the data for # df1 followed by the data for df2. And for plots whose datasets are named, you can pass the data with a keyword argument where the key is the name: my_chart = st.vega_lite_chart({ 'mark': 'line', 'encoding': {'x': 'a', 'y': 'b'}, 'datasets': { 'some_fancy_name': df1, # <-- named dataset }, 'data': {'name': 'some_fancy_name'}, }), my_chart.add_rows(some_fancy_name=df2) # <-- name used as keyword Previous: st.mapNext: st.altair_chartforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy" https://docs.streamlit.io/get-started,"DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Get startedGet started with Streamlit This Get Started guide explains how Streamlit works, how to install Streamlit on your preferred operating system, and how to create your first Streamlit app! downloadingInstallation helps you set up your development environment. Walk through installing Streamlit on Windows, macOS, or Linux. Alternatively, code right in your browser with GitHub Codespaces or Streamlit in Snowflake.descriptionFundamentals introduces you to Streamlit's data model and development flow. You'll learn what makes Streamlit the most powerful way to build data apps, including the ability to display and style data, draw charts and maps, add interactive widgets, customize app layouts, cache computation, and define themes.auto_awesomeFirst steps walks you through creating apps using core features to fetch and cache data, draw charts, plot information on a map, and use interactive widgets to filter results.rocket_launchUse GitHub Codespaces if you want to skip past local installation and code right in your browser. This guide uses Streamlit Community Cloud to help you automatically configure a codespace. 30 Days of Streamlit 🎈30 Days of Streamlit 🎈 is a free, self-paced 30 day challenge that teaches you how to build and deploy data apps with Streamlit. Complete the daily challenges, share your solutions with us on Twitter and LinkedIn, and stop by the forum with any questions!Start the challengeNext: InstallationforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy" https://docs.streamlit.io/library/advanced-features/configuration#file-location,"DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceremovePAGE ELEMENTSWrite and magicaddText elementsaddData elementsaddChart elementsaddInput widgetsaddMedia elementsaddLayouts and containersaddChat elementsaddStatus elementsaddThird-party componentsopen_in_newAPPLICATION LOGICNavigation and pagesaddExecution flowaddCaching and stateaddConnections and secretsaddCustom componentsaddUtilitiesaddConfigurationremoveconfig.tomlst.set_page_configTOOLSApp testingaddCommand lineaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Develop/API reference/Configuration/config.tomlconfig.toml config.toml is an optional file you can define for your working directory or global development environment. When config.toml is defined both globally and in your working directory, Streamlit combines the configuration options and gives precendence to the working-directory configuration. Additionally, you can use environment variables and command-line options to override additional configuration options. For more information, see Configuration options. File location To define your configuration locally or per-project, add .streamlit/config.toml to your working directory. Your working directory is wherever you call streamlit run. If you haven't previously created the .streamlit directory, you will need to add it. To define your configuration globally, you must first locate your global .streamlit directory. Streamlit adds this hidden directory to your OS user profile during installation. For MacOS/Linx, this will be ~/.streamlit/config.toml. For Windows, this will be %userprofile%/.streamlit/config.toml. File format config.toml is a TOML file. Example [client] showErrorDetails = false [theme] primaryColor = ""#F63366"" backgroundColor = ""black"" Available configuration options Below are all the sections and options you can have in your .streamlit/config.toml file. To see all configurations, use the following command in your terminal or CLI: streamlit config show Global [global] # ***DEPRECATED*** # global.disableWatchdogWarning has been deprecated has been deprecated and # will be removed in a future version. This option will be removed on or after # 2024-01-20. # **************** # By default, Streamlit checks if the Python watchdog module is available # and, if not, prints a warning asking for you to install it. The watchdog # module is not required, but highly recommended. It improves Streamlit's # ability to detect changes to files in your filesystem. # If you'd like to turn off this warning, set this to True. # Default: false disableWatchdogWarning = false # By default, Streamlit displays a warning when a user sets both a widget # default value in the function defining the widget and a widget value via # the widget's key in `st.session_state`. # If you'd like to turn off this warning, set this to True. # Default: false disableWidgetStateDuplicationWarning = false # If True, will show a warning when you run a Streamlit-enabled script # via ""python my_script.py"". # Default: true showWarningOnDirectExecution = true Logger [logger] # Level of logging: 'error', 'warning', 'info', or 'debug'. # Default: 'info' level = ""info"" # String format for logging messages. If logger.datetimeFormat is set, # logger messages will default to `%(asctime)s.%(msecs)03d %(message)s`. See # Python's documentation for available attributes: # https://docs.python.org/2.6/develop/logging.html#formatter-objects # Default: ""%(asctime)s %(message)s"" messageFormat = ""%(asctime)s %(message)s"" Client [client] # ***DEPRECATED*** # client.caching has been deprecated and is not required anymore for our new # caching commands. This option will be removed on or after 2024-01-20. # **************** # Whether to enable st.cache. This does not affect st.cache_data or # st.cache_resource. # Default: true caching = true # ***DEPRECATED*** # client.displayEnabled has been deprecated and will be removed in a future # version. This option will be removed on or after 2024-01-20. # **************** # If false, makes your Streamlit script not draw to a Streamlit app. # Default: true displayEnabled = true # Controls whether uncaught app exceptions and deprecation warnings # are displayed in the browser. By default, this is set to True and # Streamlit displays app exceptions and associated tracebacks, and # deprecation warnings, in the browser. # # If set to False, deprecation warnings and full exception messages # will print to the console only. Exceptions will still display in the # browser with a generic error message. For now, the exception type and # traceback show in the browser also, but they will be removed in the # future. # Default: true showErrorDetails = true # Change the visibility of items in the toolbar, options menu, # and settings dialog (top right of the app). # Allowed values: # * ""auto"" : Show the developer options if the app is accessed through # localhost or through Streamlit Community Cloud as a developer. # Hide them otherwise. # * ""developer"" : Show the developer options. # * ""viewer"" : Hide the developer options. # * ""minimal"" : Show only options set externally (e.g. through # Streamlit Community Cloud) or through st.set_page_config. # If there are no options left, hide the menu. # Default: ""auto"" toolbarMode = ""auto"" # Controls whether the default sidebar page navigation in a multipage app is # displayed. # Default: true showSidebarNavigation = true Runner [runner] # Allows you to type a variable or string by itself in a single line of # Python code to write it to the app. # Default: true magicEnabled = true # ***DEPRECATED*** # runner.installTracer has been deprecated and will be removed in a future # version. This option will be removed on or after 2024-01-20. # **************** # Install a Python tracer to allow you to stop or pause your script at # any point and introspect it. As a side-effect, this slows down your # script's execution. # Default: false installTracer = false # ***DEPRECATED*** # runner.fixMatplotlib has been deprecated and will be removed in a future # version. This option will be removed on or after 2024-01-20. # **************** # Sets the MPLBACKEND environment variable to Agg inside Streamlit to # prevent Python crashing. # Default: true fixMatplotlib = true # Handle script rerun requests immediately, rather than waiting for script # execution to reach a yield point. This makes Streamlit much more # responsive to user interaction, but it can lead to race conditions in # apps that mutate session_state data outside of explicit session_state # assignment statements. # Default: true fastReruns = true # Raise an exception after adding unserializable data to Session State. # Some execution environments may require serializing all data in Session # State, so it may be useful to detect incompatibility during development, # or when the execution environment will stop supporting it in the future. # Default: false enforceSerializableSessionState = false # Adjust how certain 'options' widgets like radio, selectbox, and # multiselect coerce Enum members when the Enum class gets # re-defined during a script re-run. For more information, check out the docs: # https://docs.streamlit.io/develop/concepts/design/custom-classes#enums # # Allowed values: # * ""off"" : Disables Enum coercion. # * ""nameOnly"" : Enum classes can be coerced if their member names match. # * ""nameAndValue"" : Enum classes can be coerced if their member names AND # member values match. # Default: ""nameOnly"" enumCoercion = ""nameOnly"" Server [server] # List of folders that should not be watched for changes. This # impacts both ""Run on Save"" and @st.cache. # Relative paths will be taken as relative to the current working directory. # Example: ['/home/user1/env', 'relative/path/to/folder'] # Default: [] folderWatchBlacklist = [] # Change the type of file watcher used by Streamlit, or turn it off # completely. # Allowed values: # * ""auto"" : Streamlit will attempt to use the watchdog module, and # falls back to polling if watchdog is not available. # * ""watchdog"" : Force Streamlit to use the watchdog module. # * ""poll"" : Force Streamlit to always use polling. # * ""none"" : Streamlit will not watch files. # Default: ""auto"" fileWatcherType = ""auto"" # Symmetric key used to produce signed cookies. If deploying on multiple # replicas, this should be set to the same value across all replicas to ensure # they all share the same secret. # Default: randomly generated secret key. cookieSecret = ""a-random-key-appears-here"" # If false, will attempt to open a browser window on start. # Default: false unless (1) we are on a Linux box where DISPLAY is unset, or # (2) we are running in the Streamlit Atom plugin. headless = false # Automatically rerun script when the file is modified on disk. # Default: false runOnSave = false # The address where the server will listen for client and browser # connections. Use this if you want to bind the server to a specific address. # If set, the server will only be accessible from this address, and not from # any aliases (like localhost). # Default: (unset) address = # The port where the server will listen for browser connections. # Don't use port 3000 which is reserved for internal development. # Default: 8501 port = 8501 # The base path for the URL where Streamlit should be served from. # Default: """" baseUrlPath = """" # Enables support for Cross-Origin Resource Sharing (CORS) protection, for # added security. # Due to conflicts between CORS and XSRF, if `server.enableXsrfProtection` is # on and `server.enableCORS` is off at the same time, we will prioritize # `server.enableXsrfProtection`. # Default: true enableCORS = true # Enables support for Cross-Site Request Forgery (XSRF) protection, for added # security. # Due to conflicts between CORS and XSRF, if `server.enableXsrfProtection` is # on and `server.enableCORS` is off at the same time, we will prioritize # `server.enableXsrfProtection`. # Default: true enableXsrfProtection = true # Max size, in megabytes, for files uploaded with the file_uploader. # Default: 200 maxUploadSize = 200 # Max size, in megabytes, of messages that can be sent via the WebSocket # connection. # Default: 200 maxMessageSize = 200 # Enables support for websocket compression. # Default: false enableWebsocketCompression = false # Enable serving files from a `static` directory in the running app's # directory. # Default: false enableStaticServing = false # Server certificate file for connecting via HTTPS. # Must be set at the same time as ""server.sslKeyFile"". # ['DO NOT USE THIS OPTION IN A PRODUCTION ENVIRONMENT. It has not gone through # security audits or performance tests. For the production environment, we # recommend performing SSL termination by the load balancer or the reverse # proxy.'] # sslCertFile = # Cryptographic key file for connecting via HTTPS. # Must be set at the same time as ""server.sslCertFile"". # ['DO NOT USE THIS OPTION IN A PRODUCTION ENVIRONMENT. It has not gone through # security audits or performance tests. For the production environment, we # recommend performing SSL termination by the load balancer or the reverse # proxy.'] # sslKeyFile = Browser [browser] # Internet address where users should point their browsers in order to # connect to the app. Can be IP address or DNS name and path. # This is used to: # - Set the correct URL for CORS and XSRF protection purposes. # - Show the URL on the terminal # - Open the browser # Default: ""localhost"" serverAddress = ""localhost"" # Whether to send usage statistics to Streamlit. # Default: true gatherUsageStats = true # Port where users should point their browsers in order to connect to the # app. # This is used to: # - Set the correct URL for XSRF protection purposes. # - Show the URL on the terminal (part of `streamlit run`). # - Open the browser automatically (part of `streamlit run`). # This option is for advanced use cases. To change the port of your app, use # `server.Port` instead. Don't use port 3000 which is reserved for internal # development. # Default: whatever value is set in server.port. serverPort = 8501 Mapbox [mapbox] # Configure Streamlit to use a custom Mapbox # token for elements like st.pydeck_chart and st.map. # To get a token for yourself, create an account at # https://mapbox.com. It's free (for moderate usage levels)! # Default: """" token = """" Deprecation [deprecation] # Set to false to disable the deprecation warning for using the global pyplot # instance. # Default: true showPyplotGlobalUse = true Theme [theme] # The preset Streamlit theme that your custom theme inherits from. # One of ""light"" or ""dark"". # base = # Primary accent color for interactive elements. # primaryColor = # Background color for the main content area. # backgroundColor = # Background color used for the sidebar and most interactive widgets. # secondaryBackgroundColor = # Color used for almost all text. # textColor = # Font family for all text in the app, except code blocks. One of ""sans serif"", # ""serif"", or ""monospace"". # font = Previous: ConfigurationNext: st.set_page_configforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy"