Link
stringlengths
37
191
Text
stringlengths
916
46.2k
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 = "<YOUR_SECRET_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( "<p>Foo bar.</p>" ) 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 = """ <style> p { color: red; } </style> """ 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 <class 'datetime.datetime'> 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 = "<YOUR_SECRET_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( "<p>Foo bar.</p>" ) 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 = """ <style> p { color: red; } </style> """ 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
README.md exists but content is empty. Use the Edit dataset card button to edit it.
Downloads last month
136
Edit dataset card