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
https://docs.streamlit.io/develop/tutorials/llms/build-conversational-apps#build-a-simple-chatbot-gui-with-streaming
DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceaddTutorialsremoveExecution flowaddConnect to data sourcesaddMultipage appsaddWork with LLMsremoveBuild a basic LLM chat appBuild an LLM app using LangChainQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Develop/Tutorials/Work with LLMs/Build a basic LLM chat appBuild a basic LLM chat app Introduction The advent of large language models like GPT has revolutionized the ease of developing chat-based applications. Streamlit offers several Chat elements, enabling you to build Graphical User Interfaces (GUIs) for conversational agents or chatbots. Leveraging session state along with these elements allows you to construct anything from a basic chatbot to a more advanced, ChatGPT-like experience using purely Python code. In this tutorial, we'll start by walking through Streamlit's chat elements, st.chat_message and st.chat_input. Then we'll proceed to construct three distinct applications, each showcasing an increasing level of complexity and functionality: First, we'll Build a bot that mirrors your input to get a feel for the chat elements and how they work. We'll also introduce session state and how it can be used to store the chat history. This section will serve as a foundation for the rest of the tutorial. Next, you'll learn how to Build a simple chatbot GUI with streaming. Finally, we'll Build a ChatGPT-like app that leverages session state to remember conversational context, all within less than 50 lines of code. Here's a sneak peek of the LLM-powered chatbot GUI with streaming we'll build in this tutorial: Built with Streamlit 🎈Fullscreen open_in_new Play around with the above demo to get a feel for what we'll build in this tutorial. A few things to note: There's a chat input at the bottom of the screen that's always visible. It contains some placeholder text. You can type in a message and press Enter or click the run button to send it. When you enter a message, it appears as a chat message in the container above. The container is scrollable, so you can scroll up to see previous messages. A default avatar is displayed to your messages' left. The assistant's responses are streamed to the frontend and are displayed with a different default avatar. Before we start building, let's take a closer look at the chat elements we'll use. Chat elements Streamlit offers several commands to help you build conversational apps. These chat elements are designed to be used in conjunction with each other, but you can also use them separately. st.chat_message lets you insert a chat message container into the app so you can display messages from the user or the app. Chat containers can contain other Streamlit elements, including charts, tables, text, and more. st.chat_input lets you display a chat input widget so the user can type in a message. For an overview of the API, check out this video tutorial by Chanin Nantasenamat (@dataprofessor), a Senior Developer Advocate at Streamlit. st.chat_message st.chat_message lets you insert a multi-element chat message container into your app. The returned container can contain any Streamlit element, including charts, tables, text, and more. To add elements to the returned container, you can use with notation. st.chat_message's first parameter is the name of the message author, which can be either "user" or "assistant" to enable preset styling and avatars, like in the demo above. You can also pass in a custom string to use as the author name. Currently, the name is not shown in the UI but is only set as an accessibility label. For accessibility reasons, you should not use an empty string. Here's an minimal example of how to use st.chat_message to display a welcome message: import streamlit as st with st.chat_message("user"): st.write("Hello 👋") Notice the message is displayed with a default avatar and styling since we passed in "user" as the author name. You can also pass in "assistant" as the author name to use a different default avatar and styling, or pass in a custom name and avatar. See the API reference for more details. import streamlit as st import numpy as np with st.chat_message("assistant"): st.write("Hello human") st.bar_chart(np.random.randn(30, 3)) Built with Streamlit 🎈Fullscreen open_in_new While we've used the preferred with notation in the above examples, you can also just call methods directly in the returned objects. The below example is equivalent to the one above: import streamlit as st import numpy as np message = st.chat_message("assistant") message.write("Hello human") message.bar_chart(np.random.randn(30, 3)) So far, we've displayed predefined messages. But what if we want to display messages based on user input? st.chat_input st.chat_input lets you display a chat input widget so the user can type in a message. The returned value is the user's input, which is None if the user hasn't sent a message yet. You can also pass in a default prompt to display in the input widget. Here's an example of how to use st.chat_input to display a chat input widget and show the user's input: import streamlit as st prompt = st.chat_input("Say something") if prompt: st.write(f"User has sent the following prompt: {prompt}") Built with Streamlit 🎈Fullscreen open_in_new Pretty straightforward, right? Now let's combine st.chat_message and st.chat_input to build a bot the mirrors or echoes your input. Build a bot that mirrors your input In this section, we'll build a bot that mirrors or echoes your input. More specifically, the bot will respond to your input with the same message. We'll use st.chat_message to display the user's input and st.chat_input to accept user input. We'll also use session state to store the chat history so we can display it in the chat message container. First, let's think about the different components we'll need to build our bot: Two chat message containers to display messages from the user and the bot, respectively. A chat input widget so the user can type in a message. A way to store the chat history so we can display it in the chat message containers. We can use a list to store the messages, and append to it every time the user or bot sends a message. Each entry in the list will be a dictionary with the following keys: role (the author of the message), and content (the message content). import streamlit as st st.title("Echo Bot") # Initialize chat history if "messages" not in st.session_state: st.session_state.messages = [] # Display chat messages from history on app rerun for message in st.session_state.messages: with st.chat_message(message["role"]): st.markdown(message["content"]) In the above snippet, we've added a title to our app and a for loop to iterate through the chat history and display each message in the chat message container (with the author role and message content). We've also added a check to see if the messages key is in st.session_state. If it's not, we initialize it to an empty list. This is because we'll be adding messages to the list later on, and we don't want to overwrite the list every time the app reruns. Now let's accept user input with st.chat_input, display the user's message in the chat message container, and add it to the chat history. # React to user input if prompt := st.chat_input("What is up?"): # Display user message in chat message container with st.chat_message("user"): st.markdown(prompt) # Add user message to chat history st.session_state.messages.append({"role": "user", "content": prompt}) We used the := operator to assign the user's input to the prompt variable and checked if it's not None in the same line. If the user has sent a message, we display the message in the chat message container and append it to the chat history. All that's left to do is add the chatbot's responses within the if block. We'll use the same logic as before to display the bot's response (which is just the user's prompt) in the chat message container and add it to the history. response = f"Echo: {prompt}" # Display assistant response in chat message container with st.chat_message("assistant"): st.markdown(response) # Add assistant response to chat history st.session_state.messages.append({"role": "assistant", "content": response}) Putting it all together, here's the full code for our simple chatbot GUI and the result: View full codeexpand_moreimport streamlit as st st.title("Echo Bot") # Initialize chat history if "messages" not in st.session_state: st.session_state.messages = [] # Display chat messages from history on app rerun for message in st.session_state.messages: with st.chat_message(message["role"]): st.markdown(message["content"]) # React to user input if prompt := st.chat_input("What is up?"): # Display user message in chat message container st.chat_message("user").markdown(prompt) # Add user message to chat history st.session_state.messages.append({"role": "user", "content": prompt}) response = f"Echo: {prompt}" # Display assistant response in chat message container with st.chat_message("assistant"): st.markdown(response) # Add assistant response to chat history st.session_state.messages.append({"role": "assistant", "content": response}) Built with Streamlit 🎈Fullscreen open_in_new While the above example is very simple, it's a good starting point for building more complex conversational apps. Notice how the bot responds instantly to your input. In the next section, we'll add a delay to simulate the bot "thinking" before responding. Build a simple chatbot GUI with streaming In this section, we'll build a simple chatbot GUI that responds to user input with a random message from a list of pre-determind responses. In the next section, we'll convert this simple toy example into a ChatGPT-like experience using OpenAI. Just like previously, we still require the same components to build our chatbot. Two chat message containers to display messages from the user and the bot, respectively. A chat input widget so the user can type in a message. And a way to store the chat history so we can display it in the chat message containers. Let's just copy the code from the previous section and add a few tweaks to it. import streamlit as st import random import time st.title("Simple chat") # Initialize chat history if "messages" not in st.session_state: st.session_state.messages = [] # Display chat messages from history on app rerun for message in st.session_state.messages: with st.chat_message(message["role"]): st.markdown(message["content"]) # Accept user input if prompt := st.chat_input("What is up?"): # Display user message in chat message container with st.chat_message("user"): st.markdown(prompt) # Add user message to chat history st.session_state.messages.append({"role": "user", "content": prompt}) The only difference so far is we've changed the title of our app and added imports for random and time. We'll use random to randomly select a response from a list of responses and time to add a delay to simulate the chatbot "thinking" before responding. All that's left to do is add the chatbot's responses within the if block. We'll use a list of responses and randomly select one to display. We'll also add a delay to simulate the chatbot "thinking" before responding (or stream its response). Let's make a helper function for this and insert it at the top of our app. # Streamed response emulator def response_generator(): response = random.choice( [ "Hello there! How can I assist you today?", "Hi, human! Is there anything I can help you with?", "Do you need help?", ] ) for word in response.split(): yield word + " " time.sleep(0.05) Back to writing the response in our chat interface, we'll use st.write_stream to write out the streamed response with a typewriter effect. # Display assistant response in chat message container with st.chat_message("assistant"): response = st.write_stream(response_generator()) # Add assistant response to chat history st.session_state.messages.append({"role": "assistant", "content": response}) Above, we've added a placeholder to display the chatbot's response. We've also added a for loop to iterate through the response and display it one word at a time. We've added a delay of 0.05 seconds between each word to simulate the chatbot "thinking" before responding. Finally, we append the chatbot's response to the chat history. As you've probably guessed, this is a naive implementation of streaming. We'll see how to implement streaming with OpenAI in the next section. Putting it all together, here's the full code for our simple chatbot GUI and the result: View full codeexpand_moreimport streamlit as st import random import time # Streamed response emulator def response_generator(): response = random.choice( [ "Hello there! How can I assist you today?", "Hi, human! Is there anything I can help you with?", "Do you need help?", ] ) for word in response.split(): yield word + " " time.sleep(0.05) st.title("Simple chat") # Initialize chat history if "messages" not in st.session_state: st.session_state.messages = [] # Display chat messages from history on app rerun for message in st.session_state.messages: with st.chat_message(message["role"]): st.markdown(message["content"]) # Accept user input if prompt := st.chat_input("What is up?"): # Add user message to chat history st.session_state.messages.append({"role": "user", "content": prompt}) # Display user message in chat message container with st.chat_message("user"): st.markdown(prompt) # Display assistant response in chat message container with st.chat_message("assistant"): response = st.write_stream(response_generator()) # Add assistant response to chat history st.session_state.messages.append({"role": "assistant", "content": response}) Built with Streamlit 🎈Fullscreen open_in_new Play around with the above demo to get a feel for what we've built. It's a very simple chatbot GUI, but it has all the components of a more sophisticated chatbot. In the next section, we'll see how to build a ChatGPT-like app using OpenAI. Build a ChatGPT-like app Now that you've understood the basics of Streamlit's chat elements, let's make a few tweaks to it to build our own ChatGPT-like app. You'll need to install the OpenAI Python library and get an API key to follow along. Install dependencies First let's install the dependencies we'll need for this section: pip install openai streamlit Add OpenAI API key to Streamlit secrets Next, let's add our OpenAI API key to Streamlit secrets. We do this by creating .streamlit/secrets.toml file in our project directory and adding the following lines to it: # .streamlit/secrets.toml OPENAI_API_KEY = "YOUR_API_KEY" Write the app Now let's write the app. We'll use the same code as before, but we'll replace the list of responses with a call to the OpenAI API. We'll also add a few more tweaks to make the app more ChatGPT-like. import streamlit as st from openai import OpenAI st.title("ChatGPT-like clone") # Set OpenAI API key from Streamlit secrets client = OpenAI(api_key=st.secrets["OPENAI_API_KEY"]) # Set a default model if "openai_model" not in st.session_state: st.session_state["openai_model"] = "gpt-3.5-turbo" # Initialize chat history if "messages" not in st.session_state: st.session_state.messages = [] # Display chat messages from history on app rerun for message in st.session_state.messages: with st.chat_message(message["role"]): st.markdown(message["content"]) # Accept user input if prompt := st.chat_input("What is up?"): # Add user message to chat history st.session_state.messages.append({"role": "user", "content": prompt}) # Display user message in chat message container with st.chat_message("user"): st.markdown(prompt) All that's changed is that we've added a default model to st.session_state and set our OpenAI API key from Streamlit secrets. Here's where it gets interesting. We can replace our emulated stream with the model's responses from OpenAI: # Display assistant response in chat message container with st.chat_message("assistant"): stream = client.chat.completions.create( model=st.session_state["openai_model"], messages=[ {"role": m["role"], "content": m["content"]} for m in st.session_state.messages ], stream=True, ) response = st.write_stream(stream) st.session_state.messages.append({"role": "assistant", "content": response}) Above, we've replaced the list of responses with a call to OpenAI().chat.completions.create. We've set stream=True to stream the responses to the frontend. In the API call, we pass the model name we hardcoded in session state and pass the chat history as a list of messages. We also pass the role and content of each message in the chat history. Finally, OpenAI returns a stream of responses (split into chunks of tokens), which we iterate through and display each chunk. Putting it all together, here's the full code for our ChatGPT-like app and the result: View full codeexpand_morefrom openai import OpenAI import streamlit as st st.title("ChatGPT-like clone") client = OpenAI(api_key=st.secrets["OPENAI_API_KEY"]) if "openai_model" not in st.session_state: st.session_state["openai_model"] = "gpt-3.5-turbo" if "messages" not in st.session_state: st.session_state.messages = [] for message in st.session_state.messages: with st.chat_message(message["role"]): st.markdown(message["content"]) if prompt := st.chat_input("What is up?"): st.session_state.messages.append({"role": "user", "content": prompt}) with st.chat_message("user"): st.markdown(prompt) with st.chat_message("assistant"): stream = client.chat.completions.create( model=st.session_state["openai_model"], messages=[ {"role": m["role"], "content": m["content"]} for m in st.session_state.messages ], stream=True, ) response = st.write_stream(stream) st.session_state.messages.append({"role": "assistant", "content": response}) Built with Streamlit 🎈Fullscreen open_in_new Congratulations! You've built your own ChatGPT-like app in less than 50 lines of code. We're very excited to see what you'll build with Streamlit's chat elements. Experiment with different models and tweak the code to build your own conversational apps. If you build something cool, let us know on the Forum or check out some other Generative AI apps for inspiration. 🎈Previous: Work with LLMsNext: Build an LLM app using LangChainforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy
https://docs.streamlit.io/develop/concepts/architecture/st.cache#example-5-use-caching-to-speed-up-your-app-across-users
DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsremoveCOREArchitecture & executionremoveRunning your appStreamlit's architectureThe app chromeCachingSession StateFormsFragmentsWidget behaviorMultipage appsaddApp designaddADDITIONALConnections and secretsaddCustom componentsaddConfiguration and themingaddApp testingaddAPI referenceaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Develop/Concepts/Architecture & execution/Optimize performance with st.cachedeleteDeprecation noticest.cache was deprecated in version 1.18.0. Use st.cache_data or st.cache_resource instead. Learn more in Caching. Optimize performance with st.cache Streamlit provides a caching mechanism that allows your app to stay performant even when loading data from the web, manipulating large datasets, or performing expensive computations. This is done with the @st.cache decorator. When you mark a function with the @st.cache decorator, it tells Streamlit that whenever the function is called it needs to check a few things: The input parameters that you called the function with The value of any external variable used in the function The body of the function The body of any function used inside the cached function If this is the first time Streamlit has seen these four components with these exact values and in this exact combination and order, it runs the function and stores the result in a local cache. Then, next time the cached function is called, if none of these components changed, Streamlit will just skip executing the function altogether and, instead, return the output previously stored in the cache. The way Streamlit keeps track of changes in these components is through hashing. Think of the cache as an in-memory key-value store, where the key is a hash of all of the above and the value is the actual output object passed by reference. Finally, @st.cache supports arguments to configure the cache's behavior. You can find more information on those in our API reference. Let's take a look at a few examples that illustrate how caching works in a Streamlit app. Example 1: Basic usage For starters, let's take a look at a sample app that has a function that performs an expensive, long-running computation. Without caching, this function is rerun each time the app is refreshed, leading to a poor user experience. Copy this code into a new app and try it out yourself: import streamlit as st import time def expensive_computation(a, b): time.sleep(2) # 👈 This makes the function take 2s to run return a * b a = 2 b = 21 res = expensive_computation(a, b) st.write("Result:", res) Try pressing R to rerun the app, and notice how long it takes for the result to show up. This is because expensive_computation(a, b) is being re-executed every time the app runs. This isn't a great experience. Let's add the @st.cache decorator: import streamlit as st import time @st.cache # 👈 Added this def expensive_computation(a, b): time.sleep(2) # This makes the function take 2s to run return a * b a = 2 b = 21 res = expensive_computation(a, b) st.write("Result:", res) Now run the app again and you'll notice that it is much faster every time you press R to rerun. To understand what is happening, let's add an st.write inside the function: import streamlit as st import time @st.cache(suppress_st_warning=True) # 👈 Changed this def expensive_computation(a, b): # 👇 Added this st.write("Cache miss: expensive_computation(", a, ",", b, ") ran") time.sleep(2) # This makes the function take 2s to run return a * b a = 2 b = 21 res = expensive_computation(a, b) st.write("Result:", res) Now when you rerun the app the text "Cache miss" appears on the first run, but not on any subsequent runs. That's because the cached function is only being executed once, and every time after that you're actually hitting the cache. push_pinNoteYou may have noticed that we've added the suppress_st_warning keyword to the @st.cache decorators. That's because the cached function above uses a Streamlit command itself (st.write in this case), and when Streamlit sees that, it shows a warning that your command will only execute when you get a cache miss. More often than not, when you see that warning it's because there's a bug in your code. However, in our case we're using the st.write command to demonstrate when the cache is being missed, so the behavior Streamlit is warning us about is exactly what we want. As a result, we are passing in suppress_st_warning=True to turn that warning off. Example 2: When the function arguments change Without stopping the previous app server, let's change one of the arguments to our cached function: import streamlit as st import time @st.cache(suppress_st_warning=True) def expensive_computation(a, b): st.write("Cache miss: expensive_computation(", a, ",", b, ") ran") time.sleep(2) # This makes the function take 2s to run return a * b a = 2 b = 210 # 👈 Changed this res = expensive_computation(a, b) st.write("Result:", res) Now the first time you rerun the app it's a cache miss. This is evidenced by the "Cache miss" text showing up and the app taking 2s to finish running. After that, if you press R to rerun, it's always a cache hit. That is, no such text shows up and the app is fast again. This is because Streamlit notices whenever the arguments a and b change and determines whether the function should be re-executed and re-cached. Example 3: When the function body changes Without stopping and restarting your Streamlit server, let's remove the widget from our app and modify the function's code by adding a + 1 to the return value. import streamlit as st import time @st.cache(suppress_st_warning=True) def expensive_computation(a, b): st.write("Cache miss: expensive_computation(", a, ",", b, ") ran") time.sleep(2) # This makes the function take 2s to run return a * b + 1 # 👈 Added a +1 at the end here a = 2 b = 210 res = expensive_computation(a, b) st.write("Result:", res) The first run is a "Cache miss", but when you press R each subsequent run is a cache hit. This is because on first run, Streamlit detected that the function body changed, reran the function, and put the result in the cache. starTipIf you change the function back the result will already be in the Streamlit cache from a previous run. Try it out! Example 4: When an inner function changes Let's make our cached function depend on another function internally: import streamlit as st import time def inner_func(a, b): st.write("inner_func(", a, ",", b, ") ran") return a * b @st.cache(suppress_st_warning=True) def expensive_computation(a, b): st.write("Cache miss: expensive_computation(", a, ",", b, ") ran") time.sleep(2) # This makes the function take 2s to run return inner_func(a, b) + 1 a = 2 b = 210 res = expensive_computation(a, b) st.write("Result:", res) What you see is the usual: The first run results in a cache miss. Every subsequent rerun results in a cache hit. But now let's try modifying the inner_func(): import streamlit as st import time def inner_func(a, b): st.write("inner_func(", a, ",", b, ") ran") return a ** b # 👈 Changed the * to ** here @st.cache(suppress_st_warning=True) def expensive_computation(a, b): st.write("Cache miss: expensive_computation(", a, ",", b, ") ran") time.sleep(2) # This makes the function take 2s to run return inner_func(a, b) + 1 a = 2 b = 21 res = expensive_computation(a, b) st.write("Result:", res) Even though inner_func() is not annotated with @st.cache, when we edit its body we cause a "Cache miss" in the outer expensive_computation(). That's because Streamlit always traverses your code and its dependencies to verify that the cached values are still valid. This means that while developing your app you can edit your code freely without worrying about the cache. Any change you make to your app, Streamlit should do the right thing! Streamlit is also smart enough to only traverse dependencies that belong to your app, and skip over any dependency that comes from an installed Python library. Example 5: Use caching to speed up your app across users Going back to our original function, let's add a widget to control the value of b: import streamlit as st import time @st.cache(suppress_st_warning=True) def expensive_computation(a, b): st.write("Cache miss: expensive_computation(", a, ",", b, ") ran") time.sleep(2) # This makes the function take 2s to run return a * b a = 2 b = st.slider("Pick a number", 0, 10) # 👈 Changed this res = expensive_computation(a, b) st.write("Result:", res) What you'll see: If you move the slider to a number Streamlit hasn't seen before, you'll have a cache miss again. And every subsequent rerun with the same number will be a cache hit, of course. If you move the slider back to a number Streamlit has seen before, the cache is hit and the app is fast as expected. In computer science terms, what is happening here is that @st.cache is memoizing expensive_computation(a, b). But now let's go one step further! Try the following: Move the slider to a number you haven't tried before, such as 9. Pretend you're another user by opening another browser tab pointing to your Streamlit app (usually at http://localhost:8501) In the new tab, move the slider to 9. Notice how this is actually a cache hit! That is, you don't actually see the "Cache miss" text on the second tab even though that second user never moved the slider to 9 at any point prior to this. This happens because the Streamlit cache is global to all users. So everyone contributes to everyone else's performance. Example 6: Mutating cached values As mentioned in the overview section, the Streamlit cache stores items by reference. This allows the Streamlit cache to support structures that aren't memory-managed by Python, such as TensorFlow objects. However, it can also lead to unexpected behavior — which is why Streamlit has a few checks to guide developers in the right direction. Let's look into those checks now. Let's write an app that has a cached function which returns a mutable object, and then let's follow up by mutating that object: import streamlit as st import time @st.cache(suppress_st_warning=True) def expensive_computation(a, b): st.write("Cache miss: expensive_computation(", a, ",", b, ") ran") time.sleep(2) # This makes the function take 2s to run return {"output": a * b} # 👈 Mutable object a = 2 b = 21 res = expensive_computation(a, b) st.write("Result:", res) res["output"] = "result was manually mutated" # 👈 Mutated cached value st.write("Mutated result:", res) When you run this app for the first time, you should see three messages on the screen: Cache miss: expensive_computation(...) ran Result: {output: 42} Mutated result: {output: "result was manually mutated"} No surprises here. But now notice what happens when you rerun you app (i.e. press R): Result: {output: "result was manually mutated"} Mutated result: {output: "result was manually mutated"} Cached object mutated. (...) So what's up? What's going on here is that Streamlit caches the output res by reference. When you mutated res["output"] outside the cached function you ended up inadvertently modifying the cache. This means every subsequent call to expensive_computation(2, 21) will return the wrong value! Since this behavior is usually not what you'd expect, Streamlit tries to be helpful and show you a warning, along with some ideas about how to fix your code. In this specific case, the fix is just to not mutate res["output"] outside the cached function. There was no good reason for us to do that anyway! Another solution would be to clone the result value with res = deepcopy(expensive_computation(2, 21)). Check out the section entitled Fixing caching issues for more information on these approaches and more. Advanced caching In caching, you learned about the Streamlit cache, which is accessed with the @st.cache decorator. In this article you'll see how Streamlit's caching functionality is implemented, so that you can use it to improve the performance of your Streamlit apps. The cache is a key-value store, where the key is a hash of: The input parameters that you called the function with The value of any external variable used in the function The body of the function The body of any function used inside the cached function And the value is a tuple of: The cached output A hash of the cached output (you'll see why soon) For both the key and the output hash, Streamlit uses a specialized hash function that knows how to traverse code, hash special objects, and can have its behavior customized by the user. For example, when the function expensive_computation(a, b), decorated with @st.cache, is executed with a=2 and b=21, Streamlit does the following: Computes the cache key If the key is found in the cache, then: Extracts the previously-cached (output, output_hash) tuple. Performs an Output Mutation Check, where a fresh hash of the output is computed and compared to the stored output_hash. If the two hashes are different, shows a Cached Object Mutated warning. (Note: Setting allow_output_mutation=True disables this step). If the input key is not found in the cache, then: Executes the cached function (i.e. output = expensive_computation(2, 21)). Calculates the output_hash from the function's output. Stores key → (output, output_hash) in the cache. Returns the output. If an error is encountered an exception is raised. If the error occurs while hashing either the key or the output an UnhashableTypeError error is thrown. If you run into any issues, see fixing caching issues. The hash_funcs parameter As described above, Streamlit's caching functionality relies on hashing to calculate the key for cached objects, and to detect unexpected mutations in the cached result. For added expressive power, Streamlit lets you override this hashing process using the hash_funcs argument. Suppose you define a type called FileReference which points to a file in the filesystem: class FileReference: def __init__(self, filename): self.filename = filename @st.cache def func(file_reference): ... By default, Streamlit hashes custom classes like FileReference by recursively navigating their structure. In this case, its hash is the hash of the filename property. As long as the file name doesn't change, the hash will remain constant. However, what if you wanted to have the hasher check for changes to the file's modification time, not just its name? This is possible with @st.cache's hash_funcs parameter: class FileReference: def __init__(self, filename): self.filename = filename def hash_file_reference(file_reference): filename = file_reference.filename return (filename, os.path.getmtime(filename)) @st.cache(hash_funcs={FileReference: hash_file_reference}) def func(file_reference): ... Additionally, you can hash FileReference objects by the file's contents: class FileReference: def __init__(self, filename): self.filename = filename def hash_file_reference(file_reference): with open(file_reference.filename) as f: return f.read() @st.cache(hash_funcs={FileReference: hash_file_reference}) def func(file_reference): ... push_pinNoteBecause Streamlit's hash function works recursively, you don't have to hash the contents inside hash_file_reference Instead, you can return a primitive type, in this case the contents of the file, and Streamlit's internal hasher will compute the actual hash from it. Typical hash functions While it's possible to write custom hash functions, let's take a look at some of the tools that Python provides out of the box. Here's a list of some hash functions and when it makes sense to use them. Python's id function | Example Speed: Fast Use case: If you're hashing a singleton object, like an open database connection or a TensorFlow session. These are objects that will only be instantiated once, no matter how many times your script reruns. lambda _: None | Example Speed: Fast Use case: If you want to turn off hashing of this type. This is useful if you know the object is not going to change. Python's hash() function | Example Speed: Can be slow based the size of the object being cached Use case: If Python already knows how to hash this type correctly. Custom hash function | Example Speed: N/a Use case: If you'd like to override how Streamlit hashes a particular type. Example 1: Pass a database connection around Suppose we want to open a database connection that can be reused across multiple runs of a Streamlit app. For this you can make use of the fact that cached objects are stored by reference to automatically initialize and reuse the connection: @st.cache(allow_output_mutation=True) def get_database_connection(): return db.get_connection() With just 3 lines of code, the database connection is created once and stored in the cache. Then, every subsequent time get_database_connection is called, the already-created connection object is reused automatically. In other words, it becomes a singleton. starTipUse the allow_output_mutation=True flag to suppress the immutability check. This prevents Streamlit from trying to hash the output connection, and also turns off Streamlit's mutation warning in the process. What if you want to write a function that receives a database connection as input? For that, you'll use hash_funcs: @st.cache(hash_funcs={DBConnection: id}) def get_users(connection): # Note: We assume that connection is of type DBConnection. return connection.execute_sql('SELECT * from Users') Here, we use Python's built-in id function, because the connection object is coming from the Streamlit cache via the get_database_connection function. This means that the same connection instance is passed around every time, and therefore it always has the same id. However, if you happened to have a second connection object around that pointed to an entirely different database, it would still be safe to pass it to get_users because its id is guaranteed to be different than the first id. These design patterns apply any time you have an object that points to an external resource, such as a database connection or Tensorflow session. Example 2: Turn off hashing for a specific type You can turn off hashing entirely for a particular type by giving it a custom hash function that returns a constant. One reason that you might do this is to avoid hashing large, slow-to-hash objects that you know are not going to change. For example: @st.cache(hash_funcs={pd.DataFrame: lambda _: None}) def func(huge_constant_dataframe): ... When Streamlit encounters an object of this type, it always converts the object into None, no matter which instance of FooType its looking at. This means all instances are hash to the same value, which effectively cancels out the hashing mechanism. Example 3: Use Python's hash() function Sometimes, you might want to use Python’s default hashing instead of Streamlit's. For example, maybe you've encountered a type that Streamlit is unable to hash, but it's hashable with Python's built-in hash() function: @st.cache(hash_funcs={FooType: hash}) def func(...): ... Previous: CachingNext: Experimental cache primitivesforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy
https://docs.streamlit.io/develop/api-reference/text/st.text#sttext
DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceremovePAGE ELEMENTSWrite and magicaddText elementsremoveHEADINGS & BODYst.titlest.headerst.subheaderst.markdownFORMATTED TEXTst.captionst.codest.dividerst.echost.latexst.textData elementsaddChart elementsaddInput widgetsaddMedia elementsaddLayouts and containersaddChat elementsaddStatus elementsaddThird-party componentsopen_in_newAPPLICATION LOGICNavigation and pagesaddExecution flowaddCaching and stateaddConnections and secretsaddCustom componentsaddUtilitiesaddConfigurationaddTOOLSApp testingaddCommand lineaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Develop/API reference/Text elements/st.textst.textStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeWrite fixed-width and preformatted text. Function signature[source] st.text(body, *, help=None) Parameters body (str) The string to display. help (str) An optional tooltip that gets displayed next to the text. Example import streamlit as st st.text('This is some text.') Previous: st.latexNext: Data elementsforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy
https://docs.streamlit.io/develop/api-reference/app-testing/testing-element-classes#multiselectset_value
DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceremovePAGE ELEMENTSWrite and magicaddText elementsaddData elementsaddChart elementsaddInput widgetsaddMedia elementsaddLayouts and containersaddChat elementsaddStatus elementsaddThird-party componentsopen_in_newAPPLICATION LOGICNavigation and pagesaddExecution flowaddCaching and stateaddConnections and secretsaddCustom componentsaddUtilitiesaddConfigurationaddTOOLSApp testingremovest.testing.v1.AppTestTesting element classesCommand lineaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Develop/API reference/App testing/Testing element classesTesting element classes st.testing.v1.element_tree.Block The Block class has the same methods and attributes as AppTest. A Block instance represents a container of elements just as AppTest represents the entire app. For example, Block.button will produce a WidgetList of Button in the same manner as AppTest.button. ChatMessage, Column, and Tab all inherit from Block. For all container classes, parameters of the original element can be obtained as properties. For example, ChatMessage.avatar and Tab.label. st.testing.v1.element_tree.ElementStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeElement base class for testing. This class's methods and attributes are universal for all elements implemented in testing. For example, Caption, Code, Text, and Title inherit from Element. All widget classes also inherit from Element, but have additional methods specific to each widget type. See the AppTest class for the full list of supported elements. For all element classes, parameters of the original element can be obtained as properties. For example, Button.label, Caption.help, and Toast.icon. Class description[source] st.testing.v1.element_tree.Element(proto, root) Methods run(*, timeout=None) Run the AppTest script which contains the element. Attributes value The value or contents of the element. st.testing.v1.element_tree.ButtonStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.button and st.form_submit_button. Class description[source] st.testing.v1.element_tree.Button(proto, root) Methods click() Set the value of the button to True. run(*, timeout=None) Run the AppTest script which contains the element. set_value(v) Set the value of the button. Attributes value The value of the button. (bool) st.testing.v1.element_tree.ChatInputStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.chat_input. Class description[source] st.testing.v1.element_tree.ChatInput(proto, root) Methods run(*, timeout=None) Run the AppTest script which contains the element. set_value(v) Set the value of the widget. Attributes value The value of the widget. (str) st.testing.v1.element_tree.CheckboxStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.checkbox. Class description[source] st.testing.v1.element_tree.Checkbox(proto, root) Methods check() Set the value of the widget to True. run(*, timeout=None) Run the AppTest script which contains the element. set_value(v) Set the value of the widget. uncheck() Set the value of the widget to False. Attributes value The value of the widget. (bool) st.testing.v1.element_tree.ColorPickerStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.color_picker. Class description[source] st.testing.v1.element_tree.ColorPicker(proto, root) Methods pick(v) Set the value of the widget as a hex string. May omit the "#" prefix. run(*, timeout=None) Run the AppTest script which contains the element. set_value(v) Set the value of the widget as a hex string. Attributes value The currently selected value as a hex string. (str) st.testing.v1.element_tree.DateInputStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.date_input. Class description[source] st.testing.v1.element_tree.DateInput(proto, root) Methods run(*, timeout=None) Run the AppTest script which contains the element. set_value(v) Set the value of the widget. Attributes value The value of the widget. (date or Tuple of date) st.testing.v1.element_tree.MultiselectStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.multiselect. Class description[source] st.testing.v1.element_tree.Multiselect(proto, root) Methods run(*, timeout=None) Run the AppTest script which contains the element. select(v) Add a selection to the widget. Do nothing if the value is already selected. If testing a multiselect widget with repeated options, use set_value instead. set_value(v) Set the value of the multiselect widget. (list) unselect(v) Remove a selection from the widget. Do nothing if the value is not already selected. If a value is selected multiple times, the first instance is removed. Attributes format_func The widget's formatting function for displaying options. (callable) indices The indices of the currently selected values from the options. (list) value The currently selected values from the options. (list) st.testing.v1.element_tree.NumberInputStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.number_input. Class description[source] st.testing.v1.element_tree.NumberInput(proto, root) Methods decrement() Decrement the st.number_input widget as if the user clicked "-". increment() Increment the st.number_input widget as if the user clicked "+". run(*, timeout=None) Run the AppTest script which contains the element. set_value(v) Set the value of the st.number_input widget. Attributes value Get the current value of the st.number_input widget. st.testing.v1.element_tree.RadioStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.radio. Class description[source] st.testing.v1.element_tree.Radio(proto, root) Methods run(*, timeout=None) Run the AppTest script which contains the element. set_value(v) Set the selection by value. Attributes format_func The widget's formatting function for displaying options. (callable) index The index of the current selection. (int) value The currently selected value from the options. (Any) st.testing.v1.element_tree.SelectSliderStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.select_slider. Class description[source] st.testing.v1.element_tree.SelectSlider(proto, root) Methods run(*, timeout=None) Run the AppTest script which contains the element. set_range(lower, upper) Set the ranged selection by values. set_value(v) Set the (single) selection by value. Attributes format_func The widget's formatting function for displaying options. (callable) value The currently selected value or range. (Any or Sequence of Any) st.testing.v1.element_tree.SelectboxStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.selectbox. Class description[source] st.testing.v1.element_tree.Selectbox(proto, root) Methods run(*, timeout=None) Run the AppTest script which contains the element. select(v) Set the selection by value. select_index(index) Set the selection by index. set_value(v) Set the selection by value. Attributes format_func The widget's formatting function for displaying options. (callable) index The index of the current selection. (int) value The currently selected value from the options. (Any) st.testing.v1.element_tree.SliderStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.slider. Class description[source] st.testing.v1.element_tree.Slider(proto, root) Methods run(*, timeout=None) Run the AppTest script which contains the element. set_range(lower, upper) Set the ranged value of the slider. set_value(v) Set the (single) value of the slider. Attributes value The currently selected value or range. (Any or Sequence of Any) st.testing.v1.element_tree.TextAreaStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.text_area. Class description[source] st.testing.v1.element_tree.TextArea(proto, root) Methods input(v) Set the value of the widget only if the value does not exceed the maximum allowed characters. run(*, timeout=None) Run the AppTest script which contains the element. set_value(v) Set the value of the widget. Attributes value The current value of the widget. (str) st.testing.v1.element_tree.TextInputStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.text_input. Class description[source] st.testing.v1.element_tree.TextInput(proto, root) Methods input(v) Set the value of the widget only if the value does not exceed the maximum allowed characters. run(*, timeout=None) Run the AppTest script which contains the element. set_value(v) Set the value of the widget. Attributes value The current value of the widget. (str) st.testing.v1.element_tree.TimeInputStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.time_input. Class description[source] st.testing.v1.element_tree.TimeInput(proto, root) Methods decrement() Select the previous available time. increment() Select the next available time. run(*, timeout=None) Run the AppTest script which contains the element. set_value(v) Set the value of the widget. Attributes value The current value of the widget. (time) st.testing.v1.element_tree.ToggleStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.toggle. Class description[source] st.testing.v1.element_tree.Toggle(proto, root) Methods run(*, timeout=None) Run the AppTest script which contains the element. set_value(v) Set the value of the widget. Attributes value The current value of the widget. (bool) Previous: st.testing.v1.AppTestNext: Command lineforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy
https://docs.streamlit.io/develop/concepts/custom-components#how-to-use-a-component
DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsremoveCOREArchitecture & executionaddMultipage appsaddApp designaddADDITIONALConnections and secretsaddCustom componentsremoveIntro to custom componentsCreate a ComponentPublish a ComponentLimitationsComponent galleryopen_in_newConfiguration and themingaddApp testingaddAPI referenceaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Develop/Concepts/Custom componentsCustom Components Components are third-party Python modules that extend what's possible with Streamlit. How to use a Component Components are super easy to use: Start by finding the Component you'd like to use. Two great resources for this are: The Component gallery This thread, by Fanilo A. from our forums. Install the Component using your favorite Python package manager. This step and all following steps are described in your component's instructions. For example, to use the fantastic AgGrid Component, you first install it with: pip install streamlit-aggrid In your Python code, import the Component as described in its instructions. For AgGrid, this step is: from st_aggrid import AgGrid ...now you're ready to use it! For AgGrid, that's: AgGrid(my_dataframe) Making your own Component If you're interested in making your own component, check out the following resources: Create a Component Publish a Component Components API Blog post for when we launched Components! Alternatively, if you prefer to learn using videos, our engineer Tim Conkling has put together some amazing tutorials: Video tutorial, part 1 Video tutorial, part 2 Previous: Connections and secretsNext: Intro to custom componentsforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy
https://docs.streamlit.io/develop/tutorials/databases/mssql#write-your-streamlit-app
DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceaddTutorialsremoveExecution flowaddConnect to data sourcesremoveAWS S3BigQueryDeta BaseFirestoreopen_in_newGoogle Cloud StorageMicrosoft SQL ServerMongoDBMySQLNeonPostgreSQLPrivate Google SheetPublic Google SheetSnowflakeSupabaseTableauTiDBTigerGraphMultipage appsaddWork with LLMsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Develop/Tutorials/Connect to data sources/Microsoft SQL ServerConnect Streamlit to Microsoft SQL Server Introduction This guide explains how to securely access a remote Microsoft SQL Server database from Streamlit Community Cloud. It uses the pyodbc library and Streamlit's Secrets management. Create an SQL Server database push_pinNoteIf you already have a remote database that you want to use, feel free to skip to the next step. First, follow the Microsoft documentation to install SQL Server and the sqlcmd Utility. They have detailed installation guides on how to: Install SQL Server on Windows Install on Red Hat Enterprise Linux Install on SUSE Linux Enterprise Server Install on Ubuntu Run on Docker Provision a SQL VM in Azure Once you have SQL Server installed, note down your SQL Server name, username, and password during setup. Connect locally If you are connecting locally, use sqlcmd to connect to your new local SQL Server instance. In your terminal, run the following command: sqlcmd -S localhost -U SA -P '<YourPassword>' As you are connecting locally, the SQL Server name is localhost, the username is SA, and the password is the one you provided during the SA account setup. You should see a sqlcmd command prompt 1>, if successful. If you run into a connection failure, review Microsoft's connection troubleshooting recommendations for your OS (Linux & Windows). starTipWhen connecting remotely, the SQL Server name is the machine name or IP address. You might also need to open the SQL Server TCP port (default 1433) on your firewall. Create a SQL Server database By now, you have SQL Server running and have connected to it with sqlcmd! 🥳 Let's put it to use by creating a database containing a table with some example values. From the sqlcmd command prompt, run the following Transact-SQL command to create a test database mydb: CREATE DATABASE mydb To execute the above command, type GO on a new line: GO Insert some data Next create a new table, mytable, in the mydb database with three columns and two rows. Switch to the new mydb database: USE mydb Create a new table with the following schema: CREATE TABLE mytable (name varchar(80), pet varchar(80)) Insert some data into the table: INSERT INTO mytable VALUES ('Mary', 'dog'), ('John', 'cat'), ('Robert', 'bird') Type GO to execute the above commands: GO To end your sqlcmd session, type QUIT on a new line. Add username and password to your local app secrets Your local Streamlit app will read secrets from a file .streamlit/secrets.toml in your app's root directory. Create this file if it doesn't exist yet and add the SQL Server name, database name, username, and password as shown below: # .streamlit/secrets.toml server = "localhost" database = "mydb" username = "SA" password = "xxx" priority_highImportantWhen copying your app secrets to Streamlit Community Cloud, be sure to replace the values of server, database, username, and password with those of your remote SQL Server!And add this file to .gitignore and don't commit it to your GitHub repo. Copy your app secrets to Streamlit Community Cloud As the secrets.toml file above is not committed to GitHub, you need to pass its content to your deployed app (on Streamlit Community Cloud) separately. Go to the app dashboard and in the app's dropdown menu, click on Edit Secrets. Copy the content of secrets.toml into the text area. More information is available at Secrets management. Add pyodbc to your requirements file To connect to SQL Server locally with Streamlit, you need to pip install pyodbc, in addition to the Microsoft ODBC driver you installed during the SQL Server installation. On Streamlit Cloud, we have built-in support for SQL Server. On popular demand, we directly added SQL Server tools including the ODBC drivers and the executables sqlcmd and bcp to the container image for Cloud apps, so you don't need to install them. All you need to do is add the pyodbc Python package to your requirements.txt file, and you're ready to go! 🎈 # requirements.txt pyodbc==x.x.x Replace x.x.x ☝️ with the version of pyodbc you want installed on Cloud. push_pinNoteAt this time, Streamlit Community Cloud does not support Azure Active Directory authentication. We will update this tutorial when we add support for Azure Active Directory. Write your Streamlit app Copy the code below to your Streamlit app and run it. Make sure to adapt query to use the name of your table. import streamlit as st import pyodbc # Initialize connection. # Uses st.cache_resource to only run once. @st.cache_resource def init_connection(): return pyodbc.connect( "DRIVER={ODBC Driver 17 for SQL Server};SERVER=" + st.secrets["server"] + ";DATABASE=" + st.secrets["database"] + ";UID=" + st.secrets["username"] + ";PWD=" + st.secrets["password"] ) conn = init_connection() # Perform query. # Uses st.cache_data to only rerun when the query changes or after 10 min. @st.cache_data(ttl=600) def run_query(query): with conn.cursor() as cur: cur.execute(query) return cur.fetchall() rows = run_query("SELECT * from mytable;") # Print results. for row in rows: st.write(f"{row[0]} has a :{row[1]}:") See st.cache_data above? Without it, Streamlit would run the query every time the app reruns (e.g. on a widget interaction). With st.cache_data, it only runs when the query changes or after 10 minutes (that's what ttl is for). Watch out: If your database updates more frequently, you should adapt ttl or remove caching so viewers always see the latest data. Learn more in Caching. If everything worked out (and you used the example table we created above), your app should look like this: Previous: Google Cloud StorageNext: MongoDBforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy
https://docs.streamlit.io/knowledge-base/using-streamlit/pydeck-chart-custom-mapbox-styles#how-can-i-make-stpydeck_chart-use-custom-mapbox-styles
DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Knowledge base/FAQ/How can I make st.pydeck_chart use custom Mapbox styles?How can I make st.pydeck_chart use custom Mapbox styles? If you are supplying a Mapbox token, but the resulting pydeck_chart doesn't show your custom Mapbox styles, please check that you are adding the Mapbox token to the Streamlit config.toml configuration file. Streamlit DOES NOT read Mapbox tokens from inside of a PyDeck specification (i.e. from inside of the Streamlit app). Please see this forum thread for more information.Previous: How to insert elements out of order?Next: How to remove "· Streamlit" from the app title?forumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy
https://docs.streamlit.io/develop/concepts/connections/connecting-to-data#a-simple-starting-point---using-a-local-sqlite-database
DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsremoveCOREArchitecture & executionaddMultipage appsaddApp designaddADDITIONALConnections and secretsremoveConnecting to dataSecrets managementSecurity remindersCustom componentsaddConfiguration and themingaddApp testingaddAPI referenceaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Develop/Concepts/Connections and secrets/Connecting to dataConnecting to data Most Streamlit apps need some kind of data or API access to be useful - either retrieving data to view or saving the results of some user action. This data or API is often part of some remote service, database, or other data source. Anything you can do with Python, including data connections, will generally work in Streamlit. Streamlit's tutorials are a great starting place for many data sources. However: Connecting to data in a Python application is often tedious and annoying. There are specific considerations for connecting to data from streamlit apps, such as caching and secrets management. Streamlit provides st.connection() to more easily connect your Streamlit apps to data and APIs with just a few lines of code. This page provides a basic example of using the feature and then focuses on advanced usage. For a comprehensive overview of this feature, check out this video tutorial by Joshua Carroll, Streamlit's Product Manager for Developer Experience. You'll learn about the feature's utility in creating and managing data connections within your apps by using real-world examples. Basic usage For basic startup and usage examples, read up on the relevant data source tutorial. Streamlit has built-in connections to SQL dialects and Snowflake. We also maintain installable connections for Cloud File Storage and Google Sheets. If you are just starting, the best way to learn is to pick a data source you can access and get a minimal example working from one of the pages above 👆. Here, we will provide an ultra-minimal usage example for using a SQLite database. From there, the rest of this page will focus on advanced usage. A simple starting point - using a local SQLite database A local SQLite database could be useful for your app's semi-persistent data storage. push_pinNoteCommunity Cloud apps do not guarantee the persistence of local file storage, so the platform may delete data stored using this technique at any time. To see the example below running live, check out the interactive demo below: Built with Streamlit 🎈Fullscreen open_in_new Step 1: Install prerequisite library - SQLAlchemy All SQLConnections in Streamlit use SQLAlchemy. For most other SQL dialects, you also need to install the driver. But the SQLite driver ships with python3, so it isn't necessary. pip install SQLAlchemy==1.4.0 Step 2: Set a database URL in your Streamlit secrets.toml file Create a directory and file .streamlit/secrets.toml in the same directory your app will run from. Add the following to the file. # .streamlit/secrets.toml [connections.pets_db] url = "sqlite:///pets.db" Step 3: Use the connection in your app The following app creates a connection to the database, uses it to create a table and insert some data, then queries the data back and displays it in a data frame. # streamlit_app.py import streamlit as st # Create the SQL connection to pets_db as specified in your secrets file. conn = st.connection('pets_db', type='sql') # Insert some data with conn.session. with conn.session as s: s.execute('CREATE TABLE IF NOT EXISTS pet_owners (person TEXT, pet TEXT);') s.execute('DELETE FROM pet_owners;') pet_owners = {'jerry': 'fish', 'barbara': 'cat', 'alex': 'puppy'} for k in pet_owners: s.execute( 'INSERT INTO pet_owners (person, pet) VALUES (:owner, :pet);', params=dict(owner=k, pet=pet_owners[k]) ) s.commit() # Query and display the data you inserted pet_owners = conn.query('select * from pet_owners') st.dataframe(pet_owners) In this example, we didn't set a ttl= value on the call to conn.query(), meaning Streamlit caches the result indefinitely as long as the app server runs. Now, on to more advanced topics! 🚀 Advanced topics Global secrets, managing multiple apps and multiple data stores Streamlit supports a global secrets file specified in the user's home directory, such as ~/.streamlit/secrets.toml. If you build or manage multiple apps, we recommend using a global credential or secret file for local development across apps. With this approach, you only need to set up and manage your credentials in one place, and connecting a new app to your existing data sources is effectively a one-liner. It also reduces the risk of accidentally checking in your credentials to git since they don't need to exist in the project repository. For cases where you have multiple similar data sources that you connect to during local development (such as a local vs. staging database), you can define different connection sections in your secrets or credentials file for different environments and then decide which to use at runtime. st.connection supports this with the name=env:<MY_NAME_VARIABLE> syntax. E.g., say I have a local and a staging MySQL database and want to connect my app to either at different times. I could create a global secrets file like this: # ~/.streamlit/secrets.toml [connections.local] url = "mysql://me:****@localhost:3306/local_db" [connections.staging] url = "mysql://jdoe:******@staging.acmecorp.com:3306/staging_db" Then I can configure my app connection to take its name from a specified environment variable # streamlit_app.py import streamlit as st conn = st.connection("env:DB_CONN", "sql") df = conn.query("select * from mytable") # ... Now I can specify whether to connect to local or staging at runtime by setting the DB_CONN environment variable. # connect to local DB_CONN=local streamlit run streamlit_app.py # connect to staging DB_CONN=staging streamlit run streamlit_app.py Advanced SQLConnection configuration The SQLConnection configuration uses SQLAlchemy create_engine() function. It will take a single URL argument or attempt to construct a URL from several parts (username, database, host, and so on) using SQLAlchemy.engine.URL.create(). Several popular SQLAlchemy dialects, such as Snowflake and Google BigQuery, can be configured using additional arguments to create_engine() besides the URL. These can be passed as **kwargs to the st.connection call directly or specified in an additional secrets section called create_engine_kwargs. E.g. snowflake-sqlalchemy takes an additional connect_args argument as a dictionary for configuration that isn’t supported in the URL. These could be specified as follows: # .streamlit/secrets.toml [connections.snowflake] url = "snowflake://<user_login_name>@<account_identifier>/" [connections.snowflake.create_engine_kwargs.connect_args] authenticator = "externalbrowser" warehouse = "xxx" role = "xxx" # streamlit_app.py import streamlit as st # url and connect_args from secrets.toml above are picked up and used here conn = st.connection("snowflake", "sql") # ... Alternatively, this could be specified entirely in **kwargs. # streamlit_app.py import streamlit as st # secrets.toml is not needed conn = st.connection( "snowflake", "sql", url = "snowflake://<user_login_name>@<account_identifier>/", connect_args = dict( authenticator = "externalbrowser", warehouse = "xxx", role = "xxx", ) ) # ... You can also provide both kwargs and secrets.toml values, and they will be merged (typically, kwargs take precedence). Connection considerations in frequently used or long-running apps By default, connection objects are cached without expiration using st.cache_resource. In most cases this is desired. You can do st.connection('myconn', type=MyConnection, ttl=<N>) if you want the connection object to expire after some time. Many connection types are expected to be long-running or completely stateless, so expiration is unnecessary. Suppose a connection becomes stale (such as a cached token expiring or a server-side connection being closed). In that case, every connection has a reset() method, which will invalidate the cached version and cause Streamlit to recreate the connection the next time it is retrieved Convenience methods like query() and read() will typically cache results by default using st.cache_data without an expiration. When an app can run many different read operations with large results, it can cause high memory usage over time and results to become stale in a long-running app, the same as with any other usage of st.cache_data. For production use cases, we recommend setting an appropriate ttl on these read operations, such as conn.read('path/to/file', ttl="1d"). Refer to Caching for more information. For apps that could get significant concurrent usage, ensure that you understand any thread safety implications of your connection, particularly when using a connection built by a third party. Connections built by Streamlit should provide thread-safe operations by default. Build your own connection Building your own basic connection implementation using an existing driver or SDK is quite straightforward in most cases. However, you can add more complex functionality with further effort. This custom implementation can be a great way to extend support to a new data source and contribute to the Streamlit ecosystem. Maintaining a tailored internal Connection implementation across many apps can be a powerful practice for organizations with frequently used access patterns and data sources. Check out the Build your own Connection page in the st.experimental connection demo app below for a quick tutorial and working implementation. This demo builds a minimal but very functional Connection on top of DuckDB. Built with Streamlit 🎈Fullscreen open_in_new The typical steps are: Declare the Connection class, extending ExperimentalBaseConnection with the type parameter bound to the underlying connection object: from streamlit.connections import ExperimentalBaseConnection import duckdb class DuckDBConnection(ExperimentalBaseConnection[duckdb.DuckDBPyConnection]) Implement the _connect method that reads any kwargs, external config/credential locations, and Streamlit secrets to initialize the underlying connection: def _connect(self, **kwargs) -> duckdb.DuckDBPyConnection: if 'database' in kwargs: db = kwargs.pop('database') else: db = self._secrets['database'] return duckdb.connect(database=db, **kwargs) Add useful helper methods that make sense for your connection (wrapping them in st.cache_data where caching is desired) Connection-building best practices We recommend applying the following best practices to make your Connection consistent with the Connections built into Streamlit and the wider Streamlit ecosystem. These practices are especially important for Connections that you intend to distribute publicly. Extend existing drivers or SDKs, and default to semantics that makes sense for their existing users. You should rarely need to implement complex data access logic from scratch when building a Connection. Use existing popular Python drivers and clients whenever possible. Doing so makes your Connection easier to maintain, more secure, and enables users to get the latest features. E.g. SQLConnection extends SQLAlchemy, FileConnection extends fsspec, GsheetsConnection extends gspread, etc. Consider using access patterns, method/argument naming, and return values that are consistent with the underlying package and familiar to existing users of that package. Intuitive, easy to use read methods. Much of the power of st.connection is providing intuitive, easy-to-use read methods that enable app developers to get started quickly. Most connections should expose at least one read method that is: Named with a simple verb, like read(), query(), or get() Wrapped by st.cache_data by default, with at least ttl= argument supported If the result is in a tabular format, it returns a pandas DataFrame Provides commonly used keyword arguments (such as paging or formatting) with sensible defaults - ideally, the common case requires only 1-2 arguments. Config, secrets, and precedence in _connect method. Every Connection should support commonly used connection parameters provided via Streamlit secrets and keyword arguments. The names should match the ones used when initializing or configuring the underlying package. Additionally, where relevant, Connections should support data source specific configuration through existing standard environment variables or config / credential files. In many cases, the underlying package provides constructors or factory functions that already handle this easily. When you can specify the same connection parameters in multiple places, we recommend using the following precedence order when possible (highest to lowest): Keyword arguments specified in the code Streamlit secrets data source specific configuration (if relevant) Handling thread safety and stale connections. Connections should provide thread-safe operations when practical (which should be most of the time) and clearly document any considerations around this. Most underlying drivers or SDKs should provide thread-safe objects or methods - use these when possible. If the underlying driver or SDK has a risk of stateful connection objects becoming stale or invalid, consider building a low impact health check or reset/retry pattern into the access methods. The SQLConnection built into Streamlit has a good example of this pattern using tenacity and the built-in Connection.reset() method. An alternate approach is to encourage developers to set an appropriate TTL on the st.connection() call to ensure it periodically reinitializes the connection object. Previous: Connections and secretsNext: Secrets managementforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy
https://docs.streamlit.io/develop/tutorials/databases/snowflake#connecting-to-snowflake-from-community-cloud
DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceaddTutorialsremoveExecution flowaddConnect to data sourcesremoveAWS S3BigQueryDeta BaseFirestoreopen_in_newGoogle Cloud StorageMicrosoft SQL ServerMongoDBMySQLNeonPostgreSQLPrivate Google SheetPublic Google SheetSnowflakeSupabaseTableauTiDBTigerGraphMultipage appsaddWork with LLMsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Develop/Tutorials/Connect to data sources/SnowflakeConnect Streamlit to Snowflake Introduction This guide explains how to securely access a Snowflake database from Streamlit. It uses st.connection, the Snowpark library and Streamlit's Secrets management. The below example code will only work on Streamlit version >= 1.28, when st.connection was added. Create a Snowflake database push_pinNoteIf you already have a database that you want to use, feel free to skip to the next step. First, sign up for Snowflake and log into the Snowflake web interface (note down your username, password, and account identifier!): Enter the following queries into the SQL editor in the Worksheets page to create a database and a table with some example values: CREATE DATABASE PETS; CREATE TABLE MYTABLE ( NAME varchar(80), PET varchar(80) ); INSERT INTO MYTABLE VALUES ('Mary', 'dog'), ('John', 'cat'), ('Robert', 'bird'); SELECT * FROM MYTABLE; Before you execute the queries, first determine which Snowflake UI / web interface you're using. The examples below use Snowsight. You can also use Classic Console Worksheets or any other means of running Snowflake SQL statements. Execute queries in a Worksheet To execute the queries in a Worksheet, highlight or select all the queries with your mouse, and click the play button in the top right corner. priority_highImportantBe sure to highlight or select all the queries (lines 1-10) before clicking the play button. Once you have executed the queries, you should see a preview of the table in the Results panel at the bottom of the page. Additionally, you should see your newly created database and schema by expanding the accordion on the left side of the page. Lastly, the warehouse name is displayed on the button to the left of the Share button. Make sure to note down the name of your warehouse, database, and schema. ☝️ Install snowflake-snowpark-python You can find the instructions and prerequisites for installing snowflake-snowpark-python in the Snowflake Developer Guide. pip install snowflake-snowpark-python Add connection parameters to your local app secrets Your local Streamlit app will read secrets from a file .streamlit/secrets.toml in your app’s root directory. Learn more about Streamlit secrets management here. Create this file if it doesn’t exist yet and add your Snowflake username, password, account identifier, and the name of your warehouse, database, and schema as shown below: # .streamlit/secrets.toml [connections.snowflake] account = "xxx" user = "xxx" password = "xxx" role = "xxx" warehouse = "xxx" database = "xxx" schema = "xxx" client_session_keep_alive = true If you created the database from the previous step, the names of your database and schema are PETS and PUBLIC, respectively. Streamlit will also use Snowflake config and credentials from a SnowSQL config file if available. priority_highImportantAdd this file to .gitignore and don't commit it to your GitHub repo! Write your Streamlit app Copy the code below to your Streamlit app and run it. Make sure to adapt the query to use the name of your table. # streamlit_app.py import streamlit as st # Initialize connection. conn = st.connection("snowflake") # Perform query. df = conn.query("SELECT * from mytable;", ttl=600) # Print results. for row in df.itertuples(): st.write(f"{row.NAME} has a :{row.PET}:") See st.connection above? This handles secrets retrieval, setup, query caching and retries. By default, query() results are cached without expiring. In this case, we set ttl=600 to ensure the query result is cached for no longer than 10 minutes. You can also set ttl=0 to disable caching. Learn more in Caching. If everything worked out (and you used the example table we created above), your app should look like this: Using a Snowpark Session The same SnowflakeConnection used above also provides access to the Snowpark Session for DataFrame-style operations that run natively inside Snowflake. Using this approach, you can rewrite the app above as follows: # streamlit_app.py import streamlit as st # Initialize connection. conn = st.connection("snowflake") # Load the table as a dataframe using the Snowpark Session. @st.cache_data def load_table(): session = conn.session() return session.table("mytable").to_pandas() df = load_table() # Print results. for row in df.itertuples(): st.write(f"{row.NAME} has a :{row.PET}:") If everything worked out (and you used the example table we created above), your app should look the same as the screenshot from the first example above. Connecting to Snowflake from Community Cloud This tutorial assumes a local Streamlit app, however you can also connect to Snowflake from apps hosted in Community Cloud. The main additional steps are: Include information about dependencies using a requirements.txt file with snowflake-snowpark-python and any other dependencies. Add your secrets to your Community Cloud app. Previous: Public Google SheetNext: SupabaseforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy
https://docs.streamlit.io/deploy/streamlit-community-cloud/get-started/explore-your-workspace
DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudremoveGet startedremoveQuickstartCreate your accountConnect your GitHub accountExplore your workspaceFork and edit a public appTrust and securityDeploy your appaddManage your appaddShare your appaddManage your accountaddTroubleshootingStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Deploy/Streamlit Community Cloud/Get started/Explore your workspaceExplore your workspace If you just created your account, congrats! You are now logged in and ready to go. If you are joining someone else's workspace you may already see apps populated in your workspace. If not, then you need to deploy an app! Check out our next section on how to Deploy your app. If you need an app to deploy, check out our App gallery which includes apps for machine learning, data science, and business use cases. Switching workspaces You may also find that you already have access to multiple Streamlit Community Cloud workspaces. Streamlit Community Cloud automatically groups your apps according to the corresponding GitHub repository's owner or organzation. In the upper-right corner you can see the workspaces you have access to. If apps have already been deployed from any of your repositories, then you will see those apps when you select the associated workspace in the upper-right corner. Learn more about how to Manage your app from your workspace. New app button Your workspace is your base of operations to deploy apps and manage them. You can click on "New app" to Deploy your app from a repository where you have administrative privileges. If you want additional options, click the down arrow (expand_more) to begin with a template. "Use existing repo" is the default to Deploy your app from a repository where you have administrative privileges. "Create from sample app template" will fork and deploy a simple, one-page Streamlit app. "Create new app with GitHub Codespaces" will fork and deploy our multipage Streamlit Hello app and create a codespace. To jump quickly into GitHub Codespaces for any of your deployed apps, see Edit your app with GitHub Codespaces instead. Invite other developers to your workspace Inviting other developers is simple, just invite them to your GitHub repository so that you can code on apps together, and then have them log in to share.streamlit.io/signup. Read more about connecting to a GitHub organization in Organization access. Streamlit Community Cloud inherits developer permissions from GitHub so when others sign in, they will automatically see the workspaces they share with you. From there you can all deploy, manage, and share apps together. push_pinNoteOnce a user is added to a repository on GitHub, it will take at most 15 minutes before they can deploy the app on Cloud. If a user is removed from a repository on GitHub, it will take at most 15 minutes before their permissions to manage the app from that repository are revoked. And remember, whenever anyone on the team updates the code on GitHub, the app will also automatically update for you!Previous: Connect your GitHub accountNext: Fork and edit a public appforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy
https://docs.streamlit.io/develop/api-reference/status/st.status
DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceremovePAGE ELEMENTSWrite and magicaddText elementsaddData elementsaddChart elementsaddInput widgetsaddMedia elementsaddLayouts and containersaddChat elementsaddStatus elementsremoveCALLOUTSst.successst.infost.warningst.errorst.exceptionOTHERst.progressst.spinnerst.statusst.toastst.balloonsst.snowThird-party componentsopen_in_newAPPLICATION LOGICNavigation and pagesaddExecution flowaddCaching and stateaddConnections and secretsaddCustom componentsaddUtilitiesaddConfigurationaddTOOLSApp testingaddCommand lineaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Develop/API reference/Status elements/st.statusst.statusStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeInsert a status container to display output from long-running tasks. Inserts a container into your app that is typically used to show the status and details of a process or task. The container can hold multiple elements and can be expanded or collapsed by the user similar to st.expander. When collapsed, all that is visible is the status icon and label. The label, state, and expanded state can all be updated by calling .update() on the returned object. To add elements to the returned container, you can use with notation (preferred) or just call methods directly on the returned object. By default, st.status() initializes in the "running" state. When called using with notation, it automatically updates to the "complete" state at the end of the "with" block. See examples below for more details. Function signature[source] st.status(label, *, expanded=False, state="running") Parameters label (str) The initial label of the status container. The label can optionally contain Markdown and supports the following elements: Bold, Italics, Strikethroughs, Inline Code, Emojis, and Links. This also supports: Emoji shortcodes, such as :+1: and :sunglasses:. For a list of all supported codes, see https://share.streamlit.io/streamlit/emoji-shortcodes. LaTeX expressions, by wrapping them in "$" or "$$" (the "$$" must be on their own lines). Supported LaTeX functions are listed at https://katex.org/docs/supported.html. Colored text and background colors for text, using the syntax :color[text to be colored] and :color-background[text to be colored], respectively. color must be replaced with any of the following supported colors: blue, green, orange, red, violet, gray/grey, rainbow. For example, you can use :orange[your text here] or :blue-background[your text here]. Unsupported elements are unwrapped so only their children (text contents) render. Display unsupported elements as literal characters by backslash-escaping them. E.g. 1\. Not an ordered list. expanded (bool) If True, initializes the status container in "expanded" state. Defaults to False (collapsed). state ("running", "complete", or "error") The initial state of the status container which determines which icon is shown: running (default): A spinner icon is shown. complete: A checkmark icon is shown. error: An error icon is shown. Returns(StatusContainer) A mutable status container that can hold multiple elements. The label, state, and expanded state can be updated after creation via .update(). Examples You can use the with notation to insert any element into an status container: import time import streamlit as st with st.status("Downloading data..."): st.write("Searching for data...") time.sleep(2) st.write("Found URL.") time.sleep(1) st.write("Downloading data...") time.sleep(1) st.button("Rerun") Built with Streamlit 🎈Fullscreen open_in_new You can also use .update() on the container to change the label, state, or expanded state: import time import streamlit as st with st.status("Downloading data...", expanded=True) as status: st.write("Searching for data...") time.sleep(2) st.write("Found URL.") time.sleep(1) st.write("Downloading data...") time.sleep(1) status.update(label="Download complete!", state="complete", expanded=False) st.button("Rerun") Built with Streamlit 🎈Fullscreen open_in_new StatusContainer.updateStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeUpdate the status container. Only specified arguments are updated. Container contents and unspecified arguments remain unchanged. Function signature[source] StatusContainer.update(*, label=None, expanded=None, state=None) Parameters label (str or None) A new label of the status container. If None, the label is not changed. expanded (bool or None) The new expanded state of the status container. If None, the expanded state is not changed. state ("running", "complete", "error", or None) The new state of the status container. This mainly changes the icon. If None, the state is not changed. Previous: st.spinnerNext: st.toastforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy
https://docs.streamlit.io/develop/tutorials/execution-flow/start-and-stop-fragment-auto-reruns#summary
DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceaddTutorialsremoveExecution flowremoveFRAGMENTSRerun your app from a fragmentCreate a multiple-container fragmentStart and stop a streaming fragmentConnect to data sourcesaddMultipage appsaddWork with LLMsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Develop/Tutorials/Execution flow/Start and stop a streaming fragmentStart and stop a streaming fragment Streamlit lets you turn functions into fragments, which can rerun independently from the full script. Additionally, you can tell Streamlit to rerun a fragment at a set time interval. This is great for streaming data or monitoring processes. You may want the user to start and stop this live streaming. To do this, programmatically set the run_every parameter for your fragment. Applied concepts Use a fragment to stream live data. Start and stop a fragment from automatically rerunning. Prerequisites streamlit>=1.33.0 This tutorial uses fragments, which require Streamlit version 1.33.0 or later. This tutorial assumes you have a clean working directory called your-repository. You should have a basic understanding of fragments. Summary In this example, you'll build an app that streams two data series in a line chart. Your app will gather recent data on the first load of a session and statically display the line chart. Two buttons in the sidebar will allow users to start and stop data streaming to update the chart in real time. You'll use a fragment to manage the frequency and scope of the live updates. Here's a look at what you'll build: Complete codeexpand_moreimport streamlit as st import pandas as pd import numpy as np from datetime import datetime, timedelta def get_recent_data(last_timestamp): """Generate and return data from last timestamp to now, at most 60 seconds.""" now = datetime.now() if now - last_timestamp > timedelta(seconds=60): last_timestamp = now - timedelta(seconds=60) sample_time = timedelta(seconds=0.5) # time between data points next_timestamp = last_timestamp + sample_time timestamps = np.arange(next_timestamp, now, sample_time) sample_values = np.random.randn(len(timestamps), 2) data = pd.DataFrame(sample_values, index=timestamps, columns=["A", "B"]) return data if "data" not in st.session_state: st.session_state.data = get_recent_data(datetime.now() - timedelta(seconds=60)) if "stream" not in st.session_state: st.session_state.stream = False def toggle_streaming(): st.session_state.stream = not st.session_state.stream st.title("Data feed") st.sidebar.slider( "Check for updates every: (seconds)", 0.5, 5.0, value=1.0, key="run_every" ) st.sidebar.button( "Start streaming", disabled=st.session_state.stream, on_click=toggle_streaming ) st.sidebar.button( "Stop streaming", disabled=not st.session_state.stream, on_click=toggle_streaming ) if st.session_state.stream is True: run_every = st.session_state.run_every else: run_every = None @st.experimental_fragment(run_every=run_every) def show_latest_data(): last_timestamp = st.session_state.data.index[-1] st.session_state.data = pd.concat( [st.session_state.data, get_recent_data(last_timestamp)] ) st.session_state.data = st.session_state.data[-100:] st.line_chart(st.session_state.data) show_latest_data() Built with Streamlit 🎈Fullscreen open_in_new Build the example Initialize your app In your_repository, create a file named app.py. In a terminal, change directories to your_repository and start your app. streamlit run app.py Your app will be blank since you still need to add code. In app.py, write the following: import streamlit as st import pandas as pd import numpy as np from datetime import datetime, timedelta You'll be using these libraries as follows: You'll work with two data series in a pandas.DataFrame. You'll generate random data with numpy. The data will have datetime.datetime index values. Save your app.py file and view your running app. Click "Always rerun" or hit your "A" key in your running app. Your running preview will automatically update as you save changes to app.py. Your preview will still be blank. Return to your code. Build a function to generate random, recent data To begin with, you'll define a function to randomly generate some data for two time series, which you'll call "A" and "B." It's okay to skip this section if you just want to copy the function. Complete function to randomly generate sales dataexpand_moredef get_recent_data(last_timestamp): """Generate and return data from last timestamp to now, at most 60 seconds.""" now = datetime.now() if now - last_timestamp > timedelta(seconds=60): last_timestamp = now - timedelta(seconds=60) sample_time = timedelta(seconds=0.5) # time between data points next_timestamp = last_timestamp + sample_time timestamps = np.arange(next_timestamp, now, sample_time) sample_values = np.random.randn(len(timestamps), 2) data = pd.DataFrame(sample_values, index=timestamps, columns=["A", "B"]) return data Start your function definition. def get_recent_data(last_timestamp): """Generate and return data from last timestamp to now, at most 60 seconds.""" You'll pass the timestamp of your most recent datapoint to your data-generating function. Your function will use this to only return new data. Get the current time and adjust the last timestamp if it is over 60 seconds ago. now = datetime.now() if now - last_timestamp > timedelta(seconds=60): last_timestamp = now - timedelta(seconds=60) By updating the last timestamp, you'll ensure the function never returns more than 60 seconds of data. Declare a new variable, sample_time, to define the time between datapoints. Calculate the timestamp of the first, new datapoint. sample_time = timedelta(seconds=0.5) # time between data points next_timestamp = last_timestamp + sample_time Create a datetime.datetime index and generate two data series of the same length. timestamps = np.arange(next_timestamp, now, sample_time) sample_values = np.random.randn(len(timestamps), 2) Combine the data series with the index into a pandas.DataFrame and return the data. data = pd.DataFrame(sample_values, index=timestamps, columns=["A", "B"]) return data (Optional) Test out your function by calling it and displaying the data. data = get_recent_data(datetime.now() - timedelta(seconds=60)) data Save your app.py file to see the preview. Delete these two lines when finished. Initialize Session State values for your app Since you will dynamically change the run_every parameter of @st.experimental_fragment(), you'll need to initialize the associated variables and Session State values before defining your fragment function. Your fragment function will also read and update values in Session State, so you can define those now to make the fragment function easier to understand. Initialize your data for the first app load in a session. if "data" not in st.session_state: st.session_state.data = get_recent_data(datetime.now() - timedelta(seconds=60)) Your app will display this initial data in a static line chart before a user starts streaming data. Initialize "stream" in Session State to turn streaming on and off. Set the default to off (False). if "stream" not in st.session_state: st.session_state.stream = False Create a callback function to toggle "stream" between True and False. def toggle_streaming(): st.session_state.stream = not st.session_state.stream Add a title to your app. st.title("Data feed") Add a slider to the sidebar to set how frequently to check for data while streaming. st.sidebar.slider( "Check for updates every: (seconds)", 0.5, 5.0, value=1.0, key="run_every" ) Add buttons to the sidebar to turn streaming on and off. st.sidebar.button( "Start streaming", disabled=st.session_state.stream, on_click=toggle_streaming ) st.sidebar.button( "Stop streaming", disabled=not st.session_state.stream, on_click=toggle_streaming ) Both functions use the same callback to toggle "stream" in Session State. Use the current value "stream" to disable one of the buttons. This ensures the buttons are always consistent with the current state; "Start streaming" is only clickable when streaming is off, and "Stop streaming" is only clickable when streaming is on. The buttons also provide status to the user by highlighting which action is available to them. Create and set a new variable, run_every, that will determine whether or not the fragment function will rerun automatically (and how fast). if st.session_state.stream is True: run_every = st.session_state.run_every else: run_every = None Build a fragment function to stream data To allow the user to turn data streaming on and off, you must set the run_every parameter in the @st.experimental_fragment() decorator. Complete function to show and stream dataexpand_more@st.experimental_fragment(run_every=run_every) def show_latest_data(): last_timestamp = st.session_state.data.index[-1] st.session_state.data = pd.concat( [st.session_state.data, get_recent_data(last_timestamp)] ) st.session_state.data = st.session_state.data[-100:] st.line_chart(st.session_state.data) Use an @st.experimental_fragment decorator and start your function definition. @st.experimental_fragment(run_every=run_every) def show_latest_data(): Use the run_every variable declared above to set the parameter of the same name. Retrieve the timestamp of the last datapoint in Session State. last_timestamp = st.session_state.data.index[-1] Update the data in Session State and trim to keep only the last 100 timestamps. st.session_state.data = pd.concat( [st.session_state.data, get_recent_data(last_timestamp)] ) st.session_state.data = st.session_state.data[-100:] Show the data in a line chart. st.line_chart(st.session_state.data) Your fragment-function definition is complete. Call and test out your fragment function Call your function at the bottom of your code. show_latest_data() Test out your app by clicking "Start streaming." Try adjusting the frequency of updates. Next steps Try adjusting the frequency of data generation or how much data is kept in Session State. Within get_recent_data try setting sample_time with a widget. Try using st.plotly_chart or st.altair_chart to add labels to your chart.Previous: Create a multiple-container fragmentNext: Connect to data sourcesforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy
https://docs.streamlit.io/develop/tutorials/databases/mongodb#add-username-and-password-to-your-local-app-secrets
DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceaddTutorialsremoveExecution flowaddConnect to data sourcesremoveAWS S3BigQueryDeta BaseFirestoreopen_in_newGoogle Cloud StorageMicrosoft SQL ServerMongoDBMySQLNeonPostgreSQLPrivate Google SheetPublic Google SheetSnowflakeSupabaseTableauTiDBTigerGraphMultipage appsaddWork with LLMsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Develop/Tutorials/Connect to data sources/MongoDBConnect Streamlit to MongoDB Introduction This guide explains how to securely access a remote MongoDB database from Streamlit Community Cloud. It uses the PyMongo library and Streamlit's Secrets management. Create a MongoDB Database push_pinNoteIf you already have a database that you want to use, feel free to skip to the next step. First, follow the official tutorials to install MongoDB, set up authentication (note down the username and password!), and connect to the MongoDB instance. Once you are connected, open the mongo shell and enter the following two commands to create a collection with some example values: use mydb db.mycollection.insertMany([{"name" : "Mary", "pet": "dog"}, {"name" : "John", "pet": "cat"}, {"name" : "Robert", "pet": "bird"}]) Add username and password to your local app secrets Your local Streamlit app will read secrets from a file .streamlit/secrets.toml in your app's root directory. Create this file if it doesn't exist yet and add the database information as shown below: # .streamlit/secrets.toml [mongo] host = "localhost" port = 27017 username = "xxx" password = "xxx" priority_highImportantWhen copying your app secrets to Streamlit Community Cloud, be sure to replace the values of host, port, username, and password with those of your remote MongoDB database!Add this file to .gitignore and don't commit it to your GitHub repo! Copy your app secrets to the cloud As the secrets.toml file above is not committed to GitHub, you need to pass its content to your deployed app (on Streamlit Community Cloud) separately. Go to the app dashboard and in the app's dropdown menu, click on Edit Secrets. Copy the content of secrets.toml into the text area. More information is available at Secrets management. Add PyMongo to your requirements file Add the PyMongo package to your requirements.txt file, preferably pinning its version (replace x.x.x with the version you want installed): # requirements.txt pymongo==x.x.x Write your Streamlit app Copy the code below to your Streamlit app and run it. Make sure to adapt the name of your database and collection. # streamlit_app.py import streamlit as st import pymongo # Initialize connection. # Uses st.cache_resource to only run once. @st.cache_resource def init_connection(): return pymongo.MongoClient(**st.secrets["mongo"]) client = init_connection() # Pull data from the collection. # Uses st.cache_data to only rerun when the query changes or after 10 min. @st.cache_data(ttl=600) def get_data(): db = client.mydb items = db.mycollection.find() items = list(items) # make hashable for st.cache_data return items items = get_data() # Print results. for item in items: st.write(f"{item['name']} has a :{item['pet']}:") See st.cache_data above? Without it, Streamlit would run the query every time the app reruns (e.g. on a widget interaction). With st.cache_data, it only runs when the query changes or after 10 minutes (that's what ttl is for). Watch out: If your database updates more frequently, you should adapt ttl or remove caching so viewers always see the latest data. Learn more in Caching. If everything worked out (and you used the example data we created above), your app should look like this: Previous: Microsoft SQL ServerNext: MySQLforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy
https://docs.streamlit.io/develop/quick-reference/cheat-sheet#connect-to-data-sources
DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceaddTutorialsaddQuick referenceremoveCheat sheetRelease notesPre-release featuresRoadmapopen_in_newweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Develop/Quick reference/Cheat sheetStreamlit API cheat sheet This is a summary of the docs, as of Streamlit v1.34.0. Install & Importpip install streamlit streamlit run first_app.py # Import convention >>> import streamlit as st Pre-release featurespip uninstall streamlit pip install streamlit-nightly --upgrade Learn more about experimental featuresCommand linestreamlit --help streamlit run your_script.py streamlit hello streamlit config show streamlit cache clear streamlit docs streamlit --version Magic commands# Magic commands implicitly # call st.write(). "_This_ is some **Markdown***" my_variable "dataframe:", my_data_frame Display textst.write("Most objects") # df, err, func, keras! st.write(["st", "is <", 3]) # see * st.write_stream(my_generator) st.write_stream(my_llm_stream) st.text("Fixed width text") st.markdown("_Markdown_") # see * st.latex(r""" e^{i\pi} + 1 = 0 """) st.title("My title") st.header("My header") st.subheader("My sub") st.code("for i in range(8): foo()") * optional kwarg unsafe_allow_html = True Display datast.dataframe(my_dataframe) st.table(data.iloc[0:10]) st.json({"foo":"bar","fu":"ba"}) st.metric("My metric", 42, 2) Display mediast.image("./header.png") st.audio(data) st.video(data) st.video(data, subtitles="./subs.vtt") Display chartsst.area_chart(df) st.bar_chart(df) st.line_chart(df) st.map(df) st.scatter_chart(df) st.altair_chart(chart) st.bokeh_chart(fig) st.graphviz_chart(fig) st.plotly_chart(fig) st.pydeck_chart(chart) st.pyplot(fig) st.vega_lite_chart(df) Add widgets to sidebar# Just add it after st.sidebar: >>> a = st.sidebar.radio("Select one:", [1, 2]) # Or use "with" notation: >>> with st.sidebar: >>> st.radio("Select one:", [1, 2]) Columns# Two equal columns: >>> col1, col2 = st.columns(2) >>> col1.write("This is column 1") >>> col2.write("This is column 2") # Three different columns: >>> col1, col2, col3 = st.columns([3, 1, 1]) # col1 is larger. # You can also use "with" notation: >>> with col1: >>> st.radio("Select one:", [1, 2]) Tabs# Insert containers separated into tabs: >>> tab1, tab2 = st.tabs(["Tab 1", "Tab2"]) >>> tab1.write("this is tab 1") >>> tab2.write("this is tab 2") # You can also use "with" notation: >>> with tab1: >>> st.radio("Select one:", [1, 2]) Expandable containers>>> expand = st.expander("My label") >>> expand.write("Inside the expander.") >>> pop = st.popover("Button label") >>> pop.checkbox("Show all") # You can also use "with" notation: >>> with expand: >>> st.radio("Select one:", [1, 2]) Control flow# Stop execution immediately: st.stop() # Rerun script immediately: st.rerun() # Navigate to another page: st.switch_page("pages/my_page.py") # Group multiple widgets: >>> with st.form(key="my_form"): >>> username = st.text_input("Username") >>> password = st.text_input("Password") >>> st.form_submit_button("Login") # Define a dialog function >>> @st.experimental_dialog("Welcome!") >>> def modal_dialog(): >>> st.write("Hello") >>> >>> modal_dialog() # Define a fragment >>> @st.experimental_fragment >>> def fragment_function(): >>> df = get_data() >>> st.line_chart(df) >>> st.button("Update") >>> >>> fragment_function() Display interactive widgetsst.button("Click me") st.download_button("Download file", data) st.link_button("Go to gallery", url) st.page_link("app.py", label="Home") st.data_editor("Edit data", data) st.checkbox("I agree") st.toggle("Enable") st.radio("Pick one", ["cats", "dogs"]) st.selectbox("Pick one", ["cats", "dogs"]) st.multiselect("Buy", ["milk", "apples", "potatoes"]) st.slider("Pick a number", 0, 100) st.select_slider("Pick a size", ["S", "M", "L"]) st.text_input("First name") st.number_input("Pick a number", 0, 10) st.text_area("Text to translate") st.date_input("Your birthday") st.time_input("Meeting time") st.file_uploader("Upload a CSV") st.camera_input("Take a picture") st.color_picker("Pick a color") # Use widgets' returned values in variables: >>> for i in range(int(st.number_input("Num:"))): >>> foo() >>> if st.sidebar.selectbox("I:",["f"]) == "f": >>> b() >>> my_slider_val = st.slider("Quinn Mallory", 1, 88) >>> st.write(slider_val) # Disable widgets to remove interactivity: >>> st.slider("Pick a number", 0, 100, disabled=True) Build chat-based apps# Insert a chat message container. >>> with st.chat_message("user"): >>> st.write("Hello 👋") >>> st.line_chart(np.random.randn(30, 3)) # Display a chat input widget at the bottom of the app. >>> st.chat_input("Say something") # Display a chat input widget inline. >>> with st.container(): >>> st.chat_input("Say something") Learn how to Build a basic LLM chat appMutate data# Add rows to a dataframe after # showing it. >>> element = st.dataframe(df1) >>> element.add_rows(df2) # Add rows to a chart after # showing it. >>> element = st.line_chart(df1) >>> element.add_rows(df2) Display code>>> with st.echo(): >>> st.write("Code will be executed and printed") Placeholders, help, and options# Replace any single element. >>> element = st.empty() >>> element.line_chart(...) >>> element.text_input(...) # Replaces previous. # Insert out of order. >>> elements = st.container() >>> elements.line_chart(...) >>> st.write("Hello") >>> elements.text_input(...) # Appears above "Hello". st.help(pandas.DataFrame) st.get_option(key) st.set_option(key, value) st.set_page_config(layout="wide") st.query_params[key] st.query_params.from_dict(params_dict) st.query_params.get_all(key) st.query_params.clear() st.html("<p>Hi!</p>") Connect to data sourcesst.connection("pets_db", type="sql") conn = st.connection("sql") conn = st.connection("snowflake") >>> class MyConnection(BaseConnection[myconn.MyConnection]): >>> def _connect(self, **kwargs) -> MyConnection: >>> return myconn.connect(**self._secrets, **kwargs) >>> def query(self, query): >>> return self._instance.query(query) Optimize performanceCache data objects# E.g. Dataframe computation, storing downloaded data, etc. >>> @st.cache_data ... def foo(bar): ... # Do something expensive and return data ... return data # Executes foo >>> d1 = foo(ref1) # Does not execute foo # Returns cached item by value, d1 == d2 >>> d2 = foo(ref1) # Different arg, so function foo executes >>> d3 = foo(ref2) # Clear the cached value for foo(ref1) >>> foo.clear(ref1) # Clear all cached entries for this function >>> foo.clear() # Clear values from *all* in-memory or on-disk cached functions >>> st.cache_data.clear() Cache global resources# E.g. TensorFlow session, database connection, etc. >>> @st.cache_resource ... def foo(bar): ... # Create and return a non-data object ... return session # Executes foo >>> s1 = foo(ref1) # Does not execute foo # Returns cached item by reference, s1 == s2 >>> s2 = foo(ref1) # Different arg, so function foo executes >>> s3 = foo(ref2) # Clear the cached value for foo(ref1) >>> foo.clear(ref1) # Clear all cached entries for this function >>> foo.clear() # Clear all global resources from cache >>> st.cache_resource.clear() Deprecated caching>>> @st.cache ... def foo(bar): ... # Do something expensive in here... ... return data >>> # Executes foo >>> d1 = foo(ref1) >>> # Does not execute foo >>> # Returns cached item by reference, d1 == d2 >>> d2 = foo(ref1) >>> # Different arg, so function foo executes >>> d3 = foo(ref2) Display progress and status# Show a spinner during a process >>> with st.spinner(text="In progress"): >>> time.sleep(3) >>> st.success("Done") # Show and update progress bar >>> bar = st.progress(50) >>> time.sleep(3) >>> bar.progress(100) >>> with st.status("Authenticating...") as s: >>> time.sleep(2) >>> st.write("Some long response.") >>> s.update(label="Response") st.balloons() st.snow() st.toast("Warming up...") st.error("Error message") st.warning("Warning message") st.info("Info message") st.success("Success message") st.exception(e) Personalize apps for users# Show different content based on the user's email address. >>> if st.user.email == "jane@email.com": >>> display_jane_content() >>> elif st.user.email == "adam@foocorp.io": >>> display_adam_content() >>> else: >>> st.write("Please contact us to get access!") Previous: Quick referenceNext: Release notesforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy
https://docs.streamlit.io/develop/concepts/architecture
DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsremoveCOREArchitecture & executionremoveRunning your appStreamlit's architectureThe app chromeCachingSession StateFormsFragmentsWidget behaviorMultipage appsaddApp designaddADDITIONALConnections and secretsaddCustom componentsaddConfiguration and themingaddApp testingaddAPI referenceaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Develop/Concepts/Architecture & executionWorking with Streamlit's execution model Run your appUnderstand how to start your Streamlit app.Streamlit's architectureUnderstand Streamlit's client-server architecture and related considerations.The app chromeEvery Streamlit app has a few widgets in the top right to help you as you develop your app and help your users as they view your app. This is called the app chrome.CachingMake your app performant by caching results to avoid unecessary recomputation with each rerun.Session StateManage your app's statefulness with Session State.FormsUse forms to isolate user input and prevent unnecessary app reruns.Widget behaviorUnderstand how widgets work in detail.Previous: ConceptsNext: Running your appforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy
https://docs.streamlit.io/knowledge-base/dependencies/no-matching-distribution#solution
DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Knowledge base/Installing dependencies/ERROR No matching distribution found forERROR: No matching distribution found for Problem You receive the error ERROR: No matching distribution found for when you deploy an app on Streamlit Community Cloud. Solution This error occurs when you deploy an app on Streamlit Community Cloud and have one or more of the following issues with your Python dependencies in your requirements file: The package is part of the Python Standard Library. E.g. You will see ERROR: No matching distribution found for base64 if you include base64 in your requirements file, as it is part of the Python Standard Library. The solution is to not include the package in your requirements file. Only include packages in your requirements file that are not distributed with a standard Python installation. The package name in your requirements file is misspelled. Double-check the package name before including it in your requirements file. The package does not support the operating system on which your Streamlit app is running. E.g. You see ERROR: No matching distribution found for pywin32 while deploying to Streamlit Community Cloud. The pywin32 module provides access to many of the Windows APIs from Python. Apps deployed to Streamlit Community Cloud are executed in a Linux environment. As such, pywin32 fails to install on non-Windows systems, including on Streamlit Community Cloud. The solution is to either exclude pywin32 from your requirements file, or deploy your app on a cloud service offering Windows machines. Related forum posts: https://discuss.streamlit.io/t/error-no-matching-distribution-found-for-base64/15758 https://discuss.streamlit.io/t/error-could-not-find-a-version-that-satisfies-the-requirement-pywin32-301-from-versions-none/15343/2 Previous: ModuleNotFoundError No module namedNext: Deployment issuesforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy
https://docs.streamlit.io/library/api-reference/data/st.column_config
DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceremovePAGE ELEMENTSWrite and magicaddText elementsaddData elementsremovest.dataframest.data_editorst.column_configremoveColumnText columnNumber columnCheckbox columnSelectbox columnDatetime columnDate columnTime columnList columnLink columnImage columnArea chart columnLine chart columnBar chart columnProgress columnst.tablest.metricst.jsonChart elementsaddInput widgetsaddMedia elementsaddLayouts and containersaddChat elementsaddStatus elementsaddThird-party componentsopen_in_newAPPLICATION LOGICNavigation and pagesaddExecution flowaddCaching and stateaddConnections and secretsaddCustom componentsaddUtilitiesaddConfigurationaddTOOLSApp testingaddCommand lineaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Develop/API reference/Data elements/st.column_configColumn configuration When working with data in Streamlit, the st.column_config class is a powerful tool for configuring data display and interaction. Specifically designed for the column_config parameter in st.dataframe and st.data_editor, it provides a suite of methods to tailor your columns to various data types - from simple text and numbers to lists, URLs, images, and more. Whether it's translating temporal data into user-friendly formats or utilizing charts and progress bars for clearer data visualization, column configuration not only provides the user with an enriched data viewing experience but also ensures that you're equipped with the tools to present and interact with your data, just the way you want it. ColumnConfigure a generic column.Column("Streamlit Widgets", width="medium", help="Streamlit **widget** commands 🎈") Text columnConfigure a text column.TextColumn("Widgets", max_chars=50, validate="^st\.[a-z_]+$") Number columnConfigure a number column.NumberColumn("Price (in USD)", min_value=0, format="$%d") Checkbox columnConfigure a checkbox column.CheckboxColumn("Your favorite?", help="Select your **favorite** widgets") Selectbox columnConfigure a selectbox column.SelectboxColumn("App Category", options=["🤖 LLM", "📈 Data Viz"]) Datetime columnConfigure a datetime column.DatetimeColumn("Appointment", min_value=datetime(2023, 6, 1), format="D MMM YYYY, h:mm a") Date columnConfigure a date column.DateColumn("Birthday", max_value=date(2005, 1, 1), format="DD.MM.YYYY") Time columnConfigure a time column.TimeColumn("Appointment", min_value=time(8, 0, 0), format="hh:mm a") List columnConfigure a list column.ListColumn("Sales (last 6 months)", width="medium") Link columnConfigure a link column.LinkColumn("Trending apps", max_chars=100, validate="^https://.*$") Image columnConfigure an image column.ImageColumn("Preview Image", help="The preview screenshots") Area chart columnConfigure an area chart column.AreaChartColumn("Sales (last 6 months)" y_min=0, y_max=100) Line chart columnConfigure a line chart column.LineChartColumn("Sales (last 6 months)" y_min=0, y_max=100) Bar chart columnConfigure a bar chart column.BarChartColumn("Marketing spend" y_min=0, y_max=100) Progress columnConfigure a progress column.ProgressColumn("Sales volume", min_value=0, max_value=1000, format="$%f") Previous: st.data_editorNext: ColumnforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy
https://docs.streamlit.io/en/0.76.0/api.html#utilities-and-user-info
DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceremovePAGE ELEMENTSWrite and magicaddText elementsaddData elementsaddChart elementsaddInput widgetsaddMedia elementsaddLayouts and containersaddChat elementsaddStatus elementsaddThird-party componentsopen_in_newAPPLICATION LOGICNavigation and pagesaddExecution flowaddCaching and stateaddConnections and secretsaddCustom componentsaddUtilitiesaddConfigurationaddTOOLSApp testingaddCommand lineaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Develop/API referenceAPI reference Streamlit makes it easy for you to visualize, mutate, and share data. The API reference is organized by activity type, like displaying data or optimizing performance. Each section includes methods associated with the activity type, including examples. Browse our API below and click to learn more about any of our available commands! 🎈 Display almost anything Write and magic st.writeWrite arguments to the app.st.write("Hello **world**!") st.write(my_data_frame) st.write(my_mpl_figure) st.write_streamWrite generators or streams to the app with a typewriter effect.st.write_stream(my_generator) st.write_stream(my_llm_stream) MagicAny time Streamlit sees either a variable or literal value on its own line, it automatically writes that to your app using st.write"Hello **world**!" my_data_frame my_mpl_figure Text elements MarkdownDisplay string formatted as Markdown.st.markdown("Hello **world**!") TitleDisplay text in title formatting.st.title("The app title") HeaderDisplay text in header formatting.st.header("This is a header") SubheaderDisplay text in subheader formatting.st.subheader("This is a subheader") CaptionDisplay text in small font.st.caption("This is written small caption text") Code blockDisplay a code block with optional syntax highlighting.st.code("a = 1234") EchoDisplay some code in the app, then execute it. Useful for tutorials.with st.echo(): st.write('This code will be printed') LaTeXDisplay mathematical expressions formatted as LaTeX.st.latex("\int a x^2 \,dx") Preformatted textWrite fixed-width and preformatted text.st.text("Hello world") DividerDisplay a horizontal rule.st.divider() Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration! PreviousTagsAdd tags to your Streamlit apps. Created by @gagan3012.st_tags(label='# Enter Keywords:', text='Press enter to add more', value=['Zero', 'One', 'Two'], suggestions=['five', 'six', 'seven', 'eight', 'nine', 'three', 'eleven', 'ten', 'four'], maxtags = 4, key='1') NLUApply text mining on a dataframe. Created by @JohnSnowLabs.nlu.load('sentiment').predict('I love NLU! <3') Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.mention(label="An awesome Streamlit App", icon="streamlit", url="https://extras.streamlit.app",) Annotated textDisplay annotated text in Streamlit apps. Created by @tvst.annotated_text("This ", ("is", "verb"), " some ", ("annotated", "adj"), ("text", "noun"), " for those of ", ("you", "pronoun"), " who ", ("like", "verb"), " this sort of ", ("thing", "noun"), ".") Drawable CanvasProvides a sketching canvas using Fabric.js. Created by @andfanilo.st_canvas(fill_color="rgba(255, 165, 0, 0.3)", stroke_width=stroke_width, stroke_color=stroke_color, background_color=bg_color, background_image=Image.open(bg_image) if bg_image else None, update_streamlit=realtime_update, height=150, drawing_mode=drawing_mode, point_display_radius=point_display_radius if drawing_mode == 'point' else 0, key="canvas",) TagsAdd tags to your Streamlit apps. Created by @gagan3012.st_tags(label='# Enter Keywords:', text='Press enter to add more', value=['Zero', 'One', 'Two'], suggestions=['five', 'six', 'seven', 'eight', 'nine', 'three', 'eleven', 'ten', 'four'], maxtags = 4, key='1') NLUApply text mining on a dataframe. Created by @JohnSnowLabs.nlu.load('sentiment').predict('I love NLU! <3') Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.mention(label="An awesome Streamlit App", icon="streamlit", url="https://extras.streamlit.app",) Annotated textDisplay annotated text in Streamlit apps. Created by @tvst.annotated_text("This ", ("is", "verb"), " some ", ("annotated", "adj"), ("text", "noun"), " for those of ", ("you", "pronoun"), " who ", ("like", "verb"), " this sort of ", ("thing", "noun"), ".") Drawable CanvasProvides a sketching canvas using Fabric.js. Created by @andfanilo.st_canvas(fill_color="rgba(255, 165, 0, 0.3)", stroke_width=stroke_width, stroke_color=stroke_color, background_color=bg_color, background_image=Image.open(bg_image) if bg_image else None, update_streamlit=realtime_update, height=150, drawing_mode=drawing_mode, point_display_radius=point_display_radius if drawing_mode == 'point' else 0, key="canvas",) TagsAdd tags to your Streamlit apps. Created by @gagan3012.st_tags(label='# Enter Keywords:', text='Press enter to add more', value=['Zero', 'One', 'Two'], suggestions=['five', 'six', 'seven', 'eight', 'nine', 'three', 'eleven', 'ten', 'four'], maxtags = 4, key='1') NLUApply text mining on a dataframe. Created by @JohnSnowLabs.nlu.load('sentiment').predict('I love NLU! <3') Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.mention(label="An awesome Streamlit App", icon="streamlit", url="https://extras.streamlit.app",) Next Data elements DataframesDisplay a dataframe as an interactive table.st.dataframe(my_data_frame) Data editorDisplay a data editor widget.edited = st.data_editor(df, num_rows="dynamic") Column configurationConfigure the display and editing behavior of dataframes and data editors.st.column_config.NumberColumn("Price (in USD)", min_value=0, format="$%d") Static tablesDisplay a static table.st.table(my_data_frame) MetricsDisplay a metric in big bold font, with an optional indicator of how the metric changed.st.metric("My metric", 42, 2) Dicts and JSONDisplay object or string as a pretty-printed JSON string.st.json(my_dict) Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration! PreviousImage CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates value = streamlit_image_coordinates("https://placekitten.com/200/300") st.write(value) Plotly EventsMake Plotly charts interactive!. Created by @null-jones.from streamlit_plotly_events import plotly_events fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.metric_cards import style_metric_cards col3.metric(label="No Change", value=5000, delta=0) style_metric_cards() Streamlit AggridImplementation of Ag-Grid component for Streamlit. Created by @PablocFonseca.df = pd.DataFrame({'col1': [1, 2, 3], 'col2': [4, 5, 6]}) grid_return = AgGrid(df, editable=True) new_df = grid_return['data'] Streamlit FoliumStreamlit Component for rendering Folium maps. Created by @randyzwitch.m = folium.Map(location=[39.949610, -75.150282], zoom_start=16) folium.Marker([39.949610, -75.150282], popup="Liberty Bell", tooltip="Liberty Bell").add_to(m) st_data = st_folium(m, width=725) Pandas ProfilingPandas profiling component for Streamlit. Created by @okld.df = pd.read_csv("https://storage.googleapis.com/tf-datasets/titanic/train.csv") pr = df.profile_report() st_profile_report(pr) Image CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates value = streamlit_image_coordinates("https://placekitten.com/200/300") st.write(value) Plotly EventsMake Plotly charts interactive!. Created by @null-jones.from streamlit_plotly_events import plotly_events fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.metric_cards import style_metric_cards col3.metric(label="No Change", value=5000, delta=0) style_metric_cards() Streamlit AggridImplementation of Ag-Grid component for Streamlit. Created by @PablocFonseca.df = pd.DataFrame({'col1': [1, 2, 3], 'col2': [4, 5, 6]}) grid_return = AgGrid(df, editable=True) new_df = grid_return['data'] Streamlit FoliumStreamlit Component for rendering Folium maps. Created by @randyzwitch.m = folium.Map(location=[39.949610, -75.150282], zoom_start=16) folium.Marker([39.949610, -75.150282], popup="Liberty Bell", tooltip="Liberty Bell").add_to(m) st_data = st_folium(m, width=725) Pandas ProfilingPandas profiling component for Streamlit. Created by @okld.df = pd.read_csv("https://storage.googleapis.com/tf-datasets/titanic/train.csv") pr = df.profile_report() st_profile_report(pr) Image CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates value = streamlit_image_coordinates("https://placekitten.com/200/300") st.write(value) Plotly EventsMake Plotly charts interactive!. Created by @null-jones.from streamlit_plotly_events import plotly_events fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.metric_cards import style_metric_cards col3.metric(label="No Change", value=5000, delta=0) style_metric_cards() Next Chart elements Simple area chartsDisplay an area chart.st.area_chart(my_data_frame) Simple bar chartsDisplay a bar chart.st.bar_chart(my_data_frame) Simple line chartsDisplay a line chart.st.line_chart(my_data_frame) Simple scatter chartsDisplay a line chart.st.scatter_chart(my_data_frame) Scatterplots on mapsDisplay a map with points on it.st.map(my_data_frame) MatplotlibDisplay a matplotlib.pyplot figure.st.pyplot(my_mpl_figure) AltairDisplay a chart using the Altair library.st.altair_chart(my_altair_chart) Vega-LiteDisplay a chart using the Vega-Lite library.st.vega_lite_chart(my_vega_lite_chart) PlotlyDisplay an interactive Plotly chart.st.plotly_chart(my_plotly_chart) BokehDisplay an interactive Bokeh chart.st.bokeh_chart(my_bokeh_chart) PyDeckDisplay a chart using the PyDeck library.st.pydeck_chart(my_pydeck_chart) GraphVizDisplay a graph using the dagre-d3 library.st.graphviz_chart(my_graphviz_spec) Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration! PreviousStreamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl("https://assets5.lottiefiles.com/packages/lf20_V9t630.json") st_lottie(lottie_hello, key="hello") Plotly EventsMake Plotly charts interactive!. Created by @null-jones.fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.chart += get_annotations_chart(annotations=[("Mar 01, 2008", "Pretty good day for GOOG"), ("Dec 01, 2007", "Something's going wrong for GOOG & AAPL"), ("Nov 01, 2008", "Market starts again thanks to..."), ("Dec 01, 2009", "Small crash for GOOG after..."),],) st.altair_chart(chart, use_container_width=True) PlostA deceptively simple plotting library for Streamlit. Created by @tvst.import plost plost.line_chart(my_dataframe, x='time', y='stock_value', color='stock_name',) HiPlotHigh dimensional Interactive Plotting. Created by @facebookresearch.data = [{'dropout':0.1, 'lr': 0.001, 'loss': 10.0, 'optimizer': 'SGD'}, {'dropout':0.15, 'lr': 0.01, 'loss': 3.5, 'optimizer': 'Adam'}, {'dropout':0.3, 'lr': 0.1, 'loss': 4.5, 'optimizer': 'Adam'}] hip.Experiment.from_iterable(data).display() EChartsHigh dimensional Interactive Plotting. Created by @andfanilo.from streamlit_echarts import st_echarts st_echarts(options=options) Streamlit FoliumStreamlit Component for rendering Folium maps. Created by @randyzwitch.m = folium.Map(location=[39.949610, -75.150282], zoom_start=16) st_data = st_folium(m, width=725) Spacy-StreamlitspaCy building blocks and visualizers for Streamlit apps. Created by @explosion.models = ["en_core_web_sm", "en_core_web_md"] spacy_streamlit.visualize(models, "Sundar Pichai is the CEO of Google.") Streamlit AgraphA Streamlit Graph Vis, based on react-grah-vis. Created by @ChrisDelClea.from streamlit_agraph import agraph, Node, Edge, Config agraph(nodes=nodes, edges=edges, config=config) Streamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl("https://assets5.lottiefiles.com/packages/lf20_V9t630.json") st_lottie(lottie_hello, key="hello") Plotly EventsMake Plotly charts interactive!. Created by @null-jones.fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.chart += get_annotations_chart(annotations=[("Mar 01, 2008", "Pretty good day for GOOG"), ("Dec 01, 2007", "Something's going wrong for GOOG & AAPL"), ("Nov 01, 2008", "Market starts again thanks to..."), ("Dec 01, 2009", "Small crash for GOOG after..."),],) st.altair_chart(chart, use_container_width=True) PlostA deceptively simple plotting library for Streamlit. Created by @tvst.import plost plost.line_chart(my_dataframe, x='time', y='stock_value', color='stock_name',) HiPlotHigh dimensional Interactive Plotting. Created by @facebookresearch.data = [{'dropout':0.1, 'lr': 0.001, 'loss': 10.0, 'optimizer': 'SGD'}, {'dropout':0.15, 'lr': 0.01, 'loss': 3.5, 'optimizer': 'Adam'}, {'dropout':0.3, 'lr': 0.1, 'loss': 4.5, 'optimizer': 'Adam'}] hip.Experiment.from_iterable(data).display() EChartsHigh dimensional Interactive Plotting. Created by @andfanilo.from streamlit_echarts import st_echarts st_echarts(options=options) Streamlit FoliumStreamlit Component for rendering Folium maps. Created by @randyzwitch.m = folium.Map(location=[39.949610, -75.150282], zoom_start=16) st_data = st_folium(m, width=725) Spacy-StreamlitspaCy building blocks and visualizers for Streamlit apps. Created by @explosion.models = ["en_core_web_sm", "en_core_web_md"] spacy_streamlit.visualize(models, "Sundar Pichai is the CEO of Google.") Streamlit AgraphA Streamlit Graph Vis, based on react-grah-vis. Created by @ChrisDelClea.from streamlit_agraph import agraph, Node, Edge, Config agraph(nodes=nodes, edges=edges, config=config) Streamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl("https://assets5.lottiefiles.com/packages/lf20_V9t630.json") st_lottie(lottie_hello, key="hello") Plotly EventsMake Plotly charts interactive!. Created by @null-jones.fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.chart += get_annotations_chart(annotations=[("Mar 01, 2008", "Pretty good day for GOOG"), ("Dec 01, 2007", "Something's going wrong for GOOG & AAPL"), ("Nov 01, 2008", "Market starts again thanks to..."), ("Dec 01, 2009", "Small crash for GOOG after..."),],) st.altair_chart(chart, use_container_width=True) Next Input widgets ButtonDisplay a button widget.clicked = st.button("Click me") Download buttonDisplay a download button widget.st.download_button("Download file", file) Form buttonDisplay a form submit button. For use with st.form.st.form_submit_button("Sign up") Link buttonDisplay a link button.st.link_button("Go to gallery", url) Page linkDisplay a link to another page in a multipage app.st.page_link("app.py", label="Home", icon="🏠") st.page_link("pages/profile.py", label="My profile") CheckboxDisplay a checkbox widget.selected = st.checkbox("I agree") Color pickerDisplay a color picker widget.color = st.color_picker("Pick a color") MultiselectDisplay a multiselect widget. The multiselect widget starts as empty.choices = st.multiselect("Buy", ["milk", "apples", "potatoes"]) RadioDisplay a radio button widget.choice = st.radio("Pick one", ["cats", "dogs"]) SelectboxDisplay a select widget.choice = st.selectbox("Pick one", ["cats", "dogs"]) Select-sliderDisplay a slider widget to select items from a list.size = st.select_slider("Pick a size", ["S", "M", "L"]) ToggleDisplay a toggle widget.activated = st.toggle("Activate") Number inputDisplay a numeric input widget.choice = st.number_input("Pick a number", 0, 10) SliderDisplay a slider widget.number = st.slider("Pick a number", 0, 100) Date inputDisplay a date input widget.date = st.date_input("Your birthday") Time inputDisplay a time input widget.time = st.time_input("Meeting time") Chat inputDisplay a chat input widget.prompt = st.chat_input("Say something") if prompt: st.write(f"The user has sent: {prompt}") Text-areaDisplay a multi-line text input widget.text = st.text_area("Text to translate") Text inputDisplay a single-line text input widget.name = st.text_input("First name") Data editorDisplay a data editor widget.edited = st.experimental_data_editor(df, num_rows="dynamic") File UploaderDisplay a file uploader widget.data = st.file_uploader("Upload a CSV") Camera inputDisplay a widget that allows users to upload images directly from a camera.image = st.camera_input("Take a picture") Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration! PreviousStreamlit ChatStreamlit Component for a Chatbot UI. Created by @AI-Yash.from streamlit_chat import message message("My message") message("Hello bot!", is_user=True) # align's the message to the right Streamlit Option MenuSelect a single item from a list of options in a menu. Created by @victoryhb.from streamlit_option_menu import option_menu option_menu("Main Menu", ["Home", 'Settings'], icons=['house', 'gear'], menu_icon="cast", default_index=1) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.stoggle import stoggle stoggle( "Click me!", """🥷 Surprise! Here's some additional content""",) Streamlit ElementsCreate a draggable and resizable dashboard in Streamlit. Created by @okls.from streamlit_elements import elements, mui, html with elements("new_element"): mui.Typography("Hello world") TagsAdd tags to your Streamlit apps. Created by @gagan3012.from streamlit_tags import st_tags st_tags(label='# Enter Keywords:', text='Press enter to add more', value=['Zero', 'One', 'Two'], suggestions=['five', 'six', 'seven', 'eight', 'nine', 'three', 'eleven', 'ten', 'four'], maxtags = 4, key='1') StqdmThe simplest way to handle a progress bar in streamlit app. Created by @Wirg.from stqdm import stqdm for _ in stqdm(range(50)): sleep(0.5) TimelineDisplay a Timeline in Streamlit apps using TimelineJS. Created by @innerdoc.from streamlit_timeline import timeline with open('example.json', "r") as f: timeline(f.read(), height=800) Camera input liveAlternative for st.camera_input which returns the webcam images live. Created by @blackary.from camera_input_live import camera_input_live image = camera_input_live() st.image(value) Streamlit AceAce editor component for Streamlit. Created by @okld.from streamlit_ace import st_ace content = st_ace() content Streamlit ChatStreamlit Component for a Chatbot UI. Created by @AI-Yash.from streamlit_chat import message message("My message") message("Hello bot!", is_user=True) # align's the message to the right Streamlit Option MenuSelect a single item from a list of options in a menu. Created by @victoryhb.from streamlit_option_menu import option_menu option_menu("Main Menu", ["Home", 'Settings'], icons=['house', 'gear'], menu_icon="cast", default_index=1) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.stoggle import stoggle stoggle( "Click me!", """🥷 Surprise! Here's some additional content""",) Streamlit ElementsCreate a draggable and resizable dashboard in Streamlit. Created by @okls.from streamlit_elements import elements, mui, html with elements("new_element"): mui.Typography("Hello world") TagsAdd tags to your Streamlit apps. Created by @gagan3012.from streamlit_tags import st_tags st_tags(label='# Enter Keywords:', text='Press enter to add more', value=['Zero', 'One', 'Two'], suggestions=['five', 'six', 'seven', 'eight', 'nine', 'three', 'eleven', 'ten', 'four'], maxtags = 4, key='1') StqdmThe simplest way to handle a progress bar in streamlit app. Created by @Wirg.from stqdm import stqdm for _ in stqdm(range(50)): sleep(0.5) TimelineDisplay a Timeline in Streamlit apps using TimelineJS. Created by @innerdoc.from streamlit_timeline import timeline with open('example.json', "r") as f: timeline(f.read(), height=800) Camera input liveAlternative for st.camera_input which returns the webcam images live. Created by @blackary.from camera_input_live import camera_input_live image = camera_input_live() st.image(value) Streamlit AceAce editor component for Streamlit. Created by @okld.from streamlit_ace import st_ace content = st_ace() content Streamlit ChatStreamlit Component for a Chatbot UI. Created by @AI-Yash.from streamlit_chat import message message("My message") message("Hello bot!", is_user=True) # align's the message to the right Streamlit Option MenuSelect a single item from a list of options in a menu. Created by @victoryhb.from streamlit_option_menu import option_menu option_menu("Main Menu", ["Home", 'Settings'], icons=['house', 'gear'], menu_icon="cast", default_index=1) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.stoggle import stoggle stoggle( "Click me!", """🥷 Surprise! Here's some additional content""",) Next Media elements ImageDisplay an image or list of images.st.image(numpy_array) st.image(image_bytes) st.image(file) st.image("https://example.com/myimage.jpg") AudioDisplay an audio player.st.audio(numpy_array) st.audio(audio_bytes) st.audio(file) st.audio("https://example.com/myaudio.mp3", format="audio/mp3") VideoDisplay a video player.st.video(numpy_array) st.video(video_bytes) st.video(file) st.video("https://example.com/myvideo.mp4", format="video/mp4") Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration! PreviousStreamlit CropperA simple image cropper for Streamlit. Created by @turner-anderson.from streamlit_cropper import st_cropper st_cropper(img, realtime_update=realtime_update, box_color=box_color, aspect_ratio=aspect_ratio) Image CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates streamlit_image_coordinates("https://placekitten.com/200/300") Streamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl("https://assets5.lottiefiles.com/packages/lf20_V9t630.json") st_lottie(lottie_hello, key="hello") Streamlit WebrtcHandling and transmitting real-time video/audio streams with Streamlit. Created by @whitphx.from streamlit_webrtc import webrtc_streamer webrtc_streamer(key="sample") Drawable CanvasProvides a sketching canvas using Fabric.js. Created by @andfanilo.from streamlit_drawable_canvas import st_canvas st_canvas(fill_color="rgba(255, 165, 0, 0.3)", stroke_width=stroke_width, stroke_color=stroke_color, background_color=bg_color, background_image=Image.open(bg_image) if bg_image else None, update_streamlit=realtime_update, height=150, drawing_mode=drawing_mode, point_display_radius=point_display_radius if drawing_mode == 'point' else 0, key="canvas",) Image ComparisonCompare images with a slider using JuxtaposeJS. Created by @fcakyon.from streamlit_image_comparison import image_comparison image_comparison(img1="image1.jpg", img2="image2.jpg",) Streamlit CropperA simple image cropper for Streamlit. Created by @turner-anderson.from streamlit_cropper import st_cropper st_cropper(img, realtime_update=realtime_update, box_color=box_color, aspect_ratio=aspect_ratio) Image CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates streamlit_image_coordinates("https://placekitten.com/200/300") Streamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl("https://assets5.lottiefiles.com/packages/lf20_V9t630.json") st_lottie(lottie_hello, key="hello") Streamlit WebrtcHandling and transmitting real-time video/audio streams with Streamlit. Created by @whitphx.from streamlit_webrtc import webrtc_streamer webrtc_streamer(key="sample") Drawable CanvasProvides a sketching canvas using Fabric.js. Created by @andfanilo.from streamlit_drawable_canvas import st_canvas st_canvas(fill_color="rgba(255, 165, 0, 0.3)", stroke_width=stroke_width, stroke_color=stroke_color, background_color=bg_color, background_image=Image.open(bg_image) if bg_image else None, update_streamlit=realtime_update, height=150, drawing_mode=drawing_mode, point_display_radius=point_display_radius if drawing_mode == 'point' else 0, key="canvas",) Image ComparisonCompare images with a slider using JuxtaposeJS. Created by @fcakyon.from streamlit_image_comparison import image_comparison image_comparison(img1="image1.jpg", img2="image2.jpg",) Streamlit CropperA simple image cropper for Streamlit. Created by @turner-anderson.from streamlit_cropper import st_cropper st_cropper(img, realtime_update=realtime_update, box_color=box_color, aspect_ratio=aspect_ratio) Image CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates streamlit_image_coordinates("https://placekitten.com/200/300") Streamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl("https://assets5.lottiefiles.com/packages/lf20_V9t630.json") st_lottie(lottie_hello, key="hello") Next Layouts and containers ColumnsInsert containers laid out as side-by-side columns.col1, col2 = st.columns(2) col1.write("this is column 1") col2.write("this is column 2") ContainerInsert a multi-element container.c = st.container() st.write("This will show last") c.write("This will show first") c.write("This will show second") Modal dialogsInsert a modal dialog that can rerun independently from the rest of the script.@st.experimental_dialog("Sign up") def email_form(): name = st.text_input("Name") email = st.text_input("Email") EmptyInsert a single-element container.c = st.empty() st.write("This will show last") c.write("This will be replaced") c.write("This will show first") ExpanderInsert a multi-element container that can be expanded/collapsed.with st.expander("Open to see more"): st.write("This is more content") PopoverInsert a multi-element popover container that can be opened/closed.with st.popover("Settings"): st.checkbox("Show completed") SidebarDisplay items in a sidebar.st.sidebar.write("This lives in the sidebar") st.sidebar.button("Click me!") TabsInsert containers separated into tabs.tab1, tab2 = st.tabs(["Tab 1", "Tab2"]) tab1.write("this is tab 1") tab2.write("this is tab 2") Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration!Streamlit ElementsCreate a draggable and resizable dashboard in Streamlit. Created by @okls.from streamlit_elements import elements, mui, html with elements("new_element"): mui.Typography("Hello world") PydanticAuto-generate Streamlit UI from Pydantic Models and Dataclasses. Created by @lukasmasuch.import streamlit_pydantic as sp sp.pydantic_form(key="my_form", model=ExampleModel) Streamlit PagesAn experimental version of Streamlit Multi-Page Apps. Created by @blackary.from st_pages import Page, show_pages, add_page_title show_pages([ Page("streamlit_app.py", "Home", "🏠"), Page("other_pages/page2.py", "Page 2", ":books:"), ]) Chat elements Streamlit provides a few commands to help you build conversational apps. These chat elements are designed to be used in conjunction with each other, but you can also use them separately. st.chat_message lets you insert a chat message container into the app so you can display messages from the user or the app. Chat containers can contain other Streamlit elements, including charts, tables, text, and more. st.chat_input lets you display a chat input widget so the user can type in a message. Chat inputDisplay a chat input widget.prompt = st.chat_input("Say something") if prompt: st.write(f"The user has sent: {prompt}") Chat messageInsert a chat message container.import numpy as np with st.chat_message("user"): st.write("Hello 👋") st.line_chart(np.random.randn(30, 3)) Status containerDisplay output of long-running tasks in a container.with st.status('Running'): do_something_slow() st.write_streamWrite generators or streams to the app with a typewriter effect.st.write_stream(my_generator) st.write_stream(my_llm_stream) Status elements Progress barDisplay a progress bar.for i in range(101): st.progress(i) do_something_slow() SpinnerTemporarily displays a message while executing a block of code.with st.spinner("Please wait..."): do_something_slow() Status containerDisplay output of long-running tasks in a container.with st.status('Running'): do_something_slow() ToastBriefly displays a toast message in the bottom-right corner.st.toast('Butter!', icon='🧈') BalloonsDisplay celebratory balloons!do_something() # Celebrate when all done! st.balloons() SnowflakesDisplay celebratory snowflakes!do_something() # Celebrate when all done! st.snow() Success boxDisplay a success message.st.success("Match found!") Info boxDisplay an informational message.st.info("Dataset is updated every day at midnight.") Warning boxDisplay warning message.st.warning("Unable to fetch image. Skipping...") Error boxDisplay error message.st.error("We encountered an error") Exception outputDisplay an exception.e = RuntimeError("This is an exception of type RuntimeError") st.exception(e) Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration!StqdmThe simplest way to handle a progress bar in streamlit app. Created by @Wirg.from stqdm import stqdm for _ in stqdm(range(50)): sleep(0.5) Custom notification boxA custom notification box with the ability to close it out. Created by @Socvest.from streamlit_custom_notification_box import custom_notification_box styles = {'material-icons':{'color': 'red'}, 'text-icon-link-close-container': {'box-shadow': '#3896de 0px 4px'}, 'notification-text': {'':''}, 'close-button':{'':''}, 'link':{'':''}} custom_notification_box(icon='info', textDisplay='We are almost done with your registration...', externalLink='more info', url='#', styles=styles, key="foo") Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.let_it_rain import rain rain(emoji="🎈", font_size=54, falling_speed=5, animation_length="infinite",) App logic and configuration Navigation and pages Switch pageProgrammatically navigates to a specified page.st.switch_page("pages/my_page.py") Page linkDisplay a link to another page in a multipage app.st.page_link("app.py", label="Home", icon="🏠") st.page_link("pages/profile.py", label="My profile") Execution flow Modal dialogsInsert a modal dialog that can rerun independently from the rest of the script.@st.experimental_dialog("Sign up") def email_form(): name = st.text_input("Name") email = st.text_input("Email") FormsCreate a form that batches elements together with a “Submit" button.with st.form(key='my_form'): name = st.text_input("Name") email = st.text_input("Email") st.form_submit_button("Sign up") Partial rerunsDefine a fragment to rerun independently from the rest of the script.@st.experimental_fragment(run_every="10s") def fragment(): df = get_data() st.line_chart(df) Rerun scriptRerun the script immediately.st.rerun() Stop executionStops execution immediately.st.stop() Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration!AutorefreshForce a refresh without tying up a script. Created by @kmcgrady.from streamlit_autorefresh import st_autorefresh st_autorefresh(interval=2000, limit=100, key="fizzbuzzcounter") PydanticAuto-generate Streamlit UI from Pydantic Models and Dataclasses. Created by @lukasmasuch.import streamlit_pydantic as sp sp.pydantic_form(key="my_form", model=ExampleModel) Streamlit PagesAn experimental version of Streamlit Multi-Page Apps. Created by @blackary.from st_pages import Page, show_pages, add_page_title show_pages([ Page("streamlit_app.py", "Home", "🏠"), Page("other_pages/page2.py", "Page 2", ":books:"), ]) Caching and state Cache dataFunction decorator to cache functions that return data (e.g. dataframe transforms, database queries, ML inference).@st.cache_data def long_function(param1, param2): # Perform expensive computation here or # fetch data from the web here return data Cache resourceFunction decorator to cache functions that return global resources (e.g. database connections, ML models).@st.cache_resource def init_model(): # Return a global resource here return pipeline( "sentiment-analysis", model="distilbert-base-uncased-finetuned-sst-2-english" ) Session stateSession state is a way to share variables between reruns, for each user session.st.session_state['key'] = value Query parametersGet, set, or clear the query parameters that are shown in the browser's URL bar.st.query_params[key] = value st.query_params.clear() Connections and databases Setup your connection Create a connectionConnect to a data source or APIconn = st.connection('pets_db', type='sql') pet_owners = conn.query('select * from pet_owners') st.dataframe(pet_owners) Built-in connections SnowflakeConnectionA connection to Snowflake.conn = st.connection('snowflake') SQLConnectionA connection to a SQL database using SQLAlchemy.conn = st.connection('sql') Build your own connections Connection base classBuild your own connection with BaseConnection.class MyConnection(BaseConnection[myconn.MyConnection]): def _connect(self, **kwargs) -> MyConnection: return myconn.connect(**self._secrets, **kwargs) def query(self, query): return self._instance.query(query) Secrets management Secrets singletonAccess secrets from a local TOML file.key = st.secrets["OpenAI_key"] Secrets fileSave your secrets in a per-project or per-profile TOML file.OpenAI_key = "<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/tutorials/execution-flow#fragments
DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceaddTutorialsremoveExecution flowremoveFRAGMENTSRerun your app from a fragmentCreate a multiple-container fragmentStart and stop a streaming fragmentConnect to data sourcesaddMultipage appsaddWork with LLMsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Develop/Tutorials/Execution flowUse core features to work with Streamlit's execution model Fragments Trigger a full-script rerun from inside a fragmentCall st.rerun from inside a fragment to trigger a full-script rerun when a condition is met.Create a fragment across multiple containersUse a fragment to write to multiple containers across your app.Start and stop a streaming fragmentUse a fragment to live-stream data. Use a button to start and stop the live-streaming.Previous: TutorialsNext: Rerun your app from a fragmentforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy
https://docs.streamlit.io/develop/tutorials/databases/gcs#create-a-google-cloud-storage-bucket-and-add-a-file
DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceaddTutorialsremoveExecution flowaddConnect to data sourcesremoveAWS S3BigQueryDeta BaseFirestoreopen_in_newGoogle Cloud StorageMicrosoft SQL ServerMongoDBMySQLNeonPostgreSQLPrivate Google SheetPublic Google SheetSnowflakeSupabaseTableauTiDBTigerGraphMultipage appsaddWork with LLMsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Develop/Tutorials/Connect to data sources/Google Cloud StorageConnect Streamlit to Google Cloud Storage Introduction This guide explains how to securely access files on Google Cloud Storage from Streamlit Community Cloud. It uses Streamlit FilesConnection, the gcsfs library and Streamlit's Secrets management. Create a Google Cloud Storage bucket and add a file push_pinNoteIf you already have a bucket that you want to use, feel free to skip to the next step. First, sign up for Google Cloud Platform or log in. Go to the Google Cloud Storage console and create a new bucket. Navigate to the upload section of your new bucket: And upload the following CSV file, which contains some example data: myfile.csv Enable the Google Cloud Storage API The Google Cloud Storage API is enabled by default when you create a project through the Google Cloud Console or CLI. Feel free to skip to the next step. If you do need to enable the API for programmatic access in your project, head over to the APIs & Services dashboard (select or create a project if asked). Search for the Cloud Storage API and enable it. The screenshot below has a blue "Manage" button and indicates the "API is enabled" which means no further action needs to be taken. This is very likely what you have since the API is enabled by default. However, if that is not what you see and you have an "Enable" button, you'll need to enable the API: Create a service account and key file To use the Google Cloud Storage API from Streamlit, you need a Google Cloud Platform service account (a special type for programmatic data access). Go to the Service Accounts page and create an account with Viewer permission. push_pinNoteIf the button CREATE SERVICE ACCOUNT is gray, you don't have the correct permissions. Ask the admin of your Google Cloud project for help. After clicking DONE, you should be back on the service accounts overview. Create a JSON key file for the new account and download it: Add the key to your local app secrets Your local Streamlit app will read secrets from a file .streamlit/secrets.toml in your app's root directory. Create this file if it doesn't exist yet and add the access key to it as shown below: # .streamlit/secrets.toml [connections.gcs] type = "service_account" project_id = "xxx" private_key_id = "xxx" private_key = "xxx" client_email = "xxx" client_id = "xxx" auth_uri = "https://accounts.google.com/o/oauth2/auth" token_uri = "https://oauth2.googleapis.com/token" auth_provider_x509_cert_url = "https://www.googleapis.com/oauth2/v1/certs" client_x509_cert_url = "xxx" priority_highImportantAdd this file to .gitignore and don't commit it to your GitHub repo! Copy your app secrets to the cloud As the secrets.toml file above is not committed to GitHub, you need to pass its content to your deployed app (on Streamlit Community Cloud) separately. Go to the app dashboard and in the app's dropdown menu, click on Edit Secrets. Copy the content of secrets.toml into the text area. More information is available at Secrets management. Add FilesConnection and gcsfs to your requirements file Add the FilesConnection and gcsfs packages to your requirements.txt file, preferably pinning the versions (replace x.x.x with the version you want installed): # requirements.txt gcsfs==x.x.x st-files-connection Write your Streamlit app Copy the code below to your Streamlit app and run it. Make sure to adapt the name of your bucket and file. Note that Streamlit automatically turns the access keys from your secrets file into environment variables. # streamlit_app.py import streamlit as st from st_files_connection import FilesConnection # Create connection object and retrieve file contents. # Specify input format is a csv and to cache the result for 600 seconds. conn = st.connection('gcs', type=FilesConnection) df = conn.read("streamlit-bucket/myfile.csv", input_format="csv", ttl=600) # Print results. for row in df.itertuples(): st.write(f"{row.Owner} has a :{row.Pet}:") See st.connection above? This handles secrets retrieval, setup, result caching and retries. By default, read() results are cached without expiring. In this case, we set ttl=600 to ensure the file contents is cached for no longer than 10 minutes. You can also set ttl=0 to disable caching. Learn more in Caching. If everything worked out (and you used the example file given above), your app should look like this: Previous: FirestoreNext: Microsoft SQL ServerforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy
https://docs.streamlit.io/develop/api-reference/#chart-elements
DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceremovePAGE ELEMENTSWrite and magicaddText elementsaddData elementsaddChart elementsaddInput widgetsaddMedia elementsaddLayouts and containersaddChat elementsaddStatus elementsaddThird-party componentsopen_in_newAPPLICATION LOGICNavigation and pagesaddExecution flowaddCaching and stateaddConnections and secretsaddCustom componentsaddUtilitiesaddConfigurationaddTOOLSApp testingaddCommand lineaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Develop/API referenceAPI reference Streamlit makes it easy for you to visualize, mutate, and share data. The API reference is organized by activity type, like displaying data or optimizing performance. Each section includes methods associated with the activity type, including examples. Browse our API below and click to learn more about any of our available commands! 🎈 Display almost anything Write and magic st.writeWrite arguments to the app.st.write("Hello **world**!") st.write(my_data_frame) st.write(my_mpl_figure) st.write_streamWrite generators or streams to the app with a typewriter effect.st.write_stream(my_generator) st.write_stream(my_llm_stream) MagicAny time Streamlit sees either a variable or literal value on its own line, it automatically writes that to your app using st.write"Hello **world**!" my_data_frame my_mpl_figure Text elements MarkdownDisplay string formatted as Markdown.st.markdown("Hello **world**!") TitleDisplay text in title formatting.st.title("The app title") HeaderDisplay text in header formatting.st.header("This is a header") SubheaderDisplay text in subheader formatting.st.subheader("This is a subheader") CaptionDisplay text in small font.st.caption("This is written small caption text") Code blockDisplay a code block with optional syntax highlighting.st.code("a = 1234") EchoDisplay some code in the app, then execute it. Useful for tutorials.with st.echo(): st.write('This code will be printed') LaTeXDisplay mathematical expressions formatted as LaTeX.st.latex("\int a x^2 \,dx") Preformatted textWrite fixed-width and preformatted text.st.text("Hello world") DividerDisplay a horizontal rule.st.divider() Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration! PreviousTagsAdd tags to your Streamlit apps. Created by @gagan3012.st_tags(label='# Enter Keywords:', text='Press enter to add more', value=['Zero', 'One', 'Two'], suggestions=['five', 'six', 'seven', 'eight', 'nine', 'three', 'eleven', 'ten', 'four'], maxtags = 4, key='1') NLUApply text mining on a dataframe. Created by @JohnSnowLabs.nlu.load('sentiment').predict('I love NLU! <3') Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.mention(label="An awesome Streamlit App", icon="streamlit", url="https://extras.streamlit.app",) Annotated textDisplay annotated text in Streamlit apps. Created by @tvst.annotated_text("This ", ("is", "verb"), " some ", ("annotated", "adj"), ("text", "noun"), " for those of ", ("you", "pronoun"), " who ", ("like", "verb"), " this sort of ", ("thing", "noun"), ".") Drawable CanvasProvides a sketching canvas using Fabric.js. Created by @andfanilo.st_canvas(fill_color="rgba(255, 165, 0, 0.3)", stroke_width=stroke_width, stroke_color=stroke_color, background_color=bg_color, background_image=Image.open(bg_image) if bg_image else None, update_streamlit=realtime_update, height=150, drawing_mode=drawing_mode, point_display_radius=point_display_radius if drawing_mode == 'point' else 0, key="canvas",) TagsAdd tags to your Streamlit apps. Created by @gagan3012.st_tags(label='# Enter Keywords:', text='Press enter to add more', value=['Zero', 'One', 'Two'], suggestions=['five', 'six', 'seven', 'eight', 'nine', 'three', 'eleven', 'ten', 'four'], maxtags = 4, key='1') NLUApply text mining on a dataframe. Created by @JohnSnowLabs.nlu.load('sentiment').predict('I love NLU! <3') Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.mention(label="An awesome Streamlit App", icon="streamlit", url="https://extras.streamlit.app",) Annotated textDisplay annotated text in Streamlit apps. Created by @tvst.annotated_text("This ", ("is", "verb"), " some ", ("annotated", "adj"), ("text", "noun"), " for those of ", ("you", "pronoun"), " who ", ("like", "verb"), " this sort of ", ("thing", "noun"), ".") Drawable CanvasProvides a sketching canvas using Fabric.js. Created by @andfanilo.st_canvas(fill_color="rgba(255, 165, 0, 0.3)", stroke_width=stroke_width, stroke_color=stroke_color, background_color=bg_color, background_image=Image.open(bg_image) if bg_image else None, update_streamlit=realtime_update, height=150, drawing_mode=drawing_mode, point_display_radius=point_display_radius if drawing_mode == 'point' else 0, key="canvas",) TagsAdd tags to your Streamlit apps. Created by @gagan3012.st_tags(label='# Enter Keywords:', text='Press enter to add more', value=['Zero', 'One', 'Two'], suggestions=['five', 'six', 'seven', 'eight', 'nine', 'three', 'eleven', 'ten', 'four'], maxtags = 4, key='1') NLUApply text mining on a dataframe. Created by @JohnSnowLabs.nlu.load('sentiment').predict('I love NLU! <3') Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.mention(label="An awesome Streamlit App", icon="streamlit", url="https://extras.streamlit.app",) Next Data elements DataframesDisplay a dataframe as an interactive table.st.dataframe(my_data_frame) Data editorDisplay a data editor widget.edited = st.data_editor(df, num_rows="dynamic") Column configurationConfigure the display and editing behavior of dataframes and data editors.st.column_config.NumberColumn("Price (in USD)", min_value=0, format="$%d") Static tablesDisplay a static table.st.table(my_data_frame) MetricsDisplay a metric in big bold font, with an optional indicator of how the metric changed.st.metric("My metric", 42, 2) Dicts and JSONDisplay object or string as a pretty-printed JSON string.st.json(my_dict) Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration! PreviousImage CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates value = streamlit_image_coordinates("https://placekitten.com/200/300") st.write(value) Plotly EventsMake Plotly charts interactive!. Created by @null-jones.from streamlit_plotly_events import plotly_events fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.metric_cards import style_metric_cards col3.metric(label="No Change", value=5000, delta=0) style_metric_cards() Streamlit AggridImplementation of Ag-Grid component for Streamlit. Created by @PablocFonseca.df = pd.DataFrame({'col1': [1, 2, 3], 'col2': [4, 5, 6]}) grid_return = AgGrid(df, editable=True) new_df = grid_return['data'] Streamlit FoliumStreamlit Component for rendering Folium maps. Created by @randyzwitch.m = folium.Map(location=[39.949610, -75.150282], zoom_start=16) folium.Marker([39.949610, -75.150282], popup="Liberty Bell", tooltip="Liberty Bell").add_to(m) st_data = st_folium(m, width=725) Pandas ProfilingPandas profiling component for Streamlit. Created by @okld.df = pd.read_csv("https://storage.googleapis.com/tf-datasets/titanic/train.csv") pr = df.profile_report() st_profile_report(pr) Image CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates value = streamlit_image_coordinates("https://placekitten.com/200/300") st.write(value) Plotly EventsMake Plotly charts interactive!. Created by @null-jones.from streamlit_plotly_events import plotly_events fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.metric_cards import style_metric_cards col3.metric(label="No Change", value=5000, delta=0) style_metric_cards() Streamlit AggridImplementation of Ag-Grid component for Streamlit. Created by @PablocFonseca.df = pd.DataFrame({'col1': [1, 2, 3], 'col2': [4, 5, 6]}) grid_return = AgGrid(df, editable=True) new_df = grid_return['data'] Streamlit FoliumStreamlit Component for rendering Folium maps. Created by @randyzwitch.m = folium.Map(location=[39.949610, -75.150282], zoom_start=16) folium.Marker([39.949610, -75.150282], popup="Liberty Bell", tooltip="Liberty Bell").add_to(m) st_data = st_folium(m, width=725) Pandas ProfilingPandas profiling component for Streamlit. Created by @okld.df = pd.read_csv("https://storage.googleapis.com/tf-datasets/titanic/train.csv") pr = df.profile_report() st_profile_report(pr) Image CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates value = streamlit_image_coordinates("https://placekitten.com/200/300") st.write(value) Plotly EventsMake Plotly charts interactive!. Created by @null-jones.from streamlit_plotly_events import plotly_events fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.metric_cards import style_metric_cards col3.metric(label="No Change", value=5000, delta=0) style_metric_cards() Next Chart elements Simple area chartsDisplay an area chart.st.area_chart(my_data_frame) Simple bar chartsDisplay a bar chart.st.bar_chart(my_data_frame) Simple line chartsDisplay a line chart.st.line_chart(my_data_frame) Simple scatter chartsDisplay a line chart.st.scatter_chart(my_data_frame) Scatterplots on mapsDisplay a map with points on it.st.map(my_data_frame) MatplotlibDisplay a matplotlib.pyplot figure.st.pyplot(my_mpl_figure) AltairDisplay a chart using the Altair library.st.altair_chart(my_altair_chart) Vega-LiteDisplay a chart using the Vega-Lite library.st.vega_lite_chart(my_vega_lite_chart) PlotlyDisplay an interactive Plotly chart.st.plotly_chart(my_plotly_chart) BokehDisplay an interactive Bokeh chart.st.bokeh_chart(my_bokeh_chart) PyDeckDisplay a chart using the PyDeck library.st.pydeck_chart(my_pydeck_chart) GraphVizDisplay a graph using the dagre-d3 library.st.graphviz_chart(my_graphviz_spec) Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration! PreviousStreamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl("https://assets5.lottiefiles.com/packages/lf20_V9t630.json") st_lottie(lottie_hello, key="hello") Plotly EventsMake Plotly charts interactive!. Created by @null-jones.fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.chart += get_annotations_chart(annotations=[("Mar 01, 2008", "Pretty good day for GOOG"), ("Dec 01, 2007", "Something's going wrong for GOOG & AAPL"), ("Nov 01, 2008", "Market starts again thanks to..."), ("Dec 01, 2009", "Small crash for GOOG after..."),],) st.altair_chart(chart, use_container_width=True) PlostA deceptively simple plotting library for Streamlit. Created by @tvst.import plost plost.line_chart(my_dataframe, x='time', y='stock_value', color='stock_name',) HiPlotHigh dimensional Interactive Plotting. Created by @facebookresearch.data = [{'dropout':0.1, 'lr': 0.001, 'loss': 10.0, 'optimizer': 'SGD'}, {'dropout':0.15, 'lr': 0.01, 'loss': 3.5, 'optimizer': 'Adam'}, {'dropout':0.3, 'lr': 0.1, 'loss': 4.5, 'optimizer': 'Adam'}] hip.Experiment.from_iterable(data).display() EChartsHigh dimensional Interactive Plotting. Created by @andfanilo.from streamlit_echarts import st_echarts st_echarts(options=options) Streamlit FoliumStreamlit Component for rendering Folium maps. Created by @randyzwitch.m = folium.Map(location=[39.949610, -75.150282], zoom_start=16) st_data = st_folium(m, width=725) Spacy-StreamlitspaCy building blocks and visualizers for Streamlit apps. Created by @explosion.models = ["en_core_web_sm", "en_core_web_md"] spacy_streamlit.visualize(models, "Sundar Pichai is the CEO of Google.") Streamlit AgraphA Streamlit Graph Vis, based on react-grah-vis. Created by @ChrisDelClea.from streamlit_agraph import agraph, Node, Edge, Config agraph(nodes=nodes, edges=edges, config=config) Streamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl("https://assets5.lottiefiles.com/packages/lf20_V9t630.json") st_lottie(lottie_hello, key="hello") Plotly EventsMake Plotly charts interactive!. Created by @null-jones.fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.chart += get_annotations_chart(annotations=[("Mar 01, 2008", "Pretty good day for GOOG"), ("Dec 01, 2007", "Something's going wrong for GOOG & AAPL"), ("Nov 01, 2008", "Market starts again thanks to..."), ("Dec 01, 2009", "Small crash for GOOG after..."),],) st.altair_chart(chart, use_container_width=True) PlostA deceptively simple plotting library for Streamlit. Created by @tvst.import plost plost.line_chart(my_dataframe, x='time', y='stock_value', color='stock_name',) HiPlotHigh dimensional Interactive Plotting. Created by @facebookresearch.data = [{'dropout':0.1, 'lr': 0.001, 'loss': 10.0, 'optimizer': 'SGD'}, {'dropout':0.15, 'lr': 0.01, 'loss': 3.5, 'optimizer': 'Adam'}, {'dropout':0.3, 'lr': 0.1, 'loss': 4.5, 'optimizer': 'Adam'}] hip.Experiment.from_iterable(data).display() EChartsHigh dimensional Interactive Plotting. Created by @andfanilo.from streamlit_echarts import st_echarts st_echarts(options=options) Streamlit FoliumStreamlit Component for rendering Folium maps. Created by @randyzwitch.m = folium.Map(location=[39.949610, -75.150282], zoom_start=16) st_data = st_folium(m, width=725) Spacy-StreamlitspaCy building blocks and visualizers for Streamlit apps. Created by @explosion.models = ["en_core_web_sm", "en_core_web_md"] spacy_streamlit.visualize(models, "Sundar Pichai is the CEO of Google.") Streamlit AgraphA Streamlit Graph Vis, based on react-grah-vis. Created by @ChrisDelClea.from streamlit_agraph import agraph, Node, Edge, Config agraph(nodes=nodes, edges=edges, config=config) Streamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl("https://assets5.lottiefiles.com/packages/lf20_V9t630.json") st_lottie(lottie_hello, key="hello") Plotly EventsMake Plotly charts interactive!. Created by @null-jones.fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.chart += get_annotations_chart(annotations=[("Mar 01, 2008", "Pretty good day for GOOG"), ("Dec 01, 2007", "Something's going wrong for GOOG & AAPL"), ("Nov 01, 2008", "Market starts again thanks to..."), ("Dec 01, 2009", "Small crash for GOOG after..."),],) st.altair_chart(chart, use_container_width=True) Next Input widgets ButtonDisplay a button widget.clicked = st.button("Click me") Download buttonDisplay a download button widget.st.download_button("Download file", file) Form buttonDisplay a form submit button. For use with st.form.st.form_submit_button("Sign up") Link buttonDisplay a link button.st.link_button("Go to gallery", url) Page linkDisplay a link to another page in a multipage app.st.page_link("app.py", label="Home", icon="🏠") st.page_link("pages/profile.py", label="My profile") CheckboxDisplay a checkbox widget.selected = st.checkbox("I agree") Color pickerDisplay a color picker widget.color = st.color_picker("Pick a color") MultiselectDisplay a multiselect widget. The multiselect widget starts as empty.choices = st.multiselect("Buy", ["milk", "apples", "potatoes"]) RadioDisplay a radio button widget.choice = st.radio("Pick one", ["cats", "dogs"]) SelectboxDisplay a select widget.choice = st.selectbox("Pick one", ["cats", "dogs"]) Select-sliderDisplay a slider widget to select items from a list.size = st.select_slider("Pick a size", ["S", "M", "L"]) ToggleDisplay a toggle widget.activated = st.toggle("Activate") Number inputDisplay a numeric input widget.choice = st.number_input("Pick a number", 0, 10) SliderDisplay a slider widget.number = st.slider("Pick a number", 0, 100) Date inputDisplay a date input widget.date = st.date_input("Your birthday") Time inputDisplay a time input widget.time = st.time_input("Meeting time") Chat inputDisplay a chat input widget.prompt = st.chat_input("Say something") if prompt: st.write(f"The user has sent: {prompt}") Text-areaDisplay a multi-line text input widget.text = st.text_area("Text to translate") Text inputDisplay a single-line text input widget.name = st.text_input("First name") Data editorDisplay a data editor widget.edited = st.experimental_data_editor(df, num_rows="dynamic") File UploaderDisplay a file uploader widget.data = st.file_uploader("Upload a CSV") Camera inputDisplay a widget that allows users to upload images directly from a camera.image = st.camera_input("Take a picture") Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration! PreviousStreamlit ChatStreamlit Component for a Chatbot UI. Created by @AI-Yash.from streamlit_chat import message message("My message") message("Hello bot!", is_user=True) # align's the message to the right Streamlit Option MenuSelect a single item from a list of options in a menu. Created by @victoryhb.from streamlit_option_menu import option_menu option_menu("Main Menu", ["Home", 'Settings'], icons=['house', 'gear'], menu_icon="cast", default_index=1) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.stoggle import stoggle stoggle( "Click me!", """🥷 Surprise! Here's some additional content""",) Streamlit ElementsCreate a draggable and resizable dashboard in Streamlit. Created by @okls.from streamlit_elements import elements, mui, html with elements("new_element"): mui.Typography("Hello world") TagsAdd tags to your Streamlit apps. Created by @gagan3012.from streamlit_tags import st_tags st_tags(label='# Enter Keywords:', text='Press enter to add more', value=['Zero', 'One', 'Two'], suggestions=['five', 'six', 'seven', 'eight', 'nine', 'three', 'eleven', 'ten', 'four'], maxtags = 4, key='1') StqdmThe simplest way to handle a progress bar in streamlit app. Created by @Wirg.from stqdm import stqdm for _ in stqdm(range(50)): sleep(0.5) TimelineDisplay a Timeline in Streamlit apps using TimelineJS. Created by @innerdoc.from streamlit_timeline import timeline with open('example.json', "r") as f: timeline(f.read(), height=800) Camera input liveAlternative for st.camera_input which returns the webcam images live. Created by @blackary.from camera_input_live import camera_input_live image = camera_input_live() st.image(value) Streamlit AceAce editor component for Streamlit. Created by @okld.from streamlit_ace import st_ace content = st_ace() content Streamlit ChatStreamlit Component for a Chatbot UI. Created by @AI-Yash.from streamlit_chat import message message("My message") message("Hello bot!", is_user=True) # align's the message to the right Streamlit Option MenuSelect a single item from a list of options in a menu. Created by @victoryhb.from streamlit_option_menu import option_menu option_menu("Main Menu", ["Home", 'Settings'], icons=['house', 'gear'], menu_icon="cast", default_index=1) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.stoggle import stoggle stoggle( "Click me!", """🥷 Surprise! Here's some additional content""",) Streamlit ElementsCreate a draggable and resizable dashboard in Streamlit. Created by @okls.from streamlit_elements import elements, mui, html with elements("new_element"): mui.Typography("Hello world") TagsAdd tags to your Streamlit apps. Created by @gagan3012.from streamlit_tags import st_tags st_tags(label='# Enter Keywords:', text='Press enter to add more', value=['Zero', 'One', 'Two'], suggestions=['five', 'six', 'seven', 'eight', 'nine', 'three', 'eleven', 'ten', 'four'], maxtags = 4, key='1') StqdmThe simplest way to handle a progress bar in streamlit app. Created by @Wirg.from stqdm import stqdm for _ in stqdm(range(50)): sleep(0.5) TimelineDisplay a Timeline in Streamlit apps using TimelineJS. Created by @innerdoc.from streamlit_timeline import timeline with open('example.json', "r") as f: timeline(f.read(), height=800) Camera input liveAlternative for st.camera_input which returns the webcam images live. Created by @blackary.from camera_input_live import camera_input_live image = camera_input_live() st.image(value) Streamlit AceAce editor component for Streamlit. Created by @okld.from streamlit_ace import st_ace content = st_ace() content Streamlit ChatStreamlit Component for a Chatbot UI. Created by @AI-Yash.from streamlit_chat import message message("My message") message("Hello bot!", is_user=True) # align's the message to the right Streamlit Option MenuSelect a single item from a list of options in a menu. Created by @victoryhb.from streamlit_option_menu import option_menu option_menu("Main Menu", ["Home", 'Settings'], icons=['house', 'gear'], menu_icon="cast", default_index=1) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.stoggle import stoggle stoggle( "Click me!", """🥷 Surprise! Here's some additional content""",) Next Media elements ImageDisplay an image or list of images.st.image(numpy_array) st.image(image_bytes) st.image(file) st.image("https://example.com/myimage.jpg") AudioDisplay an audio player.st.audio(numpy_array) st.audio(audio_bytes) st.audio(file) st.audio("https://example.com/myaudio.mp3", format="audio/mp3") VideoDisplay a video player.st.video(numpy_array) st.video(video_bytes) st.video(file) st.video("https://example.com/myvideo.mp4", format="video/mp4") Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration! PreviousStreamlit CropperA simple image cropper for Streamlit. Created by @turner-anderson.from streamlit_cropper import st_cropper st_cropper(img, realtime_update=realtime_update, box_color=box_color, aspect_ratio=aspect_ratio) Image CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates streamlit_image_coordinates("https://placekitten.com/200/300") Streamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl("https://assets5.lottiefiles.com/packages/lf20_V9t630.json") st_lottie(lottie_hello, key="hello") Streamlit WebrtcHandling and transmitting real-time video/audio streams with Streamlit. Created by @whitphx.from streamlit_webrtc import webrtc_streamer webrtc_streamer(key="sample") Drawable CanvasProvides a sketching canvas using Fabric.js. Created by @andfanilo.from streamlit_drawable_canvas import st_canvas st_canvas(fill_color="rgba(255, 165, 0, 0.3)", stroke_width=stroke_width, stroke_color=stroke_color, background_color=bg_color, background_image=Image.open(bg_image) if bg_image else None, update_streamlit=realtime_update, height=150, drawing_mode=drawing_mode, point_display_radius=point_display_radius if drawing_mode == 'point' else 0, key="canvas",) Image ComparisonCompare images with a slider using JuxtaposeJS. Created by @fcakyon.from streamlit_image_comparison import image_comparison image_comparison(img1="image1.jpg", img2="image2.jpg",) Streamlit CropperA simple image cropper for Streamlit. Created by @turner-anderson.from streamlit_cropper import st_cropper st_cropper(img, realtime_update=realtime_update, box_color=box_color, aspect_ratio=aspect_ratio) Image CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates streamlit_image_coordinates("https://placekitten.com/200/300") Streamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl("https://assets5.lottiefiles.com/packages/lf20_V9t630.json") st_lottie(lottie_hello, key="hello") Streamlit WebrtcHandling and transmitting real-time video/audio streams with Streamlit. Created by @whitphx.from streamlit_webrtc import webrtc_streamer webrtc_streamer(key="sample") Drawable CanvasProvides a sketching canvas using Fabric.js. Created by @andfanilo.from streamlit_drawable_canvas import st_canvas st_canvas(fill_color="rgba(255, 165, 0, 0.3)", stroke_width=stroke_width, stroke_color=stroke_color, background_color=bg_color, background_image=Image.open(bg_image) if bg_image else None, update_streamlit=realtime_update, height=150, drawing_mode=drawing_mode, point_display_radius=point_display_radius if drawing_mode == 'point' else 0, key="canvas",) Image ComparisonCompare images with a slider using JuxtaposeJS. Created by @fcakyon.from streamlit_image_comparison import image_comparison image_comparison(img1="image1.jpg", img2="image2.jpg",) Streamlit CropperA simple image cropper for Streamlit. Created by @turner-anderson.from streamlit_cropper import st_cropper st_cropper(img, realtime_update=realtime_update, box_color=box_color, aspect_ratio=aspect_ratio) Image CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates streamlit_image_coordinates("https://placekitten.com/200/300") Streamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl("https://assets5.lottiefiles.com/packages/lf20_V9t630.json") st_lottie(lottie_hello, key="hello") Next Layouts and containers ColumnsInsert containers laid out as side-by-side columns.col1, col2 = st.columns(2) col1.write("this is column 1") col2.write("this is column 2") ContainerInsert a multi-element container.c = st.container() st.write("This will show last") c.write("This will show first") c.write("This will show second") Modal dialogsInsert a modal dialog that can rerun independently from the rest of the script.@st.experimental_dialog("Sign up") def email_form(): name = st.text_input("Name") email = st.text_input("Email") EmptyInsert a single-element container.c = st.empty() st.write("This will show last") c.write("This will be replaced") c.write("This will show first") ExpanderInsert a multi-element container that can be expanded/collapsed.with st.expander("Open to see more"): st.write("This is more content") PopoverInsert a multi-element popover container that can be opened/closed.with st.popover("Settings"): st.checkbox("Show completed") SidebarDisplay items in a sidebar.st.sidebar.write("This lives in the sidebar") st.sidebar.button("Click me!") TabsInsert containers separated into tabs.tab1, tab2 = st.tabs(["Tab 1", "Tab2"]) tab1.write("this is tab 1") tab2.write("this is tab 2") Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration!Streamlit ElementsCreate a draggable and resizable dashboard in Streamlit. Created by @okls.from streamlit_elements import elements, mui, html with elements("new_element"): mui.Typography("Hello world") PydanticAuto-generate Streamlit UI from Pydantic Models and Dataclasses. Created by @lukasmasuch.import streamlit_pydantic as sp sp.pydantic_form(key="my_form", model=ExampleModel) Streamlit PagesAn experimental version of Streamlit Multi-Page Apps. Created by @blackary.from st_pages import Page, show_pages, add_page_title show_pages([ Page("streamlit_app.py", "Home", "🏠"), Page("other_pages/page2.py", "Page 2", ":books:"), ]) Chat elements Streamlit provides a few commands to help you build conversational apps. These chat elements are designed to be used in conjunction with each other, but you can also use them separately. st.chat_message lets you insert a chat message container into the app so you can display messages from the user or the app. Chat containers can contain other Streamlit elements, including charts, tables, text, and more. st.chat_input lets you display a chat input widget so the user can type in a message. Chat inputDisplay a chat input widget.prompt = st.chat_input("Say something") if prompt: st.write(f"The user has sent: {prompt}") Chat messageInsert a chat message container.import numpy as np with st.chat_message("user"): st.write("Hello 👋") st.line_chart(np.random.randn(30, 3)) Status containerDisplay output of long-running tasks in a container.with st.status('Running'): do_something_slow() st.write_streamWrite generators or streams to the app with a typewriter effect.st.write_stream(my_generator) st.write_stream(my_llm_stream) Status elements Progress barDisplay a progress bar.for i in range(101): st.progress(i) do_something_slow() SpinnerTemporarily displays a message while executing a block of code.with st.spinner("Please wait..."): do_something_slow() Status containerDisplay output of long-running tasks in a container.with st.status('Running'): do_something_slow() ToastBriefly displays a toast message in the bottom-right corner.st.toast('Butter!', icon='🧈') BalloonsDisplay celebratory balloons!do_something() # Celebrate when all done! st.balloons() SnowflakesDisplay celebratory snowflakes!do_something() # Celebrate when all done! st.snow() Success boxDisplay a success message.st.success("Match found!") Info boxDisplay an informational message.st.info("Dataset is updated every day at midnight.") Warning boxDisplay warning message.st.warning("Unable to fetch image. Skipping...") Error boxDisplay error message.st.error("We encountered an error") Exception outputDisplay an exception.e = RuntimeError("This is an exception of type RuntimeError") st.exception(e) Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration!StqdmThe simplest way to handle a progress bar in streamlit app. Created by @Wirg.from stqdm import stqdm for _ in stqdm(range(50)): sleep(0.5) Custom notification boxA custom notification box with the ability to close it out. Created by @Socvest.from streamlit_custom_notification_box import custom_notification_box styles = {'material-icons':{'color': 'red'}, 'text-icon-link-close-container': {'box-shadow': '#3896de 0px 4px'}, 'notification-text': {'':''}, 'close-button':{'':''}, 'link':{'':''}} custom_notification_box(icon='info', textDisplay='We are almost done with your registration...', externalLink='more info', url='#', styles=styles, key="foo") Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.let_it_rain import rain rain(emoji="🎈", font_size=54, falling_speed=5, animation_length="infinite",) App logic and configuration Navigation and pages Switch pageProgrammatically navigates to a specified page.st.switch_page("pages/my_page.py") Page linkDisplay a link to another page in a multipage app.st.page_link("app.py", label="Home", icon="🏠") st.page_link("pages/profile.py", label="My profile") Execution flow Modal dialogsInsert a modal dialog that can rerun independently from the rest of the script.@st.experimental_dialog("Sign up") def email_form(): name = st.text_input("Name") email = st.text_input("Email") FormsCreate a form that batches elements together with a “Submit" button.with st.form(key='my_form'): name = st.text_input("Name") email = st.text_input("Email") st.form_submit_button("Sign up") Partial rerunsDefine a fragment to rerun independently from the rest of the script.@st.experimental_fragment(run_every="10s") def fragment(): df = get_data() st.line_chart(df) Rerun scriptRerun the script immediately.st.rerun() Stop executionStops execution immediately.st.stop() Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration!AutorefreshForce a refresh without tying up a script. Created by @kmcgrady.from streamlit_autorefresh import st_autorefresh st_autorefresh(interval=2000, limit=100, key="fizzbuzzcounter") PydanticAuto-generate Streamlit UI from Pydantic Models and Dataclasses. Created by @lukasmasuch.import streamlit_pydantic as sp sp.pydantic_form(key="my_form", model=ExampleModel) Streamlit PagesAn experimental version of Streamlit Multi-Page Apps. Created by @blackary.from st_pages import Page, show_pages, add_page_title show_pages([ Page("streamlit_app.py", "Home", "🏠"), Page("other_pages/page2.py", "Page 2", ":books:"), ]) Caching and state Cache dataFunction decorator to cache functions that return data (e.g. dataframe transforms, database queries, ML inference).@st.cache_data def long_function(param1, param2): # Perform expensive computation here or # fetch data from the web here return data Cache resourceFunction decorator to cache functions that return global resources (e.g. database connections, ML models).@st.cache_resource def init_model(): # Return a global resource here return pipeline( "sentiment-analysis", model="distilbert-base-uncased-finetuned-sst-2-english" ) Session stateSession state is a way to share variables between reruns, for each user session.st.session_state['key'] = value Query parametersGet, set, or clear the query parameters that are shown in the browser's URL bar.st.query_params[key] = value st.query_params.clear() Connections and databases Setup your connection Create a connectionConnect to a data source or APIconn = st.connection('pets_db', type='sql') pet_owners = conn.query('select * from pet_owners') st.dataframe(pet_owners) Built-in connections SnowflakeConnectionA connection to Snowflake.conn = st.connection('snowflake') SQLConnectionA connection to a SQL database using SQLAlchemy.conn = st.connection('sql') Build your own connections Connection base classBuild your own connection with BaseConnection.class MyConnection(BaseConnection[myconn.MyConnection]): def _connect(self, **kwargs) -> MyConnection: return myconn.connect(**self._secrets, **kwargs) def query(self, query): return self._instance.query(query) Secrets management Secrets singletonAccess secrets from a local TOML file.key = st.secrets["OpenAI_key"] Secrets fileSave your secrets in a per-project or per-profile TOML file.OpenAI_key = "<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/concepts/app-testing/automate-tests#streamlit-app-action
DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsremoveCOREArchitecture & executionaddMultipage appsaddApp designaddADDITIONALConnections and secretsaddCustom componentsaddConfiguration and themingaddApp testingremoveGet startedBeyond the basicsAutomate your testsExampleCheat sheetAPI referenceaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Develop/Concepts/App testing/Automate your testsAutomate your tests with CI One of the key benefits of app testing is that tests can be automated using Continuous Integration (CI). By running tests automatically during development, you can validate that changes to your app don't break existing functionality. You can verify app code as you commit, catch bugs early, and prevent accidental breaks before deployment. There are many popular CI tools, including GitHub Actions, Jenkins, GitLab CI, Azure DevOps, and Circle CI. Streamlit app testing will integrate easily with any of them similar to any other Python tests. GitHub Actions Since many Streamlit apps (and all Community Cloud apps) are built in GitHub, this page uses examples from GitHub Actions. For more information about GitHub Actions, see: Quickstart for GitHub Actions GitHub Actions: About continuous integration GitHub Actions: Build & test Python Streamlit App Action Streamlit App Action provides an easy way to add automated testing to your app repository in GitHub. It also includes basic smoke testing for each page of your app without you writing any test code. To install Streamlit App Action, add a workflow .yml file to your repository's .github/workflows/ folder. For example: # .github/workflows/streamlit-app.yml name: Streamlit app on: push: branches: ["main"] pull_request: branches: ["main"] permissions: contents: read jobs: streamlit: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - uses: actions/setup-python@v5 with: python-version: "3.11" - uses: streamlit/streamlit-app-action@v0.0.3 with: app-path: streamlit_app.py Let's take a look in more detail at what this action workflow is doing. Triggering the workflow on: push: branches: ["main"] pull_request: branches: ["main"] This workflow will be triggered and execute tests on pull requests targeting the main branch, as well as any new commits pushed to the main branch. Note that it will also execute the tests on subsequent commits to any open pull requests. See GitHub Actions: Triggering a workflow for more information and examples. Setting up the test environment jobs: streamlit: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - uses: actions/setup-python@v5 with: python-version: "3.11" The workflow has a streamlit job that executes a series of steps. The job runs on a Docker container with the ubuntu-latest image. actions/checkout@v4 checks out the current repository code from GitHub and copies the code to the job environment. actions/setup-python@v5 installs Python version 3.11. Running the app tests - uses: streamlit/streamlit-app-action@v0.0.3 with: app-path: streamlit_app.py Streamlit App Action does the following: Install pytest and install any dependencies specified in requirements.txt. Run the built-in app smoke tests. Run any other Python tests found in the repository. starTipIf your app doesn't include requirements.txt in the repository root directory, you will need to add a step to install dependencies with your chosen package manager before running Streamlit App Action. The built-in smoke tests have the following behavior: Run the app specified at app-path as an AppTest. Validate that it completes successfully and does not result in an uncaught exception. Do the same for any additional pages/ of the app relative to app-path. If you want to run Streamlit App Action without the smoke tests, you can set skip-smoke: true. Linting your app code Linting is the automated checking of source code for programmatic and stylistic errors. This is done by using a lint tool (otherwise known as a linter). Linting is important to reduce errors and improve the overall quality of your code, especially for repositories with multiple developers or public repositories. You can add automated linting with Ruff by passing ruff: true to Streamlit App Action. - uses: streamlit/streamlit-app-action@v0.0.3 with: app-path: streamlit_app.py ruff: true starTipYou may want to add a pre-commit hook like ruff-pre-commit in your local development environment to fix linting errors before they get to CI. Viewing results If tests fail, the CI workflow will fail and you will see the results in GitHub. Console logs are available by clicking into the workflow run as described here. For higher-level test results, you can use pytest-results-action. You can combine this with Streamlit App Action as follows: # ... setup as above ... - uses: streamlit/streamlit-app-action@v0.0.3 with: app-path: streamlit_app.py # Add pytest-args to output junit xml pytest-args: -v --junit-xml=test-results.xml - if: always() uses: pmeier/pytest-results-action@v0.6.0 with: path: test-results.xml summary: true display-options: fEX Writing your own actions The above is just provided as an example. Streamlit App Action is a quick way to get started. Once you learn the basics of your CI tool of choice, it's easy to build and customize your own automated workflows. This is a great way to improve your overall productivity as a developer and the quality of your apps. Working example As a final working example example, take a look at our streamlit/llm-examples Actions, defined in this workflow file.Previous: Beyond the basicsNext: ExampleforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy
https://docs.streamlit.io/develop/concepts/architecture/st.cache#example-2-when-the-function-arguments-change
DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsremoveCOREArchitecture & executionremoveRunning your appStreamlit's architectureThe app chromeCachingSession StateFormsFragmentsWidget behaviorMultipage appsaddApp designaddADDITIONALConnections and secretsaddCustom componentsaddConfiguration and themingaddApp testingaddAPI referenceaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Develop/Concepts/Architecture & execution/Optimize performance with st.cachedeleteDeprecation noticest.cache was deprecated in version 1.18.0. Use st.cache_data or st.cache_resource instead. Learn more in Caching. Optimize performance with st.cache Streamlit provides a caching mechanism that allows your app to stay performant even when loading data from the web, manipulating large datasets, or performing expensive computations. This is done with the @st.cache decorator. When you mark a function with the @st.cache decorator, it tells Streamlit that whenever the function is called it needs to check a few things: The input parameters that you called the function with The value of any external variable used in the function The body of the function The body of any function used inside the cached function If this is the first time Streamlit has seen these four components with these exact values and in this exact combination and order, it runs the function and stores the result in a local cache. Then, next time the cached function is called, if none of these components changed, Streamlit will just skip executing the function altogether and, instead, return the output previously stored in the cache. The way Streamlit keeps track of changes in these components is through hashing. Think of the cache as an in-memory key-value store, where the key is a hash of all of the above and the value is the actual output object passed by reference. Finally, @st.cache supports arguments to configure the cache's behavior. You can find more information on those in our API reference. Let's take a look at a few examples that illustrate how caching works in a Streamlit app. Example 1: Basic usage For starters, let's take a look at a sample app that has a function that performs an expensive, long-running computation. Without caching, this function is rerun each time the app is refreshed, leading to a poor user experience. Copy this code into a new app and try it out yourself: import streamlit as st import time def expensive_computation(a, b): time.sleep(2) # 👈 This makes the function take 2s to run return a * b a = 2 b = 21 res = expensive_computation(a, b) st.write("Result:", res) Try pressing R to rerun the app, and notice how long it takes for the result to show up. This is because expensive_computation(a, b) is being re-executed every time the app runs. This isn't a great experience. Let's add the @st.cache decorator: import streamlit as st import time @st.cache # 👈 Added this def expensive_computation(a, b): time.sleep(2) # This makes the function take 2s to run return a * b a = 2 b = 21 res = expensive_computation(a, b) st.write("Result:", res) Now run the app again and you'll notice that it is much faster every time you press R to rerun. To understand what is happening, let's add an st.write inside the function: import streamlit as st import time @st.cache(suppress_st_warning=True) # 👈 Changed this def expensive_computation(a, b): # 👇 Added this st.write("Cache miss: expensive_computation(", a, ",", b, ") ran") time.sleep(2) # This makes the function take 2s to run return a * b a = 2 b = 21 res = expensive_computation(a, b) st.write("Result:", res) Now when you rerun the app the text "Cache miss" appears on the first run, but not on any subsequent runs. That's because the cached function is only being executed once, and every time after that you're actually hitting the cache. push_pinNoteYou may have noticed that we've added the suppress_st_warning keyword to the @st.cache decorators. That's because the cached function above uses a Streamlit command itself (st.write in this case), and when Streamlit sees that, it shows a warning that your command will only execute when you get a cache miss. More often than not, when you see that warning it's because there's a bug in your code. However, in our case we're using the st.write command to demonstrate when the cache is being missed, so the behavior Streamlit is warning us about is exactly what we want. As a result, we are passing in suppress_st_warning=True to turn that warning off. Example 2: When the function arguments change Without stopping the previous app server, let's change one of the arguments to our cached function: import streamlit as st import time @st.cache(suppress_st_warning=True) def expensive_computation(a, b): st.write("Cache miss: expensive_computation(", a, ",", b, ") ran") time.sleep(2) # This makes the function take 2s to run return a * b a = 2 b = 210 # 👈 Changed this res = expensive_computation(a, b) st.write("Result:", res) Now the first time you rerun the app it's a cache miss. This is evidenced by the "Cache miss" text showing up and the app taking 2s to finish running. After that, if you press R to rerun, it's always a cache hit. That is, no such text shows up and the app is fast again. This is because Streamlit notices whenever the arguments a and b change and determines whether the function should be re-executed and re-cached. Example 3: When the function body changes Without stopping and restarting your Streamlit server, let's remove the widget from our app and modify the function's code by adding a + 1 to the return value. import streamlit as st import time @st.cache(suppress_st_warning=True) def expensive_computation(a, b): st.write("Cache miss: expensive_computation(", a, ",", b, ") ran") time.sleep(2) # This makes the function take 2s to run return a * b + 1 # 👈 Added a +1 at the end here a = 2 b = 210 res = expensive_computation(a, b) st.write("Result:", res) The first run is a "Cache miss", but when you press R each subsequent run is a cache hit. This is because on first run, Streamlit detected that the function body changed, reran the function, and put the result in the cache. starTipIf you change the function back the result will already be in the Streamlit cache from a previous run. Try it out! Example 4: When an inner function changes Let's make our cached function depend on another function internally: import streamlit as st import time def inner_func(a, b): st.write("inner_func(", a, ",", b, ") ran") return a * b @st.cache(suppress_st_warning=True) def expensive_computation(a, b): st.write("Cache miss: expensive_computation(", a, ",", b, ") ran") time.sleep(2) # This makes the function take 2s to run return inner_func(a, b) + 1 a = 2 b = 210 res = expensive_computation(a, b) st.write("Result:", res) What you see is the usual: The first run results in a cache miss. Every subsequent rerun results in a cache hit. But now let's try modifying the inner_func(): import streamlit as st import time def inner_func(a, b): st.write("inner_func(", a, ",", b, ") ran") return a ** b # 👈 Changed the * to ** here @st.cache(suppress_st_warning=True) def expensive_computation(a, b): st.write("Cache miss: expensive_computation(", a, ",", b, ") ran") time.sleep(2) # This makes the function take 2s to run return inner_func(a, b) + 1 a = 2 b = 21 res = expensive_computation(a, b) st.write("Result:", res) Even though inner_func() is not annotated with @st.cache, when we edit its body we cause a "Cache miss" in the outer expensive_computation(). That's because Streamlit always traverses your code and its dependencies to verify that the cached values are still valid. This means that while developing your app you can edit your code freely without worrying about the cache. Any change you make to your app, Streamlit should do the right thing! Streamlit is also smart enough to only traverse dependencies that belong to your app, and skip over any dependency that comes from an installed Python library. Example 5: Use caching to speed up your app across users Going back to our original function, let's add a widget to control the value of b: import streamlit as st import time @st.cache(suppress_st_warning=True) def expensive_computation(a, b): st.write("Cache miss: expensive_computation(", a, ",", b, ") ran") time.sleep(2) # This makes the function take 2s to run return a * b a = 2 b = st.slider("Pick a number", 0, 10) # 👈 Changed this res = expensive_computation(a, b) st.write("Result:", res) What you'll see: If you move the slider to a number Streamlit hasn't seen before, you'll have a cache miss again. And every subsequent rerun with the same number will be a cache hit, of course. If you move the slider back to a number Streamlit has seen before, the cache is hit and the app is fast as expected. In computer science terms, what is happening here is that @st.cache is memoizing expensive_computation(a, b). But now let's go one step further! Try the following: Move the slider to a number you haven't tried before, such as 9. Pretend you're another user by opening another browser tab pointing to your Streamlit app (usually at http://localhost:8501) In the new tab, move the slider to 9. Notice how this is actually a cache hit! That is, you don't actually see the "Cache miss" text on the second tab even though that second user never moved the slider to 9 at any point prior to this. This happens because the Streamlit cache is global to all users. So everyone contributes to everyone else's performance. Example 6: Mutating cached values As mentioned in the overview section, the Streamlit cache stores items by reference. This allows the Streamlit cache to support structures that aren't memory-managed by Python, such as TensorFlow objects. However, it can also lead to unexpected behavior — which is why Streamlit has a few checks to guide developers in the right direction. Let's look into those checks now. Let's write an app that has a cached function which returns a mutable object, and then let's follow up by mutating that object: import streamlit as st import time @st.cache(suppress_st_warning=True) def expensive_computation(a, b): st.write("Cache miss: expensive_computation(", a, ",", b, ") ran") time.sleep(2) # This makes the function take 2s to run return {"output": a * b} # 👈 Mutable object a = 2 b = 21 res = expensive_computation(a, b) st.write("Result:", res) res["output"] = "result was manually mutated" # 👈 Mutated cached value st.write("Mutated result:", res) When you run this app for the first time, you should see three messages on the screen: Cache miss: expensive_computation(...) ran Result: {output: 42} Mutated result: {output: "result was manually mutated"} No surprises here. But now notice what happens when you rerun you app (i.e. press R): Result: {output: "result was manually mutated"} Mutated result: {output: "result was manually mutated"} Cached object mutated. (...) So what's up? What's going on here is that Streamlit caches the output res by reference. When you mutated res["output"] outside the cached function you ended up inadvertently modifying the cache. This means every subsequent call to expensive_computation(2, 21) will return the wrong value! Since this behavior is usually not what you'd expect, Streamlit tries to be helpful and show you a warning, along with some ideas about how to fix your code. In this specific case, the fix is just to not mutate res["output"] outside the cached function. There was no good reason for us to do that anyway! Another solution would be to clone the result value with res = deepcopy(expensive_computation(2, 21)). Check out the section entitled Fixing caching issues for more information on these approaches and more. Advanced caching In caching, you learned about the Streamlit cache, which is accessed with the @st.cache decorator. In this article you'll see how Streamlit's caching functionality is implemented, so that you can use it to improve the performance of your Streamlit apps. The cache is a key-value store, where the key is a hash of: The input parameters that you called the function with The value of any external variable used in the function The body of the function The body of any function used inside the cached function And the value is a tuple of: The cached output A hash of the cached output (you'll see why soon) For both the key and the output hash, Streamlit uses a specialized hash function that knows how to traverse code, hash special objects, and can have its behavior customized by the user. For example, when the function expensive_computation(a, b), decorated with @st.cache, is executed with a=2 and b=21, Streamlit does the following: Computes the cache key If the key is found in the cache, then: Extracts the previously-cached (output, output_hash) tuple. Performs an Output Mutation Check, where a fresh hash of the output is computed and compared to the stored output_hash. If the two hashes are different, shows a Cached Object Mutated warning. (Note: Setting allow_output_mutation=True disables this step). If the input key is not found in the cache, then: Executes the cached function (i.e. output = expensive_computation(2, 21)). Calculates the output_hash from the function's output. Stores key → (output, output_hash) in the cache. Returns the output. If an error is encountered an exception is raised. If the error occurs while hashing either the key or the output an UnhashableTypeError error is thrown. If you run into any issues, see fixing caching issues. The hash_funcs parameter As described above, Streamlit's caching functionality relies on hashing to calculate the key for cached objects, and to detect unexpected mutations in the cached result. For added expressive power, Streamlit lets you override this hashing process using the hash_funcs argument. Suppose you define a type called FileReference which points to a file in the filesystem: class FileReference: def __init__(self, filename): self.filename = filename @st.cache def func(file_reference): ... By default, Streamlit hashes custom classes like FileReference by recursively navigating their structure. In this case, its hash is the hash of the filename property. As long as the file name doesn't change, the hash will remain constant. However, what if you wanted to have the hasher check for changes to the file's modification time, not just its name? This is possible with @st.cache's hash_funcs parameter: class FileReference: def __init__(self, filename): self.filename = filename def hash_file_reference(file_reference): filename = file_reference.filename return (filename, os.path.getmtime(filename)) @st.cache(hash_funcs={FileReference: hash_file_reference}) def func(file_reference): ... Additionally, you can hash FileReference objects by the file's contents: class FileReference: def __init__(self, filename): self.filename = filename def hash_file_reference(file_reference): with open(file_reference.filename) as f: return f.read() @st.cache(hash_funcs={FileReference: hash_file_reference}) def func(file_reference): ... push_pinNoteBecause Streamlit's hash function works recursively, you don't have to hash the contents inside hash_file_reference Instead, you can return a primitive type, in this case the contents of the file, and Streamlit's internal hasher will compute the actual hash from it. Typical hash functions While it's possible to write custom hash functions, let's take a look at some of the tools that Python provides out of the box. Here's a list of some hash functions and when it makes sense to use them. Python's id function | Example Speed: Fast Use case: If you're hashing a singleton object, like an open database connection or a TensorFlow session. These are objects that will only be instantiated once, no matter how many times your script reruns. lambda _: None | Example Speed: Fast Use case: If you want to turn off hashing of this type. This is useful if you know the object is not going to change. Python's hash() function | Example Speed: Can be slow based the size of the object being cached Use case: If Python already knows how to hash this type correctly. Custom hash function | Example Speed: N/a Use case: If you'd like to override how Streamlit hashes a particular type. Example 1: Pass a database connection around Suppose we want to open a database connection that can be reused across multiple runs of a Streamlit app. For this you can make use of the fact that cached objects are stored by reference to automatically initialize and reuse the connection: @st.cache(allow_output_mutation=True) def get_database_connection(): return db.get_connection() With just 3 lines of code, the database connection is created once and stored in the cache. Then, every subsequent time get_database_connection is called, the already-created connection object is reused automatically. In other words, it becomes a singleton. starTipUse the allow_output_mutation=True flag to suppress the immutability check. This prevents Streamlit from trying to hash the output connection, and also turns off Streamlit's mutation warning in the process. What if you want to write a function that receives a database connection as input? For that, you'll use hash_funcs: @st.cache(hash_funcs={DBConnection: id}) def get_users(connection): # Note: We assume that connection is of type DBConnection. return connection.execute_sql('SELECT * from Users') Here, we use Python's built-in id function, because the connection object is coming from the Streamlit cache via the get_database_connection function. This means that the same connection instance is passed around every time, and therefore it always has the same id. However, if you happened to have a second connection object around that pointed to an entirely different database, it would still be safe to pass it to get_users because its id is guaranteed to be different than the first id. These design patterns apply any time you have an object that points to an external resource, such as a database connection or Tensorflow session. Example 2: Turn off hashing for a specific type You can turn off hashing entirely for a particular type by giving it a custom hash function that returns a constant. One reason that you might do this is to avoid hashing large, slow-to-hash objects that you know are not going to change. For example: @st.cache(hash_funcs={pd.DataFrame: lambda _: None}) def func(huge_constant_dataframe): ... When Streamlit encounters an object of this type, it always converts the object into None, no matter which instance of FooType its looking at. This means all instances are hash to the same value, which effectively cancels out the hashing mechanism. Example 3: Use Python's hash() function Sometimes, you might want to use Python’s default hashing instead of Streamlit's. For example, maybe you've encountered a type that Streamlit is unable to hash, but it's hashable with Python's built-in hash() function: @st.cache(hash_funcs={FooType: hash}) def func(...): ... Previous: CachingNext: Experimental cache primitivesforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy
https://docs.streamlit.io/en/latest/streamlit_components.html#making-your-own-component
DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsremoveCOREArchitecture & executionaddMultipage appsaddApp designaddADDITIONALConnections and secretsaddCustom componentsremoveIntro to custom componentsCreate a ComponentPublish a ComponentLimitationsComponent galleryopen_in_newConfiguration and themingaddApp testingaddAPI referenceaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Develop/Concepts/Custom componentsCustom Components Components are third-party Python modules that extend what's possible with Streamlit. How to use a Component Components are super easy to use: Start by finding the Component you'd like to use. Two great resources for this are: The Component gallery This thread, by Fanilo A. from our forums. Install the Component using your favorite Python package manager. This step and all following steps are described in your component's instructions. For example, to use the fantastic AgGrid Component, you first install it with: pip install streamlit-aggrid In your Python code, import the Component as described in its instructions. For AgGrid, this step is: from st_aggrid import AgGrid ...now you're ready to use it! For AgGrid, that's: AgGrid(my_dataframe) Making your own Component If you're interested in making your own component, check out the following resources: Create a Component Publish a Component Components API Blog post for when we launched Components! Alternatively, if you prefer to learn using videos, our engineer Tim Conkling has put together some amazing tutorials: Video tutorial, part 1 Video tutorial, part 2 Previous: Connections and secretsNext: Intro to custom componentsforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy
https://docs.streamlit.io/develop/api-reference/app-testing/testing-element-classes#sttestingv1element_treetoggle
DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceremovePAGE ELEMENTSWrite and magicaddText elementsaddData elementsaddChart elementsaddInput widgetsaddMedia elementsaddLayouts and containersaddChat elementsaddStatus elementsaddThird-party componentsopen_in_newAPPLICATION LOGICNavigation and pagesaddExecution flowaddCaching and stateaddConnections and secretsaddCustom componentsaddUtilitiesaddConfigurationaddTOOLSApp testingremovest.testing.v1.AppTestTesting element classesCommand lineaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Develop/API reference/App testing/Testing element classesTesting element classes st.testing.v1.element_tree.Block The Block class has the same methods and attributes as AppTest. A Block instance represents a container of elements just as AppTest represents the entire app. For example, Block.button will produce a WidgetList of Button in the same manner as AppTest.button. ChatMessage, Column, and Tab all inherit from Block. For all container classes, parameters of the original element can be obtained as properties. For example, ChatMessage.avatar and Tab.label. st.testing.v1.element_tree.ElementStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeElement base class for testing. This class's methods and attributes are universal for all elements implemented in testing. For example, Caption, Code, Text, and Title inherit from Element. All widget classes also inherit from Element, but have additional methods specific to each widget type. See the AppTest class for the full list of supported elements. For all element classes, parameters of the original element can be obtained as properties. For example, Button.label, Caption.help, and Toast.icon. Class description[source] st.testing.v1.element_tree.Element(proto, root) Methods run(*, timeout=None) Run the AppTest script which contains the element. Attributes value The value or contents of the element. st.testing.v1.element_tree.ButtonStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.button and st.form_submit_button. Class description[source] st.testing.v1.element_tree.Button(proto, root) Methods click() Set the value of the button to True. run(*, timeout=None) Run the AppTest script which contains the element. set_value(v) Set the value of the button. Attributes value The value of the button. (bool) st.testing.v1.element_tree.ChatInputStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.chat_input. Class description[source] st.testing.v1.element_tree.ChatInput(proto, root) Methods run(*, timeout=None) Run the AppTest script which contains the element. set_value(v) Set the value of the widget. Attributes value The value of the widget. (str) st.testing.v1.element_tree.CheckboxStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.checkbox. Class description[source] st.testing.v1.element_tree.Checkbox(proto, root) Methods check() Set the value of the widget to True. run(*, timeout=None) Run the AppTest script which contains the element. set_value(v) Set the value of the widget. uncheck() Set the value of the widget to False. Attributes value The value of the widget. (bool) st.testing.v1.element_tree.ColorPickerStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.color_picker. Class description[source] st.testing.v1.element_tree.ColorPicker(proto, root) Methods pick(v) Set the value of the widget as a hex string. May omit the "#" prefix. run(*, timeout=None) Run the AppTest script which contains the element. set_value(v) Set the value of the widget as a hex string. Attributes value The currently selected value as a hex string. (str) st.testing.v1.element_tree.DateInputStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.date_input. Class description[source] st.testing.v1.element_tree.DateInput(proto, root) Methods run(*, timeout=None) Run the AppTest script which contains the element. set_value(v) Set the value of the widget. Attributes value The value of the widget. (date or Tuple of date) st.testing.v1.element_tree.MultiselectStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.multiselect. Class description[source] st.testing.v1.element_tree.Multiselect(proto, root) Methods run(*, timeout=None) Run the AppTest script which contains the element. select(v) Add a selection to the widget. Do nothing if the value is already selected. If testing a multiselect widget with repeated options, use set_value instead. set_value(v) Set the value of the multiselect widget. (list) unselect(v) Remove a selection from the widget. Do nothing if the value is not already selected. If a value is selected multiple times, the first instance is removed. Attributes format_func The widget's formatting function for displaying options. (callable) indices The indices of the currently selected values from the options. (list) value The currently selected values from the options. (list) st.testing.v1.element_tree.NumberInputStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.number_input. Class description[source] st.testing.v1.element_tree.NumberInput(proto, root) Methods decrement() Decrement the st.number_input widget as if the user clicked "-". increment() Increment the st.number_input widget as if the user clicked "+". run(*, timeout=None) Run the AppTest script which contains the element. set_value(v) Set the value of the st.number_input widget. Attributes value Get the current value of the st.number_input widget. st.testing.v1.element_tree.RadioStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.radio. Class description[source] st.testing.v1.element_tree.Radio(proto, root) Methods run(*, timeout=None) Run the AppTest script which contains the element. set_value(v) Set the selection by value. Attributes format_func The widget's formatting function for displaying options. (callable) index The index of the current selection. (int) value The currently selected value from the options. (Any) st.testing.v1.element_tree.SelectSliderStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.select_slider. Class description[source] st.testing.v1.element_tree.SelectSlider(proto, root) Methods run(*, timeout=None) Run the AppTest script which contains the element. set_range(lower, upper) Set the ranged selection by values. set_value(v) Set the (single) selection by value. Attributes format_func The widget's formatting function for displaying options. (callable) value The currently selected value or range. (Any or Sequence of Any) st.testing.v1.element_tree.SelectboxStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.selectbox. Class description[source] st.testing.v1.element_tree.Selectbox(proto, root) Methods run(*, timeout=None) Run the AppTest script which contains the element. select(v) Set the selection by value. select_index(index) Set the selection by index. set_value(v) Set the selection by value. Attributes format_func The widget's formatting function for displaying options. (callable) index The index of the current selection. (int) value The currently selected value from the options. (Any) st.testing.v1.element_tree.SliderStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.slider. Class description[source] st.testing.v1.element_tree.Slider(proto, root) Methods run(*, timeout=None) Run the AppTest script which contains the element. set_range(lower, upper) Set the ranged value of the slider. set_value(v) Set the (single) value of the slider. Attributes value The currently selected value or range. (Any or Sequence of Any) st.testing.v1.element_tree.TextAreaStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.text_area. Class description[source] st.testing.v1.element_tree.TextArea(proto, root) Methods input(v) Set the value of the widget only if the value does not exceed the maximum allowed characters. run(*, timeout=None) Run the AppTest script which contains the element. set_value(v) Set the value of the widget. Attributes value The current value of the widget. (str) st.testing.v1.element_tree.TextInputStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.text_input. Class description[source] st.testing.v1.element_tree.TextInput(proto, root) Methods input(v) Set the value of the widget only if the value does not exceed the maximum allowed characters. run(*, timeout=None) Run the AppTest script which contains the element. set_value(v) Set the value of the widget. Attributes value The current value of the widget. (str) st.testing.v1.element_tree.TimeInputStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.time_input. Class description[source] st.testing.v1.element_tree.TimeInput(proto, root) Methods decrement() Select the previous available time. increment() Select the next available time. run(*, timeout=None) Run the AppTest script which contains the element. set_value(v) Set the value of the widget. Attributes value The current value of the widget. (time) st.testing.v1.element_tree.ToggleStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.toggle. Class description[source] st.testing.v1.element_tree.Toggle(proto, root) Methods run(*, timeout=None) Run the AppTest script which contains the element. set_value(v) Set the value of the widget. Attributes value The current value of the widget. (bool) Previous: st.testing.v1.AppTestNext: Command lineforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy
https://docs.streamlit.io/develop/concepts/configuration/serving-static-files#details-on-usage
DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsremoveCOREArchitecture & executionaddMultipage appsaddApp designaddADDITIONALConnections and secretsaddCustom componentsaddConfiguration and themingremoveConfiguration optionsHTTPS supportServing static filesCustomize your themeApp testingaddAPI referenceaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Develop/Concepts/Configuration and theming/Serving static filesStatic file serving Streamlit apps can host and serve small, static media files to support media embedding use cases that won't work with the normal media elements. To enable this feature, set enableStaticServing = true under [server] in your config file, or environment variable STREAMLIT_SERVER_ENABLE_STATIC_SERVING=true. Media stored in the folder ./static/ relative to the running app file is served at path app/static/[filename], such as http://localhost:8501/app/static/cat.png. Details on usage Files with the following extensions will be served normally: ".jpg", ".jpeg", ".png", ".gif". Any other file will be sent with header Content-Type:text/plain which will cause browsers to render in plain text. This is included for security - other file types that need to render should be hosted outside the app. Streamlit also sets X-Content-Type-Options:nosniff for all files rendered from the static directory. For apps running on Streamlit Community Cloud: Files available in the Github repo will always be served. Any files generated while the app is running, such as based on user interaction (file upload, etc), are not guaranteed to persist across user sessions. Apps which store and serve many files, or large files, may run into resource limits and be shut down. Example usage Put an image cat.png in the folder ./static/ Add enableStaticServing = true under [server] in your .streamlit/config.toml Any media in the ./static/ folder is served at the relative URL like app/static/cat.png # .streamlit/config.toml [server] enableStaticServing = true # app.py import streamlit as st with st.echo(): st.title("CAT") st.markdown("[![Click me](app/static/cat.png)](https://streamlit.io)") Additional resources: https://docs.streamlit.io/develop/concepts/configuration https://static-file-serving.streamlit.app/ Built with Streamlit 🎈Fullscreen open_in_newPrevious: HTTPS supportNext: Customize your themeforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy
https://docs.streamlit.io/develop/tutorials/databases/mssql#add-username-and-password-to-your-local-app-secrets
DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceaddTutorialsremoveExecution flowaddConnect to data sourcesremoveAWS S3BigQueryDeta BaseFirestoreopen_in_newGoogle Cloud StorageMicrosoft SQL ServerMongoDBMySQLNeonPostgreSQLPrivate Google SheetPublic Google SheetSnowflakeSupabaseTableauTiDBTigerGraphMultipage appsaddWork with LLMsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Develop/Tutorials/Connect to data sources/Microsoft SQL ServerConnect Streamlit to Microsoft SQL Server Introduction This guide explains how to securely access a remote Microsoft SQL Server database from Streamlit Community Cloud. It uses the pyodbc library and Streamlit's Secrets management. Create an SQL Server database push_pinNoteIf you already have a remote database that you want to use, feel free to skip to the next step. First, follow the Microsoft documentation to install SQL Server and the sqlcmd Utility. They have detailed installation guides on how to: Install SQL Server on Windows Install on Red Hat Enterprise Linux Install on SUSE Linux Enterprise Server Install on Ubuntu Run on Docker Provision a SQL VM in Azure Once you have SQL Server installed, note down your SQL Server name, username, and password during setup. Connect locally If you are connecting locally, use sqlcmd to connect to your new local SQL Server instance. In your terminal, run the following command: sqlcmd -S localhost -U SA -P '<YourPassword>' As you are connecting locally, the SQL Server name is localhost, the username is SA, and the password is the one you provided during the SA account setup. You should see a sqlcmd command prompt 1>, if successful. If you run into a connection failure, review Microsoft's connection troubleshooting recommendations for your OS (Linux & Windows). starTipWhen connecting remotely, the SQL Server name is the machine name or IP address. You might also need to open the SQL Server TCP port (default 1433) on your firewall. Create a SQL Server database By now, you have SQL Server running and have connected to it with sqlcmd! 🥳 Let's put it to use by creating a database containing a table with some example values. From the sqlcmd command prompt, run the following Transact-SQL command to create a test database mydb: CREATE DATABASE mydb To execute the above command, type GO on a new line: GO Insert some data Next create a new table, mytable, in the mydb database with three columns and two rows. Switch to the new mydb database: USE mydb Create a new table with the following schema: CREATE TABLE mytable (name varchar(80), pet varchar(80)) Insert some data into the table: INSERT INTO mytable VALUES ('Mary', 'dog'), ('John', 'cat'), ('Robert', 'bird') Type GO to execute the above commands: GO To end your sqlcmd session, type QUIT on a new line. Add username and password to your local app secrets Your local Streamlit app will read secrets from a file .streamlit/secrets.toml in your app's root directory. Create this file if it doesn't exist yet and add the SQL Server name, database name, username, and password as shown below: # .streamlit/secrets.toml server = "localhost" database = "mydb" username = "SA" password = "xxx" priority_highImportantWhen copying your app secrets to Streamlit Community Cloud, be sure to replace the values of server, database, username, and password with those of your remote SQL Server!And add this file to .gitignore and don't commit it to your GitHub repo. Copy your app secrets to Streamlit Community Cloud As the secrets.toml file above is not committed to GitHub, you need to pass its content to your deployed app (on Streamlit Community Cloud) separately. Go to the app dashboard and in the app's dropdown menu, click on Edit Secrets. Copy the content of secrets.toml into the text area. More information is available at Secrets management. Add pyodbc to your requirements file To connect to SQL Server locally with Streamlit, you need to pip install pyodbc, in addition to the Microsoft ODBC driver you installed during the SQL Server installation. On Streamlit Cloud, we have built-in support for SQL Server. On popular demand, we directly added SQL Server tools including the ODBC drivers and the executables sqlcmd and bcp to the container image for Cloud apps, so you don't need to install them. All you need to do is add the pyodbc Python package to your requirements.txt file, and you're ready to go! 🎈 # requirements.txt pyodbc==x.x.x Replace x.x.x ☝️ with the version of pyodbc you want installed on Cloud. push_pinNoteAt this time, Streamlit Community Cloud does not support Azure Active Directory authentication. We will update this tutorial when we add support for Azure Active Directory. Write your Streamlit app Copy the code below to your Streamlit app and run it. Make sure to adapt query to use the name of your table. import streamlit as st import pyodbc # Initialize connection. # Uses st.cache_resource to only run once. @st.cache_resource def init_connection(): return pyodbc.connect( "DRIVER={ODBC Driver 17 for SQL Server};SERVER=" + st.secrets["server"] + ";DATABASE=" + st.secrets["database"] + ";UID=" + st.secrets["username"] + ";PWD=" + st.secrets["password"] ) conn = init_connection() # Perform query. # Uses st.cache_data to only rerun when the query changes or after 10 min. @st.cache_data(ttl=600) def run_query(query): with conn.cursor() as cur: cur.execute(query) return cur.fetchall() rows = run_query("SELECT * from mytable;") # Print results. for row in rows: st.write(f"{row[0]} has a :{row[1]}:") See st.cache_data above? Without it, Streamlit would run the query every time the app reruns (e.g. on a widget interaction). With st.cache_data, it only runs when the query changes or after 10 minutes (that's what ttl is for). Watch out: If your database updates more frequently, you should adapt ttl or remove caching so viewers always see the latest data. Learn more in Caching. If everything worked out (and you used the example table we created above), your app should look like this: Previous: Google Cloud StorageNext: MongoDBforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy
https://docs.streamlit.io/knowledge-base/deploy/remote-start
DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Knowledge base/Deployment issues/App is not loading when running remotelyApp is not loading when running remotely Below are a few common errors that occur when users spin up their own solution to host a Streamlit app remotely. To learn about a deceptively simple way to host Streamlit apps that avoids all the issues below, check out Streamlit Community Cloud. Symptom #1: The app never loads When you enter the app's URL in a browser and all you see is a blank page, a "Page not found" error, a "Connection refused" error, or anything like that, first check that Streamlit is actually running on the remote server. On a Linux server you can SSH into it and then run: ps -Al | grep streamlit If you see Streamlit running, the most likely culprit is the Streamlit port not being exposed. The fix depends on your exact setup. Below are three example fixes: Try port 80: Some hosts expose port 80 by default. To set Streamlit to use that port, start Streamlit with the --server.port option: streamlit run my_app.py --server.port=80 AWS EC2 server: First, click on your instance in the AWS Console. Then scroll down and click on Security Groups → Inbound → Edit. Next, add a Custom TCP rule that allows the Port Range 8501 with Source 0.0.0.0/0. Other types of server: Check the firewall settings. If that still doesn't solve the problem, try running a simple HTTP server instead of Streamlit, and seeing if that works correctly. If it does, then you know the problem lies somewhere in your Streamlit app or configuration (in which case you should ask for help in our forums!) If not, then it's definitely unrelated to Streamlit. How to start a simple HTTP server: python -m http.server [port] Symptom #2: The app says "Please wait..." or shows skeleton elements forever This symptom appears differently starting from version 1.29.0. For earlier versions of Streamlit, a loading app shows a blue box in the center of the page with a "Please wait..." message. Starting from version 1.29.0, a loading app shows skeleton elements. If this loading screen does not go away, the underlying cause is likely one of the following: Using port 3000 which is reserved for internal development. Misconfigured CORS protection. Server is stripping headers from the Websocket connection, thereby breaking compression. To diagnose the issue, first make sure you are not using port 3000. If in doubt, try port 80 as described above. Next, try temporarily disabling CORS protection by running Streamlit with the --server.enableCORS flag set to false: streamlit run my_app.py --server.enableCORS=false If this fixes your issue, you should re-enable CORS protection and then set browser.serverAddress to the URL of your Streamlit app. If the issue persists, try disabling websocket compression by running Streamlit with the --server.enableWebsocketCompression flag set to false streamlit run my_app.py --server.enableWebsocketCompression=false If this fixes your issue, your server setup is likely stripping the Sec-WebSocket-Extensions HTTP header that is used to negotiate Websocket compression. Compression is not required for Streamlit to work, but it's strongly recommended as it improves performance. If you'd like to turn it back on, you'll need to find which part of your infrastructure is stripping the Sec-WebSocket-Extensions HTTP header and change that behavior. Symptom #3: Unable to upload files when running in multiple replicas If the file uploader widget returns an error with status code 403, this is probably due to a misconfiguration in your app's XSRF protection logic. To diagnose the issue, try temporarily disabling XSRF protection by running Streamlit with the --server.enableXsrfProtection flag set to false: streamlit run my_app.py --server.enableXsrfProtection=false If this fixes your issue, you should re-enable XSRF protection and try one or both of the following: Set browser.serverAddress and browser.serverPort to the URL and port of your Streamlit app. Configure your app to use the same secret across every replica by setting the server.cookieSecret config option to the same hard-to-guess string everywhere. Previous: Organizing your apps with workspaces on Streamlit Community CloudNext: Argh. This app has gone over its resource limitsforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy
https://docs.streamlit.io/develop/api-reference/charts/st.pyplot#stpyplot
DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceremovePAGE ELEMENTSWrite and magicaddText elementsaddData elementsaddChart elementsremoveSIMPLEst.area_chartst.bar_chartst.line_chartst.mapst.scatter_chartADVANCEDst.altair_chartst.bokeh_chartst.graphviz_chartst.plotly_chartst.pydeck_chartst.pyplotst.vega_lite_chartInput widgetsaddMedia elementsaddLayouts and containersaddChat elementsaddStatus elementsaddThird-party componentsopen_in_newAPPLICATION LOGICNavigation and pagesaddExecution flowaddCaching and stateaddConnections and secretsaddCustom componentsaddUtilitiesaddConfigurationaddTOOLSApp testingaddCommand lineaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Develop/API reference/Chart elements/st.pyplotst.pyplotStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeDisplay a matplotlib.pyplot figure. Function signature[source] st.pyplot(fig=None, clear_figure=None, use_container_width=True, **kwargs) Parameters fig (Matplotlib Figure) The figure to plot. When this argument isn't specified, this function will render the global figure (but this is deprecated, as described below) clear_figure (bool) If True, the figure will be cleared after being rendered. If False, the figure will not be cleared after being rendered. If left unspecified, we pick a default based on the value of fig. If fig is set, defaults to False. If fig is not set, defaults to True. This simulates Jupyter's approach to matplotlib rendering. use_container_width (bool) If True, set the chart width to the column width. Defaults to True. **kwargs (any) Arguments to pass to Matplotlib's savefig function. Example import streamlit as st import matplotlib.pyplot as plt import numpy as np arr = np.random.normal(1, 1, size=100) fig, ax = plt.subplots() ax.hist(arr, bins=20) st.pyplot(fig) Built with Streamlit 🎈Fullscreen open_in_new Notes Note Deprecation warning. After December 1st, 2020, we will remove the ability to specify no arguments in st.pyplot(), as that requires the use of Matplotlib's global figure object, which is not thread-safe. So please always pass a figure object as shown in the example section above. Matplotlib supports several types of "backends". If you're getting an error using Matplotlib with Streamlit, try setting your backend to "TkAgg": echo "backend: TkAgg" >> ~/.matplotlib/matplotlibrc For more information, see https://matplotlib.org/faq/usage_faq.html. Previous: st.pydeck_chartNext: st.vega_lite_chartforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy
https://docs.streamlit.io/#Streamlit-documentation
DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesStreamlit documentationStreamlit is an open-source Python framework for data scientists and AI/ML engineers to deliver dynamic data apps with only a few lines of code. Build and deploy powerful data apps in minutes. Let's get started!install_desktopSetup and installationGet set up to start working with Streamlit.dvrAPI referenceLearn about our APIs, with actionable explanations of specific functions and features.grid_viewApp galleryTry out awesome apps created by our users, and curated from our forums or Twitter.How to use our docsrocket_launchGet started with Streamlit! Set up your development environment and learn the fundamental concepts, and start coding!descriptionDevelop your Streamlit app! Our API reference explains each Streamlit function with examples. Dive deep into all of our features with conceptual guides. Try out our step-by-step tutorials.cloudDeploy your Streamlit app! Streamlit Community Cloud our free platform for deploying and sharing Streamlit apps. Streamlit in Snowflake is an enterprise-class solution where you can house your data and apps in one, unified, global system. Explore all your options!schoolKnowledge base is a self-serve library of tips, tricks, and articles that answer your questions about creating and deploying Streamlit apps.What's newcrop_7_5Modal dialogsIntroducing st.experimental_dialog to create modal dialogs that can rerun independently from the rest of your app.infoGoogle Material Symbolsst.toast, st.chat_message, and alert messages now support Material Symbols for their icons.highlightMarkdown support for text highlightingYou can set the background color for you text in markdown.videocamMedia autoplayYou can enable autoplay for st.audio andst.video. You can also mute videos.cachedClear specific cached valuesWhen clearing cached values for a function, you can now pass function arguments to clear a specific cached value.question_markst.query_params.from_dict()You can now set all query parameters with a single command.Latest blog postsView all updatesJoin the communityStreamlit is more than just a way to make data apps, it's also a community of creators that share their apps and ideas and help each other make their work better. Please come join us on the community forum. We love to hear your questions, ideas, and help you work through your bugs — stop by today!View forumOther MediaGitHubView the Streamlit source code and issue tracker.YouTubeWatch screencasts made by the Streamlit team and the community.TwitterFollow @streamlit on Twitter to keep up with the latest news.LinkedInFollow @streamlit on the world's largest professional network.NewsletterSign up for communications from Streamlit.Next: Get startedHomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy
https://docs.streamlit.io/deploy/streamlit-community-cloud/share-your-app/indexability#make-sure-your-app-is-public
DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudremoveGet startedaddDeploy your appaddManage your appaddShare your appremoveEmbed your appSearch indexabilityShare previewsManage your accountaddTroubleshootingStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Deploy/Streamlit Community Cloud/Share your app/Search indexabilitySEO and search indexability When you deploy a public app to Streamlit Community Cloud, it is automatically indexed by search engines like Google and Bing on a weekly basis. 🎈 This means that anyone can find your app by searching for its custom subdomain (e.g. "traingenerator.streamlit.app") or by searching for the app's title. Get the most out of app indexability Here are some tips to help you get the most out of app indexability: Make sure your app is public Choose a custom subdomain early Choose a descriptive app title Customize your app's meta description Make sure your app is public All public apps hosted on Streamlit Community Cloud are indexed by search engines. If your app is private, it will not be indexed by search engines. To make your private app public, read Share your app. Choose a custom subdomain early Streamlit Community Cloud automatically generates a random subdomain for your app. However, subdomains are customizable! Custom subdomains modify your app URLs to reflect your app content, personal branding, or whatever you’d like. Read more about custom subdomains in Custom subdomains. By choosing a custom subdomain, you can use it to help people find your app. For example, if you're deploying an app that generates training data, you might choose a subdomain like traingenerator.streamlit.app. This makes it easy for people to find your app by searching for "training generator" or "train generator streamlit app." We recommend choosing a custom subdomain when you deploy your app. This ensures that your app is indexed by search engines using your custom subdomain, rather than the automatically generated one. If you choose a custom subdomain later, your app may be indexed multiple times—once using the default subdomain and once using your custom subdomain. In this case, your old URL will result in a 404 error which can confuse users who are searching for your app. Choose a descriptive app title The meta title of your app is the text that appears in search engine results. It is also the text that appears in the browser tab when your app is open. By default, the meta title of your app is the same as the title of your app. However, you can customize the meta title of your app by setting the st.set_page_config parameter page_title to a custom string. For example: st.set_page_config(page_title="Traingenerator") This will change the meta title of your app to "Traingenerator." This makes it easier for people to find your app by searching for "Traingenerator" or "train generator streamlit app": Google search results for "train generator streamlit app" Customize your app's meta description Meta descriptions are the short descriptions that appear in search engine results. Search engines use the meta description to help users understand what your app is about. From our observations, search engines seem to favor the content in both st.header and st.text over st.title. If you put a description at the top of your app under st.header or st.text, there’s a good chance search engines will use this for the meta description. What does my indexed app look like? If you're curious about what your app looks like in search engine results, you can type the following into Google Search: site:<your-custom-subdomain>.streamlit.app Example: site:traingenerator.streamlit.app Google search results for "site:traingenerator.streamlit.app" What if I don't want my app to be indexed? If you don't want your app to be indexed by search engines, you can make it private. Read Share your app to learn more about making your app private. Note: each workspace can only have one private app. If you want to make your app private, you must first delete any other private app in your workspace or make it public. That said, Streamlit Community Cloud is an open and free platform for the community to deploy, discover, and share Streamlit apps and code with each other. As such, we encourage you to make your app public so that it can be indexed by search engines and discovered by other Streamlit users and community members.Previous: Embed your appNext: Share previewsforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy
https://docs.streamlit.io/develop/tutorials/databases/postgresql#copy-your-app-secrets-to-the-cloud
DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceaddTutorialsremoveExecution flowaddConnect to data sourcesremoveAWS S3BigQueryDeta BaseFirestoreopen_in_newGoogle Cloud StorageMicrosoft SQL ServerMongoDBMySQLNeonPostgreSQLPrivate Google SheetPublic Google SheetSnowflakeSupabaseTableauTiDBTigerGraphMultipage appsaddWork with LLMsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Develop/Tutorials/Connect to data sources/PostgreSQLConnect Streamlit to PostgreSQL Introduction This guide explains how to securely access a remote PostgreSQL database from Streamlit Community Cloud. It uses st.connection and Streamlit's Secrets management. The below example code will only work on Streamlit version >= 1.28, when st.connection was added. Create a PostgreSQL database push_pinNoteIf you already have a database that you want to use, feel free to skip to the next step. First, follow this tutorial to install PostgreSQL and create a database (note down the database name, username, and password!). Open the SQL Shell (psql) and enter the following two commands to create a table with some example values: CREATE TABLE mytable ( name varchar(80), pet varchar(80) ); INSERT INTO mytable VALUES ('Mary', 'dog'), ('John', 'cat'), ('Robert', 'bird'); Add username and password to your local app secrets Your local Streamlit app will read secrets from a file .streamlit/secrets.toml in your app's root directory. Create this file if it doesn't exist yet and add the name, user, and password of your database as shown below: # .streamlit/secrets.toml [connections.postgresql] dialect = "postgresql" host = "localhost" port = "5432" database = "xxx" username = "xxx" password = "xxx" priority_highImportantWhen copying your app secrets to Streamlit Community Cloud, be sure to replace the values of host, port, database, username, and password with those of your remote PostgreSQL database!Add this file to .gitignore and don't commit it to your GitHub repo! Copy your app secrets to the cloud As the secrets.toml file above is not committed to GitHub, you need to pass its content to your deployed app (on Streamlit Community Cloud) separately. Go to the app dashboard and in the app's dropdown menu, click on Edit Secrets. Copy the content of secrets.toml into the text area. More information is available at Secrets management. Add dependencies to your requirements file Add the psycopg2-binary and SQLAlchemy packages to your requirements.txt file, preferably pinning its version (replace x.x.x with the version you want installed): # requirements.txt psycopg2-binary==x.x.x sqlalchemy==x.x.x Write your Streamlit app Copy the code below to your Streamlit app and run it. Make sure to adapt query to use the name of your table. # streamlit_app.py import streamlit as st # Initialize connection. conn = st.connection("postgresql", type="sql") # Perform query. df = conn.query('SELECT * FROM mytable;', ttl="10m") # Print results. for row in df.itertuples(): st.write(f"{row.name} has a :{row.pet}:") See st.connection above? This handles secrets retrieval, setup, query caching and retries. By default, query() results are cached without expiring. In this case, we set ttl="10m" to ensure the query result is cached for no longer than 10 minutes. You can also set ttl=0 to disable caching. Learn more in Caching. If everything worked out (and you used the example table we created above), your app should look like this: Previous: NeonNext: Private Google SheetforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy
https://docs.streamlit.io/deploy/streamlit-community-cloud/deploy-your-app/app-dependencies#other-python-package-managers
DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudremoveGet startedaddDeploy your appremoveApp dependenciesSecrets managementManage your appaddShare your appaddManage your accountaddTroubleshootingStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Deploy/Streamlit Community Cloud/Deploy your app/App dependenciesApp dependencies The main reason that apps fail to build properly is because Streamlit Community Cloud can't find your dependencies! There are two kinds of dependencies your app might have: Python dependencies and external dependencies. Python dependencies are other Python packages (just like Streamlit!) that you import into you script. External dependencies are less common, but they include any other software your script needs to function properly. Since Streamlit Community Cloud runs on Linux, these will be Linux dependencies installed with apt-get outside the Python environment. For your dependencies to be installed correctly, make sure you: Add a requirements file for Python dependencies. (optional) Add a packages.txt file to manage any external dependencies. push_pinNotePython requirements files should be placed either in the root of your repository or in the same directory as your Streamlit app. Add Python dependencies With each import statement in your script, you are bringing in a Python dependency. You need to tell Streamlit Community Cloud how to install those dependencies through a Python package manager. We recommend using a requirements.txt which is based on pip. You should not include built-in Python libraries like math or random in your requirements.txt file. These are a part of Python and aren't installed separately. Also, Streamlit Community Cloud has streamlit installed by default. You don't strictly need to include streamlit unless you want to pin or restrict the version. If you deploy an app without a requirements.txt file, your app will run in an environment with just streamlit (and its dependencies) installed. If you have a script like the following, no extra dependencies would be needed since pandas and numpy are installed as direct dependencies of streamlit. Similarly, math and random are built into Python. import streamlit as st import pandas as pd import numpy as np import math import random st.write('Hi!') However, a valid requirements.txt file would be: streamlit pandas numpy Alternatively, if you needed to specify certain versions, another valid example would be: streamlit==1.24.1 pandas>2.0 numpy<=1.25.1 In the above example, streamlit is pinned to version 1.24.1, pandas must be strictly greater than version 2.0, and numpy must be at-or-below version 1.25.1. Each line in your requirements.txt file is effectively what you would like to pip install into your cloud environment. push_pinNoteWe recommend that you use the latest version of Streamlit to ensure full Streamlit Community Cloud functionality. Be sure to take note of Streamlit's current requirements for package compatibility when planning your environment, especially protobuf>=3.20,<5. If you pin streamlit below 1.20.0, you may experience unexpected results if you've pinned any dependencies of altair. If streamlit is installed below version 1.20.0, altair<5 will be reinstalled on top of your environment for compatibility reasons. When this happens all of altair's dependencies will be updated. Other Python package managers There are other Python package managers besides pip. If you want to consider alternatives to using a requirements.txt file, Streamlit Community Cloud will look for other Python dependency managers to use in the order below. Streamlit will stop and install the first dependency file found. Recognized FilenamePython Package ManagerPipfilepipenvenvironment.ymlcondarequirements.txtpippyproject.tomlpoetry priority_highWarningYou should only use one requirements file for your app. If you include more than one (e.g. requirements.txt and Pipfile), only the first file encountered will be used as described above. Additionally, Streamlit will first look in the directory of your Streamlit app; however, if no requirements file is found, Streamlit will then look at the root of the repo. apt-get dependencies For many apps, a packages.txt file is not required. However, if your script requires any software to be installed that is not a Python package, then you will need a packages.txt file. Streamlit Community Cloud is built on Debian Linux. Anything you would like to apt-get install needs to go in your packages.txt file. If packages.txt exists in the root directory of your repository we automatically detect it, parse it, and install the listed packages. You can read more about apt-get in Linux documentation. Add apt-get dependencies to packages.txt — one package name per line. For example, mysqlclient is a Python package which requires additional software be installed to function. A valid packages.txt file to enable mysqlclient would be: build-essential pkg-config default-libmysqlclient-dev Previous: Deploy your appNext: Secrets managementforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy
https://docs.streamlit.io/deploy/streamlit-community-cloud/get-started/connect-your-github-account#connect-your-github-account
DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudremoveGet startedremoveQuickstartCreate your accountConnect your GitHub accountExplore your workspaceFork and edit a public appTrust and securityDeploy your appaddManage your appaddShare your appaddManage your accountaddTroubleshootingStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Deploy/Streamlit Community Cloud/Get started/Connect your GitHub accountConnect your GitHub account Connecting GitHub to your Streamlit Community Cloud account allows you to deploy apps directly from the files you store in your repos. It also lets the system check for updates to those files and automatically update your app. There are two stages to this authorization: the first happens when you connect your account for the first time and the second happens when you deploy your first app. Everyone is prompted to connect GitHub when they create an account. If you need to connect GitHub to an existing primary identity, see Manage your GitHub connection. This page contains additional information about the authorization needed to connect GitHub. If you have just created your account, you are free to skip ahead and Explore your workspace. GitHub's authorization prompts occur automatically as needed. Authorize your GitHub account There are two different authorization prompts to grant access between Streamlit and your GitHub account. The first authorization—"Authorize Streamlit"—happens when you connect your GitHub account to Streamlit. The second authorization—"Streamlit is requesting additional permissions"—happens when you deploy your first app. You must click "Authorize streamlit" on both. If you are a member of any GitHub organizations, read below to understand the extras steps to authorize an organization. Questions about GitHub permissions? Read some frequently asked questions about our GitHub integration. priority_highImportantYou must have admin permissions to your repo in order to deploy apps. If you don't have admin access, talk to the repo's owner or reach out to us on the Community forum. Organization access If you are working in a repository that is owned by an organization, authorization must be granted by that organization. If you are an owner or member of a GitHub organization when you connect your GitHub account, your authorization prompts will include an extra section labeled "Organization access". Organizations you own For any organization you own, if authorization has not been previously granted or denied you can click "Grant" before you click "Authorize streamlit". Organizations owned by others For an organization you don't own, if authorization has not been previously granted or denied you can click "Request" before you click "Authorize streamlit". Previous or pending authorization If someone has already started the process of authorizing Streamlit for your organization, different options and statuses will display accordingly. Approved access If an organization has already granted Streamlit access, a green check is shown. Pending access If a request has been previously sent but not yet approved, a pending status shows. Denied access If a request has been previously sent and denied, no option to grant or request access is shown. In this case, the organization owner will need to authorize Streamlit from GitHub. See GitHub's documentation on OAuth apps and organizations. What's next? Now that you have your account you can Explore your workspace. Or if you're ready to go, jump right in and Deploy your app.Previous: Create your accountNext: Explore your workspaceforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy
https://docs.streamlit.io/develop/api-reference/app-testing/st.testing.v1.apptest#apptestradio
DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceremovePAGE ELEMENTSWrite and magicaddText elementsaddData elementsaddChart elementsaddInput widgetsaddMedia elementsaddLayouts and containersaddChat elementsaddStatus elementsaddThird-party componentsopen_in_newAPPLICATION LOGICNavigation and pagesaddExecution flowaddCaching and stateaddConnections and secretsaddCustom componentsaddUtilitiesaddConfigurationaddTOOLSApp testingremovest.testing.v1.AppTestTesting element classesCommand lineaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Develop/API reference/App testing/st.testing.v1.AppTest The AppTest class st.testing.v1.AppTestStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA simulated Streamlit app to check the correctness of displayed elements and outputs. An instance of AppTest simulates a running Streamlit app. This class provides methods to set up, manipulate, and inspect the app contents via API instead of a browser UI. It can be used to write automated tests of an app in various scenarios. These can then be run using a tool like pytest. AppTest can be initialized by one of three class methods: st.testing.v1.AppTest.from_file (recommended) st.testing.v1.AppTest.from_string st.testing.v1.AppTest.from_function Once initialized, Session State and widget values can be updated and the script can be run. Unlike an actual live-running Streamlit app, you need to call AppTest.run() explicitly to re-run the app after changing a widget value. Switching pages also requires an explicit, follow-up call to AppTest.run(). AppTest enables developers to build tests on their app as-is, in the familiar python test format, without major refactoring or abstracting out logic to be tested separately from the UI. Tests can run quickly with very low overhead. A typical pattern is to build a suite of tests for an app that ensure consistent functionality as the app evolves, and run the tests locally and/or in a CI environment like Github Actions. Note AppTest only supports testing a single page of an app per instance. For multipage apps, each page will need to be tested separately. No methods exist to programatically switch pages within AppTest. Class description[source] st.testing.v1.AppTest(script_path, *, default_timeout, args=None, kwargs=None) Methods get(element_type) Get elements or widgets of the specified type. run(*, timeout=None) Run the script from the current state. switch_page(page_path) Switch to another page of the app. Attributes secrets (dict[str, Any]) Dictionary of secrets to be used the simulated app. Use dict-like syntax to set secret values for the simulated app. session_state (SafeSessionState) Session State for the simulated app. SafeSessionState object supports read and write operations as usual for Streamlit apps. query_params (dict[str, Any]) Dictionary of query parameters to be used by the simluated app. Use dict-like syntax to set query_params values for the simulated app. button Sequence of all st.button and st.form_submit_button widgets. caption Sequence of all st.caption elements. chat_input Sequence of all st.chat_input widgets. chat_message Sequence of all st.chat_message elements. checkbox Sequence of all st.checkbox widgets. code Sequence of all st.code elements. color_picker Sequence of all st.color_picker widgets. columns Sequence of all columns within st.columns elements. dataframe Sequence of all st.dataframe elements. date_input Sequence of all st.date_input widgets. divider Sequence of all st.divider elements. error Sequence of all st.error elements. exception Sequence of all st.exception elements. expander Sequence of all st.expander elements. header Sequence of all st.header elements. info Sequence of all st.info elements. json Sequence of all st.json elements. latex Sequence of all st.latex elements. main Sequence of elements within the main body of the app. markdown Sequence of all st.markdown elements. metric Sequence of all st.metric elements. multiselect Sequence of all st.multiselect widgets. number_input Sequence of all st.number_input widgets. radio Sequence of all st.radio widgets. select_slider Sequence of all st.select_slider widgets. selectbox Sequence of all st.selectbox widgets. sidebar Sequence of all elements within st.sidebar. slider Sequence of all st.slider widgets. status Sequence of all st.status elements. subheader Sequence of all st.subheader elements. success Sequence of all st.success elements. table Sequence of all st.table elements. tabs Sequence of all tabs within st.tabs elements. text Sequence of all st.text elements. text_area Sequence of all st.text_area widgets. text_input Sequence of all st.text_input widgets. time_input Sequence of all st.time_input widgets. title Sequence of all st.title elements. toast Sequence of all st.toast elements. toggle Sequence of all st.toggle widgets. warning Sequence of all st.warning elements. Initialize a simulated app using AppTest AppTest.from_fileStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeCreate an instance of AppTest to simulate an app page defined within a file. This option is most convenient for CI workflows and testing of published apps. The script must be executable on its own and so must contain all necessary imports. Function signature[source] AppTest.from_file(cls, script_path, *, default_timeout=3) Parameters script_path (str) Path to a script file. The path should be absolute or relative to the file calling .from_file. default_timeout (float) Default time in seconds before a script run is timed out. Can be overridden for individual .run() calls. Returns(AppTest) A simulated Streamlit app for testing. The simulated app can be executed via .run(). AppTest.from_stringStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeCreate an instance of AppTest to simulate an app page defined within a string. This is useful for testing short scripts that fit comfortably as an inline string in the test itself, without having to create a separate file for it. The script must be executable on its own and so must contain all necessary imports. Function signature[source] AppTest.from_string(cls, script, *, default_timeout=3) Parameters script (str) The string contents of the script to be run. default_timeout (float) Default time in seconds before a script run is timed out. Can be overridden for individual .run() calls. Returns(AppTest) A simulated Streamlit app for testing. The simulated app can be executed via .run(). AppTest.from_functionStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeCreate an instance of AppTest to simulate an app page defined within a function. This is similar to AppTest.from_string(), but more convenient to write with IDE assistance. The script must be executable on its own and so must contain all necessary imports. Function signature[source] AppTest.from_function(cls, script, *, default_timeout=3, args=None, kwargs=None) Parameters script (Callable) A function whose body will be used as a script. Must be runnable in isolation, so it must include any necessary imports. default_timeout (float) Default time in seconds before a script run is timed out. Can be overridden for individual .run() calls. args (tuple) An optional tuple of args to pass to the script function. kwargs (dict) An optional dict of kwargs to pass to the script function. Returns(AppTest) A simulated Streamlit app for testing. The simulated app can be executed via .run(). Run an AppTest script AppTest.runStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeRun the script from the current state. This is equivalent to manually rerunning the app or the rerun that occurs upon user interaction. AppTest.run() must be manually called after updating a widget value or switching pages as script reruns do not occur automatically as they do for live-running Streamlit apps. Function signature[source] AppTest.run(*, timeout=None) Parameters timeout (null) The maximum number of seconds to run the script. None means use the default timeout set for the instance of AppTest. Returns(AppTest) self AppTest.switch_pageStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSwitch to another page of the app. This method does not automatically rerun the app. Use a follow-up call to AppTest.run() to obtain the elements on the selected page. Function signature[source] AppTest.switch_page(page_path) Parameters page_path (str) Path of the page to switch to. The path must be relative to the main script's location (e.g. "pages/my_page.py"). Returns(AppTest) self Get AppTest script elements The main value of AppTest is providing an API to programmatically inspect and interact with the elements and widgets produced by a running Streamlit app. Using the AppTest.<element type> properties or AppTest.get() method returns a collection of all the elements or widgets of the specified type that would have been displayed by running the app. Note that you can also retrieve elements within a specific container in the same way - first retrieve the container, then retrieve the elements just in that container. AppTest.getStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeGet elements or widgets of the specified type. This method returns the collection of all elements or widgets of the specified type on the current page. Retrieve a specific element by using its index (order on page) or key lookup. Function signature[source] AppTest.get(element_type) Parameters element_type (str) An element attribute of AppTest. For example, "button", "caption", or "chat_input". Returns(Sequence of Elements) Sequence of elements of the given type. Individual elements can be accessed from a Sequence by index (order on the page). When getting and element_type that is a widget, individual widgets can be accessed by key. For example, at.get("text")[0] for the first st.text element or at.get("slider")(key="my_key") for the st.slider widget with a given key. AppTest.buttonStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.button and st.form_submit_button widgets. Function signature[source] AppTest.button Returns(WidgetList of Button) Sequence of all st.button and st.form_submit_button widgets. Individual widgets can be accessed from a WidgetList by index (order on the page) or key. For example, at.button[0] for the first widget or at.button(key="my_key") for a widget with a given key. AppTest.captionStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.caption elements. Function signature[source] AppTest.caption Returns(ElementList of Caption) Sequence of all st.caption elements. Individual elements can be accessed from an ElementList by index (order on the page). For example, at.caption[0] for the first element. Caption is an extension of the Element class. AppTest.chat_inputStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.chat_input widgets. Function signature[source] AppTest.chat_input Returns(WidgetList of ChatInput) Sequence of all st.chat_input widgets. Individual widgets can be accessed from a WidgetList by index (order on the page) or key. For example, at.chat_input[0] for the first widget or at.chat_input(key="my_key") for a widget with a given key. AppTest.chat_messageStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.chat_message elements. Function signature[source] AppTest.chat_message Returns(Sequence of ChatMessage) Sequence of all st.chat_message elements. Individual elements can be accessed from an ElementList by index (order on the page). For example, at.chat_message[0] for the first element. ChatMessage is an extension of the Block class. AppTest.checkboxStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.checkbox widgets. Function signature[source] AppTest.checkbox Returns(WidgetList of Checkbox) Sequence of all st.checkbox widgets. Individual widgets can be accessed from a WidgetList by index (order on the page) or key. For example, at.checkbox[0] for the first widget or at.checkbox(key="my_key") for a widget with a given key. AppTest.codeStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.code elements. Function signature[source] AppTest.code Returns(ElementList of Code) Sequence of all st.code elements. Individual elements can be accessed from an ElementList by index (order on the page). For example, at.code[0] for the first element. Code is an extension of the Element class. AppTest.color_pickerStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.color_picker widgets. Function signature[source] AppTest.color_picker Returns(WidgetList of ColorPicker) Sequence of all st.color_picker widgets. Individual widgets can be accessed from a WidgetList by index (order on the page) or key. For example, at.color_picker[0] for the first widget or at.color_picker(key="my_key") for a widget with a given key. AppTest.columnsStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all columns within st.columns elements. Each column within a single st.columns will be returned as a separate Column in the Sequence. Function signature[source] AppTest.columns Returns(Sequence of Column) Sequence of all columns within st.columns elements. Individual columns can be accessed from an ElementList by index (order on the page). For example, at.columns[0] for the first column. Column is an extension of the Block class. AppTest.dataframeStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.dataframe elements. Function signature[source] AppTest.dataframe Returns(ElementList of Dataframe) Sequence of all st.dataframe elements. Individual elements can be accessed from an ElementList by index (order on the page). For example, at.dataframe[0] for the first element. Dataframe is an extension of the Element class. AppTest.date_inputStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.date_input widgets. Function signature[source] AppTest.date_input Returns(WidgetList of DateInput) Sequence of all st.date_input widgets. Individual widgets can be accessed from a WidgetList by index (order on the page) or key. For example, at.date_input[0] for the first widget or at.date_input(key="my_key") for a widget with a given key. AppTest.dividerStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.divider elements. Function signature[source] AppTest.divider Returns(ElementList of Divider) Sequence of all st.divider elements. Individual elements can be accessed from an ElementList by index (order on the page). For example, at.divider[0] for the first element. Divider is an extension of the Element class. AppTest.errorStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.error elements. Function signature[source] AppTest.error Returns(ElementList of Error) Sequence of all st.error elements. Individual elements can be accessed from an ElementList by index (order on the page). For example, at.error[0] for the first element. Error is an extension of the Element class. AppTest.exceptionStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.exception elements. Function signature[source] AppTest.exception Returns(ElementList of Exception) Sequence of all st.exception elements. Individual elements can be accessed from an ElementList by index (order on the page). For example, at.exception[0] for the first element. Exception is an extension of the Element class. AppTest.expanderStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.expander elements. Function signature[source] AppTest.expander Returns(Sequence of Expandable) Sequence of all st.expander elements. Individual elements can be accessed from a Sequence by index (order on the page). For example, at.expander[0] for the first element. Expandable is an extension of the Block class. AppTest.headerStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.header elements. Function signature[source] AppTest.header Returns(ElementList of Header) Sequence of all st.header elements. Individual elements can be accessed from an ElementList by index (order on the page). For example, at.header[0] for the first element. Header is an extension of the Element class. AppTest.infoStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.info elements. Function signature[source] AppTest.info Returns(ElementList of Info) Sequence of all st.info elements. Individual elements can be accessed from an ElementList by index (order on the page). For example, at.info[0] for the first element. Info is an extension of the Element class. AppTest.jsonStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.json elements. Function signature[source] AppTest.json Returns(ElementList of Json) Sequence of all st.json elements. Individual elements can be accessed from an ElementList by index (order on the page). For example, at.json[0] for the first element. Json is an extension of the Element class. AppTest.latexStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.latex elements. Function signature[source] AppTest.latex Returns(ElementList of Latex) Sequence of all st.latex elements. Individual elements can be accessed from an ElementList by index (order on the page). For example, at.latex[0] for the first element. Latex is an extension of the Element class. AppTest.mainStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of elements within the main body of the app. Function signature[source] AppTest.main Returns(Block) A container of elements. Block can be queried for elements in the same manner as AppTest. For example, Block.checkbox will return all st.checkbox within the associated container. AppTest.markdownStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.markdown elements. Function signature[source] AppTest.markdown Returns(ElementList of Markdown) Sequence of all st.markdown elements. Individual elements can be accessed from an ElementList by index (order on the page). For example, at.markdown[0] for the first element. Markdown is an extension of the Element class. AppTest.metricStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.metric elements. Function signature[source] AppTest.metric Returns(ElementList of Metric) Sequence of all st.metric elements. Individual elements can be accessed from an ElementList by index (order on the page). For example, at.metric[0] for the first element. Metric is an extension of the Element class. AppTest.multiselectStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.multiselect widgets. Function signature[source] AppTest.multiselect Returns(WidgetList of Multiselect) Sequence of all st.multiselect widgets. Individual widgets can be accessed from a WidgetList by index (order on the page) or key. For example, at.multiselect[0] for the first widget or at.multiselect(key="my_key") for a widget with a given key. AppTest.number_inputStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.number_input widgets. Function signature[source] AppTest.number_input Returns(WidgetList of NumberInput) Sequence of all st.number_input widgets. Individual widgets can be accessed from a WidgetList by index (order on the page) or key. For example, at.number_input[0] for the first widget or at.number_input(key="my_key") for a widget with a given key. AppTest.radioStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.radio widgets. Function signature[source] AppTest.radio Returns(WidgetList of Radio) Sequence of all st.radio widgets. Individual widgets can be accessed from a WidgetList by index (order on the page) or key. For example, at.radio[0] for the first widget or at.radio(key="my_key") for a widget with a given key. AppTest.select_sliderStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.select_slider widgets. Function signature[source] AppTest.select_slider Returns(WidgetList of SelectSlider) Sequence of all st.select_slider widgets. Individual widgets can be accessed from a WidgetList by index (order on the page) or key. For example, at.select_slider[0] for the first widget or at.select_slider(key="my_key") for a widget with a given key. AppTest.selectboxStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.selectbox widgets. Function signature[source] AppTest.selectbox Returns(WidgetList of Selectbox) Sequence of all st.selectbox widgets. Individual widgets can be accessed from a WidgetList by index (order on the page) or key. For example, at.selectbox[0] for the first widget or at.selectbox(key="my_key") for a widget with a given key. AppTest.sidebarStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all elements within st.sidebar. Function signature[source] AppTest.sidebar Returns(Block) A container of elements. Block can be queried for elements in the same manner as AppTest. For example, Block.checkbox will return all st.checkbox within the associated container. AppTest.sliderStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.slider widgets. Function signature[source] AppTest.slider Returns(WidgetList of Slider) Sequence of all st.slider widgets. Individual widgets can be accessed from a WidgetList by index (order on the page) or key. For example, at.slider[0] for the first widget or at.slider(key="my_key") for a widget with a given key. AppTest.subheaderStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.subheader elements. Function signature[source] AppTest.subheader Returns(ElementList of Subheader) Sequence of all st.subheader elements. Individual elements can be accessed from an ElementList by index (order on the page). For example, at.subheader[0] for the first element. Subheader is an extension of the Element class. AppTest.successStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.success elements. Function signature[source] AppTest.success Returns(ElementList of Success) Sequence of all st.success elements. Individual elements can be accessed from an ElementList by index (order on the page). For example, at.success[0] for the first element. Success is an extension of the Element class. AppTest.statusStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.status elements. Function signature[source] AppTest.status Returns(Sequence of Status) Sequence of all st.status elements. Individual elements can be accessed from a Sequence by index (order on the page). For example, at.status[0] for the first element. Status is an extension of the Block class. AppTest.tableStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.table elements. Function signature[source] AppTest.table Returns(ElementList of Table) Sequence of all st.table elements. Individual elements can be accessed from an ElementList by index (order on the page). For example, at.table[0] for the first element. Table is an extension of the Element class. AppTest.tabsStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all tabs within st.tabs elements. Each tab within a single st.tabs will be returned as a separate Tab in the Sequence. Additionally, the tab labels are forwarded to each Tab element as a property. For example, st.tabs("A","B") will yield two Tab objects, with Tab.label returning "A" and "B", respectively. Function signature[source] AppTest.tabs Returns(Sequence of Tab) Sequence of all tabs within st.tabs elements. Individual tabs can be accessed from an ElementList by index (order on the page). For example, at.tabs[0] for the first tab. Tab is an extension of the Block class. AppTest.textStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.text elements. Function signature[source] AppTest.text Returns(ElementList of Text) Sequence of all st.text elements. Individual elements can be accessed from an ElementList by index (order on the page). For example, at.text[0] for the first element. Text is an extension of the Element class. AppTest.text_areaStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.text_area widgets. Function signature[source] AppTest.text_area Returns(WidgetList of TextArea) Sequence of all st.text_area widgets. Individual widgets can be accessed from a WidgetList by index (order on the page) or key. For example, at.text_area[0] for the first widget or at.text_area(key="my_key") for a widget with a given key. AppTest.text_inputStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.text_input widgets. Function signature[source] AppTest.text_input Returns(WidgetList of TextInput) Sequence of all st.text_input widgets. Individual widgets can be accessed from a WidgetList by index (order on the page) or key. For example, at.text_input[0] for the first widget or at.text_input(key="my_key") for a widget with a given key. AppTest.time_inputStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.time_input widgets. Function signature[source] AppTest.time_input Returns(WidgetList of TimeInput) Sequence of all st.time_input widgets. Individual widgets can be accessed from a WidgetList by index (order on the page) or key. For example, at.time_input[0] for the first widget or at.time_input(key="my_key") for a widget with a given key. AppTest.titleStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.title elements. Function signature[source] AppTest.title Returns(ElementList of Title) Sequence of all st.title elements. Individual elements can be accessed from an ElementList by index (order on the page). For example, at.title[0] for the first element. Title is an extension of the Element class. AppTest.toastStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.toast elements. Function signature[source] AppTest.toast Returns(ElementList of Toast) Sequence of all st.toast elements. Individual elements can be accessed from an ElementList by index (order on the page). For example, at.toast[0] for the first element. Toast is an extension of the Element class. AppTest.toggleStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.toggle widgets. Function signature[source] AppTest.toggle Returns(WidgetList of Toggle) Sequence of all st.toggle widgets. Individual widgets can be accessed from a WidgetList by index (order on the page) or key. For example, at.toggle[0] for the first widget or at.toggle(key="my_key") for a widget with a given key. AppTest.warningStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.warning elements. Function signature[source] AppTest.warning Returns(ElementList of Warning) Sequence of all st.warning elements. Individual elements can be accessed from an ElementList by index (order on the page). For example, at.warning[0] for the first element. Warning is an extension of the Element class. Previous: App testingNext: Testing element classesforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy
https://docs.streamlit.io/deploy/tutorials/kubernetes
DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsremoveDockerKubernetesschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Deploy/Other platforms/KubernetesDeploy Streamlit using Kubernetes Introduction So you have an amazing app and you want to start sharing it with other people, what do you do? You have a few options. First, where do you want to run your Streamlit app, and how do you want to access it? On your corporate network - Most corporate networks are closed to the outside world. You typically use a VPN to log onto your corporate network and access resources there. You could run your Streamlit app on a server in your corporate network for security reasons, to ensure that only folks internal to your company can access it. On the cloud - If you'd like to access your Streamlit app from outside of a corporate network, or share your app with folks outside of your home network or laptop, you might choose this option. In this case, it'll depend on your hosting provider. We have community-submitted guides from Heroku, AWS, and other providers. Wherever you decide to deploy your app, you will first need to containerize it. This guide walks you through using Kubernetes to deploy your app. If you prefer Docker see Deploy Streamlit using Docker. Prerequisites Install Docker Engine Install the gcloud CLI Install Docker Engine If you haven't already done so, install Docker on your server. Docker provides .deb and .rpm packages from many Linux distributions, including: Debian Ubuntu Verify that Docker Engine is installed correctly by running the hello-world Docker image: sudo docker run hello-world starTipFollow Docker's official post-installation steps for Linux to run Docker as a non-root user, so that you don't have to preface the docker command with sudo. Install the gcloud CLI In this guide, we will orchestrate Docker containers with Kubernetes and host docker images on the Google Container Registry (GCR). As GCR is a Google-supported Docker registry, we need to register gcloud as the Docker credential helper. Follow the official documentation to Install the gcloud CLI and initialize it. Create a Docker container We need to create a docker container which contains all the dependencies and the application code. Below you can see the entrypoint, i.e. the command run when the container starts, and the Dockerfile definition. Create an entrypoint script Create a run.sh script containing the following: #!/bin/bash APP_PID= stopRunningProcess() { # Based on https://linuxconfig.org/how-to-propagate-a-signal-to-child-processes-from-a-bash-script if test ! "${APP_PID}" = '' && ps -p ${APP_PID} > /dev/null ; then > /proc/1/fd/1 echo "Stopping ${COMMAND_PATH} which is running with process ID ${APP_PID}" kill -TERM ${APP_PID} > /proc/1/fd/1 echo "Waiting for ${COMMAND_PATH} to process SIGTERM signal" wait ${APP_PID} > /proc/1/fd/1 echo "All processes have stopped running" else > /proc/1/fd/1 echo "${COMMAND_PATH} was not started when the signal was sent or it has already been stopped" fi } trap stopRunningProcess EXIT TERM source ${VIRTUAL_ENV}/bin/activate streamlit run ${HOME}/app/streamlit_app.py & APP_ID=${!} wait ${APP_ID} Create a Dockerfile Docker builds images by reading the instructions from a Dockerfile. A Dockerfile is a text document that contains all the commands a user could call on the command line to assemble an image. Learn more in the Dockerfile reference. The docker build command builds an image from a Dockerfile. The docker run command first creates a container over the specified image, and then starts it using the specified command. Here's an example Dockerfile that you can add to the root of your directory. FROM python:3.8-slim RUN groupadd --gid 1000 appuser \ && useradd --uid 1000 --gid 1000 -ms /bin/bash appuser RUN pip3 install --no-cache-dir --upgrade \ pip \ virtualenv RUN apt-get update && apt-get install -y \ build-essential \ software-properties-common \ git USER appuser WORKDIR /home/appuser RUN git clone https://github.com/streamlit/streamlit-example.git app ENV VIRTUAL_ENV=/home/appuser/venv RUN virtualenv ${VIRTUAL_ENV} RUN . ${VIRTUAL_ENV}/bin/activate && pip install -r app/requirements.txt EXPOSE 8501 COPY run.sh /home/appuser ENTRYPOINT ["./run.sh"] priority_highImportantAs mentioned in Development flow, for Streamlit version 1.10.0 and higher, Streamlit apps cannot be run from the root directory of Linux distributions. Your main script should live in a directory other than the root directory. If you try to run a Streamlit app from the root directory, Streamlit will throw a FileNotFoundError: [Errno 2] No such file or directory error. For more information, see GitHub issue #5239.If you are using Streamlit version 1.10.0 or higher, you must set the WORKDIR to a directory other than the root directory. For example, you can set the WORKDIR to /home/appuser as shown in the example Dockerfile above. Build a Docker image Put the above files (run.sh and Dockerfile) in the same folder and build the docker image: docker build --platform linux/amd64 -t gcr.io/$GCP_PROJECT_ID/k8s-streamlit:test . priority_highImportantReplace $GCP_PROJECT_ID in the above command with the name of your Google Cloud project. Upload the Docker image to a container registry The next step is to upload the Docker image to a container registry. In this example, we will use the Google Container Registry (GCR). Start by enabling the Container Registry API. Sign in to Google Cloud and navigate to your project’s Container Registry and click Enable. We can now build the Docker image from the previous step and push it to our project’s GCR. Be sure to replace $GCP_PROJECT_ID in the docker push command with the name of your project: gcloud auth configure-docker docker push gcr.io/$GCP_PROJECT_ID/k8s-streamlit:test Create a Kubernetes deployment For this step you will need a: Running Kubernetes service Custom domain for which you can generate a TLS certificate DNS service where you can configure your custom domain to point to the application IP As the image was uploaded to the container registry in the previous step, we can run it in Kubernetes using the below configurations. Install and run Kubernetes Make sure your Kubernetes client, kubectl, is installed and running on your machine. Configure a Google OAuth Client and oauth2-proxy For configuring the Google OAuth Client, please see Google Auth Provider. Configure oauth2-proxy to use the desired OAuth Provider Configuration and update the oath2-proxy config in the config map. The below configuration contains a ouath2-proxy sidecar container which handles the authentication with Google. You can learn more from the oauth2-proxy repository. Create a Kubernetes configuration file Create a YAML configuration file named k8s-streamlit.yaml: apiVersion: v1 kind: ConfigMap metadata: name: streamlit-configmap data: oauth2-proxy.cfg: |- http_address = "0.0.0.0:4180" upstreams = ["http://127.0.0.1:8501/"] email_domains = ["*"] client_id = "<GOOGLE_CLIENT_ID>" client_secret = "<GOOGLE_CLIENT_SECRET>" cookie_secret = "<16, 24, or 32 bytes>" redirect_url = <REDIRECT_URL> --- apiVersion: apps/v1 kind: Deployment metadata: name: streamlit-deployment labels: app: streamlit spec: replicas: 1 selector: matchLabels: app: streamlit template: metadata: labels: app: streamlit spec: containers: - name: oauth2-proxy image: quay.io/oauth2-proxy/oauth2-proxy:v7.2.0 args: ["--config", "/etc/oauth2-proxy/oauth2-proxy.cfg"] ports: - containerPort: 4180 livenessProbe: httpGet: path: /ping port: 4180 scheme: HTTP readinessProbe: httpGet: path: /ping port: 4180 scheme: HTTP volumeMounts: - mountPath: "/etc/oauth2-proxy" name: oauth2-config - name: streamlit image: gcr.io/GCP_PROJECT_ID/k8s-streamlit:test imagePullPolicy: Always ports: - containerPort: 8501 livenessProbe: httpGet: path: /_stcore/health port: 8501 scheme: HTTP timeoutSeconds: 1 readinessProbe: httpGet: path: /_stcore/health port: 8501 scheme: HTTP timeoutSeconds: 1 resources: limits: cpu: 1 memory: 2Gi requests: cpu: 100m memory: 745Mi volumes: - name: oauth2-config configMap: name: streamlit-configmap --- apiVersion: v1 kind: Service metadata: name: streamlit-service spec: type: LoadBalancer selector: app: streamlit ports: - name: streamlit-port protocol: TCP port: 80 targetPort: 4180 priority_highImportantWhile the above configurations can be copied verbatim, you will have to configure the oauth2-proxy yourself and use the correct GOOGLE_CLIENT_ID, GOOGLE_CLIENT_ID, GCP_PROJECT_ID, and REDIRECT_URL. Now create the configuration from the file in Kubernetes with the kubectl create command: kubctl create -f k8s-streamlit.yaml Set up TLS support Since you are using the Google authentication, you will need to set up TLS support. Find out how in TLS Configuration. Verify the deployment Once the deployment and the service are created, we need to wait a couple of minutes for the public IP address to become available. We can check when that is ready by running: kubectl get service streamlit-service -o jsonpath='{.status.loadBalancer.ingress[0].ip}' After the public IP is assigned, you will need to configure in your DNS service an A record pointing to the above IP address.Previous: DockerNext: Knowledge baseforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy
https://docs.streamlit.io/develop/api-reference/charts/st.map#elementadd_rows
DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceremovePAGE ELEMENTSWrite and magicaddText elementsaddData elementsaddChart elementsremoveSIMPLEst.area_chartst.bar_chartst.line_chartst.mapst.scatter_chartADVANCEDst.altair_chartst.bokeh_chartst.graphviz_chartst.plotly_chartst.pydeck_chartst.pyplotst.vega_lite_chartInput widgetsaddMedia elementsaddLayouts and containersaddChat elementsaddStatus elementsaddThird-party componentsopen_in_newAPPLICATION LOGICNavigation and pagesaddExecution flowaddCaching and stateaddConnections and secretsaddCustom componentsaddUtilitiesaddConfigurationaddTOOLSApp testingaddCommand lineaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Develop/API reference/Chart elements/st.mapst.mapStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeDisplay a map with a scatterplot overlaid onto it. This is a wrapper around st.pydeck_chart to quickly create scatterplot charts on top of a map, with auto-centering and auto-zoom. When using this command, Mapbox provides the map tiles to render map content. Note that Mapbox is a third-party product and Streamlit accepts no responsibility or liability of any kind for Mapbox or for any content or information made available by Mapbox. Mapbox requires users to register and provide a token before users can request map tiles. Currently, Streamlit provides this token for you, but this could change at any time. We strongly recommend all users create and use their own personal Mapbox token to avoid any disruptions to their experience. You can do this with the mapbox.token config option. The use of Mapbox is governed by Mapbox's Terms of Use. To get a token for yourself, create an account at https://mapbox.com. For more info on how to set config options, see https://docs.streamlit.io/library/advanced-features/configuration Function signature[source] st.map(data=None, *, latitude=None, longitude=None, color=None, size=None, zoom=None, use_container_width=True) Parameters data (pandas.DataFrame, pandas.Styler, pyarrow.Table, pyspark.sql.DataFrame, snowflake.snowpark.dataframe.DataFrame, snowflake.snowpark.table.Table, Iterable, dict, or None) The data to be plotted. latitude (str or None) The name of the column containing the latitude coordinates of the datapoints in the chart. If None, the latitude data will come from any column named 'lat', 'latitude', 'LAT', or 'LATITUDE'. longitude (str or None) The name of the column containing the longitude coordinates of the datapoints in the chart. If None, the longitude data will come from any column named 'lon', 'longitude', 'LON', or 'LONGITUDE'. color (str or tuple or None) The color of the circles representing each datapoint. Can be: None, to use the default color. A hex string like "#ffaa00" or "#ffaa0088". An RGB or RGBA tuple with the red, green, blue, and alpha components specified as ints from 0 to 255 or floats from 0.0 to 1.0. The name of the column to use for the color. Cells in this column should contain colors represented as a hex string or color tuple, as described above. size (str or float or None) The size of the circles representing each point, in meters. This can be: None, to use the default size. A number like 100, to specify a single size to use for all datapoints. The name of the column to use for the size. This allows each datapoint to be represented by a circle of a different size. zoom (int) Zoom level as specified in https://wiki.openstreetmap.org/wiki/Zoom_levels. use_container_width (bool) If True, set the chart width to the column width. This takes precedence over the width argument. Examples import streamlit as st import pandas as pd import numpy as np df = pd.DataFrame( np.random.randn(1000, 2) / [50, 50] + [37.76, -122.4], columns=['lat', 'lon']) st.map(df) Built with Streamlit 🎈Fullscreen open_in_new You can also customize the size and color of the datapoints: st.map(df, size=20, color='#0044ff') And finally, you can choose different columns to use for the latitude and longitude components, as well as set size and color of each datapoint dynamically based on other columns: import streamlit as st import pandas as pd import numpy as np df = pd.DataFrame({ "col1": np.random.randn(1000) / 50 + 37.76, "col2": np.random.randn(1000) / 50 + -122.4, "col3": np.random.randn(1000) * 100, "col4": np.random.rand(1000, 4).tolist(), }) st.map(df, latitude='col1', longitude='col2', size='col3', color='col4') Built with Streamlit 🎈Fullscreen open_in_new element.add_rowsStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeConcatenate a dataframe to the bottom of the current one. Function signature[source] element.add_rows(data=None, **kwargs) Parameters data (pandas.DataFrame, pandas.Styler, pyarrow.Table, numpy.ndarray, pyspark.sql.DataFrame, snowflake.snowpark.dataframe.DataFrame, Iterable, dict, or None) Table to concat. Optional. **kwargs (pandas.DataFrame, numpy.ndarray, Iterable, dict, or None) The named dataset to concat. Optional. You can only pass in 1 dataset (including the one in the data parameter). Example import streamlit as st import pandas as pd import numpy as np df1 = pd.DataFrame(np.random.randn(50, 20), columns=("col %d" % i for i in range(20))) my_table = st.table(df1) df2 = pd.DataFrame(np.random.randn(50, 20), columns=("col %d" % i for i in range(20))) my_table.add_rows(df2) # Now the table shown in the Streamlit app contains the data for # df1 followed by the data for df2. You can do the same thing with plots. For example, if you want to add more data to a line chart: # Assuming df1 and df2 from the example above still exist... my_chart = st.line_chart(df1) my_chart.add_rows(df2) # Now the chart shown in the Streamlit app contains the data for # df1 followed by the data for df2. And for plots whose datasets are named, you can pass the data with a keyword argument where the key is the name: my_chart = st.vega_lite_chart({ 'mark': 'line', 'encoding': {'x': 'a', 'y': 'b'}, 'datasets': { 'some_fancy_name': df1, # <-- named dataset }, 'data': {'name': 'some_fancy_name'}, }), my_chart.add_rows(some_fancy_name=df2) # <-- name used as keyword Previous: st.line_chartNext: st.scatter_chartforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy
https://docs.streamlit.io/deploy/streamlit-community-cloud/get-started/create-your-account#sign-up
DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudremoveGet startedremoveQuickstartCreate your accountConnect your GitHub accountExplore your workspaceFork and edit a public appTrust and securityDeploy your appaddManage your appaddShare your appaddManage your accountaddTroubleshootingStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Deploy/Streamlit Community Cloud/Get started/Create your accountCreate your account Before you can start deploying apps for the world to see, you need to sign up for your Streamlit Community Cloud account. Streamlit Community Cloud accounts have two underlying identities: primary and source control. Your primary identity is used for viewing analytics as well as viewing permissions. Your source-control identity is used for deploying and managing apps. Sign up Although you can begin the sign-up process with GitHub, we recommend starting with Google or email in order to have a complete account from the start. Step 1: Primary identity (Google or email) Step 2: Source control (GitHub) Step 3: Set up your account Step 1: Primary identity Your primary identity is associated to an email. You can sign in through Google or through single-use, emailed links which are valid for 15 minutes once requested. If you're sharing a private app, you will assign viewing permission by email. Therefore, your app's users will need to sign in with either Google or emailed links. Primary identity option 1: Google Go to share.streamlit.io/signup. Click "Continue with Google". Enter your Google credentials and click "Next". If you will be deploying or managing any apps, click "Connect GitHub account" and proceed to Step 2: Source Control. If you are only going to be viewing apps and will not be using GitHub, you can click "Skip this step" and proceed to Step 3: Set up your account. Primary identity option 2: email Go to share.streamlit.io/signup. Enter your email address and click "Continue with email". A confirmation screen will display, telling you to check your email. Check your inbox for an email with the subject "Sign in to Streamlit Cloud". Click the link to sign in. If you will be deploying or managing any apps, click "Connect GitHub account" and proceed to Step 2: Source control. If you are only going to be viewing apps and will not be using GitHub, you can click "Skip this step" and proceed to Step 3: Set up your account. Step 2: Source control Streamlit Community Cloud is integrated with GitHub for source control. If you begin your sign-up process with GitHub, you will not be directly prompted to create a primary identity. However, you can attach a Google account later. There are two different authorization requests to completely Connect your GitHub account. You will encounter the first authorization request when you begin connecting your GitHub account. A second authorization is needed the first time you deploy an app. If you will be deploying or managing any apps from a GitHub organization, your authorization requests will include additional options to allow Organization access. After completing Step 1: Primary identity or after clicking "Continue with GitHub" from the sign-up page, enter your GitHub credentials and click "Sign in". Click "Authorize streamlit". Continue to Step 3: Set up your account Step 3: Set up your account As a final step to account creation, please tell us about yourself and your experience with Streamlit. This is also when you can read and acknowledge our Terms of use and Privacy notice. The email you provide in this survey is not used as your account email. Fill in your information and click "Continue" at the bottom of the screen. You will be taken to your workspace. Finish up Congratulations on creating your Streamlit Community Cloud account! A warning icon (warning) next to "Settings" in the upper-right corner is expected; this indicates one of three things: You created a primary identity and skipped connecting GitHub. You started with GitHub and did not create a primary identity. You created both a primary identity and connected GitHub, but the second authorization for GitHub is still pending. You will be prompted with the second authorization when you deploy your first app. What's next? Now that you have your account you can Explore your workspace. Or if you're ready to go, jump right in and Deploy your app.Previous: QuickstartNext: Connect your GitHub accountforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy
https://docs.streamlit.io/develop/api-reference/caching-and-state/st.experimental_singleton#supported-widgets
DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceremovePAGE ELEMENTSWrite and magicaddText elementsaddData elementsaddChart elementsaddInput widgetsaddMedia elementsaddLayouts and containersaddChat elementsaddStatus elementsaddThird-party componentsopen_in_newAPPLICATION LOGICNavigation and pagesaddExecution flowaddCaching and stateremovest.cache_datast.cache_resourcest.cachedeletest.session_statest.query_paramsst.experimental_get_query_paramsdeletest.experimental_set_query_paramsdeleteConnections and secretsaddCustom componentsaddUtilitiesaddConfigurationaddTOOLSApp testingaddCommand lineaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Develop/API reference/Caching and state/st.experimental_singletonpriority_highImportantThis is an experimental feature. Experimental features and their APIs may change or be removed at any time. To learn more, click here. st.experimental_singletonStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakedeleteDeprecation noticest.experimental_singleton was deprecated in version 1.18.0. Use st.cache_resource instead. Learn more in Caching.Decorator to cache functions that return global resources (e.g. database connections, ML models). Cached objects are shared across all users, sessions, and reruns. They must be thread-safe because they can be accessed from multiple threads concurrently. If thread safety is an issue, consider using st.session_state to store resources per session instead. You can clear a function's cache with func.clear() or clear the entire cache with st.cache_resource.clear(). To cache data, use st.cache_data instead. Learn more about caching at https://docs.streamlit.io/library/advanced-features/caching. Function signature[source] st.experimental_singleton(func, *, ttl, max_entries, show_spinner, validate, experimental_allow_widgets, hash_funcs=None) Parameters func (callable) The function that creates the cached resource. Streamlit hashes the function's source code. ttl (float, timedelta, str, or None) The maximum time to keep an entry in the cache. Can be one of: None if cache entries should never expire (default). A number specifying the time in seconds. A string specifying the time in a format supported by Pandas's Timedelta constructor, e.g. "1d", "1.5 days", or "1h23s". A timedelta object from Python's built-in datetime library, e.g. timedelta(days=1). max_entries (int or None) The maximum number of entries to keep in the cache, or None for an unbounded cache. When a new entry is added to a full cache, the oldest cached entry will be removed. Defaults to None. show_spinner (bool or str) Enable the spinner. Default is True to show a spinner when there is a "cache miss" and the cached resource is being created. If string, value of show_spinner param will be used for spinner text. validate (callable or None) An optional validation function for cached data. validate is called each time the cached value is accessed. It receives the cached value as its only parameter and it must return a boolean. If validate returns False, the current cached value is discarded, and the decorated function is called to compute a new value. This is useful e.g. to check the health of database connections. experimental_allow_widgets (bool) Allow widgets to be used in the cached function. Defaults to False. Support for widgets in cached functions is currently experimental. Setting this parameter to True may lead to excessive memory use since the widget value is treated as an additional input parameter to the cache. We may remove support for this option at any time without notice. hash_funcs (dict or None) Mapping of types or fully qualified names to hash functions. This is used to override the behavior of the hasher inside Streamlit's caching mechanism: when the hasher encounters an object, it will first check to see if its type matches a key in this dict and, if so, will use the provided function to generate a hash for it. See below for an example of how this can be used. Example import streamlit as st @st.cache_resource def get_database_session(url): # Create a database session object that points to the URL. return session s1 = get_database_session(SESSION_URL_1) # Actually executes the function, since this is the first time it was # encountered. s2 = get_database_session(SESSION_URL_1) # Does not execute the function. Instead, returns its previously computed # value. This means that now the connection object in s1 is the same as in s2. s3 = get_database_session(SESSION_URL_2) # This is a different URL, so the function executes. By default, all parameters to a cache_resource function must be hashable. Any parameter whose name begins with _ will not be hashed. You can use this as an "escape hatch" for parameters that are not hashable: import streamlit as st @st.cache_resource def get_database_session(_sessionmaker, url): # Create a database connection object that points to the URL. return connection s1 = get_database_session(create_sessionmaker(), DATA_URL_1) # Actually executes the function, since this is the first time it was # encountered. s2 = get_database_session(create_sessionmaker(), DATA_URL_1) # Does not execute the function. Instead, returns its previously computed # value - even though the _sessionmaker parameter was different # in both calls. A cache_resource function's cache can be procedurally cleared: import streamlit as st @st.cache_resource def get_database_session(_sessionmaker, url): # Create a database connection object that points to the URL. return connection fetch_and_clean_data.clear(_sessionmaker, "https://streamlit.io/") # Clear the cached entry for the arguments provided. get_database_session.clear() # Clear all cached entries for this function. To override the default hashing behavior, pass a custom hash function. You can do that by mapping a type (e.g. Person) to a hash function (str) like this: import streamlit as st from pydantic import BaseModel class Person(BaseModel): name: str @st.cache_resource(hash_funcs={Person: str}) def get_person_name(person: Person): return person.name Alternatively, you can map the type's fully-qualified name (e.g. "__main__.Person") to the hash function instead: import streamlit as st from pydantic import BaseModel class Person(BaseModel): name: str @st.cache_resource(hash_funcs={"__main__.Person": str}) def get_person_name(person: Person): return person.name st.experimental_singleton.clearStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakedeleteDeprecation noticest.experimental_singleton.clear was deprecated in version 1.18.0. Use st.cache_resource.clear instead. Learn more in Caching.Clear all cache_resource caches. Function signature[source] st.experimental_singleton.clear() Example In the example below, pressing the "Clear All" button will clear all singleton caches. i.e. Clears cached singleton objects from all functions decorated with @st.experimental_singleton. import streamlit as st from transformers import BertModel @st.experimental_singleton def get_database_session(url): # Create a database session object that points to the URL. return session @st.experimental_singleton def get_model(model_type): # Create a model of the specified type. return BertModel.from_pretrained(model_type) if st.button("Clear All"): # Clears all singleton caches: st.experimental_singleton.clear() Validating the cache The @st.experimental_singleton decorator is used to cache the output of a function, so that it only needs to be executed once. This can improve performance in certain situations, such as when a function takes a long time to execute or makes a network request. However, in some cases, the cached output may become invalid over time, such as when a database connection times out. To handle this, the @st.experimental_singleton decorator supports an optional validate parameter, which accepts a validation function that is called each time the cached output is accessed. If the validation function returns False, the cached output is discarded and the decorated function is executed again. Best Practices Use the validate parameter when the cached output may become invalid over time, such as when a database connection or an API key expires. Use the validate parameter judiciously, as it will add an additional overhead of calling the validation function each time the cached output is accessed. Make sure that the validation function is as fast as possible, as it will be called each time the cached output is accessed. Consider to validate cached data periodically, instead of each time it is accessed, to mitigate the performance impact. Handle errors that may occur during validation and provide a fallback mechanism if the validation fails. Replay static st elements in cache-decorated functions Functions decorated with @st.experimental_singleton can contain static st elements. When a cache-decorated function is executed, we record the element and block messages produced, so the elements will appear in the app even when execution of the function is skipped because the result was cached. In the example below, the @st.experimental_singleton decorator is used to cache the execution of the get_model function, that returns a 🤗 Hugging Face Transformers model. Notice the cached function also contains a st.bar_chart command, which will be replayed when the function is skipped because the result was cached. import numpy as np import pandas as pd import streamlit as st from transformers import AutoModel @st.experimental_singleton def get_model(model_type): # Contains a static element st.bar_chart st.bar_chart( np.random.rand(10, 1) ) # This will be recorded and displayed even when the function is skipped # Create a model of the specified type return AutoModel.from_pretrained(model_type) bert_model = get_model("distilbert-base-uncased") st.help(bert_model) # Display the model's docstring Supported static st elements in cache-decorated functions include: st.alert st.altair_chart st.area_chart st.audio st.bar_chart st.ballons st.bokeh_chart st.caption st.code st.components.v1.html st.components.v1.iframe st.container st.dataframe st.echo st.empty st.error st.exception st.expander st.experimental_get_query_params st.experimental_set_query_params st.form st.form_submit_button st.graphviz_chart st.help st.image st.info st.json st.latex st.line_chart st.markdown st.metric st.plotly_chart st.progress st.pydeck_chart st.snow st.spinner st.success st.table st.text st.vega_lite_chart st.video st.warning Replay input widgets in cache-decorated functions In addition to static elements, functions decorated with @st.experimental_singleton can also contain input widgets! Replaying input widgets is disabled by default. To enable it, you can set the experimental_allow_widgets parameter for @st.experimental_singleton to True. The example below enables widget replaying, and shows the use of a checkbox widget within a cache-decorated function. import streamlit as st # Enable widget replay @st.experimental_singleton(experimental_allow_widgets=True) def func(): # Contains an input widget st.checkbox("Works!") func() If the cache decorated function contains input widgets, but experimental_allow_widgets is set to False or unset, Streamlit will throw a CachedStFunctionWarning, like the one below: import streamlit as st # Widget replay is disabled by default @st.experimental_singleton def func(): # Streamlit will throw a CachedStFunctionWarning st.checkbox("Doesn't work") func() How widget replay works Let's demystify how widget replay in cache-decorated functions works and gain a conceptual understanding. Widget values are treated as additional inputs to the function, and are used to determine whether the function should be executed or not. Consider the following example: import streamlit as st @st.experimental_singleton(experimental_allow_widgets=True) def plus_one(x): y = x + 1 if st.checkbox("Nuke the value 💥"): st.write("Value was nuked, returning 0") y = 0 return y st.write(plus_one(2)) The plus_one function takes an integer x as input, and returns x + 1. The function also contains a checkbox widget, which is used to "nuke" the value of x. i.e. the return value of plus_one depends on the state of the checkbox: if it is checked, the function returns 0, otherwise it returns 3. In order to know which value the cache should return (in case of a cache hit), Streamlit treats the checkbox state (checked / unchecked) as an additional input to the function plus_one (just like x). If the user checks the checkbox (thereby changing its state), we look up the cache for the same value of x (2) and the same checkbox state (checked). If the cache contains a value for this combination of inputs, we return it. Otherwise, we execute the function and store the result in the cache. Let's now understand how enabling and disabling widget replay changes the behavior of the function. Widget replay disabled Widgets in cached functions throw a CachedStFunctionWarning and are ignored. Other static elements in cached functions replay as expected. Widget replay enabled Widgets in cached functions don't lead to a warning, and are replayed as expected. Interacting with a widget in a cached function will cause the function to be executed again, and the cache to be updated. Widgets in cached functions retain their state across reruns. Each unique combination of widget values is treated as a separate input to the function, and is used to determine whether the function should be executed or not. i.e. Each unique combination of widget values has its own cache entry; the cached function runs the first time and the saved value is used afterwards. Calling a cached function multiple times in one script run with the same arguments triggers a DuplicateWidgetID error. If the arguments to a cached function change, widgets from that function that render again retain their state. Changing the source code of a cached function invalidates the cache. Both st.experimental_singleton and st.experimental_memo support widget replay. Fundamentally, the behavior of a function with (supported) widgets in it doesn't change when it is decorated with @st.experimental_singleton or @st.experimental_memo. The only difference is that the function is only executed when we detect a cache "miss". Supported widgets All input widgets are supported in cache-decorated functions. The following is an exhaustive list of supported widgets: st.button st.camera_input st.checkbox st.color_picker st.date_input st.download_button st.file_uploader st.multiselect st.number_input st.radio st.selectbox st.select_slider st.slider st.text_area st.text_input st.time_input Previous: st.experimental_memoNext: st.session_stateforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy
https://docs.streamlit.io/develop/api-reference/#api-reference
DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceremovePAGE ELEMENTSWrite and magicaddText elementsaddData elementsaddChart elementsaddInput widgetsaddMedia elementsaddLayouts and containersaddChat elementsaddStatus elementsaddThird-party componentsopen_in_newAPPLICATION LOGICNavigation and pagesaddExecution flowaddCaching and stateaddConnections and secretsaddCustom componentsaddUtilitiesaddConfigurationaddTOOLSApp testingaddCommand lineaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Develop/API referenceAPI reference Streamlit makes it easy for you to visualize, mutate, and share data. The API reference is organized by activity type, like displaying data or optimizing performance. Each section includes methods associated with the activity type, including examples. Browse our API below and click to learn more about any of our available commands! 🎈 Display almost anything Write and magic st.writeWrite arguments to the app.st.write("Hello **world**!") st.write(my_data_frame) st.write(my_mpl_figure) st.write_streamWrite generators or streams to the app with a typewriter effect.st.write_stream(my_generator) st.write_stream(my_llm_stream) MagicAny time Streamlit sees either a variable or literal value on its own line, it automatically writes that to your app using st.write"Hello **world**!" my_data_frame my_mpl_figure Text elements MarkdownDisplay string formatted as Markdown.st.markdown("Hello **world**!") TitleDisplay text in title formatting.st.title("The app title") HeaderDisplay text in header formatting.st.header("This is a header") SubheaderDisplay text in subheader formatting.st.subheader("This is a subheader") CaptionDisplay text in small font.st.caption("This is written small caption text") Code blockDisplay a code block with optional syntax highlighting.st.code("a = 1234") EchoDisplay some code in the app, then execute it. Useful for tutorials.with st.echo(): st.write('This code will be printed') LaTeXDisplay mathematical expressions formatted as LaTeX.st.latex("\int a x^2 \,dx") Preformatted textWrite fixed-width and preformatted text.st.text("Hello world") DividerDisplay a horizontal rule.st.divider() Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration! PreviousTagsAdd tags to your Streamlit apps. Created by @gagan3012.st_tags(label='# Enter Keywords:', text='Press enter to add more', value=['Zero', 'One', 'Two'], suggestions=['five', 'six', 'seven', 'eight', 'nine', 'three', 'eleven', 'ten', 'four'], maxtags = 4, key='1') NLUApply text mining on a dataframe. Created by @JohnSnowLabs.nlu.load('sentiment').predict('I love NLU! <3') Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.mention(label="An awesome Streamlit App", icon="streamlit", url="https://extras.streamlit.app",) Annotated textDisplay annotated text in Streamlit apps. Created by @tvst.annotated_text("This ", ("is", "verb"), " some ", ("annotated", "adj"), ("text", "noun"), " for those of ", ("you", "pronoun"), " who ", ("like", "verb"), " this sort of ", ("thing", "noun"), ".") Drawable CanvasProvides a sketching canvas using Fabric.js. Created by @andfanilo.st_canvas(fill_color="rgba(255, 165, 0, 0.3)", stroke_width=stroke_width, stroke_color=stroke_color, background_color=bg_color, background_image=Image.open(bg_image) if bg_image else None, update_streamlit=realtime_update, height=150, drawing_mode=drawing_mode, point_display_radius=point_display_radius if drawing_mode == 'point' else 0, key="canvas",) TagsAdd tags to your Streamlit apps. Created by @gagan3012.st_tags(label='# Enter Keywords:', text='Press enter to add more', value=['Zero', 'One', 'Two'], suggestions=['five', 'six', 'seven', 'eight', 'nine', 'three', 'eleven', 'ten', 'four'], maxtags = 4, key='1') NLUApply text mining on a dataframe. Created by @JohnSnowLabs.nlu.load('sentiment').predict('I love NLU! <3') Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.mention(label="An awesome Streamlit App", icon="streamlit", url="https://extras.streamlit.app",) Annotated textDisplay annotated text in Streamlit apps. Created by @tvst.annotated_text("This ", ("is", "verb"), " some ", ("annotated", "adj"), ("text", "noun"), " for those of ", ("you", "pronoun"), " who ", ("like", "verb"), " this sort of ", ("thing", "noun"), ".") Drawable CanvasProvides a sketching canvas using Fabric.js. Created by @andfanilo.st_canvas(fill_color="rgba(255, 165, 0, 0.3)", stroke_width=stroke_width, stroke_color=stroke_color, background_color=bg_color, background_image=Image.open(bg_image) if bg_image else None, update_streamlit=realtime_update, height=150, drawing_mode=drawing_mode, point_display_radius=point_display_radius if drawing_mode == 'point' else 0, key="canvas",) TagsAdd tags to your Streamlit apps. Created by @gagan3012.st_tags(label='# Enter Keywords:', text='Press enter to add more', value=['Zero', 'One', 'Two'], suggestions=['five', 'six', 'seven', 'eight', 'nine', 'three', 'eleven', 'ten', 'four'], maxtags = 4, key='1') NLUApply text mining on a dataframe. Created by @JohnSnowLabs.nlu.load('sentiment').predict('I love NLU! <3') Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.mention(label="An awesome Streamlit App", icon="streamlit", url="https://extras.streamlit.app",) Next Data elements DataframesDisplay a dataframe as an interactive table.st.dataframe(my_data_frame) Data editorDisplay a data editor widget.edited = st.data_editor(df, num_rows="dynamic") Column configurationConfigure the display and editing behavior of dataframes and data editors.st.column_config.NumberColumn("Price (in USD)", min_value=0, format="$%d") Static tablesDisplay a static table.st.table(my_data_frame) MetricsDisplay a metric in big bold font, with an optional indicator of how the metric changed.st.metric("My metric", 42, 2) Dicts and JSONDisplay object or string as a pretty-printed JSON string.st.json(my_dict) Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration! PreviousImage CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates value = streamlit_image_coordinates("https://placekitten.com/200/300") st.write(value) Plotly EventsMake Plotly charts interactive!. Created by @null-jones.from streamlit_plotly_events import plotly_events fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.metric_cards import style_metric_cards col3.metric(label="No Change", value=5000, delta=0) style_metric_cards() Streamlit AggridImplementation of Ag-Grid component for Streamlit. Created by @PablocFonseca.df = pd.DataFrame({'col1': [1, 2, 3], 'col2': [4, 5, 6]}) grid_return = AgGrid(df, editable=True) new_df = grid_return['data'] Streamlit FoliumStreamlit Component for rendering Folium maps. Created by @randyzwitch.m = folium.Map(location=[39.949610, -75.150282], zoom_start=16) folium.Marker([39.949610, -75.150282], popup="Liberty Bell", tooltip="Liberty Bell").add_to(m) st_data = st_folium(m, width=725) Pandas ProfilingPandas profiling component for Streamlit. Created by @okld.df = pd.read_csv("https://storage.googleapis.com/tf-datasets/titanic/train.csv") pr = df.profile_report() st_profile_report(pr) Image CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates value = streamlit_image_coordinates("https://placekitten.com/200/300") st.write(value) Plotly EventsMake Plotly charts interactive!. Created by @null-jones.from streamlit_plotly_events import plotly_events fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.metric_cards import style_metric_cards col3.metric(label="No Change", value=5000, delta=0) style_metric_cards() Streamlit AggridImplementation of Ag-Grid component for Streamlit. Created by @PablocFonseca.df = pd.DataFrame({'col1': [1, 2, 3], 'col2': [4, 5, 6]}) grid_return = AgGrid(df, editable=True) new_df = grid_return['data'] Streamlit FoliumStreamlit Component for rendering Folium maps. Created by @randyzwitch.m = folium.Map(location=[39.949610, -75.150282], zoom_start=16) folium.Marker([39.949610, -75.150282], popup="Liberty Bell", tooltip="Liberty Bell").add_to(m) st_data = st_folium(m, width=725) Pandas ProfilingPandas profiling component for Streamlit. Created by @okld.df = pd.read_csv("https://storage.googleapis.com/tf-datasets/titanic/train.csv") pr = df.profile_report() st_profile_report(pr) Image CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates value = streamlit_image_coordinates("https://placekitten.com/200/300") st.write(value) Plotly EventsMake Plotly charts interactive!. Created by @null-jones.from streamlit_plotly_events import plotly_events fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.metric_cards import style_metric_cards col3.metric(label="No Change", value=5000, delta=0) style_metric_cards() Next Chart elements Simple area chartsDisplay an area chart.st.area_chart(my_data_frame) Simple bar chartsDisplay a bar chart.st.bar_chart(my_data_frame) Simple line chartsDisplay a line chart.st.line_chart(my_data_frame) Simple scatter chartsDisplay a line chart.st.scatter_chart(my_data_frame) Scatterplots on mapsDisplay a map with points on it.st.map(my_data_frame) MatplotlibDisplay a matplotlib.pyplot figure.st.pyplot(my_mpl_figure) AltairDisplay a chart using the Altair library.st.altair_chart(my_altair_chart) Vega-LiteDisplay a chart using the Vega-Lite library.st.vega_lite_chart(my_vega_lite_chart) PlotlyDisplay an interactive Plotly chart.st.plotly_chart(my_plotly_chart) BokehDisplay an interactive Bokeh chart.st.bokeh_chart(my_bokeh_chart) PyDeckDisplay a chart using the PyDeck library.st.pydeck_chart(my_pydeck_chart) GraphVizDisplay a graph using the dagre-d3 library.st.graphviz_chart(my_graphviz_spec) Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration! PreviousStreamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl("https://assets5.lottiefiles.com/packages/lf20_V9t630.json") st_lottie(lottie_hello, key="hello") Plotly EventsMake Plotly charts interactive!. Created by @null-jones.fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.chart += get_annotations_chart(annotations=[("Mar 01, 2008", "Pretty good day for GOOG"), ("Dec 01, 2007", "Something's going wrong for GOOG & AAPL"), ("Nov 01, 2008", "Market starts again thanks to..."), ("Dec 01, 2009", "Small crash for GOOG after..."),],) st.altair_chart(chart, use_container_width=True) PlostA deceptively simple plotting library for Streamlit. Created by @tvst.import plost plost.line_chart(my_dataframe, x='time', y='stock_value', color='stock_name',) HiPlotHigh dimensional Interactive Plotting. Created by @facebookresearch.data = [{'dropout':0.1, 'lr': 0.001, 'loss': 10.0, 'optimizer': 'SGD'}, {'dropout':0.15, 'lr': 0.01, 'loss': 3.5, 'optimizer': 'Adam'}, {'dropout':0.3, 'lr': 0.1, 'loss': 4.5, 'optimizer': 'Adam'}] hip.Experiment.from_iterable(data).display() EChartsHigh dimensional Interactive Plotting. Created by @andfanilo.from streamlit_echarts import st_echarts st_echarts(options=options) Streamlit FoliumStreamlit Component for rendering Folium maps. Created by @randyzwitch.m = folium.Map(location=[39.949610, -75.150282], zoom_start=16) st_data = st_folium(m, width=725) Spacy-StreamlitspaCy building blocks and visualizers for Streamlit apps. Created by @explosion.models = ["en_core_web_sm", "en_core_web_md"] spacy_streamlit.visualize(models, "Sundar Pichai is the CEO of Google.") Streamlit AgraphA Streamlit Graph Vis, based on react-grah-vis. Created by @ChrisDelClea.from streamlit_agraph import agraph, Node, Edge, Config agraph(nodes=nodes, edges=edges, config=config) Streamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl("https://assets5.lottiefiles.com/packages/lf20_V9t630.json") st_lottie(lottie_hello, key="hello") Plotly EventsMake Plotly charts interactive!. Created by @null-jones.fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.chart += get_annotations_chart(annotations=[("Mar 01, 2008", "Pretty good day for GOOG"), ("Dec 01, 2007", "Something's going wrong for GOOG & AAPL"), ("Nov 01, 2008", "Market starts again thanks to..."), ("Dec 01, 2009", "Small crash for GOOG after..."),],) st.altair_chart(chart, use_container_width=True) PlostA deceptively simple plotting library for Streamlit. Created by @tvst.import plost plost.line_chart(my_dataframe, x='time', y='stock_value', color='stock_name',) HiPlotHigh dimensional Interactive Plotting. Created by @facebookresearch.data = [{'dropout':0.1, 'lr': 0.001, 'loss': 10.0, 'optimizer': 'SGD'}, {'dropout':0.15, 'lr': 0.01, 'loss': 3.5, 'optimizer': 'Adam'}, {'dropout':0.3, 'lr': 0.1, 'loss': 4.5, 'optimizer': 'Adam'}] hip.Experiment.from_iterable(data).display() EChartsHigh dimensional Interactive Plotting. Created by @andfanilo.from streamlit_echarts import st_echarts st_echarts(options=options) Streamlit FoliumStreamlit Component for rendering Folium maps. Created by @randyzwitch.m = folium.Map(location=[39.949610, -75.150282], zoom_start=16) st_data = st_folium(m, width=725) Spacy-StreamlitspaCy building blocks and visualizers for Streamlit apps. Created by @explosion.models = ["en_core_web_sm", "en_core_web_md"] spacy_streamlit.visualize(models, "Sundar Pichai is the CEO of Google.") Streamlit AgraphA Streamlit Graph Vis, based on react-grah-vis. Created by @ChrisDelClea.from streamlit_agraph import agraph, Node, Edge, Config agraph(nodes=nodes, edges=edges, config=config) Streamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl("https://assets5.lottiefiles.com/packages/lf20_V9t630.json") st_lottie(lottie_hello, key="hello") Plotly EventsMake Plotly charts interactive!. Created by @null-jones.fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.chart += get_annotations_chart(annotations=[("Mar 01, 2008", "Pretty good day for GOOG"), ("Dec 01, 2007", "Something's going wrong for GOOG & AAPL"), ("Nov 01, 2008", "Market starts again thanks to..."), ("Dec 01, 2009", "Small crash for GOOG after..."),],) st.altair_chart(chart, use_container_width=True) Next Input widgets ButtonDisplay a button widget.clicked = st.button("Click me") Download buttonDisplay a download button widget.st.download_button("Download file", file) Form buttonDisplay a form submit button. For use with st.form.st.form_submit_button("Sign up") Link buttonDisplay a link button.st.link_button("Go to gallery", url) Page linkDisplay a link to another page in a multipage app.st.page_link("app.py", label="Home", icon="🏠") st.page_link("pages/profile.py", label="My profile") CheckboxDisplay a checkbox widget.selected = st.checkbox("I agree") Color pickerDisplay a color picker widget.color = st.color_picker("Pick a color") MultiselectDisplay a multiselect widget. The multiselect widget starts as empty.choices = st.multiselect("Buy", ["milk", "apples", "potatoes"]) RadioDisplay a radio button widget.choice = st.radio("Pick one", ["cats", "dogs"]) SelectboxDisplay a select widget.choice = st.selectbox("Pick one", ["cats", "dogs"]) Select-sliderDisplay a slider widget to select items from a list.size = st.select_slider("Pick a size", ["S", "M", "L"]) ToggleDisplay a toggle widget.activated = st.toggle("Activate") Number inputDisplay a numeric input widget.choice = st.number_input("Pick a number", 0, 10) SliderDisplay a slider widget.number = st.slider("Pick a number", 0, 100) Date inputDisplay a date input widget.date = st.date_input("Your birthday") Time inputDisplay a time input widget.time = st.time_input("Meeting time") Chat inputDisplay a chat input widget.prompt = st.chat_input("Say something") if prompt: st.write(f"The user has sent: {prompt}") Text-areaDisplay a multi-line text input widget.text = st.text_area("Text to translate") Text inputDisplay a single-line text input widget.name = st.text_input("First name") Data editorDisplay a data editor widget.edited = st.experimental_data_editor(df, num_rows="dynamic") File UploaderDisplay a file uploader widget.data = st.file_uploader("Upload a CSV") Camera inputDisplay a widget that allows users to upload images directly from a camera.image = st.camera_input("Take a picture") Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration! PreviousStreamlit ChatStreamlit Component for a Chatbot UI. Created by @AI-Yash.from streamlit_chat import message message("My message") message("Hello bot!", is_user=True) # align's the message to the right Streamlit Option MenuSelect a single item from a list of options in a menu. Created by @victoryhb.from streamlit_option_menu import option_menu option_menu("Main Menu", ["Home", 'Settings'], icons=['house', 'gear'], menu_icon="cast", default_index=1) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.stoggle import stoggle stoggle( "Click me!", """🥷 Surprise! Here's some additional content""",) Streamlit ElementsCreate a draggable and resizable dashboard in Streamlit. Created by @okls.from streamlit_elements import elements, mui, html with elements("new_element"): mui.Typography("Hello world") TagsAdd tags to your Streamlit apps. Created by @gagan3012.from streamlit_tags import st_tags st_tags(label='# Enter Keywords:', text='Press enter to add more', value=['Zero', 'One', 'Two'], suggestions=['five', 'six', 'seven', 'eight', 'nine', 'three', 'eleven', 'ten', 'four'], maxtags = 4, key='1') StqdmThe simplest way to handle a progress bar in streamlit app. Created by @Wirg.from stqdm import stqdm for _ in stqdm(range(50)): sleep(0.5) TimelineDisplay a Timeline in Streamlit apps using TimelineJS. Created by @innerdoc.from streamlit_timeline import timeline with open('example.json', "r") as f: timeline(f.read(), height=800) Camera input liveAlternative for st.camera_input which returns the webcam images live. Created by @blackary.from camera_input_live import camera_input_live image = camera_input_live() st.image(value) Streamlit AceAce editor component for Streamlit. Created by @okld.from streamlit_ace import st_ace content = st_ace() content Streamlit ChatStreamlit Component for a Chatbot UI. Created by @AI-Yash.from streamlit_chat import message message("My message") message("Hello bot!", is_user=True) # align's the message to the right Streamlit Option MenuSelect a single item from a list of options in a menu. Created by @victoryhb.from streamlit_option_menu import option_menu option_menu("Main Menu", ["Home", 'Settings'], icons=['house', 'gear'], menu_icon="cast", default_index=1) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.stoggle import stoggle stoggle( "Click me!", """🥷 Surprise! Here's some additional content""",) Streamlit ElementsCreate a draggable and resizable dashboard in Streamlit. Created by @okls.from streamlit_elements import elements, mui, html with elements("new_element"): mui.Typography("Hello world") TagsAdd tags to your Streamlit apps. Created by @gagan3012.from streamlit_tags import st_tags st_tags(label='# Enter Keywords:', text='Press enter to add more', value=['Zero', 'One', 'Two'], suggestions=['five', 'six', 'seven', 'eight', 'nine', 'three', 'eleven', 'ten', 'four'], maxtags = 4, key='1') StqdmThe simplest way to handle a progress bar in streamlit app. Created by @Wirg.from stqdm import stqdm for _ in stqdm(range(50)): sleep(0.5) TimelineDisplay a Timeline in Streamlit apps using TimelineJS. Created by @innerdoc.from streamlit_timeline import timeline with open('example.json', "r") as f: timeline(f.read(), height=800) Camera input liveAlternative for st.camera_input which returns the webcam images live. Created by @blackary.from camera_input_live import camera_input_live image = camera_input_live() st.image(value) Streamlit AceAce editor component for Streamlit. Created by @okld.from streamlit_ace import st_ace content = st_ace() content Streamlit ChatStreamlit Component for a Chatbot UI. Created by @AI-Yash.from streamlit_chat import message message("My message") message("Hello bot!", is_user=True) # align's the message to the right Streamlit Option MenuSelect a single item from a list of options in a menu. Created by @victoryhb.from streamlit_option_menu import option_menu option_menu("Main Menu", ["Home", 'Settings'], icons=['house', 'gear'], menu_icon="cast", default_index=1) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.stoggle import stoggle stoggle( "Click me!", """🥷 Surprise! Here's some additional content""",) Next Media elements ImageDisplay an image or list of images.st.image(numpy_array) st.image(image_bytes) st.image(file) st.image("https://example.com/myimage.jpg") AudioDisplay an audio player.st.audio(numpy_array) st.audio(audio_bytes) st.audio(file) st.audio("https://example.com/myaudio.mp3", format="audio/mp3") VideoDisplay a video player.st.video(numpy_array) st.video(video_bytes) st.video(file) st.video("https://example.com/myvideo.mp4", format="video/mp4") Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration! PreviousStreamlit CropperA simple image cropper for Streamlit. Created by @turner-anderson.from streamlit_cropper import st_cropper st_cropper(img, realtime_update=realtime_update, box_color=box_color, aspect_ratio=aspect_ratio) Image CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates streamlit_image_coordinates("https://placekitten.com/200/300") Streamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl("https://assets5.lottiefiles.com/packages/lf20_V9t630.json") st_lottie(lottie_hello, key="hello") Streamlit WebrtcHandling and transmitting real-time video/audio streams with Streamlit. Created by @whitphx.from streamlit_webrtc import webrtc_streamer webrtc_streamer(key="sample") Drawable CanvasProvides a sketching canvas using Fabric.js. Created by @andfanilo.from streamlit_drawable_canvas import st_canvas st_canvas(fill_color="rgba(255, 165, 0, 0.3)", stroke_width=stroke_width, stroke_color=stroke_color, background_color=bg_color, background_image=Image.open(bg_image) if bg_image else None, update_streamlit=realtime_update, height=150, drawing_mode=drawing_mode, point_display_radius=point_display_radius if drawing_mode == 'point' else 0, key="canvas",) Image ComparisonCompare images with a slider using JuxtaposeJS. Created by @fcakyon.from streamlit_image_comparison import image_comparison image_comparison(img1="image1.jpg", img2="image2.jpg",) Streamlit CropperA simple image cropper for Streamlit. Created by @turner-anderson.from streamlit_cropper import st_cropper st_cropper(img, realtime_update=realtime_update, box_color=box_color, aspect_ratio=aspect_ratio) Image CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates streamlit_image_coordinates("https://placekitten.com/200/300") Streamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl("https://assets5.lottiefiles.com/packages/lf20_V9t630.json") st_lottie(lottie_hello, key="hello") Streamlit WebrtcHandling and transmitting real-time video/audio streams with Streamlit. Created by @whitphx.from streamlit_webrtc import webrtc_streamer webrtc_streamer(key="sample") Drawable CanvasProvides a sketching canvas using Fabric.js. Created by @andfanilo.from streamlit_drawable_canvas import st_canvas st_canvas(fill_color="rgba(255, 165, 0, 0.3)", stroke_width=stroke_width, stroke_color=stroke_color, background_color=bg_color, background_image=Image.open(bg_image) if bg_image else None, update_streamlit=realtime_update, height=150, drawing_mode=drawing_mode, point_display_radius=point_display_radius if drawing_mode == 'point' else 0, key="canvas",) Image ComparisonCompare images with a slider using JuxtaposeJS. Created by @fcakyon.from streamlit_image_comparison import image_comparison image_comparison(img1="image1.jpg", img2="image2.jpg",) Streamlit CropperA simple image cropper for Streamlit. Created by @turner-anderson.from streamlit_cropper import st_cropper st_cropper(img, realtime_update=realtime_update, box_color=box_color, aspect_ratio=aspect_ratio) Image CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates streamlit_image_coordinates("https://placekitten.com/200/300") Streamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl("https://assets5.lottiefiles.com/packages/lf20_V9t630.json") st_lottie(lottie_hello, key="hello") Next Layouts and containers ColumnsInsert containers laid out as side-by-side columns.col1, col2 = st.columns(2) col1.write("this is column 1") col2.write("this is column 2") ContainerInsert a multi-element container.c = st.container() st.write("This will show last") c.write("This will show first") c.write("This will show second") Modal dialogsInsert a modal dialog that can rerun independently from the rest of the script.@st.experimental_dialog("Sign up") def email_form(): name = st.text_input("Name") email = st.text_input("Email") EmptyInsert a single-element container.c = st.empty() st.write("This will show last") c.write("This will be replaced") c.write("This will show first") ExpanderInsert a multi-element container that can be expanded/collapsed.with st.expander("Open to see more"): st.write("This is more content") PopoverInsert a multi-element popover container that can be opened/closed.with st.popover("Settings"): st.checkbox("Show completed") SidebarDisplay items in a sidebar.st.sidebar.write("This lives in the sidebar") st.sidebar.button("Click me!") TabsInsert containers separated into tabs.tab1, tab2 = st.tabs(["Tab 1", "Tab2"]) tab1.write("this is tab 1") tab2.write("this is tab 2") Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration!Streamlit ElementsCreate a draggable and resizable dashboard in Streamlit. Created by @okls.from streamlit_elements import elements, mui, html with elements("new_element"): mui.Typography("Hello world") PydanticAuto-generate Streamlit UI from Pydantic Models and Dataclasses. Created by @lukasmasuch.import streamlit_pydantic as sp sp.pydantic_form(key="my_form", model=ExampleModel) Streamlit PagesAn experimental version of Streamlit Multi-Page Apps. Created by @blackary.from st_pages import Page, show_pages, add_page_title show_pages([ Page("streamlit_app.py", "Home", "🏠"), Page("other_pages/page2.py", "Page 2", ":books:"), ]) Chat elements Streamlit provides a few commands to help you build conversational apps. These chat elements are designed to be used in conjunction with each other, but you can also use them separately. st.chat_message lets you insert a chat message container into the app so you can display messages from the user or the app. Chat containers can contain other Streamlit elements, including charts, tables, text, and more. st.chat_input lets you display a chat input widget so the user can type in a message. Chat inputDisplay a chat input widget.prompt = st.chat_input("Say something") if prompt: st.write(f"The user has sent: {prompt}") Chat messageInsert a chat message container.import numpy as np with st.chat_message("user"): st.write("Hello 👋") st.line_chart(np.random.randn(30, 3)) Status containerDisplay output of long-running tasks in a container.with st.status('Running'): do_something_slow() st.write_streamWrite generators or streams to the app with a typewriter effect.st.write_stream(my_generator) st.write_stream(my_llm_stream) Status elements Progress barDisplay a progress bar.for i in range(101): st.progress(i) do_something_slow() SpinnerTemporarily displays a message while executing a block of code.with st.spinner("Please wait..."): do_something_slow() Status containerDisplay output of long-running tasks in a container.with st.status('Running'): do_something_slow() ToastBriefly displays a toast message in the bottom-right corner.st.toast('Butter!', icon='🧈') BalloonsDisplay celebratory balloons!do_something() # Celebrate when all done! st.balloons() SnowflakesDisplay celebratory snowflakes!do_something() # Celebrate when all done! st.snow() Success boxDisplay a success message.st.success("Match found!") Info boxDisplay an informational message.st.info("Dataset is updated every day at midnight.") Warning boxDisplay warning message.st.warning("Unable to fetch image. Skipping...") Error boxDisplay error message.st.error("We encountered an error") Exception outputDisplay an exception.e = RuntimeError("This is an exception of type RuntimeError") st.exception(e) Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration!StqdmThe simplest way to handle a progress bar in streamlit app. Created by @Wirg.from stqdm import stqdm for _ in stqdm(range(50)): sleep(0.5) Custom notification boxA custom notification box with the ability to close it out. Created by @Socvest.from streamlit_custom_notification_box import custom_notification_box styles = {'material-icons':{'color': 'red'}, 'text-icon-link-close-container': {'box-shadow': '#3896de 0px 4px'}, 'notification-text': {'':''}, 'close-button':{'':''}, 'link':{'':''}} custom_notification_box(icon='info', textDisplay='We are almost done with your registration...', externalLink='more info', url='#', styles=styles, key="foo") Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.let_it_rain import rain rain(emoji="🎈", font_size=54, falling_speed=5, animation_length="infinite",) App logic and configuration Navigation and pages Switch pageProgrammatically navigates to a specified page.st.switch_page("pages/my_page.py") Page linkDisplay a link to another page in a multipage app.st.page_link("app.py", label="Home", icon="🏠") st.page_link("pages/profile.py", label="My profile") Execution flow Modal dialogsInsert a modal dialog that can rerun independently from the rest of the script.@st.experimental_dialog("Sign up") def email_form(): name = st.text_input("Name") email = st.text_input("Email") FormsCreate a form that batches elements together with a “Submit" button.with st.form(key='my_form'): name = st.text_input("Name") email = st.text_input("Email") st.form_submit_button("Sign up") Partial rerunsDefine a fragment to rerun independently from the rest of the script.@st.experimental_fragment(run_every="10s") def fragment(): df = get_data() st.line_chart(df) Rerun scriptRerun the script immediately.st.rerun() Stop executionStops execution immediately.st.stop() Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration!AutorefreshForce a refresh without tying up a script. Created by @kmcgrady.from streamlit_autorefresh import st_autorefresh st_autorefresh(interval=2000, limit=100, key="fizzbuzzcounter") PydanticAuto-generate Streamlit UI from Pydantic Models and Dataclasses. Created by @lukasmasuch.import streamlit_pydantic as sp sp.pydantic_form(key="my_form", model=ExampleModel) Streamlit PagesAn experimental version of Streamlit Multi-Page Apps. Created by @blackary.from st_pages import Page, show_pages, add_page_title show_pages([ Page("streamlit_app.py", "Home", "🏠"), Page("other_pages/page2.py", "Page 2", ":books:"), ]) Caching and state Cache dataFunction decorator to cache functions that return data (e.g. dataframe transforms, database queries, ML inference).@st.cache_data def long_function(param1, param2): # Perform expensive computation here or # fetch data from the web here return data Cache resourceFunction decorator to cache functions that return global resources (e.g. database connections, ML models).@st.cache_resource def init_model(): # Return a global resource here return pipeline( "sentiment-analysis", model="distilbert-base-uncased-finetuned-sst-2-english" ) Session stateSession state is a way to share variables between reruns, for each user session.st.session_state['key'] = value Query parametersGet, set, or clear the query parameters that are shown in the browser's URL bar.st.query_params[key] = value st.query_params.clear() Connections and databases Setup your connection Create a connectionConnect to a data source or APIconn = st.connection('pets_db', type='sql') pet_owners = conn.query('select * from pet_owners') st.dataframe(pet_owners) Built-in connections SnowflakeConnectionA connection to Snowflake.conn = st.connection('snowflake') SQLConnectionA connection to a SQL database using SQLAlchemy.conn = st.connection('sql') Build your own connections Connection base classBuild your own connection with BaseConnection.class MyConnection(BaseConnection[myconn.MyConnection]): def _connect(self, **kwargs) -> MyConnection: return myconn.connect(**self._secrets, **kwargs) def query(self, query): return self._instance.query(query) Secrets management Secrets singletonAccess secrets from a local TOML file.key = st.secrets["OpenAI_key"] Secrets fileSave your secrets in a per-project or per-profile TOML file.OpenAI_key = "<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/concepts/architecture/widget-behavior#updating-a-slider-with-a-default-value
DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsremoveCOREArchitecture & executionremoveRunning your appStreamlit's architectureThe app chromeCachingSession StateFormsFragmentsWidget behaviorMultipage appsaddApp designaddADDITIONALConnections and secretsaddCustom componentsaddConfiguration and themingaddApp testingaddAPI referenceaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Develop/Concepts/Architecture & execution/Widget behaviorUnderstanding widget behavior Widgets (like st.button, st.selectbox, and st.text_input) are at the heart of Streamlit apps. They are the interactive elements of Streamlit that pass information from your users into your Python code. Widgets are magical and often work how you want, but they can have surprising behavior in some situations. Understanding the different parts of a widget and the precise order in which events occur helps you achieve your desired results. This guide covers advanced concepts about widgets. Generally, it begins with simpler concepts and increases in complexity. For most beginning users, these details won't be important to know right away. When you want to dynamically change widgets or preserve widget information between pages, these concepts will be important to understand. We recommend having a basic understanding of Session State before reading this guide. 🎈 TL;DRexpand_more The actions of one user do not affect the widgets of any other user. A widget function call returns the widget's current value, which is a simple Python type. (e.g. st.button returns a boolean value.) Widgets return their default values on their first call before a user interacts with them. A widget's identity depends on the arguments passed to the widget function. Changing a widget's label, min or max value, default value, placeholder text, help text, or key will cause it to reset. If you don't call a widget function in a script run, Streamlit will delete the widget's information—including its key-value pair in Session State. If you call the same widget function later, Streamlit treats it as a new widget. The last two points (widget identity and widget deletion) are the most relevant when dynamically changing widgets or working with multi-page applications. This is covered in detail later in this guide: Statefulness of widgets and Widget life cycle. Anatomy of a widget There are four parts to keep in mind when using widgets: The frontend component as seen by the user. The backend value or value as seen through st.session_state. The key of the widget used to access its value via st.session_state. The return value given by the widget's function. Widgets are session dependent Widget states are dependent on a particular session (browser connection). The actions of one user do not affect the widgets of any other user. Furthermore, if a user opens up multiple tabs to access an app, each tab will be a unique session. Changing a widget in one tab will not affect the same widget in another tab. Widgets return simple Python data types The value of a widget as seen through st.session_state and returned by the widget function are of simple Python types. For example, st.button returns a boolean value and will have the same boolean value saved in st.session_state if using a key. The first time a widget function is called (before a user interacts with it), it will return its default value. (e.g. st.selectbox returns the first option by default.) Default values are configurable for all widgets with a few special exceptions like st.button and st.file_uploader. Keys help distinguish widgets and access their values Widget keys serve two purposes: Distinguishing two otherwise identical widgets. Creating a means to access and manipulate the widget's value through st.session_state. Whenever possible, Streamlit updates widgets incrementally on the frontend instead of rebuilding them with each rerun. This means Streamlit assigns an ID to each widget from the arguments passed to the widget function. A widget's ID is based on parameters such as label, min or max value, default value, placeholder text, help text, and key. The page where the widget appears also factors into a widget's ID. If you have two widgets of the same type with the same arguments on the same page, you will get a DuplicateWidgetID error. In this case, assign unique keys to the two widgets. Streamlit can't understand two identical widgets on the same page # This will cause a DuplicateWidgetID error. st.button("OK") st.button("OK") Use keys to distinguish otherwise identical widgets st.button("OK", key="privacy") st.button("OK", key="terms") Order of operations When a user interacts with a widget, the order of logic is: Its value in st.session_state is updated. The callback function (if any) is executed. The page reruns with the widget function returning its new value. If the callback function writes anything to the screen, that content will appear above the rest of the page. A callback function runs as a prefix to the script rerunning. Consequently, that means anything written via a callback function will disappear as soon as the user performs their next action. Other widgets should generally not be created within a callback function. push_pinNoteIf a callback function is passed any args or kwargs, those arguments will be established when the widget is rendered. In particular, if you want to use a widget's new value in its own callback function, you cannot pass that value to the callback function via the args parameter; you will have to assign a key to the widget and look up its new value using a call to st.session_state within the callback function. Using callback functions with forms Using a callback function with a form requires consideration of this order of operations. import streamlit as st if "attendance" not in st.session_state: st.session_state.attendance = set() def take_attendance(): if st.session_state.name in st.session_state.attendance: st.info(f"{st.session_state.name} has already been counted.") else: st.session_state.attendance.add(st.session_state.name) with st.form(key="my_form"): st.text_input("Name", key="name") st.form_submit_button("I'm here!", on_click=take_attendance) Built with Streamlit 🎈Fullscreen open_in_new Statefulness of widgets As long as the defining parameters of a widget remain the same and that widget is continuously rendered on the frontend, then it will be stateful and remember user input. Changing parameters of a widget will reset it If any of the defining parameters of a widget change, Streamlit will see it as a new widget and it will reset. The use of manually assigned keys and default values is particularly important in this case. Note that callback functions, callback args and kwargs, label visibility, and disabling a widget do not affect a widget's identity. In this example, we have a slider whose min and max values are changed. Try interacting with each slider to change its value then change the min or max setting to see what happens. import streamlit as st cols = st.columns([2, 1, 2]) minimum = cols[0].number_input("Minimum", 1, 5) maximum = cols[2].number_input("Maximum", 6, 10, 10) st.slider("No default, no key", minimum, maximum) st.slider("No default, with key", minimum, maximum, key="a") st.slider("With default, no key", minimum, maximum, value=5) st.slider("With default, with key", minimum, maximum, value=5, key="b") Built with Streamlit 🎈Fullscreen open_in_new Updating a slider with no default value For the first two sliders above, as soon as the min or max value is changed, the sliders reset to the min value. The changing of the min or max value makes them "new" widgets from Streamlit's perspective and so they are recreated from scratch when the app reruns with the changed parameters. Since no default value is defined, each widget will reset to its min value. This is the same with or without a key since it's seen as a new widget either way. There is a subtle point to understand about pre-existing keys connecting to widgets. This will be explained further down in Widget life cycle. Updating a slider with a default value For the last two sliders above, a change to the min or max value will result in the widgets being seen as "new" and thus recreated like before. Since a default value of 5 is defined, each widget will reset to 5 whenever the min or max is changed. This is again the same (with or without a key). A solution to Retain statefulness when changing a widget's parameters is provided further on. Widgets do not persist when not continually rendered If a widget's function is not called during a script run, then none of its parts will be retained, including its value in st.session_state. If a widget has a key and you navigate away from that widget, its key and associated value in st.session_state will be deleted. Even temporarily hiding a widget will cause it to reset when it reappears; Streamlit will treat it like a new widget. You can either interrupt the Widget clean-up process (described at the end of this page) or save the value to another key. Save widget values in Session State to preserve them between pages If you want to navigate away from a widget and return to it while keeping its value, use a separate key in st.session_state to save the information independently from the widget. In this example, a temporary key is used with a widget. The temporary key uses an underscore prefix. Hence, "_my_key" is used as the widget key, but the data is copied to "my_key" to preserve it between pages. import streamlit as st def store_value(): # Copy the value to the permanent key st.session_state["my_key"] = st.session_state["_my_key"] # Copy the saved value to the temporary key st.session_state["_my_key"] = st.session_state["my_key"] st.number_input("Number of filters", key="_my_key", on_change=store_value) If this is functionalized to work with multiple widgets, it could look something like this: import streamlit as st def store_value(key): st.session_state[key] = st.session_state["_"+key] def load_value(key): st.session_state["_"+key] = st.session_state[key] load_value("my_key") st.number_input("Number of filters", key="_my_key", on_change=store_value, args=["my_key"]) Widget life cycle When a widget function is called, Streamlit will check if it already has a widget with the same parameters. Streamlit will reconnect if it thinks the widget already exists. Otherwise, it will make a new one. As mentioned earlier, Streamlit determines a widget's ID based on parameters such as label, min or max value, default value, placeholder text, help text, and key. The page name also factors into a widget's ID. On the other hand, callback functions, callback args and kwargs, label visibility, and disabling a widget do not affect a widget's identity. Calling a widget function when the widget doesn't already exist If your script rerun calls a widget function with changed parameters or calls a widget function that wasn't used on the last script run: Streamlit will build the frontend and backend parts of the widget. If the widget has been assigned a key, Streamlit will check if that key already exists in Session State. a. If it exists and is not currently associated with another widget, Streamlit will attach to that key and take on its value for the widget. b. Otherwise, it will assign the default value to the key in st.session_state (creating a new key-value pair or overwriting an existing one). If there are args or kwargs for a callback function, they are computed and saved at this point in time. The default value is then returned by the function. Step 2 can be tricky. If you have a widget: st.number_input("Alpha",key="A") and you change it on a page rerun to: st.number_input("Beta",key="A") Streamlit will see that as a new widget because of the label change. The key "A" will be considered part of the widget labeled "Alpha" and will not be attached as-is to the new widget labeled "Beta". Streamlit will destroy st.session_state.A and recreate it with the default value. If a widget attaches to a pre-existing key when created and is also manually assigned a default value, you will get a warning if there is a disparity. If you want to control a widget's value through st.session_state, initialize the widget's value through st.session_state and avoid the default value argument to prevent conflict. Calling a widget function when the widget already exists When rerunning a script without changing a widget's parameters: Streamlit will connect to the existing frontend and backend parts. If the widget has a key that was deleted from st.session_state, then Streamlit will recreate the key using the current frontend value. (e.g Deleting a key will not revert the widget to a default value.) It will return the current value of the widget. Widget clean-up process When Streamlit gets to the end of a script run, it will delete the data for any widgets it has in memory that were not rendered on the screen. Most importantly, that means Streamlit will delete all key-value pairs in st.session_state associated with a widget not currently on screen. Additional examples As promised, let's address how to retain the statefulness of widgets when changing pages or modifying their parameters. There are two ways to do this. Use dummy keys to duplicate widget values in st.session_state and protect the data from being deleted along with the widget. Interrupt the widget clean-up process. The first method was shown above in Save widget values in Session State to preserve them between pages Interrupting the widget clean-up process To retain information for a widget with key="my_key", just add this to the top of every page: st.session_state.my_key = st.session_state.my_key When you manually save data to a key in st.session_state, it will become detached from any widget as far as the clean-up process is concerned. If you navigate away from a widget with some key "my_key" and save data to st.session_state.my_key on the new page, you will interrupt the widget clean-up process and prevent the key-value pair from being deleted or overwritten if another widget with the same key exists. Retain statefulness when changing a widget's parameters Here is a solution to our earlier example of changing a slider's min and max values. This solution interrupts the clean-up process as described above. import streamlit as st # Set default value if "a" not in st.session_state: st.session_state.a = 5 cols = st.columns(2) minimum = cols[0].number_input("Min", 1, 5, key="min") maximum = cols[1].number_input("Max", 6, 10, 10, key="max") def update_value(): # Helper function to ensure consistency between widget parameters and value st.session_state.a = min(st.session_state.a, maximum) st.session_state.a = max(st.session_state.a, minimum) # Validate the slider value before rendering update_value() st.slider("A", minimum, maximum, key="a") Built with Streamlit 🎈Fullscreen open_in_new The update_value() helper function is actually doing two things. On the surface, it's making sure there are no inconsistent changes to the parameters values as described. Importantly, it's also interrupting the widget clean-up process. When the min or max value of the widget changes, Streamlit sees it as a new widget on rerun. Without saving a value to st.session_state.a, the value would be thrown out and replaced by the "new" widget's default value.Previous: FragmentsNext: Multipage appsforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy
https://docs.streamlit.io/develop/concepts/custom-components/intro#working-with-themes
DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsremoveCOREArchitecture & executionaddMultipage appsaddApp designaddADDITIONALConnections and secretsaddCustom componentsremoveIntro to custom componentsCreate a ComponentPublish a ComponentLimitationsComponent galleryopen_in_newConfiguration and themingaddApp testingaddAPI referenceaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Develop/Concepts/Custom components/Intro to custom componentsIntro to custom components The first step in developing a Streamlit Component is deciding whether to create a static component (i.e. rendered once, controlled by Python) or to create a bi-directional component that can communicate from Python to JavaScript and back. Create a static component If your goal in creating a Streamlit Component is solely to display HTML code or render a chart from a Python visualization library, Streamlit provides two methods that greatly simplify the process: components.html() and components.iframe(). If you are unsure whether you need bi-directional communication, start here first! Render an HTML string While st.text, st.markdown and st.write make it easy to write text to a Streamlit app, sometimes you'd rather implement a custom piece of HTML. Similarly, while Streamlit natively supports many charting libraries, you may want to implement a specific HTML/JavaScript template for a new charting library. components.html works by giving you the ability to embed an iframe inside of a Streamlit app that contains your desired output. Example import streamlit as st import streamlit.components.v1 as components # bootstrap 4 collapse example components.html( """ <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous"> <script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script> <div id="accordion"> <div class="card"> <div class="card-header" id="headingOne"> <h5 class="mb-0"> <button class="btn btn-link" data-toggle="collapse" data-target="#collapseOne" aria-expanded="true" aria-controls="collapseOne"> Collapsible Group Item #1 </button> </h5> </div> <div id="collapseOne" class="collapse show" aria-labelledby="headingOne" data-parent="#accordion"> <div class="card-body"> Collapsible Group Item #1 content </div> </div> </div> <div class="card"> <div class="card-header" id="headingTwo"> <h5 class="mb-0"> <button class="btn btn-link collapsed" data-toggle="collapse" data-target="#collapseTwo" aria-expanded="false" aria-controls="collapseTwo"> Collapsible Group Item #2 </button> </h5> </div> <div id="collapseTwo" class="collapse" aria-labelledby="headingTwo" data-parent="#accordion"> <div class="card-body"> Collapsible Group Item #2 content </div> </div> </div> </div> """, height=600, ) Render an iframe URL components.iframe is similar in features to components.html, with the difference being that components.iframe takes a URL as its input. This is used for situations where you want to include an entire page within a Streamlit app. Example import streamlit as st import streamlit.components.v1 as components # embed streamlit docs in a streamlit app components.iframe("https://example.com", height=500) Create a bi-directional component A bi-directional Streamlit Component has two parts: A frontend, which is built out of HTML and any other web tech you like (JavaScript, React, Vue, etc.), and gets rendered in Streamlit apps via an iframe tag. A Python API, which Streamlit apps use to instantiate and talk to that frontend To make the process of creating bi-directional Streamlit Components easier, we've created a React template and a TypeScript-only template in the Streamlit Component-template GitHub repo. We also provide some example Components in the same repo. Development Environment Setup To build a Streamlit Component, you need the following installed in your development environment: Python 3.8 - Python 3.12 Streamlit 1.11.1 or higher nodejs npm or yarn Clone the component-template GitHub repo, then decide whether you want to use the React.js ("template") or plain TypeScript ("template-reactless") template. Initialize and build the component template frontend from the terminal: # React template template/my_component/frontend npm install # Initialize the project and install npm dependencies npm run start # Start the Webpack dev server # or # TypeScript-only template template-reactless/my_component/frontend npm install # Initialize the project and install npm dependencies npm run start # Start the Webpack dev server From a separate terminal, run the Streamlit app (Python) that declares and uses the component: # React template cd template . venv/bin/activate # or similar to activate the venv/conda environment where Streamlit is installed pip install -e . # install template as editable package streamlit run my_component/example.py # run the example # or # TypeScript-only template cd template-reactless . venv/bin/activate # or similar to activate the venv/conda environment where Streamlit is installed pip install -e . # install template as editable package streamlit run my_component/example.py # run the example After running the steps above, you should see a Streamlit app in your browser that looks like this: The example app from the template shows how bi-directional communication is implemented. The Streamlit Component displays a button (Python → JavaScript), and the end-user can click the button. Each time the button is clicked, the JavaScript front-end increments the counter value and passes it back to Python (JavaScript → Python), which is then displayed by Streamlit (Python → JavaScript). Frontend Because each Streamlit Component is its own webpage that gets rendered into an iframe, you can use just about any web tech you'd like to create that web page. We provide two templates to get started with in the Streamlit Components-template GitHub repo; one of those templates uses React and the other does not. push_pinNoteEven if you're not already familiar with React, you may still want to check out the React-based template. It handles most of the boilerplate required to send and receive data from Streamlit, and you can learn the bits of React you need as you go.If you'd rather not use React, please read this section anyway! It explains the fundamentals of Streamlit ↔ Component communication. React The React-based template is in template/my_component/frontend/src/MyComponent.tsx. MyComponent.render() is called automatically when the component needs to be re-rendered (just like in any React app) Arguments passed from the Python script are available via the this.props.args dictionary: # Send arguments in Python: result = my_component(greeting="Hello", name="Streamlit") // Receive arguments in frontend: let greeting = this.props.args["greeting"]; // greeting = "Hello" let name = this.props.args["name"]; // name = "Streamlit" Use Streamlit.setComponentValue() to return data from the component to the Python script: // Set value in frontend: Streamlit.setComponentValue(3.14); # Access value in Python: result = my_component(greeting="Hello", name="Streamlit") st.write("result = ", result) # result = 3.14 When you call Streamlit.setComponentValue(new_value), that new value is sent to Streamlit, which then re-executes the Python script from top to bottom. When the script is re-executed, the call to my_component(...) will return the new value. From a code flow perspective, it appears that you're transmitting data synchronously with the frontend: Python sends the arguments to JavaScript, and JavaScript returns a value to Python, all in a single function call! But in reality this is all happening asynchronously, and it's the re-execution of the Python script that achieves the sleight of hand. Use Streamlit.setFrameHeight() to control the height of your component. By default, the React template calls this automatically (see StreamlitComponentBase.componentDidUpdate()). You can override this behavior if you need more control. There's a tiny bit of magic in the last line of the file: export default withStreamlitConnection(MyComponent) - this does some handshaking with Streamlit, and sets up the mechanisms for bi-directional data communication. TypeScript-only The TypeScript-only template is in template-reactless/my_component/frontend/src/MyComponent.tsx. This template has much more code than its React sibling, in that all the mechanics of handshaking, setting up event listeners, and updating the component's frame height are done manually. The React version of the template handles most of these details automatically. Towards the bottom of the source file, the template calls Streamlit.setComponentReady() to tell Streamlit it's ready to start receiving data. (You'll generally want to do this after creating and loading everything that the Component relies on.) It subscribes to Streamlit.RENDER_EVENT to be notified of when to redraw. (This event won't be fired until setComponentReady is called) Within its onRender event handler, it accesses the arguments passed in the Python script via event.detail.args It sends data back to the Python script in the same way that the React template does—clicking on the "Click Me!" button calls Streamlit.setComponentValue() It informs Streamlit when its height may have changed via Streamlit.setFrameHeight() Working with Themes push_pinNoteCustom component theme support requires streamlit-component-lib version 1.2.0 or higher. Along with sending an args object to your component, Streamlit also sends a theme object defining the active theme so that your component can adjust its styling in a compatible way. This object is sent in the same message as args, so it can be accessed via this.props.theme (when using the React template) or event.detail.theme (when using the plain TypeScript template). The theme object has the following shape: { "base": "lightORdark", "primaryColor": "someColor1", "backgroundColor": "someColor2", "secondaryBackgroundColor": "someColor3", "textColor": "someColor4", "font": "someFont" } The base option allows you to specify a preset Streamlit theme that your custom theme inherits from. Any theme config options not defined in your theme settings have their values set to those of the base theme. Valid values for base are "light" and "dark". Note that the theme object has fields with the same names and semantics as the options in the "theme" section of the config options printed with the command streamlit config show. When using the React template, the following CSS variables are also set automatically. --base --primary-color --background-color --secondary-background-color --text-color --font If you're not familiar with CSS variables, the TLDR version is that you can use them like this: .mySelector { color: var(--text-color); } These variables match the fields defined in the theme object above, and whether to use CSS variables or the theme object in your component is a matter of personal preference. Other frontend details Because you're hosting your component from a dev server (via npm run start), any changes you make should be automatically reflected in the Streamlit app when you save. If you want to add more packages to your component, run npm add to add them from within your component's frontend/ directory. npm add baseui To build a static version of your component, run npm run export. See Prepare your Component for more information Python API components.declare_component() is all that's required to create your Component's Python API: import streamlit.components.v1 as components my_component = components.declare_component( "my_component", url="http://localhost:3001" ) You can then use the returned my_component function to send and receive data with your frontend code: # Send data to the frontend using named arguments. return_value = my_component(name="Blackbeard", ship="Queen Anne's Revenge") # `my_component`'s return value is the data returned from the frontend. st.write("Value = ", return_value) While the above is all you need to define from the Python side to have a working Component, we recommend creating a "wrapper" function with named arguments and default values, input validation and so on. This will make it easier for end-users to understand what data values your function accepts and allows for defining helpful docstrings. Please see this example from the Components-template for an example of creating a wrapper function. Data serialization Python → Frontend You send data from Python to the frontend by passing keyword args to your Component's invoke function (that is, the function returned from declare_component). You can send the following types of data from Python to the frontend: Any JSON-serializable data numpy.array pandas.DataFrame Any JSON-serializable data gets serialized to a JSON string, and deserialized to its JavaScript equivalent. numpy.array and pandas.DataFrame get serialized using Apache Arrow and are deserialized as instances of ArrowTable, which is a custom type that wraps Arrow structures and provides a convenient API on top of them. Check out the CustomDataframe and SelectableDataTable Component example code for more context on how to use ArrowTable. Frontend → Python You send data from the frontend to Python via the Streamlit.setComponentValue() API (which is part of the template code). Unlike arg-passing from Python → frontend, this API takes a single value. If you want to return multiple values, you'll need to wrap them in an Array or Object. Custom Components can send JSON-serializable data from the frontend to Python, as well as Apache Arrow ArrowTables to represent dataframes.Previous: Custom componentsNext: Create a ComponentforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy
https://docs.streamlit.io/develop/api-reference/connections/st.connections.sqlconnection#basic-usage
DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceremovePAGE ELEMENTSWrite and magicaddText elementsaddData elementsaddChart elementsaddInput widgetsaddMedia elementsaddLayouts and containersaddChat elementsaddStatus elementsaddThird-party componentsopen_in_newAPPLICATION LOGICNavigation and pagesaddExecution flowaddCaching and stateaddConnections and secretsremoveSECRETSst.secretssecrets.tomlCONNECTIONSst.connectionSnowflakeConnectionSQLConnectionBaseConnectionSnowparkConnectiondeleteCustom componentsaddUtilitiesaddConfigurationaddTOOLSApp testingaddCommand lineaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Develop/API reference/Connections and secrets/SQLConnectionstarTipThis page only contains the st.connections.SQLConnection class. For a deeper dive into creating and managing data connections within Streamlit apps, read Connecting to data. st.connections.SQLConnectionStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA connection to a SQL database using a SQLAlchemy Engine. Initialize using st.connection("<name>", type="sql"). SQLConnection provides the query() convenience method, which can be used to run simple read-only queries with both caching and simple error handling/retries. More complex DB interactions can be performed by using the .session property to receive a regular SQLAlchemy Session. SQLConnections should always be created using st.connection(), not initialized directly. Connection parameters for a SQLConnection can be specified using either st.secrets or **kwargs. Some frequently used parameters include: url or arguments for sqlalchemy.engine.URL.create(). Most commonly it includes a dialect, host, database, username and password. create_engine_kwargs can be passed via st.secrets, such as for snowflake-sqlalchemy or Google BigQuery. These can also be passed directly as **kwargs to connection(). autocommit=True to run with isolation level AUTOCOMMIT. Default is False. Class description[source] st.connections.SQLConnection(connection_name, **kwargs) Methods connect() Call .connect() on the underlying SQLAlchemy Engine, returning a new sqlalchemy.engine.Connection object. query(sql, *, show_spinner="Running `sql.query(...)`.", ttl=None, index_col=None, chunksize=None, params=None, **kwargs) Run a read-only query. reset() Reset this connection so that it gets reinitialized the next time it's used. Attributes driver The name of the driver used by the underlying SQLAlchemy Engine. engine The underlying SQLAlchemy Engine. session Return a SQLAlchemy Session. Example import streamlit as st conn = st.connection("sql") df = conn.query("select * from pet_owners") st.dataframe(df) Basic usage: SQLAlchemy and any required drivers must be installed to use this connection. import streamlit as st conn = st.connection("sql") df = conn.query("select * from pet_owners") st.dataframe(df) In case you want to pass a connection URL (or other parameters) directly, it also works: conn = st.connection( "local_db", type="sql", url="mysql://user:pass@localhost:3306/mydb" ) Or specify parameters in secrets: # .streamlit/secrets.toml [connections.mydb] dialect = "mysql" username = "myuser" password = "password" host = "localhost" database = "mydb" # streamlit_app.py conn = st.connection("mydb", type="sql", autocommit=True) As described above, some cloud databases use extra **kwargs to specify credentials. These can be passed via secrets using the create_engine_kwargs section: # .streamlit/secrets.toml [connections.snowflake] url = "snowflake://<username>@<account>/" [connections.snowflake.create_engine_kwargs.connect_args] authenticator = "externalbrowser" role = "..." # ... SQLConnection.connectStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeCall .connect() on the underlying SQLAlchemy Engine, returning a new sqlalchemy.engine.Connection object. Calling this method is equivalent to calling self._instance.connect(). NOTE: This method should not be confused with the internal _connect method used to implement a Streamlit Connection. Function signature[source] SQLConnection.connect() SQLConnection.queryStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeRun a read-only query. This method implements both query result caching (with caching behavior identical to that of using @st.cache_data) as well as simple error handling/retries. Note Queries that are run without a specified ttl are cached indefinitely. Aside from the ttl kwarg, all kwargs passed to this function are passed down to pandas.read_sql and have the behavior described in the pandas documentation. Function signature[source] SQLConnection.query(sql, *, show_spinner="Running `sql.query(...)`.", ttl=None, index_col=None, chunksize=None, params=None, **kwargs) Parameters sql (str) The read-only SQL query to execute. show_spinner (boolean or string) Enable the spinner. The default is to show a spinner when there is a "cache miss" and the cached resource is being created. If a string, the value of the show_spinner param will be used for the spinner text. ttl (float, int, timedelta or None) The maximum number of seconds to keep results in the cache, or None if cached results should not expire. The default is None. index_col (str, list of str, or None) Column(s) to set as index(MultiIndex). Default is None. chunksize (int or None) If specified, return an iterator where chunksize is the number of rows to include in each chunk. Default is None. params (list, tuple, dict or None) List of parameters to pass to the execute method. The syntax used to pass parameters is database driver dependent. Check your database driver documentation for which of the five syntax styles, described in PEP 249 paramstyle, is supported. Default is None. **kwargs (dict) Additional keyword arguments are passed to pandas.read_sql. Returns(pandas.DataFrame) The result of running the query, formatted as a pandas DataFrame. Example import streamlit as st conn = st.connection("sql") df = conn.query("select * from pet_owners where owner = :owner", ttl=3600, params={"owner":"barbara"}) st.dataframe(df) SQLConnection.resetStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeReset this connection so that it gets reinitialized the next time it's used. This method can be useful when a connection has become stale, an auth token has expired, or in similar scenarios where a broken connection might be fixed by reinitializing it. Note that some connection methods may already use reset() in their error handling code. Function signature[source] SQLConnection.reset() Example import streamlit as st conn = st.connection("my_conn") # Reset the connection before using it if it isn't healthy # Note: is_healthy() isn't a real method and is just shown for example here. if not conn.is_healthy(): conn.reset() # Do stuff with conn... SQLConnection.driverStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeThe name of the driver used by the underlying SQLAlchemy Engine. This is equivalent to accessing self._instance.driver. Function signature[source] SQLConnection.driver SQLConnection.engineStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeThe underlying SQLAlchemy Engine. This is equivalent to accessing self._instance. Function signature[source] SQLConnection.engine SQLConnection.sessionStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeReturn a SQLAlchemy Session. Users of this connection should use the contextmanager pattern for writes, transactions, and anything more complex than simple read queries. See the usage example below, which assumes we have a table numbers with a single integer column val. The SQLAlchemy docs also contain much more information on the usage of sessions. Function signature[source] SQLConnection.session Example import streamlit as st conn = st.connection("sql") n = st.slider("Pick a number") if st.button("Add the number!"): with conn.session as session: session.execute("INSERT INTO numbers (val) VALUES (:n);", {"n": n}) session.commit() Previous: SnowflakeConnectionNext: BaseConnectionforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy
https://docs.streamlit.io/develop/api-reference/app-testing/testing-element-classes#textinputinput
DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceremovePAGE ELEMENTSWrite and magicaddText elementsaddData elementsaddChart elementsaddInput widgetsaddMedia elementsaddLayouts and containersaddChat elementsaddStatus elementsaddThird-party componentsopen_in_newAPPLICATION LOGICNavigation and pagesaddExecution flowaddCaching and stateaddConnections and secretsaddCustom componentsaddUtilitiesaddConfigurationaddTOOLSApp testingremovest.testing.v1.AppTestTesting element classesCommand lineaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Develop/API reference/App testing/Testing element classesTesting element classes st.testing.v1.element_tree.Block The Block class has the same methods and attributes as AppTest. A Block instance represents a container of elements just as AppTest represents the entire app. For example, Block.button will produce a WidgetList of Button in the same manner as AppTest.button. ChatMessage, Column, and Tab all inherit from Block. For all container classes, parameters of the original element can be obtained as properties. For example, ChatMessage.avatar and Tab.label. st.testing.v1.element_tree.ElementStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeElement base class for testing. This class's methods and attributes are universal for all elements implemented in testing. For example, Caption, Code, Text, and Title inherit from Element. All widget classes also inherit from Element, but have additional methods specific to each widget type. See the AppTest class for the full list of supported elements. For all element classes, parameters of the original element can be obtained as properties. For example, Button.label, Caption.help, and Toast.icon. Class description[source] st.testing.v1.element_tree.Element(proto, root) Methods run(*, timeout=None) Run the AppTest script which contains the element. Attributes value The value or contents of the element. st.testing.v1.element_tree.ButtonStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.button and st.form_submit_button. Class description[source] st.testing.v1.element_tree.Button(proto, root) Methods click() Set the value of the button to True. run(*, timeout=None) Run the AppTest script which contains the element. set_value(v) Set the value of the button. Attributes value The value of the button. (bool) st.testing.v1.element_tree.ChatInputStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.chat_input. Class description[source] st.testing.v1.element_tree.ChatInput(proto, root) Methods run(*, timeout=None) Run the AppTest script which contains the element. set_value(v) Set the value of the widget. Attributes value The value of the widget. (str) st.testing.v1.element_tree.CheckboxStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.checkbox. Class description[source] st.testing.v1.element_tree.Checkbox(proto, root) Methods check() Set the value of the widget to True. run(*, timeout=None) Run the AppTest script which contains the element. set_value(v) Set the value of the widget. uncheck() Set the value of the widget to False. Attributes value The value of the widget. (bool) st.testing.v1.element_tree.ColorPickerStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.color_picker. Class description[source] st.testing.v1.element_tree.ColorPicker(proto, root) Methods pick(v) Set the value of the widget as a hex string. May omit the "#" prefix. run(*, timeout=None) Run the AppTest script which contains the element. set_value(v) Set the value of the widget as a hex string. Attributes value The currently selected value as a hex string. (str) st.testing.v1.element_tree.DateInputStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.date_input. Class description[source] st.testing.v1.element_tree.DateInput(proto, root) Methods run(*, timeout=None) Run the AppTest script which contains the element. set_value(v) Set the value of the widget. Attributes value The value of the widget. (date or Tuple of date) st.testing.v1.element_tree.MultiselectStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.multiselect. Class description[source] st.testing.v1.element_tree.Multiselect(proto, root) Methods run(*, timeout=None) Run the AppTest script which contains the element. select(v) Add a selection to the widget. Do nothing if the value is already selected. If testing a multiselect widget with repeated options, use set_value instead. set_value(v) Set the value of the multiselect widget. (list) unselect(v) Remove a selection from the widget. Do nothing if the value is not already selected. If a value is selected multiple times, the first instance is removed. Attributes format_func The widget's formatting function for displaying options. (callable) indices The indices of the currently selected values from the options. (list) value The currently selected values from the options. (list) st.testing.v1.element_tree.NumberInputStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.number_input. Class description[source] st.testing.v1.element_tree.NumberInput(proto, root) Methods decrement() Decrement the st.number_input widget as if the user clicked "-". increment() Increment the st.number_input widget as if the user clicked "+". run(*, timeout=None) Run the AppTest script which contains the element. set_value(v) Set the value of the st.number_input widget. Attributes value Get the current value of the st.number_input widget. st.testing.v1.element_tree.RadioStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.radio. Class description[source] st.testing.v1.element_tree.Radio(proto, root) Methods run(*, timeout=None) Run the AppTest script which contains the element. set_value(v) Set the selection by value. Attributes format_func The widget's formatting function for displaying options. (callable) index The index of the current selection. (int) value The currently selected value from the options. (Any) st.testing.v1.element_tree.SelectSliderStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.select_slider. Class description[source] st.testing.v1.element_tree.SelectSlider(proto, root) Methods run(*, timeout=None) Run the AppTest script which contains the element. set_range(lower, upper) Set the ranged selection by values. set_value(v) Set the (single) selection by value. Attributes format_func The widget's formatting function for displaying options. (callable) value The currently selected value or range. (Any or Sequence of Any) st.testing.v1.element_tree.SelectboxStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.selectbox. Class description[source] st.testing.v1.element_tree.Selectbox(proto, root) Methods run(*, timeout=None) Run the AppTest script which contains the element. select(v) Set the selection by value. select_index(index) Set the selection by index. set_value(v) Set the selection by value. Attributes format_func The widget's formatting function for displaying options. (callable) index The index of the current selection. (int) value The currently selected value from the options. (Any) st.testing.v1.element_tree.SliderStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.slider. Class description[source] st.testing.v1.element_tree.Slider(proto, root) Methods run(*, timeout=None) Run the AppTest script which contains the element. set_range(lower, upper) Set the ranged value of the slider. set_value(v) Set the (single) value of the slider. Attributes value The currently selected value or range. (Any or Sequence of Any) st.testing.v1.element_tree.TextAreaStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.text_area. Class description[source] st.testing.v1.element_tree.TextArea(proto, root) Methods input(v) Set the value of the widget only if the value does not exceed the maximum allowed characters. run(*, timeout=None) Run the AppTest script which contains the element. set_value(v) Set the value of the widget. Attributes value The current value of the widget. (str) st.testing.v1.element_tree.TextInputStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.text_input. Class description[source] st.testing.v1.element_tree.TextInput(proto, root) Methods input(v) Set the value of the widget only if the value does not exceed the maximum allowed characters. run(*, timeout=None) Run the AppTest script which contains the element. set_value(v) Set the value of the widget. Attributes value The current value of the widget. (str) st.testing.v1.element_tree.TimeInputStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.time_input. Class description[source] st.testing.v1.element_tree.TimeInput(proto, root) Methods decrement() Select the previous available time. increment() Select the next available time. run(*, timeout=None) Run the AppTest script which contains the element. set_value(v) Set the value of the widget. Attributes value The current value of the widget. (time) st.testing.v1.element_tree.ToggleStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.toggle. Class description[source] st.testing.v1.element_tree.Toggle(proto, root) Methods run(*, timeout=None) Run the AppTest script which contains the element. set_value(v) Set the value of the widget. Attributes value The current value of the widget. (bool) Previous: st.testing.v1.AppTestNext: Command lineforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy
https://docs.streamlit.io/develop/api-reference/app-testing/st.testing.v1.apptest#apptesttext_input
DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceremovePAGE ELEMENTSWrite and magicaddText elementsaddData elementsaddChart elementsaddInput widgetsaddMedia elementsaddLayouts and containersaddChat elementsaddStatus elementsaddThird-party componentsopen_in_newAPPLICATION LOGICNavigation and pagesaddExecution flowaddCaching and stateaddConnections and secretsaddCustom componentsaddUtilitiesaddConfigurationaddTOOLSApp testingremovest.testing.v1.AppTestTesting element classesCommand lineaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Develop/API reference/App testing/st.testing.v1.AppTest The AppTest class st.testing.v1.AppTestStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA simulated Streamlit app to check the correctness of displayed elements and outputs. An instance of AppTest simulates a running Streamlit app. This class provides methods to set up, manipulate, and inspect the app contents via API instead of a browser UI. It can be used to write automated tests of an app in various scenarios. These can then be run using a tool like pytest. AppTest can be initialized by one of three class methods: st.testing.v1.AppTest.from_file (recommended) st.testing.v1.AppTest.from_string st.testing.v1.AppTest.from_function Once initialized, Session State and widget values can be updated and the script can be run. Unlike an actual live-running Streamlit app, you need to call AppTest.run() explicitly to re-run the app after changing a widget value. Switching pages also requires an explicit, follow-up call to AppTest.run(). AppTest enables developers to build tests on their app as-is, in the familiar python test format, without major refactoring or abstracting out logic to be tested separately from the UI. Tests can run quickly with very low overhead. A typical pattern is to build a suite of tests for an app that ensure consistent functionality as the app evolves, and run the tests locally and/or in a CI environment like Github Actions. Note AppTest only supports testing a single page of an app per instance. For multipage apps, each page will need to be tested separately. No methods exist to programatically switch pages within AppTest. Class description[source] st.testing.v1.AppTest(script_path, *, default_timeout, args=None, kwargs=None) Methods get(element_type) Get elements or widgets of the specified type. run(*, timeout=None) Run the script from the current state. switch_page(page_path) Switch to another page of the app. Attributes secrets (dict[str, Any]) Dictionary of secrets to be used the simulated app. Use dict-like syntax to set secret values for the simulated app. session_state (SafeSessionState) Session State for the simulated app. SafeSessionState object supports read and write operations as usual for Streamlit apps. query_params (dict[str, Any]) Dictionary of query parameters to be used by the simluated app. Use dict-like syntax to set query_params values for the simulated app. button Sequence of all st.button and st.form_submit_button widgets. caption Sequence of all st.caption elements. chat_input Sequence of all st.chat_input widgets. chat_message Sequence of all st.chat_message elements. checkbox Sequence of all st.checkbox widgets. code Sequence of all st.code elements. color_picker Sequence of all st.color_picker widgets. columns Sequence of all columns within st.columns elements. dataframe Sequence of all st.dataframe elements. date_input Sequence of all st.date_input widgets. divider Sequence of all st.divider elements. error Sequence of all st.error elements. exception Sequence of all st.exception elements. expander Sequence of all st.expander elements. header Sequence of all st.header elements. info Sequence of all st.info elements. json Sequence of all st.json elements. latex Sequence of all st.latex elements. main Sequence of elements within the main body of the app. markdown Sequence of all st.markdown elements. metric Sequence of all st.metric elements. multiselect Sequence of all st.multiselect widgets. number_input Sequence of all st.number_input widgets. radio Sequence of all st.radio widgets. select_slider Sequence of all st.select_slider widgets. selectbox Sequence of all st.selectbox widgets. sidebar Sequence of all elements within st.sidebar. slider Sequence of all st.slider widgets. status Sequence of all st.status elements. subheader Sequence of all st.subheader elements. success Sequence of all st.success elements. table Sequence of all st.table elements. tabs Sequence of all tabs within st.tabs elements. text Sequence of all st.text elements. text_area Sequence of all st.text_area widgets. text_input Sequence of all st.text_input widgets. time_input Sequence of all st.time_input widgets. title Sequence of all st.title elements. toast Sequence of all st.toast elements. toggle Sequence of all st.toggle widgets. warning Sequence of all st.warning elements. Initialize a simulated app using AppTest AppTest.from_fileStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeCreate an instance of AppTest to simulate an app page defined within a file. This option is most convenient for CI workflows and testing of published apps. The script must be executable on its own and so must contain all necessary imports. Function signature[source] AppTest.from_file(cls, script_path, *, default_timeout=3) Parameters script_path (str) Path to a script file. The path should be absolute or relative to the file calling .from_file. default_timeout (float) Default time in seconds before a script run is timed out. Can be overridden for individual .run() calls. Returns(AppTest) A simulated Streamlit app for testing. The simulated app can be executed via .run(). AppTest.from_stringStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeCreate an instance of AppTest to simulate an app page defined within a string. This is useful for testing short scripts that fit comfortably as an inline string in the test itself, without having to create a separate file for it. The script must be executable on its own and so must contain all necessary imports. Function signature[source] AppTest.from_string(cls, script, *, default_timeout=3) Parameters script (str) The string contents of the script to be run. default_timeout (float) Default time in seconds before a script run is timed out. Can be overridden for individual .run() calls. Returns(AppTest) A simulated Streamlit app for testing. The simulated app can be executed via .run(). AppTest.from_functionStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeCreate an instance of AppTest to simulate an app page defined within a function. This is similar to AppTest.from_string(), but more convenient to write with IDE assistance. The script must be executable on its own and so must contain all necessary imports. Function signature[source] AppTest.from_function(cls, script, *, default_timeout=3, args=None, kwargs=None) Parameters script (Callable) A function whose body will be used as a script. Must be runnable in isolation, so it must include any necessary imports. default_timeout (float) Default time in seconds before a script run is timed out. Can be overridden for individual .run() calls. args (tuple) An optional tuple of args to pass to the script function. kwargs (dict) An optional dict of kwargs to pass to the script function. Returns(AppTest) A simulated Streamlit app for testing. The simulated app can be executed via .run(). Run an AppTest script AppTest.runStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeRun the script from the current state. This is equivalent to manually rerunning the app or the rerun that occurs upon user interaction. AppTest.run() must be manually called after updating a widget value or switching pages as script reruns do not occur automatically as they do for live-running Streamlit apps. Function signature[source] AppTest.run(*, timeout=None) Parameters timeout (null) The maximum number of seconds to run the script. None means use the default timeout set for the instance of AppTest. Returns(AppTest) self AppTest.switch_pageStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSwitch to another page of the app. This method does not automatically rerun the app. Use a follow-up call to AppTest.run() to obtain the elements on the selected page. Function signature[source] AppTest.switch_page(page_path) Parameters page_path (str) Path of the page to switch to. The path must be relative to the main script's location (e.g. "pages/my_page.py"). Returns(AppTest) self Get AppTest script elements The main value of AppTest is providing an API to programmatically inspect and interact with the elements and widgets produced by a running Streamlit app. Using the AppTest.<element type> properties or AppTest.get() method returns a collection of all the elements or widgets of the specified type that would have been displayed by running the app. Note that you can also retrieve elements within a specific container in the same way - first retrieve the container, then retrieve the elements just in that container. AppTest.getStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeGet elements or widgets of the specified type. This method returns the collection of all elements or widgets of the specified type on the current page. Retrieve a specific element by using its index (order on page) or key lookup. Function signature[source] AppTest.get(element_type) Parameters element_type (str) An element attribute of AppTest. For example, "button", "caption", or "chat_input". Returns(Sequence of Elements) Sequence of elements of the given type. Individual elements can be accessed from a Sequence by index (order on the page). When getting and element_type that is a widget, individual widgets can be accessed by key. For example, at.get("text")[0] for the first st.text element or at.get("slider")(key="my_key") for the st.slider widget with a given key. AppTest.buttonStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.button and st.form_submit_button widgets. Function signature[source] AppTest.button Returns(WidgetList of Button) Sequence of all st.button and st.form_submit_button widgets. Individual widgets can be accessed from a WidgetList by index (order on the page) or key. For example, at.button[0] for the first widget or at.button(key="my_key") for a widget with a given key. AppTest.captionStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.caption elements. Function signature[source] AppTest.caption Returns(ElementList of Caption) Sequence of all st.caption elements. Individual elements can be accessed from an ElementList by index (order on the page). For example, at.caption[0] for the first element. Caption is an extension of the Element class. AppTest.chat_inputStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.chat_input widgets. Function signature[source] AppTest.chat_input Returns(WidgetList of ChatInput) Sequence of all st.chat_input widgets. Individual widgets can be accessed from a WidgetList by index (order on the page) or key. For example, at.chat_input[0] for the first widget or at.chat_input(key="my_key") for a widget with a given key. AppTest.chat_messageStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.chat_message elements. Function signature[source] AppTest.chat_message Returns(Sequence of ChatMessage) Sequence of all st.chat_message elements. Individual elements can be accessed from an ElementList by index (order on the page). For example, at.chat_message[0] for the first element. ChatMessage is an extension of the Block class. AppTest.checkboxStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.checkbox widgets. Function signature[source] AppTest.checkbox Returns(WidgetList of Checkbox) Sequence of all st.checkbox widgets. Individual widgets can be accessed from a WidgetList by index (order on the page) or key. For example, at.checkbox[0] for the first widget or at.checkbox(key="my_key") for a widget with a given key. AppTest.codeStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.code elements. Function signature[source] AppTest.code Returns(ElementList of Code) Sequence of all st.code elements. Individual elements can be accessed from an ElementList by index (order on the page). For example, at.code[0] for the first element. Code is an extension of the Element class. AppTest.color_pickerStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.color_picker widgets. Function signature[source] AppTest.color_picker Returns(WidgetList of ColorPicker) Sequence of all st.color_picker widgets. Individual widgets can be accessed from a WidgetList by index (order on the page) or key. For example, at.color_picker[0] for the first widget or at.color_picker(key="my_key") for a widget with a given key. AppTest.columnsStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all columns within st.columns elements. Each column within a single st.columns will be returned as a separate Column in the Sequence. Function signature[source] AppTest.columns Returns(Sequence of Column) Sequence of all columns within st.columns elements. Individual columns can be accessed from an ElementList by index (order on the page). For example, at.columns[0] for the first column. Column is an extension of the Block class. AppTest.dataframeStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.dataframe elements. Function signature[source] AppTest.dataframe Returns(ElementList of Dataframe) Sequence of all st.dataframe elements. Individual elements can be accessed from an ElementList by index (order on the page). For example, at.dataframe[0] for the first element. Dataframe is an extension of the Element class. AppTest.date_inputStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.date_input widgets. Function signature[source] AppTest.date_input Returns(WidgetList of DateInput) Sequence of all st.date_input widgets. Individual widgets can be accessed from a WidgetList by index (order on the page) or key. For example, at.date_input[0] for the first widget or at.date_input(key="my_key") for a widget with a given key. AppTest.dividerStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.divider elements. Function signature[source] AppTest.divider Returns(ElementList of Divider) Sequence of all st.divider elements. Individual elements can be accessed from an ElementList by index (order on the page). For example, at.divider[0] for the first element. Divider is an extension of the Element class. AppTest.errorStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.error elements. Function signature[source] AppTest.error Returns(ElementList of Error) Sequence of all st.error elements. Individual elements can be accessed from an ElementList by index (order on the page). For example, at.error[0] for the first element. Error is an extension of the Element class. AppTest.exceptionStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.exception elements. Function signature[source] AppTest.exception Returns(ElementList of Exception) Sequence of all st.exception elements. Individual elements can be accessed from an ElementList by index (order on the page). For example, at.exception[0] for the first element. Exception is an extension of the Element class. AppTest.expanderStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.expander elements. Function signature[source] AppTest.expander Returns(Sequence of Expandable) Sequence of all st.expander elements. Individual elements can be accessed from a Sequence by index (order on the page). For example, at.expander[0] for the first element. Expandable is an extension of the Block class. AppTest.headerStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.header elements. Function signature[source] AppTest.header Returns(ElementList of Header) Sequence of all st.header elements. Individual elements can be accessed from an ElementList by index (order on the page). For example, at.header[0] for the first element. Header is an extension of the Element class. AppTest.infoStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.info elements. Function signature[source] AppTest.info Returns(ElementList of Info) Sequence of all st.info elements. Individual elements can be accessed from an ElementList by index (order on the page). For example, at.info[0] for the first element. Info is an extension of the Element class. AppTest.jsonStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.json elements. Function signature[source] AppTest.json Returns(ElementList of Json) Sequence of all st.json elements. Individual elements can be accessed from an ElementList by index (order on the page). For example, at.json[0] for the first element. Json is an extension of the Element class. AppTest.latexStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.latex elements. Function signature[source] AppTest.latex Returns(ElementList of Latex) Sequence of all st.latex elements. Individual elements can be accessed from an ElementList by index (order on the page). For example, at.latex[0] for the first element. Latex is an extension of the Element class. AppTest.mainStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of elements within the main body of the app. Function signature[source] AppTest.main Returns(Block) A container of elements. Block can be queried for elements in the same manner as AppTest. For example, Block.checkbox will return all st.checkbox within the associated container. AppTest.markdownStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.markdown elements. Function signature[source] AppTest.markdown Returns(ElementList of Markdown) Sequence of all st.markdown elements. Individual elements can be accessed from an ElementList by index (order on the page). For example, at.markdown[0] for the first element. Markdown is an extension of the Element class. AppTest.metricStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.metric elements. Function signature[source] AppTest.metric Returns(ElementList of Metric) Sequence of all st.metric elements. Individual elements can be accessed from an ElementList by index (order on the page). For example, at.metric[0] for the first element. Metric is an extension of the Element class. AppTest.multiselectStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.multiselect widgets. Function signature[source] AppTest.multiselect Returns(WidgetList of Multiselect) Sequence of all st.multiselect widgets. Individual widgets can be accessed from a WidgetList by index (order on the page) or key. For example, at.multiselect[0] for the first widget or at.multiselect(key="my_key") for a widget with a given key. AppTest.number_inputStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.number_input widgets. Function signature[source] AppTest.number_input Returns(WidgetList of NumberInput) Sequence of all st.number_input widgets. Individual widgets can be accessed from a WidgetList by index (order on the page) or key. For example, at.number_input[0] for the first widget or at.number_input(key="my_key") for a widget with a given key. AppTest.radioStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.radio widgets. Function signature[source] AppTest.radio Returns(WidgetList of Radio) Sequence of all st.radio widgets. Individual widgets can be accessed from a WidgetList by index (order on the page) or key. For example, at.radio[0] for the first widget or at.radio(key="my_key") for a widget with a given key. AppTest.select_sliderStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.select_slider widgets. Function signature[source] AppTest.select_slider Returns(WidgetList of SelectSlider) Sequence of all st.select_slider widgets. Individual widgets can be accessed from a WidgetList by index (order on the page) or key. For example, at.select_slider[0] for the first widget or at.select_slider(key="my_key") for a widget with a given key. AppTest.selectboxStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.selectbox widgets. Function signature[source] AppTest.selectbox Returns(WidgetList of Selectbox) Sequence of all st.selectbox widgets. Individual widgets can be accessed from a WidgetList by index (order on the page) or key. For example, at.selectbox[0] for the first widget or at.selectbox(key="my_key") for a widget with a given key. AppTest.sidebarStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all elements within st.sidebar. Function signature[source] AppTest.sidebar Returns(Block) A container of elements. Block can be queried for elements in the same manner as AppTest. For example, Block.checkbox will return all st.checkbox within the associated container. AppTest.sliderStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.slider widgets. Function signature[source] AppTest.slider Returns(WidgetList of Slider) Sequence of all st.slider widgets. Individual widgets can be accessed from a WidgetList by index (order on the page) or key. For example, at.slider[0] for the first widget or at.slider(key="my_key") for a widget with a given key. AppTest.subheaderStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.subheader elements. Function signature[source] AppTest.subheader Returns(ElementList of Subheader) Sequence of all st.subheader elements. Individual elements can be accessed from an ElementList by index (order on the page). For example, at.subheader[0] for the first element. Subheader is an extension of the Element class. AppTest.successStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.success elements. Function signature[source] AppTest.success Returns(ElementList of Success) Sequence of all st.success elements. Individual elements can be accessed from an ElementList by index (order on the page). For example, at.success[0] for the first element. Success is an extension of the Element class. AppTest.statusStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.status elements. Function signature[source] AppTest.status Returns(Sequence of Status) Sequence of all st.status elements. Individual elements can be accessed from a Sequence by index (order on the page). For example, at.status[0] for the first element. Status is an extension of the Block class. AppTest.tableStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.table elements. Function signature[source] AppTest.table Returns(ElementList of Table) Sequence of all st.table elements. Individual elements can be accessed from an ElementList by index (order on the page). For example, at.table[0] for the first element. Table is an extension of the Element class. AppTest.tabsStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all tabs within st.tabs elements. Each tab within a single st.tabs will be returned as a separate Tab in the Sequence. Additionally, the tab labels are forwarded to each Tab element as a property. For example, st.tabs("A","B") will yield two Tab objects, with Tab.label returning "A" and "B", respectively. Function signature[source] AppTest.tabs Returns(Sequence of Tab) Sequence of all tabs within st.tabs elements. Individual tabs can be accessed from an ElementList by index (order on the page). For example, at.tabs[0] for the first tab. Tab is an extension of the Block class. AppTest.textStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.text elements. Function signature[source] AppTest.text Returns(ElementList of Text) Sequence of all st.text elements. Individual elements can be accessed from an ElementList by index (order on the page). For example, at.text[0] for the first element. Text is an extension of the Element class. AppTest.text_areaStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.text_area widgets. Function signature[source] AppTest.text_area Returns(WidgetList of TextArea) Sequence of all st.text_area widgets. Individual widgets can be accessed from a WidgetList by index (order on the page) or key. For example, at.text_area[0] for the first widget or at.text_area(key="my_key") for a widget with a given key. AppTest.text_inputStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.text_input widgets. Function signature[source] AppTest.text_input Returns(WidgetList of TextInput) Sequence of all st.text_input widgets. Individual widgets can be accessed from a WidgetList by index (order on the page) or key. For example, at.text_input[0] for the first widget or at.text_input(key="my_key") for a widget with a given key. AppTest.time_inputStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.time_input widgets. Function signature[source] AppTest.time_input Returns(WidgetList of TimeInput) Sequence of all st.time_input widgets. Individual widgets can be accessed from a WidgetList by index (order on the page) or key. For example, at.time_input[0] for the first widget or at.time_input(key="my_key") for a widget with a given key. AppTest.titleStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.title elements. Function signature[source] AppTest.title Returns(ElementList of Title) Sequence of all st.title elements. Individual elements can be accessed from an ElementList by index (order on the page). For example, at.title[0] for the first element. Title is an extension of the Element class. AppTest.toastStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.toast elements. Function signature[source] AppTest.toast Returns(ElementList of Toast) Sequence of all st.toast elements. Individual elements can be accessed from an ElementList by index (order on the page). For example, at.toast[0] for the first element. Toast is an extension of the Element class. AppTest.toggleStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.toggle widgets. Function signature[source] AppTest.toggle Returns(WidgetList of Toggle) Sequence of all st.toggle widgets. Individual widgets can be accessed from a WidgetList by index (order on the page) or key. For example, at.toggle[0] for the first widget or at.toggle(key="my_key") for a widget with a given key. AppTest.warningStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.warning elements. Function signature[source] AppTest.warning Returns(ElementList of Warning) Sequence of all st.warning elements. Individual elements can be accessed from an ElementList by index (order on the page). For example, at.warning[0] for the first element. Warning is an extension of the Element class. Previous: App testingNext: Testing element classesforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy
https://docs.streamlit.io/deploy/streamlit-community-cloud/troubleshooting#what-happens-when-a-users-permissions-change-on-github
DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudremoveGet startedaddDeploy your appaddManage your appaddShare your appaddManage your accountaddTroubleshootingStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Deploy/Streamlit Community Cloud/TroubleshootingTroubleshooting Sorry to hear you're having issues! Please take a look at some frequently asked questions and issues below. If you cannot find an answer to your issue, please post on our Community forum so that our engineers or community members can help you. Table of contents General help Deploying apps Sharing and accessing apps Data and app security GitHub integration Limitations and known issues General help How can I get help with my app? If you have any questions, feedback, run into any issues, or need to reach us, you can ask on our Community forum. This is best suited for any questions related to the open source library and Community Cloud - debugging code, deployment, resource limits, etc. Deploying apps My repo isn't showing on the Deploy page It's possible it just isn't showing up even though it is already there. Try typing it in. If we don't recognize it, you'll see the message below with a link to click and give access. If for some reason that doesn't work, please try logging out and back in again to make sure the change took effect. And if that doesn't work - please let us know and we'll get you sorted! It won't let me deploy the app To deploy an app for the first time you must have admin-level access to the repo in GitHub. Please check with your administrator to make sure you have that access. If not, please ask them to deploy for the first time (we need this in order to establish webhooks for continuous integration) and from there you can then push updates to the app. I need to set a specific Python version for my app When deploying an app, under advanced settings, you can choose which version of Python you wish your app to use. How do I store files locally? If you want to store your data locally as opposed to in a database, you can store the file in your GitHub repository. Streamlit is just python, so you can read the file using: pandas.read_csv("data.csv") or open("data.csv") starTipIf you have really big or binary data that you change frequently, and git is feeling slow, you might want to check out Git Large File Store (LFS) as a better way to store large files in GitHub. You don't need to make any changes to your app to start using it. If your GitHub repo uses LFS, it will now just work with Streamlit. My app is running into issues while deploying Check your Cloud logs by clicking on the "Manage app" expander in the bottom right corner of your screen. Often the trouble is due to a dependency not being declared. See here for more information on dependency management. If that's not the issue, then please send the logs and warning you are seeing to our Community forum and we'll help get you sorted! My app is hitting resource limits / my app is running very slowly If your app is running slowly or you're hitting the 'Argh' page, we first highly recommend going through and implementing the suggestions in the following blog posts to prevent your app from hitting the resource limits and to detect if your Streamlit app leaks memory: Common app problems: Resource limits 3 steps to fix app memory leaks If you're still having issues, click here to learn more about resource limits. Can I get a custom URL for my app? Yes! You can find instructions for setting a custom subdomain here. Sharing and accessing apps Don't have SSO? No problem! You can sign in to Streamlit with your email address. Click here for step-by-step instructions on how to sign in with email. */} How do I add viewers to my Streamlit apps? Viewer auth allows you to restrict the viewers of your private app. To access your app, users have to authenticate using an email-based passwordless login or Google OAuth. To learn more about how to share your public and private apps with viewers, click here. Do viewers need access to the GitHub repo? Nope! You only need access to the GitHub repo if you want to push changes to the app. What will unauthorized/logged out viewers see when they view my app? A 404 error is displayed to unauthorized viewers to avoid providing any unnecessary information about your app to unintended viewers. Users who satisfy any of the following conditions will see a 404 error when attempting to view your app after you have configured viewer auth: User is not logged in with their primary identity. User is not included in the list of allowed viewers provided in the app settings. User lacks read access to your app's GitHub repo. User has read access to your app's GitHub repo but is not enrolled in Streamlit Community Cloud. I've added someone to the viewer list but they still see a 404 error when attempting to view the app If a user is still seeing a 404 error after their email address has been added to the viewer list, we recommend that you: Check that the user did not log into a different Google account via Single Sign-On (if you have added their work email address to the viewer list, ask the user to check that they are not logged into their personal Google account, and vice versa). Check that the user has navigated to the correct URL. Check that the user's email address has been entered correctly in the viewer list. Reach out on our Community forum and we will be happy to help. Data and app security How will Streamlit secure my data? Streamlit takes a number of industry best-practice measures to ensure your code, data, and apps are all secure. Read more in our Trust and Security memo. How do I set up SSO for my organization? Community Cloud uses Google OAuth, by default. If you use Google for authentication you're all set. Billing and administration The Community Cloud is a free service. You don't have to worry about setting up billing or being charged. GitHub integration Why does Streamlit require additional OAuth scope? In order to deploy your app, Streamlit requires access to your app's source code in GitHub and also the ability to manage the public keys associated with the repositories. The default GitHub OAuth scopes are sufficient to work with apps in public GitHub repositories. However, in order to work with apps in private GitHub repositories, Streamlit requires the additional repo OAuth scope from GitHub. We recognize that this scope provides Streamlit with extra permissions that we do not really need, and which, as people who prize security, we'd rather not even be granted. Alas, we need to work with the APIs we are provided by GitHub. After deploying my private-repo app, I received an email from GitHub saying a new public key was added to my repo. Is this expected? This is the expected behavior. When you try to deploy an app that lives in a private repo, Streamlit Community Cloud needs to get access to that repo somehow. For this, we create a read-only GitHub Deploy Key then access your repo using a public SSH key. When we set this up, GitHub notifies admins of the repo that the key was created as a security measure. What happens when a user's permissions change on GitHub? Once a user is added to a repository on GitHub, it will take at most 15 minutes before they can deploy the app on Cloud. If a user is removed from a repository on GitHub, it will take at most 15 minutes before their permissions to manage the app from that repository are revoked. Limitations and known issues Here are some limitations and known issues that we're actively working to resolve. When you print something to the Cloud logs, you may need to do a sys.stdout.flush() before it shows up. Matplotlib doesn't work well with threads. So if you're using Matplotlib you should wrap your code with locks as shown in the snippet below. This Matplotlib bug is more prominent when you share your app apps since you're more likely to get more concurrent users then. from matplotlib.backends.backend_agg import RendererAgg _lock = RendererAgg.lock with _lock: fig.title('This is a figure)') fig.plot([1,20,3,40]) st.pyplot(fig) All apps are hosted in the United States. This is currently not configurable. Previous: Manage your accountNext: Streamlit in SnowflakeforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy
https://docs.streamlit.io/deploy/streamlit-community-cloud/manage-your-app/delete-your-app#delete-your-app-from-your-workspace
DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudremoveGet startedaddDeploy your appaddManage your appremoveApp analyticsApp settingsDelete your appEdit your appFavorite your appReboot your appShare your appaddManage your accountaddTroubleshootingStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Deploy/Streamlit Community Cloud/Manage your app/Delete your appDelete your app If you need to delete your app, it's simple and easy. There are several cases where you may need to delete your app: You have finished playing around with an example app. You want to deploy from a private repository but already have a private app. You want to change the Python version for your app or otherwise redeploy your app. If you delete your app and intend to immediately redploy it, your custom subdomain should be immediately available for reuse. Read more about data deletion in Streamlit trust and security. You can delete your app: From your workspace. From your Cloud logs. Delete your app from your workspace From your workspace at share.streamlit.io, click the overflow icon (more_vert) next to your app. Click "Delete". A confirmation will display. Enter the required confirmation string and click "Delete". Delete your app from your Cloud logs From your app at <your-custom-subdomain>.streamlit.app, click "Manage app" in the lower-right corner. Click the overflow menu icon (more_vert) and click "Delete app". A confirmation will display. Enter the required confirmation string and click "Delete". Previous: App settingsNext: Edit your appforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy
https://docs.streamlit.io/knowledge-base/deploy/share-apps-with-viewers-outside-organization#share-your-app
DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudremoveGet startedaddDeploy your appaddManage your appaddShare your appremoveEmbed your appSearch indexabilityShare previewsManage your accountaddTroubleshootingStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Deploy/Streamlit Community Cloud/Share your appShare your app Now that your app is deployed you can easily share it and collaborate on it. But first, let's take a moment and do a little joy dance for getting that app deployed! 🕺💃 Your app is now live at a fixed URL, so go wild and share it with whomever you want. Your app will inherit permissions from your GitHub repo, meaning that if your repo is private your app will be private and if your repo is public your app will be public. If you want to change that you can simply do so from the app settings menu. You are only allowed one private app at a time. If you've deployed from a private repository, you will have to make that app public or delete it before you can deploy another app from a private repository. Only developers can change your app between public and private. Make your app public or private Share your public app Share your private app Make your app public or private If you deployed your app from a public repository, your app will be public by default. If you deployed your app from a private repository, you will need to make the app public if you want to freely share it with the community at large. Set privacy from your app settings Access your App settings and go to the "Sharing" section. Set your app's privacy under "Who can view this app." Select "This app is public and searchable" to make your app public. Select "Only specific people can view this app" to make your app private. Set privacy from the share button From your app at <your-custom-subdomain>.streamlit.app, click "Share" in the upper-right corner. Toggle your app between public and private by clicking "Make this app public". Share your public app Once your app is public, just give anyone your app's URL and they view it! Streamlit Community Cloud has several convenient shortcuts for sharing your app. Share your app on social media From your app at <your-custom-subdomain>.streamlit.app, click "Share" in the upper-right corner. Click "Social" to access convenient social media share buttons. starTipUse the social media sharing buttons to post your app on our forum! We'd love to see what you make and perhaps feature your app as our app of the month. 💖 Invite viewers by email Whether your app is public or private, you can send an email invite to your app directly from Streamlit Community Cloud. This grants the viewer access to analytics for all your public apps and the ability to invite other viewers to your workspace. Developers and invited viewers are identified by their email in analytics instead of appearing anonymously (if they view any of your apps while logged in). Read more about viewers in App analytics. From your app at <your-custom-subdomain>.streamlit.app, click "Share" in the upper-right corner. Enter an email address and click "Invite". Invited users will get a direct link to your app in their inbox. Copy your app's URL You can convenitiently copy your app's URL from the share menu or from your workspace. From your app click "Share" in the upper-right corner then click "Copy link". From your workspace click the overflow menu icon (more_vert) then click "Copy URL". Add a badge to your GitHub repository To help others find and play with your Streamlit app, you can add Streamlit's GitHub badge to your repo. Below is an enlarged example of what the badge looks like. Clicking on the badge takes you to—in this case—Streamlit's Roadmap. Once you deploy your app, you can embed this badge right into your GitHub README.md by adding the following Markdown: [![Streamlit App](https://static.streamlit.io/badges/streamlit_badge_black_white.svg)](https://<your-custom-subdomain>.streamlit.app) push_pinNoteBe sure to replace https://<your-custom-subdomain>.streamlit.app with the URL of your deployed app! Share your private app By default an app deployed from a private repository will be private to the developers in the workspace. A private app will not be visible to anyone else unless you grant them explicit permission. You can grant permission by adding them as a developer on GitHub or by adding them as a viewer on Streamlit Community Cloud. Once you have added someone's email address to your app's viewer list, that person will be able to sign in and view your private app. If their email is associated to a Google account, they will be able to sign in with Google OAuth. Otherwise, they will be able to sign in with single-use, emailed links. Streamlit sends an email invitation with a link to your app every time you invite someone. priority_highImportantWhen you add a viewer to any app in your workspace, they are granted access to analytics for that app as well as analytics for all your public apps. They can also pass these permissions to others by inviting more viewers. All viewers and developers in your workspace are identified by their email in analytics. Furthermore, their emails show in analytics for every app in your workspace and not just apps they are explicitly invited to. Read more about viewers in App analytics Invite viewers from the share button From your app at <your-custom-subdomain>.streamlit.app, click "Share" in the upper-right corner. Enter the email to send an invitation to and click "Invite". Invited users appear in the list below. Invited users will get a direct link to your app in their inbox. To remove a viewer, simply access the share menu as above and click the close next to their name. Invite viewers from your app settings Access your App settings and go to the "Sharing" section. Add or remove users from the list of viewers. Click "Save". Previous: Manage your appNext: Embed your appforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy
https://docs.streamlit.io/knowledge-base/using-streamlit/insert-elements-out-of-order
DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Knowledge base/FAQ/How to insert elements out of order?How to insert elements out of order? You can use the st.empty method as a placeholder, to "save" a slot in your app that you can use later. st.text('This will appear first') # Appends some text to the app. my_slot1 = st.empty() # Appends an empty slot to the app. We'll use this later. my_slot2 = st.empty() # Appends another empty slot. st.text('This will appear last') # Appends some more text to the app. my_slot1.text('This will appear second') # Replaces the first empty slot with a text string. my_slot2.line_chart(np.random.randn(20, 2)) # Replaces the second empty slot with a chart. Previous: How do I upgrade to the latest version of Streamlit?Next: How can I make st.pydeck_chart use custom Mapbox styles?forumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy
https://docs.streamlit.io/deploy/streamlit-community-cloud/manage-your-account#access-your-workspace-settings
DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudremoveGet startedaddDeploy your appaddManage your appaddShare your appaddManage your accountremoveSign in & sign outWorkspace settingsManage your GitHub connectionUpdate your emailDelete your accountTroubleshootingStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Deploy/Streamlit Community Cloud/Manage your accountManage your account You can Update your email or Delete your account entirely through Workspace settings. When using Streamlit Community Cloud, you have two identities behind your account: a primary identity (Google or email) and source control (GitHub). Your primary identity allows other users to share private apps with you and grant you access to their analytics. Your source control identity allows you to deploy apps from GitHub repositories and manage them through your Streamlit Community Cloud workspace. Access your workspace settings To manage your account, sign in to share.streamlit.io and click "Settings" in the top right corner to access your workspace settings. Learn more about how to Update your email and Delete your account.Previous: Share your appNext: Sign in & sign outforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy
https://docs.streamlit.io/develop/api-reference/charts/st.bar_chart#elementadd_rows
DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceremovePAGE ELEMENTSWrite and magicaddText elementsaddData elementsaddChart elementsremoveSIMPLEst.area_chartst.bar_chartst.line_chartst.mapst.scatter_chartADVANCEDst.altair_chartst.bokeh_chartst.graphviz_chartst.plotly_chartst.pydeck_chartst.pyplotst.vega_lite_chartInput widgetsaddMedia elementsaddLayouts and containersaddChat elementsaddStatus elementsaddThird-party componentsopen_in_newAPPLICATION LOGICNavigation and pagesaddExecution flowaddCaching and stateaddConnections and secretsaddCustom componentsaddUtilitiesaddConfigurationaddTOOLSApp testingaddCommand lineaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Develop/API reference/Chart elements/st.bar_chartst.bar_chartStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeDisplay a bar chart. This is syntax-sugar around st.altair_chart. The main difference is this command uses the data's own column and indices to figure out the chart's spec. As a result this is easier to use for many "just plot this" scenarios, while being less customizable. If st.bar_chart does not guess the data specification correctly, try specifying your desired chart using st.altair_chart. Function signature[source] st.bar_chart(data=None, *, x=None, y=None, color=None, width=0, height=0, use_container_width=True) Parameters data (pandas.DataFrame, pandas.Styler, pyarrow.Table, numpy.ndarray, pyspark.sql.DataFrame, snowflake.snowpark.dataframe.DataFrame, snowflake.snowpark.table.Table, Iterable, or dict) Data to be plotted. x (str or None) Column name to use for the x-axis. If None, uses the data index for the x-axis. y (str, Sequence of str, or None) Column name(s) to use for the y-axis. If a Sequence of strings, draws several series on the same chart by melting your wide-format table into a long-format table behind the scenes. If None, draws the data of all remaining columns as data series. color (str, tuple, Sequence of str, Sequence of tuple, or None) The color to use for different series in this chart. For a bar chart with just one series, this can be: None, to use the default color. A hex string like "#ffaa00" or "#ffaa0088". An RGB or RGBA tuple with the red, green, blue, and alpha components specified as ints from 0 to 255 or floats from 0.0 to 1.0. For a bar chart with multiple series, where the dataframe is in long format (that is, y is None or just one column), this can be: None, to use the default colors. The name of a column in the dataset. Data points will be grouped into series of the same color based on the value of this column. In addition, if the values in this column match one of the color formats above (hex string or color tuple), then that color will be used. For example: if the dataset has 1000 rows, but this column only contains the values "adult", "child", and "baby", then those 1000 datapoints will be grouped into three series whose colors will be automatically selected from the default palette. But, if for the same 1000-row dataset, this column contained the values "#ffaa00", "#f0f", "#0000ff", then then those 1000 datapoints would still be grouped into 3 series, but their colors would be "#ffaa00", "#f0f", "#0000ff" this time around. For a bar chart with multiple series, where the dataframe is in wide format (that is, y is a Sequence of columns), this can be: None, to use the default colors. A list of string colors or color tuples to be used for each of the series in the chart. This list should have the same length as the number of y values (e.g. color=["#fd0", "#f0f", "#04f"] for three lines). width (int) The chart width in pixels. If 0, selects the width automatically. height (int) The chart height in pixels. If 0, selects the height automatically. use_container_width (bool) If True, set the chart width to the column width. This takes precedence over the width argument. Examples import streamlit as st import pandas as pd import numpy as np chart_data = pd.DataFrame(np.random.randn(20, 3), columns=["a", "b", "c"]) st.bar_chart(chart_data) Built with Streamlit 🎈Fullscreen open_in_new You can also choose different columns to use for x and y, as well as set the color dynamically based on a 3rd column (assuming your dataframe is in long format): import streamlit as st import pandas as pd import numpy as np chart_data = pd.DataFrame( { "col1": list(range(20)) * 3, "col2": np.random.randn(60), "col3": ["A"] * 20 + ["B"] * 20 + ["C"] * 20, } ) st.bar_chart(chart_data, x="col1", y="col2", color="col3") Built with Streamlit 🎈Fullscreen open_in_new Finally, if your dataframe is in wide format, you can group multiple columns under the y argument to show multiple series with different colors: import streamlit as st import pandas as pd import numpy as np chart_data = pd.DataFrame( {"col1": list(range(20)), "col2": np.random.randn(20), "col3": np.random.randn(20)} ) st.bar_chart( chart_data, x="col1", y=["col2", "col3"], color=["#FF0000", "#0000FF"] # Optional ) Built with Streamlit 🎈Fullscreen open_in_new element.add_rowsStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeConcatenate a dataframe to the bottom of the current one. Function signature[source] element.add_rows(data=None, **kwargs) Parameters data (pandas.DataFrame, pandas.Styler, pyarrow.Table, numpy.ndarray, pyspark.sql.DataFrame, snowflake.snowpark.dataframe.DataFrame, Iterable, dict, or None) Table to concat. Optional. **kwargs (pandas.DataFrame, numpy.ndarray, Iterable, dict, or None) The named dataset to concat. Optional. You can only pass in 1 dataset (including the one in the data parameter). Example import streamlit as st import pandas as pd import numpy as np df1 = pd.DataFrame(np.random.randn(50, 20), columns=("col %d" % i for i in range(20))) my_table = st.table(df1) df2 = pd.DataFrame(np.random.randn(50, 20), columns=("col %d" % i for i in range(20))) my_table.add_rows(df2) # Now the table shown in the Streamlit app contains the data for # df1 followed by the data for df2. You can do the same thing with plots. For example, if you want to add more data to a line chart: # Assuming df1 and df2 from the example above still exist... my_chart = st.line_chart(df1) my_chart.add_rows(df2) # Now the chart shown in the Streamlit app contains the data for # df1 followed by the data for df2. And for plots whose datasets are named, you can pass the data with a keyword argument where the key is the name: my_chart = st.vega_lite_chart({ 'mark': 'line', 'encoding': {'x': 'a', 'y': 'b'}, 'datasets': { 'some_fancy_name': df1, # <-- named dataset }, 'data': {'name': 'some_fancy_name'}, }), my_chart.add_rows(some_fancy_name=df2) # <-- name used as keyword Previous: st.area_chartNext: st.line_chartforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy
https://docs.streamlit.io/develop/concepts/design/dataframes#stdataframe-ui-features
DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsremoveCOREArchitecture & executionaddMultipage appsaddApp designremoveAnimate & update elementsButton behavior and examplesDataframesUsing custom classesWorking with timezonesADDITIONALConnections and secretsaddCustom componentsaddConfiguration and themingaddApp testingaddAPI referenceaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Develop/Concepts/App design/DataframesDataframes Dataframes are a great way to display and edit data in a tabular format. Working with Pandas DataFrames and other tabular data structures is key to data science workflows. If developers and data scientists want to display this data in Streamlit, they have multiple options: st.dataframe and st.data_editor. If you want to solely display data in a table-like UI, st.dataframe is the way to go. If you want to interactively edit data, use st.data_editor. We explore the use cases and advantages of each option in the following sections. Display dataframes with st.dataframe Streamlit can display dataframes in a table-like UI via st.dataframe : import streamlit as st import pandas as pd df = pd.DataFrame( [ {"command": "st.selectbox", "rating": 4, "is_widget": True}, {"command": "st.balloons", "rating": 5, "is_widget": False}, {"command": "st.time_input", "rating": 3, "is_widget": True}, ] ) st.dataframe(df, use_container_width=True) Built with Streamlit 🎈Fullscreen open_in_new st.dataframe UI features st.dataframe provides additional functionality by using glide-data-grid under the hood: Column sorting: Sort columns by clicking on their headers. Column resizing: Resize columns by dragging and dropping column header borders. Table resizing: Resize tables by dragging and dropping the bottom right corner. Fullscreen view: Enlarge tables to fullscreen by clicking the fullscreen icon (fullscreen) in the toolbar. Search: Click the search icon (search) in the toolbar or use hotkeys (⌘+F or Ctrl+F) to search through the data. Download: Click the download icon in the toolbar to download the data as a CSV file. Copy to clipboard: Select one or multiple cells, copy them to the clipboard (⌘+C or Ctrl+C), and paste them into your favorite spreadsheet software. Try out all the UI features using the embedded app from the prior section. In addition to Pandas DataFrames, st.dataframe also supports other common Python types, e.g., list, dict, or numpy array. It also supports Snowpark and PySpark DataFrames, which allow you to lazily evaluate and pull data from databases. This can be useful for working with large datasets. Edit data with st.data_editor Streamlit supports editable dataframes via the st.data_editor command. Check out its API in st.data_editor. It shows the dataframe in a table, similar to st.dataframe. But in contrast to st.dataframe, this table isn't static! The user can click on cells and edit them. The edited data is then returned on the Python side. Here's an example: df = pd.DataFrame( [ {"command": "st.selectbox", "rating": 4, "is_widget": True}, {"command": "st.balloons", "rating": 5, "is_widget": False}, {"command": "st.time_input", "rating": 3, "is_widget": True}, ] ) edited_df = st.data_editor(df) # 👈 An editable dataframe favorite_command = edited_df.loc[edited_df["rating"].idxmax()]["command"] st.markdown(f"Your favorite command is **{favorite_command}** 🎈") Built with Streamlit 🎈Fullscreen open_in_new Try it out by double-clicking on any cell. You'll notice you can edit all cell values. Try editing the values in the rating column and observe how the text output at the bottom changes: st.data_editor UI features st.data_editor also supports a few additional things: Add and delete rows: You can do this by setting num_rows= "dynamic" when calling st.data_editor. This will allow users to add and delete rows as needed. Copy and paste support: Copy and paste both between st.data_editor and spreadsheet software like Google Sheets and Excel. Access edited data: Access only the individual edits instead of the entire edited data structure via Session State. Bulk edits: Similar to Excel, just drag a handle to edit neighboring cells. Automatic input validation: Column Configuration provides strong data type support and other configurable options. For example, there's no way to enter letters into a number cell. Number cells can have a designated min and max. Edit common data structures: st.data_editor supports lists, dicts, NumPy ndarray, and more! Add and delete rows With st.data_editor, viewers can add or delete rows via the table UI. This mode can be activated by setting the num_rows parameter to "dynamic": edited_df = st.data_editor(df, num_rows="dynamic") To add new rows, click the plus icon (add) in the toolbar. Alternatively, click inside a shaded cell below the bottom row of the table. To delete rows, select one or more rows using the checkboxes on the left. Click the delete icon (delete) or press the delete key on your keyboard. Built with Streamlit 🎈Fullscreen open_in_new Copy and paste support The data editor supports pasting in tabular data from Google Sheets, Excel, Notion, and many other similar tools. You can also copy-paste data between st.data_editor instances. This functionality, powered by the Clipboard API, can be a huge time saver for users who need to work with data across multiple platforms. To try it out: Copy data from this Google Sheets document to your clipboard. Single click any cell in the name column in the app above. Paste it in using hotkeys (⌘+V or Ctrl+V). push_pinNoteEvery cell of the pasted data will be evaluated individually and inserted into the cells if the data is compatible with the column type. For example, pasting in non-numerical text data into a number column will be ignored. starTipIf you embed your apps with iframes, you'll need to allow the iframe to access the clipboard if you want to use the copy-paste functionality. To do so, give the iframe clipboard-write and clipboard-read permissions. E.g.<iframe allow="clipboard-write;clipboard-read;" ... src="https://your-app-url"></iframe> As developers, ensure the app is served with a valid, trusted certificate when using TLS. If users encounter issues with copying and pasting data, direct them to check if their browser has activated clipboard access permissions for the Streamlit application, either when prompted or through the browser's site settings. Access edited data Sometimes, it is more convenient to know which cells have been changed rather than getting the entire edited dataframe back. Streamlit makes this easy through the use of Session State. If a key parameter is set, Streamlit will store any changes made to the dataframe in Session State. This snippet shows how you can access changed data using Session State: st.data_editor(df, key="my_key", num_rows="dynamic") # 👈 Set a key st.write("Here's the value in Session State:") st.write(st.session_state["my_key"]) # 👈 Show the value in Session State In this code snippet, the key parameter is set to "my_key". After the data editor is created, the value associated to "my_key" in Session State is displayed in the app using st.write. This shows the additions, edits, and deletions that were made. This can be useful when working with large dataframes and you only need to know which cells have changed, rather than access the entire edited dataframe. Built with Streamlit 🎈Fullscreen open_in_new Use all we've learned so far and apply them to the above embedded app. Try editing cells, adding new rows, and deleting rows. Notice how edits to the table are reflected in Session State. When you make any edits, a rerun is triggered which sends the edits to the backend. The widget's state is a JSON object containing three properties: edited_rows, added_rows, and deleted rows:. priority_highWarningWhen going from st.experimental_data_editor to st.data_editor in 1.23.0, the data editor's representation in st.session_state was changed. The edited_cells dictionary is now called edited_rows and uses a different format ({0: {"column name": "edited value"}} instead of {"0:1": "edited value"}). You may need to adjust your code if your app uses st.experimental_data_editor in combination with st.session_state." edited_rows is a dictionary containing all edits. Keys are zero-based row indices and values are dictionaries that map column names to edits (e.g. {0: {"col1": ..., "col2": ...}}). added_rows is a list of newly added rows. Each value is a dictionary with the same format as above (e.g. [{"col1": ..., "col2": ...}]). deleted_rows is a list of row numbers that have been deleted from the table (e.g. [0, 2]). st.data_editor does not support reordering rows, so added rows will always be appended to the end of the dataframe with any edits and deletions applicable to the original rows. Bulk edits The data editor includes a feature that allows for bulk editing of cells. Similar to Excel, you can drag a handle across a selection of cells to edit their values in bulk. You can even apply commonly used keyboard shortcuts in spreadsheet software. This is useful when you need to make the same change across multiple cells, rather than editing each cell individually. Edit common data structures Editing doesn't just work for Pandas DataFrames! You can also edit lists, tuples, sets, dictionaries, NumPy arrays, or Snowpark & PySpark DataFrames. Most data types will be returned in their original format. But some types (e.g. Snowpark and PySpark) are converted to Pandas DataFrames. To learn about all the supported types, read the st.data_editor API. For example, you can easily let the user add items to a list: edited_list = st.data_editor(["red", "green", "blue"], num_rows= "dynamic") st.write("Here are all the colors you entered:") st.write(edited_list) Or numpy arrays: import numpy as np st.data_editor(np.array([ ["st.text_area", "widget", 4.92], ["st.markdown", "element", 47.22] ])) Or lists of records: st.data_editor([ {"name": "st.text_area", "type": "widget"}, {"name": "st.markdown", "type": "element"}, ]) Or dictionaries and many more types! st.data_editor({ "st.text_area": "widget", "st.markdown": "element" }) Automatic input validation The data editor includes automatic input validation to help prevent errors when editing cells. For example, if you have a column that contains numerical data, the input field will automatically restrict the user to only entering numerical data. This helps to prevent errors that could occur if the user were to accidentally enter a non-numerical value. Additional input validation can be configured through the Column configuration API. Keep reading below for an overview of column configuration, including validation options. Configuring columns You can configure the display and editing behavior of columns in st.dataframe and st.data_editor via the Column configuration API. We have developed the API to let you add images, charts, and clickable URLs in dataframe and data editor columns. Additionally, you can make individual columns editable, set columns as categorical and specify which options they can take, hide the index of the dataframe, and much more. Column configuration includes the following column types: Text, Number, Checkbox, Selectbox, Date, Time, Datetime, List, Link, Image, Line chart, Bar chart, and Progress. There is also a generic Column option. See the embedded app below to view these different column types. Each column type is individually previewed in the Column configuration API documentation. Built with Streamlit 🎈Fullscreen open_in_new Format values A format parameter is available in column configuration for Text, Date, Time, and Datetime columns. Chart-like columns can also be formatted. Line chart and Bar chart columns have a y_min and y_max parameters to set the vertical bounds. For a Progress column, you can declare the horizontal bounds with min_value and max_value. Validate input When specifying a column configuration, you can declare not only the data type of the column but also value restrictions. All column configuration elements allow you to make a column required with the keyword parameter required=True. For Text and Link columns, you can specify the maximum number of characters with max_chars or use regular expressions to validate entries through validate. Numerical columns, including Number, Date, Time, and Datetime have min_value and max_value parameters. Selectbox columns have a configurable list of options. The data type for Number columns is float by default. Passing a value of type int to any of min_value, max_value, step, or default will set the type for the column as int. Configure an empty dataframe You can use st.data_editor to collect tabular input from a user. When starting from an empty dataframe, default column types are text. Use column configuration to specify the data types you want to collect from users. import streamlit as st import pandas as pd df = pd.DataFrame(columns=['name','age','color']) colors = ['red', 'orange', 'yellow', 'green', 'blue', 'indigo', 'violet'] config = { 'name' : st.column_config.TextColumn('Full Name (required)', width='large', required=True), 'age' : st.column_config.NumberColumn('Age (years)', min_value=0, max_value=122), 'color' : st.column_config.SelectboxColumn('Favorite Color', options=colors) } result = st.data_editor(df, column_config = config, num_rows='dynamic') if st.button('Get results'): st.write(result) Built with Streamlit 🎈Fullscreen open_in_new Additional formatting options In addition to column configuration, st.dataframe and st.data_editor have a few more parameters to customize the display of your dataframe. hide_index : Set to True to hide the dataframe's index. column_order : Pass a list of column labels to specify the order of display. disabled : Pass a list of column labels to disable them from editing. This let's you avoid disabling them individually. Handling large datasets st.dataframe and st.data_editor have been designed to theoretically handle tables with millions of rows thanks to their highly performant implementation using the glide-data-grid library and HTML canvas. However, the maximum amount of data that an app can realistically handle will depend on several other factors, including: The maximum size of WebSocket messages: Streamlit's WebSocket messages are configurable via the server.maxMessageSize config option, which limits the amount of data that can be transferred via the WebSocket connection at once. The server memory: The amount of data that your app can handle will also depend on the amount of memory available on your server. If the server's memory is exceeded, the app may become slow or unresponsive. The user's browser memory: Since all the data needs to be transferred to the user's browser for rendering, the amount of memory available on the user's device can also affect the app's performance. If the browser's memory is exceeded, it may crash or become unresponsive. In addition to these factors, a slow network connection can also significantly slow down apps that handle large datasets. When handling large datasets with more than 150,000 rows, Streamlit applies additional optimizations and disables column sorting. This can help to reduce the amount of data that needs to be processed at once and improve the app's performance. Limitations Streamlit casts all column names to strings internally, so st.data_editor will return a DataFrame where all column names are strings. The dataframe toolbar is not currently configurable. While Streamlit's data editing capabilities offer a lot of functionality, editing is enabled for a limited set of column types (TextColumn, NumberColumn, LinkColumn, CheckboxColumn, SelectboxColumn, DateColumn, TimeColumn, and DatetimeColumn). We are actively working on supporting editing for other column types as well, such as images, lists, and charts. Almost all editable datatypes are supported for index editing. However, pandas.CategoricalIndex and pandas.MultiIndex are not supported for editing. Sorting is not supported for st.data_editor when num_rows="dynamic". Sorting is deactivated to optimize performance on large datasets with more than 150,000 rows. We are continually working to improve Streamlit's handling of DataFrame and add functionality to data editing, so keep an eye out for updates.Previous: Button behavior and examplesNext: Using custom classesforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy
https://docs.streamlit.io/knowledge-base/deploy/authentication-without-sso#step-1-add-the-password-to-your-local-app-secrets
DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Knowledge base/Deployment issues/Authentication without SSOAuthentication without SSO Introduction Want to secure your Streamlit app with passwords, but cannot implement single sign-on? We got you covered! This guide shows you two simple techniques for adding basic authentication to your Streamlit app, using Secrets management. priority_highWarningWhile this technique adds some level of security, it is NOT comparable to proper authentication with an SSO provider. Option 1: One global password for all users This is the easiest option! Your app will ask for a password that's shared between all users. It will be stored in the app secrets using Secrets management. If you want to change this password or revoke a user's access, you will need to change it for everyone. If you want to have one password per user instead, jump to Option 2 below. Step 1: Add the password to your local app secrets Your local Streamlit app will read secrets from a file .streamlit/secrets.toml in your app's root dir. Create this file if it doesn't exist yet and add your password to it as shown below: # .streamlit/secrets.toml password = "streamlit123" priority_highImportantBe sure to add this file to your .gitignore so you don't commit your secrets! Step 2: Copy your app secrets to the cloud As the secrets.toml file above is not committed to GitHub, you need to pass its content to your deployed app (on Streamlit Community Cloud) separately. Go to the app dashboard and in the app's dropdown menu, click on Edit Secrets. Copy the content of secrets.toml into the text area. More information is available at Secrets management. Step 3: Ask for the password in your Streamlit app Copy the code below to your Streamlit app, insert your normal app code below the check_password() function call at the bottom, and run it: # streamlit_app.py import hmac import streamlit as st def check_password(): """Returns `True` if the user had the correct password.""" def password_entered(): """Checks whether a password entered by the user is correct.""" if hmac.compare_digest(st.session_state["password"], st.secrets["password"]): st.session_state["password_correct"] = True del st.session_state["password"] # Don't store the password. else: st.session_state["password_correct"] = False # Return True if the password is validated. if st.session_state.get("password_correct", False): return True # Show input for password. st.text_input( "Password", type="password", on_change=password_entered, key="password" ) if "password_correct" in st.session_state: st.error("😕 Password incorrect") return False if not check_password(): st.stop() # Do not continue if check_password is not True. # Main Streamlit app starts here st.write("Here goes your normal Streamlit app...") st.button("Click me") If everything worked out, your app should look like this: Option 2: Individual password for each user This option allows you to set a username and password for each user of your app. Like in Option 1, both values will be stored in the app secrets using Secrets management. Step 1: Add usernames & passwords to your local app secrets Your local Streamlit app will read secrets from a file .streamlit/secrets.toml in your app's root dir. Create this file if it doesn't exist yet and add the usernames & password to it as shown below: # .streamlit/secrets.toml [passwords] # Follow the rule: username = "password" alice_foo = "streamlit123" bob_bar = "mycrazypw" priority_highImportantBe sure to add this file to your .gitignore so you don't commit your secrets! Alternatively, you could set up and manage usernames & passwords via a spreadsheet or database. To use secrets to securely connect to Google Sheets, AWS, and other data providers, read our tutorials on how to Connect Streamlit to data sources. Step 2: Copy your app secrets to the cloud As the secrets.toml file above is not committed to GitHub, you need to pass its content to your deployed app (on Streamlit Community Cloud) separately. Go to the app dashboard and in the app's dropdown menu, click on Edit Secrets. Copy the content of secrets.toml into the text area. More information is available at Secrets management. Step 3: Ask for username & password in your Streamlit app Copy the code below to your Streamlit app, insert your normal app code below the check_password() function call at the bottom, and run it: # streamlit_app.py import hmac import streamlit as st def check_password(): """Returns `True` if the user had a correct password.""" def login_form(): """Form with widgets to collect user information""" with st.form("Credentials"): st.text_input("Username", key="username") st.text_input("Password", type="password", key="password") st.form_submit_button("Log in", on_click=password_entered) def password_entered(): """Checks whether a password entered by the user is correct.""" if st.session_state["username"] in st.secrets[ "passwords" ] and hmac.compare_digest( st.session_state["password"], st.secrets.passwords[st.session_state["username"]], ): st.session_state["password_correct"] = True del st.session_state["password"] # Don't store the username or password. del st.session_state["username"] else: st.session_state["password_correct"] = False # Return True if the username + password is validated. if st.session_state.get("password_correct", False): return True # Show inputs for username + password. login_form() if "password_correct" in st.session_state: st.error("😕 User not known or password incorrect") return False if not check_password(): st.stop() # Main Streamlit app starts here st.write("Here goes your normal Streamlit app...") st.button("Click me") If everything worked out, your app should look like this: Previous: Deployment issuesNext: How can I deploy multiple Streamlit apps on different subdomains?forumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy
https://docs.streamlit.io/en/0.76.0/api.html#write-and-magic
DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceremovePAGE ELEMENTSWrite and magicaddText elementsaddData elementsaddChart elementsaddInput widgetsaddMedia elementsaddLayouts and containersaddChat elementsaddStatus elementsaddThird-party componentsopen_in_newAPPLICATION LOGICNavigation and pagesaddExecution flowaddCaching and stateaddConnections and secretsaddCustom componentsaddUtilitiesaddConfigurationaddTOOLSApp testingaddCommand lineaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Develop/API referenceAPI reference Streamlit makes it easy for you to visualize, mutate, and share data. The API reference is organized by activity type, like displaying data or optimizing performance. Each section includes methods associated with the activity type, including examples. Browse our API below and click to learn more about any of our available commands! 🎈 Display almost anything Write and magic st.writeWrite arguments to the app.st.write("Hello **world**!") st.write(my_data_frame) st.write(my_mpl_figure) st.write_streamWrite generators or streams to the app with a typewriter effect.st.write_stream(my_generator) st.write_stream(my_llm_stream) MagicAny time Streamlit sees either a variable or literal value on its own line, it automatically writes that to your app using st.write"Hello **world**!" my_data_frame my_mpl_figure Text elements MarkdownDisplay string formatted as Markdown.st.markdown("Hello **world**!") TitleDisplay text in title formatting.st.title("The app title") HeaderDisplay text in header formatting.st.header("This is a header") SubheaderDisplay text in subheader formatting.st.subheader("This is a subheader") CaptionDisplay text in small font.st.caption("This is written small caption text") Code blockDisplay a code block with optional syntax highlighting.st.code("a = 1234") EchoDisplay some code in the app, then execute it. Useful for tutorials.with st.echo(): st.write('This code will be printed') LaTeXDisplay mathematical expressions formatted as LaTeX.st.latex("\int a x^2 \,dx") Preformatted textWrite fixed-width and preformatted text.st.text("Hello world") DividerDisplay a horizontal rule.st.divider() Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration! PreviousTagsAdd tags to your Streamlit apps. Created by @gagan3012.st_tags(label='# Enter Keywords:', text='Press enter to add more', value=['Zero', 'One', 'Two'], suggestions=['five', 'six', 'seven', 'eight', 'nine', 'three', 'eleven', 'ten', 'four'], maxtags = 4, key='1') NLUApply text mining on a dataframe. Created by @JohnSnowLabs.nlu.load('sentiment').predict('I love NLU! <3') Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.mention(label="An awesome Streamlit App", icon="streamlit", url="https://extras.streamlit.app",) Annotated textDisplay annotated text in Streamlit apps. Created by @tvst.annotated_text("This ", ("is", "verb"), " some ", ("annotated", "adj"), ("text", "noun"), " for those of ", ("you", "pronoun"), " who ", ("like", "verb"), " this sort of ", ("thing", "noun"), ".") Drawable CanvasProvides a sketching canvas using Fabric.js. Created by @andfanilo.st_canvas(fill_color="rgba(255, 165, 0, 0.3)", stroke_width=stroke_width, stroke_color=stroke_color, background_color=bg_color, background_image=Image.open(bg_image) if bg_image else None, update_streamlit=realtime_update, height=150, drawing_mode=drawing_mode, point_display_radius=point_display_radius if drawing_mode == 'point' else 0, key="canvas",) TagsAdd tags to your Streamlit apps. Created by @gagan3012.st_tags(label='# Enter Keywords:', text='Press enter to add more', value=['Zero', 'One', 'Two'], suggestions=['five', 'six', 'seven', 'eight', 'nine', 'three', 'eleven', 'ten', 'four'], maxtags = 4, key='1') NLUApply text mining on a dataframe. Created by @JohnSnowLabs.nlu.load('sentiment').predict('I love NLU! <3') Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.mention(label="An awesome Streamlit App", icon="streamlit", url="https://extras.streamlit.app",) Annotated textDisplay annotated text in Streamlit apps. Created by @tvst.annotated_text("This ", ("is", "verb"), " some ", ("annotated", "adj"), ("text", "noun"), " for those of ", ("you", "pronoun"), " who ", ("like", "verb"), " this sort of ", ("thing", "noun"), ".") Drawable CanvasProvides a sketching canvas using Fabric.js. Created by @andfanilo.st_canvas(fill_color="rgba(255, 165, 0, 0.3)", stroke_width=stroke_width, stroke_color=stroke_color, background_color=bg_color, background_image=Image.open(bg_image) if bg_image else None, update_streamlit=realtime_update, height=150, drawing_mode=drawing_mode, point_display_radius=point_display_radius if drawing_mode == 'point' else 0, key="canvas",) TagsAdd tags to your Streamlit apps. Created by @gagan3012.st_tags(label='# Enter Keywords:', text='Press enter to add more', value=['Zero', 'One', 'Two'], suggestions=['five', 'six', 'seven', 'eight', 'nine', 'three', 'eleven', 'ten', 'four'], maxtags = 4, key='1') NLUApply text mining on a dataframe. Created by @JohnSnowLabs.nlu.load('sentiment').predict('I love NLU! <3') Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.mention(label="An awesome Streamlit App", icon="streamlit", url="https://extras.streamlit.app",) Next Data elements DataframesDisplay a dataframe as an interactive table.st.dataframe(my_data_frame) Data editorDisplay a data editor widget.edited = st.data_editor(df, num_rows="dynamic") Column configurationConfigure the display and editing behavior of dataframes and data editors.st.column_config.NumberColumn("Price (in USD)", min_value=0, format="$%d") Static tablesDisplay a static table.st.table(my_data_frame) MetricsDisplay a metric in big bold font, with an optional indicator of how the metric changed.st.metric("My metric", 42, 2) Dicts and JSONDisplay object or string as a pretty-printed JSON string.st.json(my_dict) Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration! PreviousImage CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates value = streamlit_image_coordinates("https://placekitten.com/200/300") st.write(value) Plotly EventsMake Plotly charts interactive!. Created by @null-jones.from streamlit_plotly_events import plotly_events fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.metric_cards import style_metric_cards col3.metric(label="No Change", value=5000, delta=0) style_metric_cards() Streamlit AggridImplementation of Ag-Grid component for Streamlit. Created by @PablocFonseca.df = pd.DataFrame({'col1': [1, 2, 3], 'col2': [4, 5, 6]}) grid_return = AgGrid(df, editable=True) new_df = grid_return['data'] Streamlit FoliumStreamlit Component for rendering Folium maps. Created by @randyzwitch.m = folium.Map(location=[39.949610, -75.150282], zoom_start=16) folium.Marker([39.949610, -75.150282], popup="Liberty Bell", tooltip="Liberty Bell").add_to(m) st_data = st_folium(m, width=725) Pandas ProfilingPandas profiling component for Streamlit. Created by @okld.df = pd.read_csv("https://storage.googleapis.com/tf-datasets/titanic/train.csv") pr = df.profile_report() st_profile_report(pr) Image CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates value = streamlit_image_coordinates("https://placekitten.com/200/300") st.write(value) Plotly EventsMake Plotly charts interactive!. Created by @null-jones.from streamlit_plotly_events import plotly_events fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.metric_cards import style_metric_cards col3.metric(label="No Change", value=5000, delta=0) style_metric_cards() Streamlit AggridImplementation of Ag-Grid component for Streamlit. Created by @PablocFonseca.df = pd.DataFrame({'col1': [1, 2, 3], 'col2': [4, 5, 6]}) grid_return = AgGrid(df, editable=True) new_df = grid_return['data'] Streamlit FoliumStreamlit Component for rendering Folium maps. Created by @randyzwitch.m = folium.Map(location=[39.949610, -75.150282], zoom_start=16) folium.Marker([39.949610, -75.150282], popup="Liberty Bell", tooltip="Liberty Bell").add_to(m) st_data = st_folium(m, width=725) Pandas ProfilingPandas profiling component for Streamlit. Created by @okld.df = pd.read_csv("https://storage.googleapis.com/tf-datasets/titanic/train.csv") pr = df.profile_report() st_profile_report(pr) Image CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates value = streamlit_image_coordinates("https://placekitten.com/200/300") st.write(value) Plotly EventsMake Plotly charts interactive!. Created by @null-jones.from streamlit_plotly_events import plotly_events fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.metric_cards import style_metric_cards col3.metric(label="No Change", value=5000, delta=0) style_metric_cards() Next Chart elements Simple area chartsDisplay an area chart.st.area_chart(my_data_frame) Simple bar chartsDisplay a bar chart.st.bar_chart(my_data_frame) Simple line chartsDisplay a line chart.st.line_chart(my_data_frame) Simple scatter chartsDisplay a line chart.st.scatter_chart(my_data_frame) Scatterplots on mapsDisplay a map with points on it.st.map(my_data_frame) MatplotlibDisplay a matplotlib.pyplot figure.st.pyplot(my_mpl_figure) AltairDisplay a chart using the Altair library.st.altair_chart(my_altair_chart) Vega-LiteDisplay a chart using the Vega-Lite library.st.vega_lite_chart(my_vega_lite_chart) PlotlyDisplay an interactive Plotly chart.st.plotly_chart(my_plotly_chart) BokehDisplay an interactive Bokeh chart.st.bokeh_chart(my_bokeh_chart) PyDeckDisplay a chart using the PyDeck library.st.pydeck_chart(my_pydeck_chart) GraphVizDisplay a graph using the dagre-d3 library.st.graphviz_chart(my_graphviz_spec) Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration! PreviousStreamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl("https://assets5.lottiefiles.com/packages/lf20_V9t630.json") st_lottie(lottie_hello, key="hello") Plotly EventsMake Plotly charts interactive!. Created by @null-jones.fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.chart += get_annotations_chart(annotations=[("Mar 01, 2008", "Pretty good day for GOOG"), ("Dec 01, 2007", "Something's going wrong for GOOG & AAPL"), ("Nov 01, 2008", "Market starts again thanks to..."), ("Dec 01, 2009", "Small crash for GOOG after..."),],) st.altair_chart(chart, use_container_width=True) PlostA deceptively simple plotting library for Streamlit. Created by @tvst.import plost plost.line_chart(my_dataframe, x='time', y='stock_value', color='stock_name',) HiPlotHigh dimensional Interactive Plotting. Created by @facebookresearch.data = [{'dropout':0.1, 'lr': 0.001, 'loss': 10.0, 'optimizer': 'SGD'}, {'dropout':0.15, 'lr': 0.01, 'loss': 3.5, 'optimizer': 'Adam'}, {'dropout':0.3, 'lr': 0.1, 'loss': 4.5, 'optimizer': 'Adam'}] hip.Experiment.from_iterable(data).display() EChartsHigh dimensional Interactive Plotting. Created by @andfanilo.from streamlit_echarts import st_echarts st_echarts(options=options) Streamlit FoliumStreamlit Component for rendering Folium maps. Created by @randyzwitch.m = folium.Map(location=[39.949610, -75.150282], zoom_start=16) st_data = st_folium(m, width=725) Spacy-StreamlitspaCy building blocks and visualizers for Streamlit apps. Created by @explosion.models = ["en_core_web_sm", "en_core_web_md"] spacy_streamlit.visualize(models, "Sundar Pichai is the CEO of Google.") Streamlit AgraphA Streamlit Graph Vis, based on react-grah-vis. Created by @ChrisDelClea.from streamlit_agraph import agraph, Node, Edge, Config agraph(nodes=nodes, edges=edges, config=config) Streamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl("https://assets5.lottiefiles.com/packages/lf20_V9t630.json") st_lottie(lottie_hello, key="hello") Plotly EventsMake Plotly charts interactive!. Created by @null-jones.fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.chart += get_annotations_chart(annotations=[("Mar 01, 2008", "Pretty good day for GOOG"), ("Dec 01, 2007", "Something's going wrong for GOOG & AAPL"), ("Nov 01, 2008", "Market starts again thanks to..."), ("Dec 01, 2009", "Small crash for GOOG after..."),],) st.altair_chart(chart, use_container_width=True) PlostA deceptively simple plotting library for Streamlit. Created by @tvst.import plost plost.line_chart(my_dataframe, x='time', y='stock_value', color='stock_name',) HiPlotHigh dimensional Interactive Plotting. Created by @facebookresearch.data = [{'dropout':0.1, 'lr': 0.001, 'loss': 10.0, 'optimizer': 'SGD'}, {'dropout':0.15, 'lr': 0.01, 'loss': 3.5, 'optimizer': 'Adam'}, {'dropout':0.3, 'lr': 0.1, 'loss': 4.5, 'optimizer': 'Adam'}] hip.Experiment.from_iterable(data).display() EChartsHigh dimensional Interactive Plotting. Created by @andfanilo.from streamlit_echarts import st_echarts st_echarts(options=options) Streamlit FoliumStreamlit Component for rendering Folium maps. Created by @randyzwitch.m = folium.Map(location=[39.949610, -75.150282], zoom_start=16) st_data = st_folium(m, width=725) Spacy-StreamlitspaCy building blocks and visualizers for Streamlit apps. Created by @explosion.models = ["en_core_web_sm", "en_core_web_md"] spacy_streamlit.visualize(models, "Sundar Pichai is the CEO of Google.") Streamlit AgraphA Streamlit Graph Vis, based on react-grah-vis. Created by @ChrisDelClea.from streamlit_agraph import agraph, Node, Edge, Config agraph(nodes=nodes, edges=edges, config=config) Streamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl("https://assets5.lottiefiles.com/packages/lf20_V9t630.json") st_lottie(lottie_hello, key="hello") Plotly EventsMake Plotly charts interactive!. Created by @null-jones.fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.chart += get_annotations_chart(annotations=[("Mar 01, 2008", "Pretty good day for GOOG"), ("Dec 01, 2007", "Something's going wrong for GOOG & AAPL"), ("Nov 01, 2008", "Market starts again thanks to..."), ("Dec 01, 2009", "Small crash for GOOG after..."),],) st.altair_chart(chart, use_container_width=True) Next Input widgets ButtonDisplay a button widget.clicked = st.button("Click me") Download buttonDisplay a download button widget.st.download_button("Download file", file) Form buttonDisplay a form submit button. For use with st.form.st.form_submit_button("Sign up") Link buttonDisplay a link button.st.link_button("Go to gallery", url) Page linkDisplay a link to another page in a multipage app.st.page_link("app.py", label="Home", icon="🏠") st.page_link("pages/profile.py", label="My profile") CheckboxDisplay a checkbox widget.selected = st.checkbox("I agree") Color pickerDisplay a color picker widget.color = st.color_picker("Pick a color") MultiselectDisplay a multiselect widget. The multiselect widget starts as empty.choices = st.multiselect("Buy", ["milk", "apples", "potatoes"]) RadioDisplay a radio button widget.choice = st.radio("Pick one", ["cats", "dogs"]) SelectboxDisplay a select widget.choice = st.selectbox("Pick one", ["cats", "dogs"]) Select-sliderDisplay a slider widget to select items from a list.size = st.select_slider("Pick a size", ["S", "M", "L"]) ToggleDisplay a toggle widget.activated = st.toggle("Activate") Number inputDisplay a numeric input widget.choice = st.number_input("Pick a number", 0, 10) SliderDisplay a slider widget.number = st.slider("Pick a number", 0, 100) Date inputDisplay a date input widget.date = st.date_input("Your birthday") Time inputDisplay a time input widget.time = st.time_input("Meeting time") Chat inputDisplay a chat input widget.prompt = st.chat_input("Say something") if prompt: st.write(f"The user has sent: {prompt}") Text-areaDisplay a multi-line text input widget.text = st.text_area("Text to translate") Text inputDisplay a single-line text input widget.name = st.text_input("First name") Data editorDisplay a data editor widget.edited = st.experimental_data_editor(df, num_rows="dynamic") File UploaderDisplay a file uploader widget.data = st.file_uploader("Upload a CSV") Camera inputDisplay a widget that allows users to upload images directly from a camera.image = st.camera_input("Take a picture") Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration! PreviousStreamlit ChatStreamlit Component for a Chatbot UI. Created by @AI-Yash.from streamlit_chat import message message("My message") message("Hello bot!", is_user=True) # align's the message to the right Streamlit Option MenuSelect a single item from a list of options in a menu. Created by @victoryhb.from streamlit_option_menu import option_menu option_menu("Main Menu", ["Home", 'Settings'], icons=['house', 'gear'], menu_icon="cast", default_index=1) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.stoggle import stoggle stoggle( "Click me!", """🥷 Surprise! Here's some additional content""",) Streamlit ElementsCreate a draggable and resizable dashboard in Streamlit. Created by @okls.from streamlit_elements import elements, mui, html with elements("new_element"): mui.Typography("Hello world") TagsAdd tags to your Streamlit apps. Created by @gagan3012.from streamlit_tags import st_tags st_tags(label='# Enter Keywords:', text='Press enter to add more', value=['Zero', 'One', 'Two'], suggestions=['five', 'six', 'seven', 'eight', 'nine', 'three', 'eleven', 'ten', 'four'], maxtags = 4, key='1') StqdmThe simplest way to handle a progress bar in streamlit app. Created by @Wirg.from stqdm import stqdm for _ in stqdm(range(50)): sleep(0.5) TimelineDisplay a Timeline in Streamlit apps using TimelineJS. Created by @innerdoc.from streamlit_timeline import timeline with open('example.json', "r") as f: timeline(f.read(), height=800) Camera input liveAlternative for st.camera_input which returns the webcam images live. Created by @blackary.from camera_input_live import camera_input_live image = camera_input_live() st.image(value) Streamlit AceAce editor component for Streamlit. Created by @okld.from streamlit_ace import st_ace content = st_ace() content Streamlit ChatStreamlit Component for a Chatbot UI. Created by @AI-Yash.from streamlit_chat import message message("My message") message("Hello bot!", is_user=True) # align's the message to the right Streamlit Option MenuSelect a single item from a list of options in a menu. Created by @victoryhb.from streamlit_option_menu import option_menu option_menu("Main Menu", ["Home", 'Settings'], icons=['house', 'gear'], menu_icon="cast", default_index=1) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.stoggle import stoggle stoggle( "Click me!", """🥷 Surprise! Here's some additional content""",) Streamlit ElementsCreate a draggable and resizable dashboard in Streamlit. Created by @okls.from streamlit_elements import elements, mui, html with elements("new_element"): mui.Typography("Hello world") TagsAdd tags to your Streamlit apps. Created by @gagan3012.from streamlit_tags import st_tags st_tags(label='# Enter Keywords:', text='Press enter to add more', value=['Zero', 'One', 'Two'], suggestions=['five', 'six', 'seven', 'eight', 'nine', 'three', 'eleven', 'ten', 'four'], maxtags = 4, key='1') StqdmThe simplest way to handle a progress bar in streamlit app. Created by @Wirg.from stqdm import stqdm for _ in stqdm(range(50)): sleep(0.5) TimelineDisplay a Timeline in Streamlit apps using TimelineJS. Created by @innerdoc.from streamlit_timeline import timeline with open('example.json', "r") as f: timeline(f.read(), height=800) Camera input liveAlternative for st.camera_input which returns the webcam images live. Created by @blackary.from camera_input_live import camera_input_live image = camera_input_live() st.image(value) Streamlit AceAce editor component for Streamlit. Created by @okld.from streamlit_ace import st_ace content = st_ace() content Streamlit ChatStreamlit Component for a Chatbot UI. Created by @AI-Yash.from streamlit_chat import message message("My message") message("Hello bot!", is_user=True) # align's the message to the right Streamlit Option MenuSelect a single item from a list of options in a menu. Created by @victoryhb.from streamlit_option_menu import option_menu option_menu("Main Menu", ["Home", 'Settings'], icons=['house', 'gear'], menu_icon="cast", default_index=1) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.stoggle import stoggle stoggle( "Click me!", """🥷 Surprise! Here's some additional content""",) Next Media elements ImageDisplay an image or list of images.st.image(numpy_array) st.image(image_bytes) st.image(file) st.image("https://example.com/myimage.jpg") AudioDisplay an audio player.st.audio(numpy_array) st.audio(audio_bytes) st.audio(file) st.audio("https://example.com/myaudio.mp3", format="audio/mp3") VideoDisplay a video player.st.video(numpy_array) st.video(video_bytes) st.video(file) st.video("https://example.com/myvideo.mp4", format="video/mp4") Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration! PreviousStreamlit CropperA simple image cropper for Streamlit. Created by @turner-anderson.from streamlit_cropper import st_cropper st_cropper(img, realtime_update=realtime_update, box_color=box_color, aspect_ratio=aspect_ratio) Image CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates streamlit_image_coordinates("https://placekitten.com/200/300") Streamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl("https://assets5.lottiefiles.com/packages/lf20_V9t630.json") st_lottie(lottie_hello, key="hello") Streamlit WebrtcHandling and transmitting real-time video/audio streams with Streamlit. Created by @whitphx.from streamlit_webrtc import webrtc_streamer webrtc_streamer(key="sample") Drawable CanvasProvides a sketching canvas using Fabric.js. Created by @andfanilo.from streamlit_drawable_canvas import st_canvas st_canvas(fill_color="rgba(255, 165, 0, 0.3)", stroke_width=stroke_width, stroke_color=stroke_color, background_color=bg_color, background_image=Image.open(bg_image) if bg_image else None, update_streamlit=realtime_update, height=150, drawing_mode=drawing_mode, point_display_radius=point_display_radius if drawing_mode == 'point' else 0, key="canvas",) Image ComparisonCompare images with a slider using JuxtaposeJS. Created by @fcakyon.from streamlit_image_comparison import image_comparison image_comparison(img1="image1.jpg", img2="image2.jpg",) Streamlit CropperA simple image cropper for Streamlit. Created by @turner-anderson.from streamlit_cropper import st_cropper st_cropper(img, realtime_update=realtime_update, box_color=box_color, aspect_ratio=aspect_ratio) Image CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates streamlit_image_coordinates("https://placekitten.com/200/300") Streamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl("https://assets5.lottiefiles.com/packages/lf20_V9t630.json") st_lottie(lottie_hello, key="hello") Streamlit WebrtcHandling and transmitting real-time video/audio streams with Streamlit. Created by @whitphx.from streamlit_webrtc import webrtc_streamer webrtc_streamer(key="sample") Drawable CanvasProvides a sketching canvas using Fabric.js. Created by @andfanilo.from streamlit_drawable_canvas import st_canvas st_canvas(fill_color="rgba(255, 165, 0, 0.3)", stroke_width=stroke_width, stroke_color=stroke_color, background_color=bg_color, background_image=Image.open(bg_image) if bg_image else None, update_streamlit=realtime_update, height=150, drawing_mode=drawing_mode, point_display_radius=point_display_radius if drawing_mode == 'point' else 0, key="canvas",) Image ComparisonCompare images with a slider using JuxtaposeJS. Created by @fcakyon.from streamlit_image_comparison import image_comparison image_comparison(img1="image1.jpg", img2="image2.jpg",) Streamlit CropperA simple image cropper for Streamlit. Created by @turner-anderson.from streamlit_cropper import st_cropper st_cropper(img, realtime_update=realtime_update, box_color=box_color, aspect_ratio=aspect_ratio) Image CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates streamlit_image_coordinates("https://placekitten.com/200/300") Streamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl("https://assets5.lottiefiles.com/packages/lf20_V9t630.json") st_lottie(lottie_hello, key="hello") Next Layouts and containers ColumnsInsert containers laid out as side-by-side columns.col1, col2 = st.columns(2) col1.write("this is column 1") col2.write("this is column 2") ContainerInsert a multi-element container.c = st.container() st.write("This will show last") c.write("This will show first") c.write("This will show second") Modal dialogsInsert a modal dialog that can rerun independently from the rest of the script.@st.experimental_dialog("Sign up") def email_form(): name = st.text_input("Name") email = st.text_input("Email") EmptyInsert a single-element container.c = st.empty() st.write("This will show last") c.write("This will be replaced") c.write("This will show first") ExpanderInsert a multi-element container that can be expanded/collapsed.with st.expander("Open to see more"): st.write("This is more content") PopoverInsert a multi-element popover container that can be opened/closed.with st.popover("Settings"): st.checkbox("Show completed") SidebarDisplay items in a sidebar.st.sidebar.write("This lives in the sidebar") st.sidebar.button("Click me!") TabsInsert containers separated into tabs.tab1, tab2 = st.tabs(["Tab 1", "Tab2"]) tab1.write("this is tab 1") tab2.write("this is tab 2") Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration!Streamlit ElementsCreate a draggable and resizable dashboard in Streamlit. Created by @okls.from streamlit_elements import elements, mui, html with elements("new_element"): mui.Typography("Hello world") PydanticAuto-generate Streamlit UI from Pydantic Models and Dataclasses. Created by @lukasmasuch.import streamlit_pydantic as sp sp.pydantic_form(key="my_form", model=ExampleModel) Streamlit PagesAn experimental version of Streamlit Multi-Page Apps. Created by @blackary.from st_pages import Page, show_pages, add_page_title show_pages([ Page("streamlit_app.py", "Home", "🏠"), Page("other_pages/page2.py", "Page 2", ":books:"), ]) Chat elements Streamlit provides a few commands to help you build conversational apps. These chat elements are designed to be used in conjunction with each other, but you can also use them separately. st.chat_message lets you insert a chat message container into the app so you can display messages from the user or the app. Chat containers can contain other Streamlit elements, including charts, tables, text, and more. st.chat_input lets you display a chat input widget so the user can type in a message. Chat inputDisplay a chat input widget.prompt = st.chat_input("Say something") if prompt: st.write(f"The user has sent: {prompt}") Chat messageInsert a chat message container.import numpy as np with st.chat_message("user"): st.write("Hello 👋") st.line_chart(np.random.randn(30, 3)) Status containerDisplay output of long-running tasks in a container.with st.status('Running'): do_something_slow() st.write_streamWrite generators or streams to the app with a typewriter effect.st.write_stream(my_generator) st.write_stream(my_llm_stream) Status elements Progress barDisplay a progress bar.for i in range(101): st.progress(i) do_something_slow() SpinnerTemporarily displays a message while executing a block of code.with st.spinner("Please wait..."): do_something_slow() Status containerDisplay output of long-running tasks in a container.with st.status('Running'): do_something_slow() ToastBriefly displays a toast message in the bottom-right corner.st.toast('Butter!', icon='🧈') BalloonsDisplay celebratory balloons!do_something() # Celebrate when all done! st.balloons() SnowflakesDisplay celebratory snowflakes!do_something() # Celebrate when all done! st.snow() Success boxDisplay a success message.st.success("Match found!") Info boxDisplay an informational message.st.info("Dataset is updated every day at midnight.") Warning boxDisplay warning message.st.warning("Unable to fetch image. Skipping...") Error boxDisplay error message.st.error("We encountered an error") Exception outputDisplay an exception.e = RuntimeError("This is an exception of type RuntimeError") st.exception(e) Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration!StqdmThe simplest way to handle a progress bar in streamlit app. Created by @Wirg.from stqdm import stqdm for _ in stqdm(range(50)): sleep(0.5) Custom notification boxA custom notification box with the ability to close it out. Created by @Socvest.from streamlit_custom_notification_box import custom_notification_box styles = {'material-icons':{'color': 'red'}, 'text-icon-link-close-container': {'box-shadow': '#3896de 0px 4px'}, 'notification-text': {'':''}, 'close-button':{'':''}, 'link':{'':''}} custom_notification_box(icon='info', textDisplay='We are almost done with your registration...', externalLink='more info', url='#', styles=styles, key="foo") Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.let_it_rain import rain rain(emoji="🎈", font_size=54, falling_speed=5, animation_length="infinite",) App logic and configuration Navigation and pages Switch pageProgrammatically navigates to a specified page.st.switch_page("pages/my_page.py") Page linkDisplay a link to another page in a multipage app.st.page_link("app.py", label="Home", icon="🏠") st.page_link("pages/profile.py", label="My profile") Execution flow Modal dialogsInsert a modal dialog that can rerun independently from the rest of the script.@st.experimental_dialog("Sign up") def email_form(): name = st.text_input("Name") email = st.text_input("Email") FormsCreate a form that batches elements together with a “Submit" button.with st.form(key='my_form'): name = st.text_input("Name") email = st.text_input("Email") st.form_submit_button("Sign up") Partial rerunsDefine a fragment to rerun independently from the rest of the script.@st.experimental_fragment(run_every="10s") def fragment(): df = get_data() st.line_chart(df) Rerun scriptRerun the script immediately.st.rerun() Stop executionStops execution immediately.st.stop() Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration!AutorefreshForce a refresh without tying up a script. Created by @kmcgrady.from streamlit_autorefresh import st_autorefresh st_autorefresh(interval=2000, limit=100, key="fizzbuzzcounter") PydanticAuto-generate Streamlit UI from Pydantic Models and Dataclasses. Created by @lukasmasuch.import streamlit_pydantic as sp sp.pydantic_form(key="my_form", model=ExampleModel) Streamlit PagesAn experimental version of Streamlit Multi-Page Apps. Created by @blackary.from st_pages import Page, show_pages, add_page_title show_pages([ Page("streamlit_app.py", "Home", "🏠"), Page("other_pages/page2.py", "Page 2", ":books:"), ]) Caching and state Cache dataFunction decorator to cache functions that return data (e.g. dataframe transforms, database queries, ML inference).@st.cache_data def long_function(param1, param2): # Perform expensive computation here or # fetch data from the web here return data Cache resourceFunction decorator to cache functions that return global resources (e.g. database connections, ML models).@st.cache_resource def init_model(): # Return a global resource here return pipeline( "sentiment-analysis", model="distilbert-base-uncased-finetuned-sst-2-english" ) Session stateSession state is a way to share variables between reruns, for each user session.st.session_state['key'] = value Query parametersGet, set, or clear the query parameters that are shown in the browser's URL bar.st.query_params[key] = value st.query_params.clear() Connections and databases Setup your connection Create a connectionConnect to a data source or APIconn = st.connection('pets_db', type='sql') pet_owners = conn.query('select * from pet_owners') st.dataframe(pet_owners) Built-in connections SnowflakeConnectionA connection to Snowflake.conn = st.connection('snowflake') SQLConnectionA connection to a SQL database using SQLAlchemy.conn = st.connection('sql') Build your own connections Connection base classBuild your own connection with BaseConnection.class MyConnection(BaseConnection[myconn.MyConnection]): def _connect(self, **kwargs) -> MyConnection: return myconn.connect(**self._secrets, **kwargs) def query(self, query): return self._instance.query(query) Secrets management Secrets singletonAccess secrets from a local TOML file.key = st.secrets["OpenAI_key"] Secrets fileSave your secrets in a per-project or per-profile TOML file.OpenAI_key = "<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/concepts/design/custom-classes#patterns-to-define-your-custom-classes
DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsremoveCOREArchitecture & executionaddMultipage appsaddApp designremoveAnimate & update elementsButton behavior and examplesDataframesUsing custom classesWorking with timezonesADDITIONALConnections and secretsaddCustom componentsaddConfiguration and themingaddApp testingaddAPI referenceaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Develop/Concepts/App design/Using custom classesUsing custom Python classes in your Streamlit app If you are building a complex Streamlit app or working with existing code, you may have custom Python classes defined in your script. Common examples include the following: Defining a @dataclass to store related data within your app. Defining an Enum class to represent a fixed set of options or values. Defining custom interfaces to external services or databases not covered by st.connection. Because Streamlit reruns your script after every user interaction, custom classes may be redefined multiple times within the same Streamlit session. This may result in unwanted effects, especially with class and instance comparisons. Read on to understand this common pitfall and how to avoid it. We begin by covering some general-purpose patterns you can use for different types of custom classes, and follow with a few more technical details explaining why this matters. Finally, we go into more detail about Using Enum classes specifically, and describe a configuration option which can make them more convenient. Patterns to define your custom classes Pattern 1: Define your class in a separate module This is the recommended, general solution. If possible, move class definitions into their own module file and import them into your app script. As long as you are not editing the file where your class is defined, Streamlit will not re-import it with each rerun. Therefore, if a class is defined in an external file and imported into your script, the class will not be redefined during the session. Example: Move your class definition Try running the following Streamlit app where MyClass is defined within the page's script. isinstance() will return True on the first script run then return False on each rerun thereafter. # app.py import streamlit as st # MyClass gets redefined every time app.py reruns class MyClass: def __init__(self, var1, var2): self.var1 = var1 self.var2 = var2 if "my_instance" not in st.session_state: st.session_state.my_instance = MyClass("foo", "bar") # Displays True on the first run then False on every rerun st.write(isinstance(st.session_state.my_instance, MyClass)) st.button("Rerun") If you move the class definition out of app.py into another file, you can make isinstance() consistently return True. Consider the following file structure: myproject/ ├── my_class.py └── app.py # my_class.py class MyClass: def __init__(self, var1, var2): self.var1 = var1 self.var2 = var2 # app.py import streamlit as st from my_class import MyClass # MyClass doesn't get redefined with each rerun if "my_instance" not in st.session_state: st.session_state.my_instance = MyClass("foo", "bar") # Displays True on every rerun st.write(isinstance(st.session_state.my_instance, MyClass)) st.button("Rerun") Streamlit only reloads code in imported modules when it detects the code has changed. Thus, if you are actively editing the file where your class is defined, you may need to stop and restart your Streamlit server to avoid an undesirable class redefinition mid-session. Pattern 2: Force your class to compare internal values For classes that store data (like dataclasses), you may be more interested in comparing the internally stored values rather than the class itself. If you define a custom __eq__ method, you can force comparisons to be made on the internally stored values. Example: Define __eq__ Try running the following Streamlit app and observe how the comparison is True on the first run then False on every rerun thereafter. import streamlit as st from dataclasses import dataclass @dataclass class MyDataclass: var1: int var2: float if "my_dataclass" not in st.session_state: st.session_state.my_dataclass = MyDataclass(1, 5.5) # Displays True on the first run the False on every rerun st.session_state.my_dataclass == MyDataclass(1, 5.5) st.button("Rerun") Since MyDataclass gets redefined with each rerun, the instance stored in Session State will not be equal to any instance defined in a later script run. You can fix this by forcing a comparison of internal values as follows: import streamlit as st from dataclasses import dataclass @dataclass class MyDataclass: var1: int var2: float def __eq__(self, other): # An instance of MyDataclass is equal to another object if the object # contains the same fields with the same values return (self.var1, self.var2) == (other.var1, other.var2) if "my_dataclass" not in st.session_state: st.session_state.my_dataclass = MyDataclass(1, 5.5) # Displays True on every rerun st.session_state.my_dataclass == MyDataclass(1, 5.5) st.button("Rerun") The default Python __eq__ implementation for a regular class or @dataclass depends on the in-memory ID of the class or class instance. To avoid problems in Streamlit, your custom __eq__ method should not depend the type() of self and other. Pattern 3: Store your class as serialized data Another option for classes that store data is to define serialization and deserialization methods like to_str and from_str for your class. You can use these to store class instance data in st.session_state rather than storing the class instance itself. Similar to pattern 2, this is a way to force comparison of the internal data and bypass the changing in-memory IDs. Example: Save your class instance as a string Using the same example from pattern 2, this can be done as follows: import streamlit as st from dataclasses import dataclass @dataclass class MyDataclass: var1: int var2: float def to_str(self): return f"{self.var1},{self.var2}" @classmethod def from_str(cls, serial_str): values = serial_str.split(",") var1 = int(values[0]) var2 = float(values[1]) return cls(var1, var2) if "my_dataclass" not in st.session_state: st.session_state.my_dataclass = MyDataclass(1, 5.5).to_str() # Displays True on every rerun MyDataclass.from_str(st.session_state.my_dataclass) == MyDataclass(1, 5.5) st.button("Rerun") Pattern 4: Use caching to preserve your class For classes that are used as resources (database connections, state managers, APIs), consider using the cached singleton pattern. Use @st.cache_resource to decorate a @staticmethod of your class to generate a single, cached instance of the class. For example: import streamlit as st class MyResource: def __init__(self, api_url: str): self._url = api_url @st.cache_resource(ttl=300) @staticmethod def get_resource_manager(api_url: str): return MyResource(api_url) # This is cached until Session State is cleared or 5 minutes has elapsed. resource_manager = MyResource.get_resource_manager("http://example.com/api/") When you use one of Streamlit's caching decorators on a function, Streamlit doesn't use the function object to look up cached values. Instead, Streamlit's caching decorators index return values using the function's qualified name and module. So, even though Streamlit redefines MyResource with each script run, st.cache_resource is unaffected by this. get_resource_manager() will return its cached value with each rerun, until the value expires. Understanding how Python defines and compares classes So what's really happening here? We'll consider a simple example to illustrate why this is a pitfall. Feel free to skip this section if you don't want to deal more details. You can jump ahead to learn about Using Enum classes. Example: What happens when you define the same class twice? Set aside Streamlit for a moment and think about this simple Python script: from dataclasses import dataclass @dataclass class Student: student_id: int name: str Marshall_A = Student(1, "Marshall") Marshall_B = Student(1, "Marshall") # This is True (because a dataclass will compare two of its instances by value) Marshall_A == Marshall_B # Redefine the class @dataclass class Student: student_id: int name: str Marshall_C = Student(1, "Marshall") # This is False Marshall_A == Marshall_C In this example, the dataclass Student is defined twice. All three Marshalls have the same internal values. If you compare Marshall_A and Marshall_B they will be equal because they were both created from the first definition of Student. However, if you compare Marshall_A and Marshall_C they will not be equal because Marshall_C was created from the second definition of Student. Even though both Student dataclasses are defined exactly the same, they have differnt in-memory IDs and are therefore different. What's happening in Streamlit? In Streamlit, you probably don't have the same class written twice in your page script. However, the rerun logic of Streamlit creates the same effect. Let's use the above example for an analogy. If you define a class in one script run and save an instance in Session State, then a later rerun will redefine the class and you may end up comparing a Mashall_C in your rerun to a Marshall_A in Session State. Since widgets rely on Session State under the hood, this is where things can get confusing. How Streamlit widgets store options Several Streamlit UI elements, such as st.selectbox or st.radio, accept multiple-choice options via an options argument. The user of your application can typically select one or more of these options. The selected value is returned by the widget function. For example: number = st.selectbox("Pick a number, any number", options=[1, 2, 3]) # number == whatever value the user has selected from the UI. When you call a function like st.selectbox and pass an Iterable to options, the Iterable and current selection are saved into a hidden portion of Session State called the Widget Metadata. When the user of your application interacts with the st.selectbox widget, the broswer sends the index of their selection to your Streamlit server. This index is used to determine which values from the original options list, saved in the Widget Metadata from the previous page execution, are returned to your application. The key detail is that the value returned by st.selectbox (or similar widget function) is from an Iterable saved in Session State during a previous execution of the page, NOT the values passed to options on the current execution. There are a number of architectural reasons why Streamlit is designed this way, which we won't go into here. However, this is how we end up comparing instances of different classes when we think we are comparing instances of the same class. A pathological example The above explanation might be a bit confusing, so here's a pathological example to illustrate the idea. import streamlit as st from dataclasses import dataclass @dataclass class Student: student_id: int name: str Marshall_A = Student(1, "Marshall") if "B" not in st.session_state: st.session_state.B = Student(1, "Marshall") Marshall_B = st.session_state.B options = [Marshall_A,Marshall_B] selected = st.selectbox("Pick", options) # This comparison does not return expected results: selected == Marshall_A # This comparison evaluates as expected: selected == Marshall_B As a final note, we used @dataclass in the example for this section to illustrate a point, but in fact it is possible to encounter these same problems with classes, in general. Any class which checks class identity inside of a comparison operator—such as __eq__ or __gt__—can exhibit these issues. Using Enum classes in Streamlit The Enum class from the Python standard library is a powerful way to define custom symbolic names that can be used as options for st.multiselect or st.selectbox in place of str values. For example, you might add the following to your streamlit page: from enum import Enum import streamlit as st # class syntax class Color(Enum): RED = 1 GREEN = 2 BLUE = 3 selected_colors = set(st.multiselect("Pick colors", options=Color)) if selected_colors == {Color.RED, Color.GREEN}: st.write("Hooray, you found the color YELLOW!") If you're using the latest version of Streamlit, this Streamlit page will work as it appears it should. When a user picks both Color.RED and Color.GREEN, they are shown the special message. However, if you've read the rest of this page you might notice something tricky going on. Specifically, the Enum class Color gets redefined every time this script is run. In Python, if you define two Enum classes with the same class name, members, and values, the classes and their members are still considered unique from each other. This should cause the above if condition to always evaluate to False. In any script rerun, the Color values returned by st.multiselect would be of a different class than the Color defined in that script run. If you run the snippet above with Streamlit version 1.28.0 or less, you will not be able see the special message. Thankfully, as of version 1.29.0, Streamlit introduced a configuration option to greatly simplify the problem. That's where the enabled-by-default enumCoercion configuration option comes in. Understanding the enumCoercion configuration option When enumCoercion is enabled, Streamlit tries to recognize when you are using an element like st.multiselect or st.selectbox with a set of Enum members as options. If Streamlit detects this, it will convert the widget's returned values to members of the Enum class defined in the latest script run. This is something we call automatic Enum coercion. This behavior is configurable via the enumCoercion setting in your Streamlit config.toml file. It is enabled by default, and may be disabled or set to a stricter set of matching criteria. If you find that you still encounter issues with enumCoercion enabled, consider using the custom class patterns described above, such as moving your Enum class definition to a separate module file.Previous: DataframesNext: Working with timezonesforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy
https://docs.streamlit.io/develop/tutorials/databases/mssql#connect-locally
DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceaddTutorialsremoveExecution flowaddConnect to data sourcesremoveAWS S3BigQueryDeta BaseFirestoreopen_in_newGoogle Cloud StorageMicrosoft SQL ServerMongoDBMySQLNeonPostgreSQLPrivate Google SheetPublic Google SheetSnowflakeSupabaseTableauTiDBTigerGraphMultipage appsaddWork with LLMsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Develop/Tutorials/Connect to data sources/Microsoft SQL ServerConnect Streamlit to Microsoft SQL Server Introduction This guide explains how to securely access a remote Microsoft SQL Server database from Streamlit Community Cloud. It uses the pyodbc library and Streamlit's Secrets management. Create an SQL Server database push_pinNoteIf you already have a remote database that you want to use, feel free to skip to the next step. First, follow the Microsoft documentation to install SQL Server and the sqlcmd Utility. They have detailed installation guides on how to: Install SQL Server on Windows Install on Red Hat Enterprise Linux Install on SUSE Linux Enterprise Server Install on Ubuntu Run on Docker Provision a SQL VM in Azure Once you have SQL Server installed, note down your SQL Server name, username, and password during setup. Connect locally If you are connecting locally, use sqlcmd to connect to your new local SQL Server instance. In your terminal, run the following command: sqlcmd -S localhost -U SA -P '<YourPassword>' As you are connecting locally, the SQL Server name is localhost, the username is SA, and the password is the one you provided during the SA account setup. You should see a sqlcmd command prompt 1>, if successful. If you run into a connection failure, review Microsoft's connection troubleshooting recommendations for your OS (Linux & Windows). starTipWhen connecting remotely, the SQL Server name is the machine name or IP address. You might also need to open the SQL Server TCP port (default 1433) on your firewall. Create a SQL Server database By now, you have SQL Server running and have connected to it with sqlcmd! 🥳 Let's put it to use by creating a database containing a table with some example values. From the sqlcmd command prompt, run the following Transact-SQL command to create a test database mydb: CREATE DATABASE mydb To execute the above command, type GO on a new line: GO Insert some data Next create a new table, mytable, in the mydb database with three columns and two rows. Switch to the new mydb database: USE mydb Create a new table with the following schema: CREATE TABLE mytable (name varchar(80), pet varchar(80)) Insert some data into the table: INSERT INTO mytable VALUES ('Mary', 'dog'), ('John', 'cat'), ('Robert', 'bird') Type GO to execute the above commands: GO To end your sqlcmd session, type QUIT on a new line. Add username and password to your local app secrets Your local Streamlit app will read secrets from a file .streamlit/secrets.toml in your app's root directory. Create this file if it doesn't exist yet and add the SQL Server name, database name, username, and password as shown below: # .streamlit/secrets.toml server = "localhost" database = "mydb" username = "SA" password = "xxx" priority_highImportantWhen copying your app secrets to Streamlit Community Cloud, be sure to replace the values of server, database, username, and password with those of your remote SQL Server!And add this file to .gitignore and don't commit it to your GitHub repo. Copy your app secrets to Streamlit Community Cloud As the secrets.toml file above is not committed to GitHub, you need to pass its content to your deployed app (on Streamlit Community Cloud) separately. Go to the app dashboard and in the app's dropdown menu, click on Edit Secrets. Copy the content of secrets.toml into the text area. More information is available at Secrets management. Add pyodbc to your requirements file To connect to SQL Server locally with Streamlit, you need to pip install pyodbc, in addition to the Microsoft ODBC driver you installed during the SQL Server installation. On Streamlit Cloud, we have built-in support for SQL Server. On popular demand, we directly added SQL Server tools including the ODBC drivers and the executables sqlcmd and bcp to the container image for Cloud apps, so you don't need to install them. All you need to do is add the pyodbc Python package to your requirements.txt file, and you're ready to go! 🎈 # requirements.txt pyodbc==x.x.x Replace x.x.x ☝️ with the version of pyodbc you want installed on Cloud. push_pinNoteAt this time, Streamlit Community Cloud does not support Azure Active Directory authentication. We will update this tutorial when we add support for Azure Active Directory. Write your Streamlit app Copy the code below to your Streamlit app and run it. Make sure to adapt query to use the name of your table. import streamlit as st import pyodbc # Initialize connection. # Uses st.cache_resource to only run once. @st.cache_resource def init_connection(): return pyodbc.connect( "DRIVER={ODBC Driver 17 for SQL Server};SERVER=" + st.secrets["server"] + ";DATABASE=" + st.secrets["database"] + ";UID=" + st.secrets["username"] + ";PWD=" + st.secrets["password"] ) conn = init_connection() # Perform query. # Uses st.cache_data to only rerun when the query changes or after 10 min. @st.cache_data(ttl=600) def run_query(query): with conn.cursor() as cur: cur.execute(query) return cur.fetchall() rows = run_query("SELECT * from mytable;") # Print results. for row in rows: st.write(f"{row[0]} has a :{row[1]}:") See st.cache_data above? Without it, Streamlit would run the query every time the app reruns (e.g. on a widget interaction). With st.cache_data, it only runs when the query changes or after 10 minutes (that's what ttl is for). Watch out: If your database updates more frequently, you should adapt ttl or remove caching so viewers always see the latest data. Learn more in Caching. If everything worked out (and you used the example table we created above), your app should look like this: Previous: Google Cloud StorageNext: MongoDBforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy
https://docs.streamlit.io/develop/concepts/custom-components/intro#frontend
DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsremoveCOREArchitecture & executionaddMultipage appsaddApp designaddADDITIONALConnections and secretsaddCustom componentsremoveIntro to custom componentsCreate a ComponentPublish a ComponentLimitationsComponent galleryopen_in_newConfiguration and themingaddApp testingaddAPI referenceaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Develop/Concepts/Custom components/Intro to custom componentsIntro to custom components The first step in developing a Streamlit Component is deciding whether to create a static component (i.e. rendered once, controlled by Python) or to create a bi-directional component that can communicate from Python to JavaScript and back. Create a static component If your goal in creating a Streamlit Component is solely to display HTML code or render a chart from a Python visualization library, Streamlit provides two methods that greatly simplify the process: components.html() and components.iframe(). If you are unsure whether you need bi-directional communication, start here first! Render an HTML string While st.text, st.markdown and st.write make it easy to write text to a Streamlit app, sometimes you'd rather implement a custom piece of HTML. Similarly, while Streamlit natively supports many charting libraries, you may want to implement a specific HTML/JavaScript template for a new charting library. components.html works by giving you the ability to embed an iframe inside of a Streamlit app that contains your desired output. Example import streamlit as st import streamlit.components.v1 as components # bootstrap 4 collapse example components.html( """ <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous"> <script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script> <div id="accordion"> <div class="card"> <div class="card-header" id="headingOne"> <h5 class="mb-0"> <button class="btn btn-link" data-toggle="collapse" data-target="#collapseOne" aria-expanded="true" aria-controls="collapseOne"> Collapsible Group Item #1 </button> </h5> </div> <div id="collapseOne" class="collapse show" aria-labelledby="headingOne" data-parent="#accordion"> <div class="card-body"> Collapsible Group Item #1 content </div> </div> </div> <div class="card"> <div class="card-header" id="headingTwo"> <h5 class="mb-0"> <button class="btn btn-link collapsed" data-toggle="collapse" data-target="#collapseTwo" aria-expanded="false" aria-controls="collapseTwo"> Collapsible Group Item #2 </button> </h5> </div> <div id="collapseTwo" class="collapse" aria-labelledby="headingTwo" data-parent="#accordion"> <div class="card-body"> Collapsible Group Item #2 content </div> </div> </div> </div> """, height=600, ) Render an iframe URL components.iframe is similar in features to components.html, with the difference being that components.iframe takes a URL as its input. This is used for situations where you want to include an entire page within a Streamlit app. Example import streamlit as st import streamlit.components.v1 as components # embed streamlit docs in a streamlit app components.iframe("https://example.com", height=500) Create a bi-directional component A bi-directional Streamlit Component has two parts: A frontend, which is built out of HTML and any other web tech you like (JavaScript, React, Vue, etc.), and gets rendered in Streamlit apps via an iframe tag. A Python API, which Streamlit apps use to instantiate and talk to that frontend To make the process of creating bi-directional Streamlit Components easier, we've created a React template and a TypeScript-only template in the Streamlit Component-template GitHub repo. We also provide some example Components in the same repo. Development Environment Setup To build a Streamlit Component, you need the following installed in your development environment: Python 3.8 - Python 3.12 Streamlit 1.11.1 or higher nodejs npm or yarn Clone the component-template GitHub repo, then decide whether you want to use the React.js ("template") or plain TypeScript ("template-reactless") template. Initialize and build the component template frontend from the terminal: # React template template/my_component/frontend npm install # Initialize the project and install npm dependencies npm run start # Start the Webpack dev server # or # TypeScript-only template template-reactless/my_component/frontend npm install # Initialize the project and install npm dependencies npm run start # Start the Webpack dev server From a separate terminal, run the Streamlit app (Python) that declares and uses the component: # React template cd template . venv/bin/activate # or similar to activate the venv/conda environment where Streamlit is installed pip install -e . # install template as editable package streamlit run my_component/example.py # run the example # or # TypeScript-only template cd template-reactless . venv/bin/activate # or similar to activate the venv/conda environment where Streamlit is installed pip install -e . # install template as editable package streamlit run my_component/example.py # run the example After running the steps above, you should see a Streamlit app in your browser that looks like this: The example app from the template shows how bi-directional communication is implemented. The Streamlit Component displays a button (Python → JavaScript), and the end-user can click the button. Each time the button is clicked, the JavaScript front-end increments the counter value and passes it back to Python (JavaScript → Python), which is then displayed by Streamlit (Python → JavaScript). Frontend Because each Streamlit Component is its own webpage that gets rendered into an iframe, you can use just about any web tech you'd like to create that web page. We provide two templates to get started with in the Streamlit Components-template GitHub repo; one of those templates uses React and the other does not. push_pinNoteEven if you're not already familiar with React, you may still want to check out the React-based template. It handles most of the boilerplate required to send and receive data from Streamlit, and you can learn the bits of React you need as you go.If you'd rather not use React, please read this section anyway! It explains the fundamentals of Streamlit ↔ Component communication. React The React-based template is in template/my_component/frontend/src/MyComponent.tsx. MyComponent.render() is called automatically when the component needs to be re-rendered (just like in any React app) Arguments passed from the Python script are available via the this.props.args dictionary: # Send arguments in Python: result = my_component(greeting="Hello", name="Streamlit") // Receive arguments in frontend: let greeting = this.props.args["greeting"]; // greeting = "Hello" let name = this.props.args["name"]; // name = "Streamlit" Use Streamlit.setComponentValue() to return data from the component to the Python script: // Set value in frontend: Streamlit.setComponentValue(3.14); # Access value in Python: result = my_component(greeting="Hello", name="Streamlit") st.write("result = ", result) # result = 3.14 When you call Streamlit.setComponentValue(new_value), that new value is sent to Streamlit, which then re-executes the Python script from top to bottom. When the script is re-executed, the call to my_component(...) will return the new value. From a code flow perspective, it appears that you're transmitting data synchronously with the frontend: Python sends the arguments to JavaScript, and JavaScript returns a value to Python, all in a single function call! But in reality this is all happening asynchronously, and it's the re-execution of the Python script that achieves the sleight of hand. Use Streamlit.setFrameHeight() to control the height of your component. By default, the React template calls this automatically (see StreamlitComponentBase.componentDidUpdate()). You can override this behavior if you need more control. There's a tiny bit of magic in the last line of the file: export default withStreamlitConnection(MyComponent) - this does some handshaking with Streamlit, and sets up the mechanisms for bi-directional data communication. TypeScript-only The TypeScript-only template is in template-reactless/my_component/frontend/src/MyComponent.tsx. This template has much more code than its React sibling, in that all the mechanics of handshaking, setting up event listeners, and updating the component's frame height are done manually. The React version of the template handles most of these details automatically. Towards the bottom of the source file, the template calls Streamlit.setComponentReady() to tell Streamlit it's ready to start receiving data. (You'll generally want to do this after creating and loading everything that the Component relies on.) It subscribes to Streamlit.RENDER_EVENT to be notified of when to redraw. (This event won't be fired until setComponentReady is called) Within its onRender event handler, it accesses the arguments passed in the Python script via event.detail.args It sends data back to the Python script in the same way that the React template does—clicking on the "Click Me!" button calls Streamlit.setComponentValue() It informs Streamlit when its height may have changed via Streamlit.setFrameHeight() Working with Themes push_pinNoteCustom component theme support requires streamlit-component-lib version 1.2.0 or higher. Along with sending an args object to your component, Streamlit also sends a theme object defining the active theme so that your component can adjust its styling in a compatible way. This object is sent in the same message as args, so it can be accessed via this.props.theme (when using the React template) or event.detail.theme (when using the plain TypeScript template). The theme object has the following shape: { "base": "lightORdark", "primaryColor": "someColor1", "backgroundColor": "someColor2", "secondaryBackgroundColor": "someColor3", "textColor": "someColor4", "font": "someFont" } The base option allows you to specify a preset Streamlit theme that your custom theme inherits from. Any theme config options not defined in your theme settings have their values set to those of the base theme. Valid values for base are "light" and "dark". Note that the theme object has fields with the same names and semantics as the options in the "theme" section of the config options printed with the command streamlit config show. When using the React template, the following CSS variables are also set automatically. --base --primary-color --background-color --secondary-background-color --text-color --font If you're not familiar with CSS variables, the TLDR version is that you can use them like this: .mySelector { color: var(--text-color); } These variables match the fields defined in the theme object above, and whether to use CSS variables or the theme object in your component is a matter of personal preference. Other frontend details Because you're hosting your component from a dev server (via npm run start), any changes you make should be automatically reflected in the Streamlit app when you save. If you want to add more packages to your component, run npm add to add them from within your component's frontend/ directory. npm add baseui To build a static version of your component, run npm run export. See Prepare your Component for more information Python API components.declare_component() is all that's required to create your Component's Python API: import streamlit.components.v1 as components my_component = components.declare_component( "my_component", url="http://localhost:3001" ) You can then use the returned my_component function to send and receive data with your frontend code: # Send data to the frontend using named arguments. return_value = my_component(name="Blackbeard", ship="Queen Anne's Revenge") # `my_component`'s return value is the data returned from the frontend. st.write("Value = ", return_value) While the above is all you need to define from the Python side to have a working Component, we recommend creating a "wrapper" function with named arguments and default values, input validation and so on. This will make it easier for end-users to understand what data values your function accepts and allows for defining helpful docstrings. Please see this example from the Components-template for an example of creating a wrapper function. Data serialization Python → Frontend You send data from Python to the frontend by passing keyword args to your Component's invoke function (that is, the function returned from declare_component). You can send the following types of data from Python to the frontend: Any JSON-serializable data numpy.array pandas.DataFrame Any JSON-serializable data gets serialized to a JSON string, and deserialized to its JavaScript equivalent. numpy.array and pandas.DataFrame get serialized using Apache Arrow and are deserialized as instances of ArrowTable, which is a custom type that wraps Arrow structures and provides a convenient API on top of them. Check out the CustomDataframe and SelectableDataTable Component example code for more context on how to use ArrowTable. Frontend → Python You send data from the frontend to Python via the Streamlit.setComponentValue() API (which is part of the template code). Unlike arg-passing from Python → frontend, this API takes a single value. If you want to return multiple values, you'll need to wrap them in an Array or Object. Custom Components can send JSON-serializable data from the frontend to Python, as well as Apache Arrow ArrowTables to represent dataframes.Previous: Custom componentsNext: Create a ComponentforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy
https://docs.streamlit.io/develop/tutorials/databases/bigquery#enable-the-bigquery-api
DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceaddTutorialsremoveExecution flowaddConnect to data sourcesremoveAWS S3BigQueryDeta BaseFirestoreopen_in_newGoogle Cloud StorageMicrosoft SQL ServerMongoDBMySQLNeonPostgreSQLPrivate Google SheetPublic Google SheetSnowflakeSupabaseTableauTiDBTigerGraphMultipage appsaddWork with LLMsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Develop/Tutorials/Connect to data sources/BigQueryConnect Streamlit to Google BigQuery Introduction This guide explains how to securely access a BigQuery database from Streamlit Community Cloud. It uses the google-cloud-bigquery library and Streamlit's Secrets management. Create a BigQuery database push_pinNoteIf you already have a database that you want to use, feel free to skip to the next step. For this example, we will use one of the sample datasets from BigQuery (namely the shakespeare table). If you want to create a new dataset instead, follow Google's quickstart guide. Enable the BigQuery API Programmatic access to BigQuery is controlled through Google Cloud Platform. Create an account or sign in and head over to the APIs & Services dashboard (select or create a project if asked). As shown below, search for the BigQuery API and enable it: Create a service account & key file To use the BigQuery API from Streamlit Community Cloud, you need a Google Cloud Platform service account (a special account type for programmatic data access). Go to the Service Accounts page and create an account with the Viewer permission (this will let the account access data but not change it): push_pinNoteIf the button CREATE SERVICE ACCOUNT is gray, you don't have the correct permissions. Ask the admin of your Google Cloud project for help. After clicking DONE, you should be back on the service accounts overview. Create a JSON key file for the new account and download it: Add the key file to your local app secrets Your local Streamlit app will read secrets from a file .streamlit/secrets.toml in your app's root directory. Create this file if it doesn't exist yet and add the content of the key file you just downloaded to it as shown below: # .streamlit/secrets.toml [gcp_service_account] type = "service_account" project_id = "xxx" private_key_id = "xxx" private_key = "xxx" client_email = "xxx" client_id = "xxx" auth_uri = "https://accounts.google.com/o/oauth2/auth" token_uri = "https://oauth2.googleapis.com/token" auth_provider_x509_cert_url = "https://www.googleapis.com/oauth2/v1/certs" client_x509_cert_url = "xxx" priority_highImportantAdd this file to .gitignore and don't commit it to your GitHub repo! Copy your app secrets to the cloud As the secrets.toml file above is not committed to GitHub, you need to pass its content to your deployed app (on Streamlit Community Cloud) separately. Go to the app dashboard and in the app's dropdown menu, click on Edit Secrets. Copy the content of secrets.toml into the text area. More information is available at Secrets management. Add google-cloud-bigquery to your requirements file Add the google-cloud-bigquery package to your requirements.txt file, preferably pinning its version (replace x.x.x with the version want installed): # requirements.txt google-cloud-bigquery==x.x.x Write your Streamlit app Copy the code below to your Streamlit app and run it. Make sure to adapt the query if you don't use the sample table. # streamlit_app.py import streamlit as st from google.oauth2 import service_account from google.cloud import bigquery # Create API client. credentials = service_account.Credentials.from_service_account_info( st.secrets["gcp_service_account"] ) client = bigquery.Client(credentials=credentials) # Perform query. # Uses st.cache_data to only rerun when the query changes or after 10 min. @st.cache_data(ttl=600) def run_query(query): query_job = client.query(query) rows_raw = query_job.result() # Convert to list of dicts. Required for st.cache_data to hash the return value. rows = [dict(row) for row in rows_raw] return rows rows = run_query("SELECT word FROM `bigquery-public-data.samples.shakespeare` LIMIT 10") # Print results. st.write("Some wise words from Shakespeare:") for row in rows: st.write("✍️ " + row['word']) See st.cache_data above? Without it, Streamlit would run the query every time the app reruns (e.g. on a widget interaction). With st.cache_data, it only runs when the query changes or after 10 minutes (that's what ttl is for). Watch out: If your database updates more frequently, you should adapt ttl or remove caching so viewers always see the latest data. Learn more in Caching. Alternatively, you can use pandas to read from BigQuery right into a dataframe! Follow all the above steps, install the pandas-gbq library (don't forget to add it to requirements.txt!), and call pandas.read_gbq(query, credentials=credentials). More info in the pandas docs. If everything worked out (and you used the sample table), your app should look like this: Previous: AWS S3Next: Deta BaseforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy
https://docs.streamlit.io/develop/api-reference/connections/st.connections.snowflakeconnection#using-streamlit-secrets
DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceremovePAGE ELEMENTSWrite and magicaddText elementsaddData elementsaddChart elementsaddInput widgetsaddMedia elementsaddLayouts and containersaddChat elementsaddStatus elementsaddThird-party componentsopen_in_newAPPLICATION LOGICNavigation and pagesaddExecution flowaddCaching and stateaddConnections and secretsremoveSECRETSst.secretssecrets.tomlCONNECTIONSst.connectionSnowflakeConnectionSQLConnectionBaseConnectionSnowparkConnectiondeleteCustom componentsaddUtilitiesaddConfigurationaddTOOLSApp testingaddCommand lineaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Develop/API reference/Connections and secrets/SnowflakeConnectionstarTipThis page only contains the st.connections.SnowflakeConnection class. For a deeper dive into creating and managing data connections within Streamlit apps, read Connecting to data. st.connections.SnowflakeConnectionStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA connection to Snowflake using the Snowflake Python Connector. Initialize using st.connection("<name>", type="snowflake"). SnowflakeConnection supports direct SQL querying using .query("..."), access to the underlying Snowflake Python Connector object with .raw_connection, and other convenience functions. See the methods below for more information. SnowflakeConnections should always be created using st.connection(), not initialized directly. Class description[source] st.connections.SnowflakeConnection(connection_name, **kwargs) Methods cursor() Return a PEP 249-compliant cursor object. query(sql, *, ttl=None, show_spinner="Running `snowflake.query(...)`.", params=None, **kwargs) Run a read-only SQL query. reset() Reset this connection so that it gets reinitialized the next time it's used. session() Create a new Snowpark Session from this connection. write_pandas(df, table_name, database=None, schema=None, chunk_size=None, **kwargs) Call snowflake.connector.pandas_tools.write_pandas with this connection. Attributes raw_connection Access the underlying Snowflake Python connector object. Configuration st.connection("snowflake") can be configured using Streamlit secrets or keyword args just like any other connection. It can also use existing Snowflake connection configuration when available. Note that snowflake-snowpark-python must be installed to use this connection. Using Streamlit secrets For example, if your Snowflake account supports SSO, you can set up a quick local connection for development using browser-based SSO and secrets.toml as follows: # .streamlit/secrets.toml [connections.snowflake] account = "<ACCOUNT ID>" user = "<USERNAME>" authenticator = "EXTERNALBROWSER" Learn more about account indentifier here. You could also specify the full configuration and credentials in your secrets file, as in the example here. Using existing Snowflake configuration Snowflake's python driver also supports a connection configuration file, which is well integrated with Streamlit SnowflakeConnection. If you already have one or more connections configured, all you need to do is pass Streamlit the name of the connection to use. This can be done in several ways: Set connection_name in your app code, such as st.connnection("<name>", type="snowflake"). Set connection_name = "<name>" in the [connections.snowflake] section of your Streamlit secrets. Set the environment variable SNOWFLAKE_DEFAULT_CONNECTION_NAME=<name>. Set a default connection in your Snowflake configuration. When available in Streamlit in Snowflake, st.connection("snowflake") will connect automatically using the app owner role and does not require any configuration. Learn more about setting up connections in the Connecting Streamlit to Snowflake tutorial and Connecting to data. SnowflakeConnection.cursorStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeReturn a PEP 249-compliant cursor object. For more information, see the Snowflake Python Connector documentation. Function signature[source] SnowflakeConnection.cursor() SnowflakeConnection.queryStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeRun a read-only SQL query. This method implements both query result caching (with caching behavior identical to that of using @st.cache_data) as well as simple error handling/retries. Note Queries that are run without a specified ttl are cached indefinitely. Function signature[source] SnowflakeConnection.query(sql, *, ttl=None, show_spinner="Running `snowflake.query(...)`.", params=None, **kwargs) Parameters sql (str) The read-only SQL query to execute. ttl (float, int, timedelta or None) The maximum number of seconds to keep results in the cache, or None if cached results should not expire. The default is None. show_spinner (boolean or string) Enable the spinner. The default is to show a spinner when there is a "cache miss" and the cached resource is being created. If a string, the value of the show_spinner param will be used for the spinner text. params (list, tuple, dict or None) List of parameters to pass to the execute method. This connector supports binding data to a SQL statement using qmark bindings. For more information and examples, see the Snowflake Python Connector documentation. Default is None. Returns(pandas.DataFrame) The result of running the query, formatted as a pandas DataFrame. Example import streamlit as st conn = st.connection("snowflake") df = conn.query("select * from pet_owners") st.dataframe(df) SnowflakeConnection.raw_connectionStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeAccess the underlying Snowflake Python connector object. Information on how to use the Snowflake Python Connector can be found in the Snowflake Python Connector documentation. Function signature[source] SnowflakeConnection.raw_connection SnowflakeConnection.resetStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeReset this connection so that it gets reinitialized the next time it's used. This method can be useful when a connection has become stale, an auth token has expired, or in similar scenarios where a broken connection might be fixed by reinitializing it. Note that some connection methods may already use reset() in their error handling code. Function signature[source] SnowflakeConnection.reset() Example import streamlit as st conn = st.connection("my_conn") # Reset the connection before using it if it isn't healthy # Note: is_healthy() isn't a real method and is just shown for example here. if not conn.is_healthy(): conn.reset() # Do stuff with conn... SnowflakeConnection.sessionStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeCreate a new Snowpark Session from this connection. Information on how to use Snowpark sessions can be found in the Snowpark documentation. Function signature[source] SnowflakeConnection.session() SnowflakeConnection.write_pandasStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeCall snowflake.connector.pandas_tools.write_pandas with this connection. This convenience method is simply a thin wrapper around the write_pandas function of the same name from snowflake.connector.pandas_tools. For more information, see the Snowflake Python Connector documentation. Function signature[source] SnowflakeConnection.write_pandas(df, table_name, database=None, schema=None, chunk_size=None, **kwargs) Returns(tuple[bool, int, int]) A tuple containing three values: A bool that is True if the write was successful. An int giving the number of chunks of data that were copied. An int giving the number of rows that were inserted. Previous: st.connectionNext: SQLConnectionforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy
https://docs.streamlit.io/develop/api-reference/widgets/st.download_button#stdownload_button
DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceremovePAGE ELEMENTSWrite and magicaddText elementsaddData elementsaddChart elementsaddInput widgetsremoveBUTTONSst.buttonst.download_buttonst.form_submit_buttonlinkst.link_buttonst.page_linkSELECTIONSst.checkboxst.color_pickerst.multiselectst.radiost.selectboxst.select_sliderst.toggleNUMERICst.number_inputst.sliderDATE & TIMEst.date_inputst.time_inputTEXTst.chat_inputlinkst.text_areast.text_inputMEDIA & FILESst.camera_inputst.data_editorlinkst.file_uploaderMedia elementsaddLayouts and containersaddChat elementsaddStatus elementsaddThird-party componentsopen_in_newAPPLICATION LOGICNavigation and pagesaddExecution flowaddCaching and stateaddConnections and secretsaddCustom componentsaddUtilitiesaddConfigurationaddTOOLSApp testingaddCommand lineaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Develop/API reference/Input widgets/st.download_buttonst.download_buttonStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeDisplay a download button widget. This is useful when you would like to provide a way for your users to download a file directly from your app. Note that the data to be downloaded is stored in-memory while the user is connected, so it's a good idea to keep file sizes under a couple hundred megabytes to conserve memory. Function signature[source] st.download_button(label, data, file_name=None, mime=None, key=None, help=None, on_click=None, args=None, kwargs=None, *, type="secondary", disabled=False, use_container_width=False) Parameters label (str) A short label explaining to the user what this button is for. The label can optionally contain Markdown and supports the following elements: Bold, Italics, Strikethroughs, Inline Code, and Emojis. This also supports: Emoji shortcodes, such as :+1: and :sunglasses:. For a list of all supported codes, see https://share.streamlit.io/streamlit/emoji-shortcodes. LaTeX expressions, by wrapping them in "$" or "$$" (the "$$" must be on their own lines). Supported LaTeX functions are listed at https://katex.org/docs/supported.html. Colored text and background colors for text, using the syntax :color[text to be colored] and :color-background[text to be colored], respectively. color must be replaced with any of the following supported colors: blue, green, orange, red, violet, gray/grey, rainbow. For example, you can use :orange[your text here] or :blue-background[your text here]. Unsupported elements are unwrapped so only their children (text contents) render. Display unsupported elements as literal characters by backslash-escaping them. E.g. 1\. Not an ordered list. data (str or bytes or file) The contents of the file to be downloaded. See example below for caching techniques to avoid recomputing this data unnecessarily. file_name (str) An optional string to use as the name of the file to be downloaded, such as 'my_file.csv'. If not specified, the name will be automatically generated. mime (str or None) The MIME type of the data. If None, defaults to "text/plain" (if data is of type str or is a textual file) or "application/octet-stream" (if data is of type bytes or is a binary file). key (str or int) An optional string or integer to use as the unique key for the widget. If this is omitted, a key will be generated for the widget based on its content. Multiple widgets of the same type may not share the same key. help (str) An optional tooltip that gets displayed when the button is hovered over. on_click (callable) An optional callback invoked when this button is clicked. args (tuple) An optional tuple of args to pass to the callback. kwargs (dict) An optional dict of kwargs to pass to the callback. type ("secondary" or "primary") An optional string that specifies the button type. Can be "primary" for a button with additional emphasis or "secondary" for a normal button. Defaults to "secondary". disabled (bool) An optional boolean, which disables the download button if set to True. The default is False. use_container_width (bool) An optional boolean, which makes the button stretch its width to match the parent container. Returns(bool) True if the button was clicked on the last run of the app, False otherwise. Examples Download a large DataFrame as a CSV: import streamlit as st @st.cache_data def convert_df(df): # IMPORTANT: Cache the conversion to prevent computation on every rerun return df.to_csv().encode("utf-8") csv = convert_df(my_large_df) st.download_button( label="Download data as CSV", data=csv, file_name="large_df.csv", mime="text/csv", ) Download a string as a file: import streamlit as st text_contents = '''This is some text''' st.download_button("Download some text", text_contents) Download a binary file: import streamlit as st binary_contents = b"example content" # Defaults to "application/octet-stream" st.download_button("Download binary file", binary_contents) Download an image: import streamlit as st with open("flower.png", "rb") as file: btn = st.download_button( label="Download image", data=file, file_name="flower.png", mime="image/png" ) Built with Streamlit 🎈Fullscreen open_in_new Previous: st.buttonNext: st.form_submit_buttonforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy
https://docs.streamlit.io/library/advanced-features/configuration#configtoml
DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceremovePAGE ELEMENTSWrite and magicaddText elementsaddData elementsaddChart elementsaddInput widgetsaddMedia elementsaddLayouts and containersaddChat elementsaddStatus elementsaddThird-party componentsopen_in_newAPPLICATION LOGICNavigation and pagesaddExecution flowaddCaching and stateaddConnections and secretsaddCustom componentsaddUtilitiesaddConfigurationremoveconfig.tomlst.set_page_configTOOLSApp testingaddCommand lineaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Develop/API reference/Configuration/config.tomlconfig.toml config.toml is an optional file you can define for your working directory or global development environment. When config.toml is defined both globally and in your working directory, Streamlit combines the configuration options and gives precendence to the working-directory configuration. Additionally, you can use environment variables and command-line options to override additional configuration options. For more information, see Configuration options. File location To define your configuration locally or per-project, add .streamlit/config.toml to your working directory. Your working directory is wherever you call streamlit run. If you haven't previously created the .streamlit directory, you will need to add it. To define your configuration globally, you must first locate your global .streamlit directory. Streamlit adds this hidden directory to your OS user profile during installation. For MacOS/Linx, this will be ~/.streamlit/config.toml. For Windows, this will be %userprofile%/.streamlit/config.toml. File format config.toml is a TOML file. Example [client] showErrorDetails = false [theme] primaryColor = "#F63366" backgroundColor = "black" Available configuration options Below are all the sections and options you can have in your .streamlit/config.toml file. To see all configurations, use the following command in your terminal or CLI: streamlit config show Global [global] # ***DEPRECATED*** # global.disableWatchdogWarning has been deprecated has been deprecated and # will be removed in a future version. This option will be removed on or after # 2024-01-20. # **************** # By default, Streamlit checks if the Python watchdog module is available # and, if not, prints a warning asking for you to install it. The watchdog # module is not required, but highly recommended. It improves Streamlit's # ability to detect changes to files in your filesystem. # If you'd like to turn off this warning, set this to True. # Default: false disableWatchdogWarning = false # By default, Streamlit displays a warning when a user sets both a widget # default value in the function defining the widget and a widget value via # the widget's key in `st.session_state`. # If you'd like to turn off this warning, set this to True. # Default: false disableWidgetStateDuplicationWarning = false # If True, will show a warning when you run a Streamlit-enabled script # via "python my_script.py". # Default: true showWarningOnDirectExecution = true Logger [logger] # Level of logging: 'error', 'warning', 'info', or 'debug'. # Default: 'info' level = "info" # String format for logging messages. If logger.datetimeFormat is set, # logger messages will default to `%(asctime)s.%(msecs)03d %(message)s`. See # Python's documentation for available attributes: # https://docs.python.org/2.6/develop/logging.html#formatter-objects # Default: "%(asctime)s %(message)s" messageFormat = "%(asctime)s %(message)s" Client [client] # ***DEPRECATED*** # client.caching has been deprecated and is not required anymore for our new # caching commands. This option will be removed on or after 2024-01-20. # **************** # Whether to enable st.cache. This does not affect st.cache_data or # st.cache_resource. # Default: true caching = true # ***DEPRECATED*** # client.displayEnabled has been deprecated and will be removed in a future # version. This option will be removed on or after 2024-01-20. # **************** # If false, makes your Streamlit script not draw to a Streamlit app. # Default: true displayEnabled = true # Controls whether uncaught app exceptions and deprecation warnings # are displayed in the browser. By default, this is set to True and # Streamlit displays app exceptions and associated tracebacks, and # deprecation warnings, in the browser. # # If set to False, deprecation warnings and full exception messages # will print to the console only. Exceptions will still display in the # browser with a generic error message. For now, the exception type and # traceback show in the browser also, but they will be removed in the # future. # Default: true showErrorDetails = true # Change the visibility of items in the toolbar, options menu, # and settings dialog (top right of the app). # Allowed values: # * "auto" : Show the developer options if the app is accessed through # localhost or through Streamlit Community Cloud as a developer. # Hide them otherwise. # * "developer" : Show the developer options. # * "viewer" : Hide the developer options. # * "minimal" : Show only options set externally (e.g. through # Streamlit Community Cloud) or through st.set_page_config. # If there are no options left, hide the menu. # Default: "auto" toolbarMode = "auto" # Controls whether the default sidebar page navigation in a multipage app is # displayed. # Default: true showSidebarNavigation = true Runner [runner] # Allows you to type a variable or string by itself in a single line of # Python code to write it to the app. # Default: true magicEnabled = true # ***DEPRECATED*** # runner.installTracer has been deprecated and will be removed in a future # version. This option will be removed on or after 2024-01-20. # **************** # Install a Python tracer to allow you to stop or pause your script at # any point and introspect it. As a side-effect, this slows down your # script's execution. # Default: false installTracer = false # ***DEPRECATED*** # runner.fixMatplotlib has been deprecated and will be removed in a future # version. This option will be removed on or after 2024-01-20. # **************** # Sets the MPLBACKEND environment variable to Agg inside Streamlit to # prevent Python crashing. # Default: true fixMatplotlib = true # Handle script rerun requests immediately, rather than waiting for script # execution to reach a yield point. This makes Streamlit much more # responsive to user interaction, but it can lead to race conditions in # apps that mutate session_state data outside of explicit session_state # assignment statements. # Default: true fastReruns = true # Raise an exception after adding unserializable data to Session State. # Some execution environments may require serializing all data in Session # State, so it may be useful to detect incompatibility during development, # or when the execution environment will stop supporting it in the future. # Default: false enforceSerializableSessionState = false # Adjust how certain 'options' widgets like radio, selectbox, and # multiselect coerce Enum members when the Enum class gets # re-defined during a script re-run. For more information, check out the docs: # https://docs.streamlit.io/develop/concepts/design/custom-classes#enums # # Allowed values: # * "off" : Disables Enum coercion. # * "nameOnly" : Enum classes can be coerced if their member names match. # * "nameAndValue" : Enum classes can be coerced if their member names AND # member values match. # Default: "nameOnly" enumCoercion = "nameOnly" Server [server] # List of folders that should not be watched for changes. This # impacts both "Run on Save" and @st.cache. # Relative paths will be taken as relative to the current working directory. # Example: ['/home/user1/env', 'relative/path/to/folder'] # Default: [] folderWatchBlacklist = [] # Change the type of file watcher used by Streamlit, or turn it off # completely. # Allowed values: # * "auto" : Streamlit will attempt to use the watchdog module, and # falls back to polling if watchdog is not available. # * "watchdog" : Force Streamlit to use the watchdog module. # * "poll" : Force Streamlit to always use polling. # * "none" : Streamlit will not watch files. # Default: "auto" fileWatcherType = "auto" # Symmetric key used to produce signed cookies. If deploying on multiple # replicas, this should be set to the same value across all replicas to ensure # they all share the same secret. # Default: randomly generated secret key. cookieSecret = "a-random-key-appears-here" # If false, will attempt to open a browser window on start. # Default: false unless (1) we are on a Linux box where DISPLAY is unset, or # (2) we are running in the Streamlit Atom plugin. headless = false # Automatically rerun script when the file is modified on disk. # Default: false runOnSave = false # The address where the server will listen for client and browser # connections. Use this if you want to bind the server to a specific address. # If set, the server will only be accessible from this address, and not from # any aliases (like localhost). # Default: (unset) address = # The port where the server will listen for browser connections. # Don't use port 3000 which is reserved for internal development. # Default: 8501 port = 8501 # The base path for the URL where Streamlit should be served from. # Default: "" baseUrlPath = "" # Enables support for Cross-Origin Resource Sharing (CORS) protection, for # added security. # Due to conflicts between CORS and XSRF, if `server.enableXsrfProtection` is # on and `server.enableCORS` is off at the same time, we will prioritize # `server.enableXsrfProtection`. # Default: true enableCORS = true # Enables support for Cross-Site Request Forgery (XSRF) protection, for added # security. # Due to conflicts between CORS and XSRF, if `server.enableXsrfProtection` is # on and `server.enableCORS` is off at the same time, we will prioritize # `server.enableXsrfProtection`. # Default: true enableXsrfProtection = true # Max size, in megabytes, for files uploaded with the file_uploader. # Default: 200 maxUploadSize = 200 # Max size, in megabytes, of messages that can be sent via the WebSocket # connection. # Default: 200 maxMessageSize = 200 # Enables support for websocket compression. # Default: false enableWebsocketCompression = false # Enable serving files from a `static` directory in the running app's # directory. # Default: false enableStaticServing = false # Server certificate file for connecting via HTTPS. # Must be set at the same time as "server.sslKeyFile". # ['DO NOT USE THIS OPTION IN A PRODUCTION ENVIRONMENT. It has not gone through # security audits or performance tests. For the production environment, we # recommend performing SSL termination by the load balancer or the reverse # proxy.'] # sslCertFile = # Cryptographic key file for connecting via HTTPS. # Must be set at the same time as "server.sslCertFile". # ['DO NOT USE THIS OPTION IN A PRODUCTION ENVIRONMENT. It has not gone through # security audits or performance tests. For the production environment, we # recommend performing SSL termination by the load balancer or the reverse # proxy.'] # sslKeyFile = Browser [browser] # Internet address where users should point their browsers in order to # connect to the app. Can be IP address or DNS name and path. # This is used to: # - Set the correct URL for CORS and XSRF protection purposes. # - Show the URL on the terminal # - Open the browser # Default: "localhost" serverAddress = "localhost" # Whether to send usage statistics to Streamlit. # Default: true gatherUsageStats = true # Port where users should point their browsers in order to connect to the # app. # This is used to: # - Set the correct URL for XSRF protection purposes. # - Show the URL on the terminal (part of `streamlit run`). # - Open the browser automatically (part of `streamlit run`). # This option is for advanced use cases. To change the port of your app, use # `server.Port` instead. Don't use port 3000 which is reserved for internal # development. # Default: whatever value is set in server.port. serverPort = 8501 Mapbox [mapbox] # Configure Streamlit to use a custom Mapbox # token for elements like st.pydeck_chart and st.map. # To get a token for yourself, create an account at # https://mapbox.com. It's free (for moderate usage levels)! # Default: "" token = "" Deprecation [deprecation] # Set to false to disable the deprecation warning for using the global pyplot # instance. # Default: true showPyplotGlobalUse = true Theme [theme] # The preset Streamlit theme that your custom theme inherits from. # One of "light" or "dark". # base = # Primary accent color for interactive elements. # primaryColor = # Background color for the main content area. # backgroundColor = # Background color used for the sidebar and most interactive widgets. # secondaryBackgroundColor = # Color used for almost all text. # textColor = # Font family for all text in the app, except code blocks. One of "sans serif", # "serif", or "monospace". # font = Previous: ConfigurationNext: st.set_page_configforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy
https://docs.streamlit.io/deploy/streamlit-community-cloud/get-started/trust-and-security#incident-response
DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudremoveGet startedremoveQuickstartCreate your accountConnect your GitHub accountExplore your workspaceFork and edit a public appTrust and securityDeploy your appaddManage your appaddShare your appaddManage your accountaddTroubleshootingStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Deploy/Streamlit Community Cloud/Get started/Trust and securityStreamlit trust and security Streamlit is a framework that turns Python scripts into interactive apps, giving data scientists the ability to quickly create data and model-based apps for the entire company. A simple Streamlit app is: import streamlit as st number = st.slider("Pick a number: ", min_value=1, max_value=10) st.text("Your number is " + str(number)) When you streamlit run my_app.py, you start a web server that runs the interactive application on your local computer at http://localhost:8501. This is great for local development. When you want to share with your colleagues, Streamlit Community Cloud enables you to deploy and run these applications in the cloud. Streamlit Community Cloud handles the details of containerization and provides you an interface for easily managing your deployed apps. This document provides an overview of the security safeguards we've implemented to protect you and your data. Security, however, is a shared responsibility and you are ultimately responsible for making appropriate use of Streamlit and the Streamlit Community Cloud, including implementation of appropriate user-configurable security safeguards and best practices. Product security Authentication You must authenticate through GitHub to deploy or administer an app. Authentication through Google or single-use emailed links are required to view a private app when you don't have push or admin permissions on the associated GitHub repository. The single-use emailed links are valid for 15 minutes once requested. Permissions Streamlit Community Cloud inherits the permissions you have assigned in GitHub. Users with write access to a GitHub repository for a given app will be able to make changes in the Streamlit administrative console. However, only users with admin access to a repository are able to deploy and delete apps. Network and application security Data hosting Our physical infrastructure is hosted and managed within secure data centers maintained by infrastructure-as-a-service cloud providers. Streamlit leverages many of these platforms' built-in security, privacy, and redundancy features. Our cloud providers continually monitor their data centers for risk and undergo assessments to ensure compliance with industry standards. Data deletion Community Cloud users have the option to delete any apps they’ve deployed as well as their entire account. When a user deletes their application from the admin console, we delete their source code, including any files copied from their GitHub repository or created within our system from the running app. However, we keep a record representing the application in our database. This record contains the coordinates of the application: the GitHub organization or user, the GitHub repository, the branch, and the path of the main module file. When a user deletes their account, we perform a hard deletion of their data and a hard deletion of all the apps that belong to the GitHub identity associated with their account. In this case, we do not maintain the records of application coordinates described above. When an account is deleted, we also delete any HubSpot contact associated with the Community Cloud account. Virtual private cloud All of our servers are within a virtual private cloud (VPC) with firewalls and network access control lists (ACLs) to allow external access to a select few API endpoints; all other internal services are only accessible within the VPC. Encryption Streamlit apps are served entirely over HTTPS. We use only strong cipher suites and HTTP Strict Transport Security (HSTS) to ensure browsers interact with Streamlit apps over HTTPS. All data sent to or from Streamlit over the public internet is encrypted in transit using 256-bit encryption. Our API and application endpoints use Transport Layer Security (TLS) 1.2 (or better). We also encrypt data at rest on disk using AES-256. Permissions and authentication Access to Community Cloud user account data is limited to authorized personnel. We run a zero-trust corporate network, utilize single sign-on and multi-factor authentication (MFA), and enforce strong password policies to ensure access to cloud-related services is protected. Incident response Our internal protocol for handling security events includes detection, analysis, response, escalation, and mitigation. Security advisories are made available at https://streamlit.io/advisories. Penetration testing Streamlit uses third-party security tools to scan for vulnerabilities on a regular basis. Our security teams conduct periodic, intensive penetration tests on the Streamlit platform. Our product development team responds to any identified issues or potential vulnerabilities to ensure the quality, security, and availability of Streamlit applications. Vulnerability management We keep our systems up-to-date with the latest security patches and continuously monitor for new vulnerabilities. This includes automated scanning of our code repositories for vulnerable dependencies. If you discover a vulnerability in one of our products or websites, please report the issue to HackerOne.Previous: Fork and edit a public appNext: Deploy your appforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy
https://docs.streamlit.io/develop/concepts/architecture/forms#forms-are-containers
DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsremoveCOREArchitecture & executionremoveRunning your appStreamlit's architectureThe app chromeCachingSession StateFormsFragmentsWidget behaviorMultipage appsaddApp designaddADDITIONALConnections and secretsaddCustom componentsaddConfiguration and themingaddApp testingaddAPI referenceaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Develop/Concepts/Architecture & execution/FormsUsing forms When you don't want to rerun your script with each input made by a user, st.form is here to help! Forms make it easy to batch user input into a single rerun. This guide to using forms provides examples and explains how users interact with forms. Example In the following example, a user can set multiple parameters to update the map. As the user changes the parameters, the script will not rerun and the map will not update. When the user submits the form with the button labeled "Update map", the script reruns and the map updates. If at any time the user clicks "Generate new points" which is outside of the form, the script will rerun. If the user has any unsubmitted changes within the form, these will not be sent with the rerun. All changes made to a form will only be sent to the Python backend when the form itself is submitted. View source codeexpand_moreimport streamlit as st import pandas as pd import numpy as np def get_data(): df = pd.DataFrame({ "lat": np.random.randn(200) / 50 + 37.76, "lon": np.random.randn(200) / 50 + -122.4, "team": ['A','B']*100 }) return df if st.button('Generate new points'): st.session_state.df = get_data() if 'df' not in st.session_state: st.session_state.df = get_data() df = st.session_state.df with st.form("my_form"): header = st.columns([1,2,2]) header[0].subheader('Color') header[1].subheader('Opacity') header[2].subheader('Size') row1 = st.columns([1,2,2]) colorA = row1[0].color_picker('Team A', '#0000FF') opacityA = row1[1].slider('A opacity', 20, 100, 50, label_visibility='hidden') sizeA = row1[2].slider('A size', 50, 200, 100, step=10, label_visibility='hidden') row2 = st.columns([1,2,2]) colorB = row2[0].color_picker('Team B', '#FF0000') opacityB = row2[1].slider('B opacity', 20, 100, 50, label_visibility='hidden') sizeB = row2[2].slider('B size', 50, 200, 100, step=10, label_visibility='hidden') st.form_submit_button('Update map') alphaA = int(opacityA*255/100) alphaB = int(opacityB*255/100) df['color'] = np.where(df.team=='A',colorA+f'{alphaA:02x}',colorB+f'{alphaB:02x}') df['size'] = np.where(df.team=='A',sizeA, sizeB) st.map(df, size='size', color='color') Built with Streamlit 🎈Fullscreen open_in_new User interaction If a widget is not in a form, that widget will trigger a script rerun whenever a user changes its value. For widgets with keyed input (st.number_input, st.text_input, st.text_area), a new value triggers a rerun when the user clicks or tabs out of the widget. A user can also submit a change by pressing Enter while thier cursor is active in the widget. On the other hand if a widget is inside of a form, the script will not rerun when a user clicks or tabs out of that widget. For widgets inside a form, the script will rerun when the form is submitted and all widgets within the form will send their updated values to the Python backend. A user can submit a form using Enter on their keyboard if their cursor active in a widget that accepts keyed input. Within st.number_input and st.text_input a user presses Enter to submit the form. Within st.text_area a user presses Ctrl+Enter/⌘+Enter to submit the form. Widget values Before a form is submitted, all widgets within that form will have default values, just like widgets outside of a form have default values. import streamlit as st with st.form("my_form"): st.write("Inside the form") my_number = st.slider('Pick a number', 1, 10) my_color = st.selectbox('Pick a color', ['red','orange','green','blue','violet']) st.form_submit_button('Submit my picks') # This is outside the form st.write(my_number) st.write(my_color) Built with Streamlit 🎈Fullscreen open_in_new Forms are containers When st.form is called, a container is created on the frontend. You can write to that container like you do with other container elements. That is, you can use Python's with statement as shown in the example above, or you can assign the form container to a variable and call methods on it directly. Additionally, you can place st.form_submit_button anywhere in the form container. import streamlit as st animal = st.form('my_animal') # This is writing directly to the main body. Since the form container is # defined above, this will appear below everything written in the form. sound = st.selectbox('Sounds like', ['meow','woof','squeak','tweet']) # These methods called on the form container, so they appear inside the form. submit = animal.form_submit_button(f'Say it with {sound}!') sentence = animal.text_input('Your sentence:', 'Where\'s the tuna?') say_it = sentence.rstrip('.,!?') + f', {sound}!' if submit: animal.subheader(say_it) else: animal.subheader('&nbsp;') Built with Streamlit 🎈Fullscreen open_in_new Processing form submissions The purpose of a form is to override the default behavior of Streamlit which reruns a script as soon as the user makes a change. For widgets outside of a form, the logical flow is: The user changes a widget's value on the frontend. The widget's value in st.session_state and in the Python backend (server) is updated. The script rerun begins. If the widget has a callback, it is executed as a prefix to the page rerun. When the updated widget's function is executed during the rerun, it outputs the new value. For widgets inside a form, any changes made by a user (step 1) do not get passed to the Python backend (step 2) until the form is submitted. Furthermore, the only widget inside a form that can have a callback function is the st.form_submit_button. If you need to execute a process using newly submitted values, you have three major patterns for doing so. Execute the process after the form If you need to execute a one-time process as a result of a form submission, you can condition that process on the st.form_submit_button and execute it after the form. If you need results from your process to display above the form, you can use containers to control where the form displays relative to your output. import streamlit as st col1,col2 = st.columns([1,2]) col1.title('Sum:') with st.form('addition'): a = st.number_input('a') b = st.number_input('b') submit = st.form_submit_button('add') if submit: col2.title(f'{a+b:.2f}') Built with Streamlit 🎈Fullscreen open_in_new Use a callback with session state You can use a callback to execute a process as a prefix to the script rerunning. priority_highImportantWhen processing newly updated values within a callback, do not pass those values to the callback directly through the args or kwargs parameters. You need to assign a key to any widget whose value you use within the callback. If you look up the value of that widget from st.session_state within the body of the callback, you will be able to access the newly submitted value. See the example below. import streamlit as st if 'sum' not in st.session_state: st.session_state.sum = '' def sum(): result = st.session_state.a + st.session_state.b st.session_state.sum = result col1,col2 = st.columns(2) col1.title('Sum:') if isinstance(st.session_state.sum, float): col2.title(f'{st.session_state.sum:.2f}') with st.form('addition'): st.number_input('a', key = 'a') st.number_input('b', key = 'b') st.form_submit_button('add', on_click=sum) Built with Streamlit 🎈Fullscreen open_in_new Use st.rerun If your process affects content above your form, another alternative is using an extra rerun. This can be less resource-efficient though, and may be less desirable that the above options. import streamlit as st if 'sum' not in st.session_state: st.session_state.sum = '' col1,col2 = st.columns(2) col1.title('Sum:') if isinstance(st.session_state.sum, float): col2.title(f'{st.session_state.sum:.2f}') with st.form('addition'): a = st.number_input('a') b = st.number_input('b') submit = st.form_submit_button('add') # The value of st.session_state.sum is updated at the end of the script rerun, # so the displayed value at the top in col2 does not show the new sum. Trigger # a second rerun when the form is submitted to update the value above. st.session_state.sum = a + b if submit: st.rerun() Built with Streamlit 🎈Fullscreen open_in_new Limitations Every form must contain a st.form_submit_button. st.button and st.download_button cannot be added to a form. st.form cannot be embedded inside another st.form. Callback functions can only be assigned to st.form_submit_button within a form; no other widgets in a form can have a callback. Interdependent widgets within a form are unlikely to be particularly useful. If you pass widget1's value into widget2 when they are both inside a form, then widget2 will only update when the form is submitted. Previous: Session StateNext: FragmentsforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy
https://docs.streamlit.io/develop/api-reference/app-testing/testing-element-classes#selectboxselect
DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceremovePAGE ELEMENTSWrite and magicaddText elementsaddData elementsaddChart elementsaddInput widgetsaddMedia elementsaddLayouts and containersaddChat elementsaddStatus elementsaddThird-party componentsopen_in_newAPPLICATION LOGICNavigation and pagesaddExecution flowaddCaching and stateaddConnections and secretsaddCustom componentsaddUtilitiesaddConfigurationaddTOOLSApp testingremovest.testing.v1.AppTestTesting element classesCommand lineaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Develop/API reference/App testing/Testing element classesTesting element classes st.testing.v1.element_tree.Block The Block class has the same methods and attributes as AppTest. A Block instance represents a container of elements just as AppTest represents the entire app. For example, Block.button will produce a WidgetList of Button in the same manner as AppTest.button. ChatMessage, Column, and Tab all inherit from Block. For all container classes, parameters of the original element can be obtained as properties. For example, ChatMessage.avatar and Tab.label. st.testing.v1.element_tree.ElementStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeElement base class for testing. This class's methods and attributes are universal for all elements implemented in testing. For example, Caption, Code, Text, and Title inherit from Element. All widget classes also inherit from Element, but have additional methods specific to each widget type. See the AppTest class for the full list of supported elements. For all element classes, parameters of the original element can be obtained as properties. For example, Button.label, Caption.help, and Toast.icon. Class description[source] st.testing.v1.element_tree.Element(proto, root) Methods run(*, timeout=None) Run the AppTest script which contains the element. Attributes value The value or contents of the element. st.testing.v1.element_tree.ButtonStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.button and st.form_submit_button. Class description[source] st.testing.v1.element_tree.Button(proto, root) Methods click() Set the value of the button to True. run(*, timeout=None) Run the AppTest script which contains the element. set_value(v) Set the value of the button. Attributes value The value of the button. (bool) st.testing.v1.element_tree.ChatInputStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.chat_input. Class description[source] st.testing.v1.element_tree.ChatInput(proto, root) Methods run(*, timeout=None) Run the AppTest script which contains the element. set_value(v) Set the value of the widget. Attributes value The value of the widget. (str) st.testing.v1.element_tree.CheckboxStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.checkbox. Class description[source] st.testing.v1.element_tree.Checkbox(proto, root) Methods check() Set the value of the widget to True. run(*, timeout=None) Run the AppTest script which contains the element. set_value(v) Set the value of the widget. uncheck() Set the value of the widget to False. Attributes value The value of the widget. (bool) st.testing.v1.element_tree.ColorPickerStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.color_picker. Class description[source] st.testing.v1.element_tree.ColorPicker(proto, root) Methods pick(v) Set the value of the widget as a hex string. May omit the "#" prefix. run(*, timeout=None) Run the AppTest script which contains the element. set_value(v) Set the value of the widget as a hex string. Attributes value The currently selected value as a hex string. (str) st.testing.v1.element_tree.DateInputStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.date_input. Class description[source] st.testing.v1.element_tree.DateInput(proto, root) Methods run(*, timeout=None) Run the AppTest script which contains the element. set_value(v) Set the value of the widget. Attributes value The value of the widget. (date or Tuple of date) st.testing.v1.element_tree.MultiselectStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.multiselect. Class description[source] st.testing.v1.element_tree.Multiselect(proto, root) Methods run(*, timeout=None) Run the AppTest script which contains the element. select(v) Add a selection to the widget. Do nothing if the value is already selected. If testing a multiselect widget with repeated options, use set_value instead. set_value(v) Set the value of the multiselect widget. (list) unselect(v) Remove a selection from the widget. Do nothing if the value is not already selected. If a value is selected multiple times, the first instance is removed. Attributes format_func The widget's formatting function for displaying options. (callable) indices The indices of the currently selected values from the options. (list) value The currently selected values from the options. (list) st.testing.v1.element_tree.NumberInputStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.number_input. Class description[source] st.testing.v1.element_tree.NumberInput(proto, root) Methods decrement() Decrement the st.number_input widget as if the user clicked "-". increment() Increment the st.number_input widget as if the user clicked "+". run(*, timeout=None) Run the AppTest script which contains the element. set_value(v) Set the value of the st.number_input widget. Attributes value Get the current value of the st.number_input widget. st.testing.v1.element_tree.RadioStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.radio. Class description[source] st.testing.v1.element_tree.Radio(proto, root) Methods run(*, timeout=None) Run the AppTest script which contains the element. set_value(v) Set the selection by value. Attributes format_func The widget's formatting function for displaying options. (callable) index The index of the current selection. (int) value The currently selected value from the options. (Any) st.testing.v1.element_tree.SelectSliderStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.select_slider. Class description[source] st.testing.v1.element_tree.SelectSlider(proto, root) Methods run(*, timeout=None) Run the AppTest script which contains the element. set_range(lower, upper) Set the ranged selection by values. set_value(v) Set the (single) selection by value. Attributes format_func The widget's formatting function for displaying options. (callable) value The currently selected value or range. (Any or Sequence of Any) st.testing.v1.element_tree.SelectboxStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.selectbox. Class description[source] st.testing.v1.element_tree.Selectbox(proto, root) Methods run(*, timeout=None) Run the AppTest script which contains the element. select(v) Set the selection by value. select_index(index) Set the selection by index. set_value(v) Set the selection by value. Attributes format_func The widget's formatting function for displaying options. (callable) index The index of the current selection. (int) value The currently selected value from the options. (Any) st.testing.v1.element_tree.SliderStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.slider. Class description[source] st.testing.v1.element_tree.Slider(proto, root) Methods run(*, timeout=None) Run the AppTest script which contains the element. set_range(lower, upper) Set the ranged value of the slider. set_value(v) Set the (single) value of the slider. Attributes value The currently selected value or range. (Any or Sequence of Any) st.testing.v1.element_tree.TextAreaStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.text_area. Class description[source] st.testing.v1.element_tree.TextArea(proto, root) Methods input(v) Set the value of the widget only if the value does not exceed the maximum allowed characters. run(*, timeout=None) Run the AppTest script which contains the element. set_value(v) Set the value of the widget. Attributes value The current value of the widget. (str) st.testing.v1.element_tree.TextInputStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.text_input. Class description[source] st.testing.v1.element_tree.TextInput(proto, root) Methods input(v) Set the value of the widget only if the value does not exceed the maximum allowed characters. run(*, timeout=None) Run the AppTest script which contains the element. set_value(v) Set the value of the widget. Attributes value The current value of the widget. (str) st.testing.v1.element_tree.TimeInputStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.time_input. Class description[source] st.testing.v1.element_tree.TimeInput(proto, root) Methods decrement() Select the previous available time. increment() Select the next available time. run(*, timeout=None) Run the AppTest script which contains the element. set_value(v) Set the value of the widget. Attributes value The current value of the widget. (time) st.testing.v1.element_tree.ToggleStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.toggle. Class description[source] st.testing.v1.element_tree.Toggle(proto, root) Methods run(*, timeout=None) Run the AppTest script which contains the element. set_value(v) Set the value of the widget. Attributes value The current value of the widget. (bool) Previous: st.testing.v1.AppTestNext: Command lineforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy
https://docs.streamlit.io/deploy/tutorials/kubernetes#create-a-kubernetes-configuration-file
DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsremoveDockerKubernetesschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Deploy/Other platforms/KubernetesDeploy Streamlit using Kubernetes Introduction So you have an amazing app and you want to start sharing it with other people, what do you do? You have a few options. First, where do you want to run your Streamlit app, and how do you want to access it? On your corporate network - Most corporate networks are closed to the outside world. You typically use a VPN to log onto your corporate network and access resources there. You could run your Streamlit app on a server in your corporate network for security reasons, to ensure that only folks internal to your company can access it. On the cloud - If you'd like to access your Streamlit app from outside of a corporate network, or share your app with folks outside of your home network or laptop, you might choose this option. In this case, it'll depend on your hosting provider. We have community-submitted guides from Heroku, AWS, and other providers. Wherever you decide to deploy your app, you will first need to containerize it. This guide walks you through using Kubernetes to deploy your app. If you prefer Docker see Deploy Streamlit using Docker. Prerequisites Install Docker Engine Install the gcloud CLI Install Docker Engine If you haven't already done so, install Docker on your server. Docker provides .deb and .rpm packages from many Linux distributions, including: Debian Ubuntu Verify that Docker Engine is installed correctly by running the hello-world Docker image: sudo docker run hello-world starTipFollow Docker's official post-installation steps for Linux to run Docker as a non-root user, so that you don't have to preface the docker command with sudo. Install the gcloud CLI In this guide, we will orchestrate Docker containers with Kubernetes and host docker images on the Google Container Registry (GCR). As GCR is a Google-supported Docker registry, we need to register gcloud as the Docker credential helper. Follow the official documentation to Install the gcloud CLI and initialize it. Create a Docker container We need to create a docker container which contains all the dependencies and the application code. Below you can see the entrypoint, i.e. the command run when the container starts, and the Dockerfile definition. Create an entrypoint script Create a run.sh script containing the following: #!/bin/bash APP_PID= stopRunningProcess() { # Based on https://linuxconfig.org/how-to-propagate-a-signal-to-child-processes-from-a-bash-script if test ! "${APP_PID}" = '' && ps -p ${APP_PID} > /dev/null ; then > /proc/1/fd/1 echo "Stopping ${COMMAND_PATH} which is running with process ID ${APP_PID}" kill -TERM ${APP_PID} > /proc/1/fd/1 echo "Waiting for ${COMMAND_PATH} to process SIGTERM signal" wait ${APP_PID} > /proc/1/fd/1 echo "All processes have stopped running" else > /proc/1/fd/1 echo "${COMMAND_PATH} was not started when the signal was sent or it has already been stopped" fi } trap stopRunningProcess EXIT TERM source ${VIRTUAL_ENV}/bin/activate streamlit run ${HOME}/app/streamlit_app.py & APP_ID=${!} wait ${APP_ID} Create a Dockerfile Docker builds images by reading the instructions from a Dockerfile. A Dockerfile is a text document that contains all the commands a user could call on the command line to assemble an image. Learn more in the Dockerfile reference. The docker build command builds an image from a Dockerfile. The docker run command first creates a container over the specified image, and then starts it using the specified command. Here's an example Dockerfile that you can add to the root of your directory. FROM python:3.8-slim RUN groupadd --gid 1000 appuser \ && useradd --uid 1000 --gid 1000 -ms /bin/bash appuser RUN pip3 install --no-cache-dir --upgrade \ pip \ virtualenv RUN apt-get update && apt-get install -y \ build-essential \ software-properties-common \ git USER appuser WORKDIR /home/appuser RUN git clone https://github.com/streamlit/streamlit-example.git app ENV VIRTUAL_ENV=/home/appuser/venv RUN virtualenv ${VIRTUAL_ENV} RUN . ${VIRTUAL_ENV}/bin/activate && pip install -r app/requirements.txt EXPOSE 8501 COPY run.sh /home/appuser ENTRYPOINT ["./run.sh"] priority_highImportantAs mentioned in Development flow, for Streamlit version 1.10.0 and higher, Streamlit apps cannot be run from the root directory of Linux distributions. Your main script should live in a directory other than the root directory. If you try to run a Streamlit app from the root directory, Streamlit will throw a FileNotFoundError: [Errno 2] No such file or directory error. For more information, see GitHub issue #5239.If you are using Streamlit version 1.10.0 or higher, you must set the WORKDIR to a directory other than the root directory. For example, you can set the WORKDIR to /home/appuser as shown in the example Dockerfile above. Build a Docker image Put the above files (run.sh and Dockerfile) in the same folder and build the docker image: docker build --platform linux/amd64 -t gcr.io/$GCP_PROJECT_ID/k8s-streamlit:test . priority_highImportantReplace $GCP_PROJECT_ID in the above command with the name of your Google Cloud project. Upload the Docker image to a container registry The next step is to upload the Docker image to a container registry. In this example, we will use the Google Container Registry (GCR). Start by enabling the Container Registry API. Sign in to Google Cloud and navigate to your project’s Container Registry and click Enable. We can now build the Docker image from the previous step and push it to our project’s GCR. Be sure to replace $GCP_PROJECT_ID in the docker push command with the name of your project: gcloud auth configure-docker docker push gcr.io/$GCP_PROJECT_ID/k8s-streamlit:test Create a Kubernetes deployment For this step you will need a: Running Kubernetes service Custom domain for which you can generate a TLS certificate DNS service where you can configure your custom domain to point to the application IP As the image was uploaded to the container registry in the previous step, we can run it in Kubernetes using the below configurations. Install and run Kubernetes Make sure your Kubernetes client, kubectl, is installed and running on your machine. Configure a Google OAuth Client and oauth2-proxy For configuring the Google OAuth Client, please see Google Auth Provider. Configure oauth2-proxy to use the desired OAuth Provider Configuration and update the oath2-proxy config in the config map. The below configuration contains a ouath2-proxy sidecar container which handles the authentication with Google. You can learn more from the oauth2-proxy repository. Create a Kubernetes configuration file Create a YAML configuration file named k8s-streamlit.yaml: apiVersion: v1 kind: ConfigMap metadata: name: streamlit-configmap data: oauth2-proxy.cfg: |- http_address = "0.0.0.0:4180" upstreams = ["http://127.0.0.1:8501/"] email_domains = ["*"] client_id = "<GOOGLE_CLIENT_ID>" client_secret = "<GOOGLE_CLIENT_SECRET>" cookie_secret = "<16, 24, or 32 bytes>" redirect_url = <REDIRECT_URL> --- apiVersion: apps/v1 kind: Deployment metadata: name: streamlit-deployment labels: app: streamlit spec: replicas: 1 selector: matchLabels: app: streamlit template: metadata: labels: app: streamlit spec: containers: - name: oauth2-proxy image: quay.io/oauth2-proxy/oauth2-proxy:v7.2.0 args: ["--config", "/etc/oauth2-proxy/oauth2-proxy.cfg"] ports: - containerPort: 4180 livenessProbe: httpGet: path: /ping port: 4180 scheme: HTTP readinessProbe: httpGet: path: /ping port: 4180 scheme: HTTP volumeMounts: - mountPath: "/etc/oauth2-proxy" name: oauth2-config - name: streamlit image: gcr.io/GCP_PROJECT_ID/k8s-streamlit:test imagePullPolicy: Always ports: - containerPort: 8501 livenessProbe: httpGet: path: /_stcore/health port: 8501 scheme: HTTP timeoutSeconds: 1 readinessProbe: httpGet: path: /_stcore/health port: 8501 scheme: HTTP timeoutSeconds: 1 resources: limits: cpu: 1 memory: 2Gi requests: cpu: 100m memory: 745Mi volumes: - name: oauth2-config configMap: name: streamlit-configmap --- apiVersion: v1 kind: Service metadata: name: streamlit-service spec: type: LoadBalancer selector: app: streamlit ports: - name: streamlit-port protocol: TCP port: 80 targetPort: 4180 priority_highImportantWhile the above configurations can be copied verbatim, you will have to configure the oauth2-proxy yourself and use the correct GOOGLE_CLIENT_ID, GOOGLE_CLIENT_ID, GCP_PROJECT_ID, and REDIRECT_URL. Now create the configuration from the file in Kubernetes with the kubectl create command: kubctl create -f k8s-streamlit.yaml Set up TLS support Since you are using the Google authentication, you will need to set up TLS support. Find out how in TLS Configuration. Verify the deployment Once the deployment and the service are created, we need to wait a couple of minutes for the public IP address to become available. We can check when that is ready by running: kubectl get service streamlit-service -o jsonpath='{.status.loadBalancer.ingress[0].ip}' After the public IP is assigned, you will need to configure in your DNS service an A record pointing to the above IP address.Previous: DockerNext: Knowledge baseforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy
https://docs.streamlit.io/develop/api-reference/configuration/config.toml
DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceremovePAGE ELEMENTSWrite and magicaddText elementsaddData elementsaddChart elementsaddInput widgetsaddMedia elementsaddLayouts and containersaddChat elementsaddStatus elementsaddThird-party componentsopen_in_newAPPLICATION LOGICNavigation and pagesaddExecution flowaddCaching and stateaddConnections and secretsaddCustom componentsaddUtilitiesaddConfigurationremoveconfig.tomlst.set_page_configTOOLSApp testingaddCommand lineaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Develop/API reference/Configuration/config.tomlconfig.toml config.toml is an optional file you can define for your working directory or global development environment. When config.toml is defined both globally and in your working directory, Streamlit combines the configuration options and gives precendence to the working-directory configuration. Additionally, you can use environment variables and command-line options to override additional configuration options. For more information, see Configuration options. File location To define your configuration locally or per-project, add .streamlit/config.toml to your working directory. Your working directory is wherever you call streamlit run. If you haven't previously created the .streamlit directory, you will need to add it. To define your configuration globally, you must first locate your global .streamlit directory. Streamlit adds this hidden directory to your OS user profile during installation. For MacOS/Linx, this will be ~/.streamlit/config.toml. For Windows, this will be %userprofile%/.streamlit/config.toml. File format config.toml is a TOML file. Example [client] showErrorDetails = false [theme] primaryColor = "#F63366" backgroundColor = "black" Available configuration options Below are all the sections and options you can have in your .streamlit/config.toml file. To see all configurations, use the following command in your terminal or CLI: streamlit config show Global [global] # ***DEPRECATED*** # global.disableWatchdogWarning has been deprecated has been deprecated and # will be removed in a future version. This option will be removed on or after # 2024-01-20. # **************** # By default, Streamlit checks if the Python watchdog module is available # and, if not, prints a warning asking for you to install it. The watchdog # module is not required, but highly recommended. It improves Streamlit's # ability to detect changes to files in your filesystem. # If you'd like to turn off this warning, set this to True. # Default: false disableWatchdogWarning = false # By default, Streamlit displays a warning when a user sets both a widget # default value in the function defining the widget and a widget value via # the widget's key in `st.session_state`. # If you'd like to turn off this warning, set this to True. # Default: false disableWidgetStateDuplicationWarning = false # If True, will show a warning when you run a Streamlit-enabled script # via "python my_script.py". # Default: true showWarningOnDirectExecution = true Logger [logger] # Level of logging: 'error', 'warning', 'info', or 'debug'. # Default: 'info' level = "info" # String format for logging messages. If logger.datetimeFormat is set, # logger messages will default to `%(asctime)s.%(msecs)03d %(message)s`. See # Python's documentation for available attributes: # https://docs.python.org/2.6/develop/logging.html#formatter-objects # Default: "%(asctime)s %(message)s" messageFormat = "%(asctime)s %(message)s" Client [client] # ***DEPRECATED*** # client.caching has been deprecated and is not required anymore for our new # caching commands. This option will be removed on or after 2024-01-20. # **************** # Whether to enable st.cache. This does not affect st.cache_data or # st.cache_resource. # Default: true caching = true # ***DEPRECATED*** # client.displayEnabled has been deprecated and will be removed in a future # version. This option will be removed on or after 2024-01-20. # **************** # If false, makes your Streamlit script not draw to a Streamlit app. # Default: true displayEnabled = true # Controls whether uncaught app exceptions and deprecation warnings # are displayed in the browser. By default, this is set to True and # Streamlit displays app exceptions and associated tracebacks, and # deprecation warnings, in the browser. # # If set to False, deprecation warnings and full exception messages # will print to the console only. Exceptions will still display in the # browser with a generic error message. For now, the exception type and # traceback show in the browser also, but they will be removed in the # future. # Default: true showErrorDetails = true # Change the visibility of items in the toolbar, options menu, # and settings dialog (top right of the app). # Allowed values: # * "auto" : Show the developer options if the app is accessed through # localhost or through Streamlit Community Cloud as a developer. # Hide them otherwise. # * "developer" : Show the developer options. # * "viewer" : Hide the developer options. # * "minimal" : Show only options set externally (e.g. through # Streamlit Community Cloud) or through st.set_page_config. # If there are no options left, hide the menu. # Default: "auto" toolbarMode = "auto" # Controls whether the default sidebar page navigation in a multipage app is # displayed. # Default: true showSidebarNavigation = true Runner [runner] # Allows you to type a variable or string by itself in a single line of # Python code to write it to the app. # Default: true magicEnabled = true # ***DEPRECATED*** # runner.installTracer has been deprecated and will be removed in a future # version. This option will be removed on or after 2024-01-20. # **************** # Install a Python tracer to allow you to stop or pause your script at # any point and introspect it. As a side-effect, this slows down your # script's execution. # Default: false installTracer = false # ***DEPRECATED*** # runner.fixMatplotlib has been deprecated and will be removed in a future # version. This option will be removed on or after 2024-01-20. # **************** # Sets the MPLBACKEND environment variable to Agg inside Streamlit to # prevent Python crashing. # Default: true fixMatplotlib = true # Handle script rerun requests immediately, rather than waiting for script # execution to reach a yield point. This makes Streamlit much more # responsive to user interaction, but it can lead to race conditions in # apps that mutate session_state data outside of explicit session_state # assignment statements. # Default: true fastReruns = true # Raise an exception after adding unserializable data to Session State. # Some execution environments may require serializing all data in Session # State, so it may be useful to detect incompatibility during development, # or when the execution environment will stop supporting it in the future. # Default: false enforceSerializableSessionState = false # Adjust how certain 'options' widgets like radio, selectbox, and # multiselect coerce Enum members when the Enum class gets # re-defined during a script re-run. For more information, check out the docs: # https://docs.streamlit.io/develop/concepts/design/custom-classes#enums # # Allowed values: # * "off" : Disables Enum coercion. # * "nameOnly" : Enum classes can be coerced if their member names match. # * "nameAndValue" : Enum classes can be coerced if their member names AND # member values match. # Default: "nameOnly" enumCoercion = "nameOnly" Server [server] # List of folders that should not be watched for changes. This # impacts both "Run on Save" and @st.cache. # Relative paths will be taken as relative to the current working directory. # Example: ['/home/user1/env', 'relative/path/to/folder'] # Default: [] folderWatchBlacklist = [] # Change the type of file watcher used by Streamlit, or turn it off # completely. # Allowed values: # * "auto" : Streamlit will attempt to use the watchdog module, and # falls back to polling if watchdog is not available. # * "watchdog" : Force Streamlit to use the watchdog module. # * "poll" : Force Streamlit to always use polling. # * "none" : Streamlit will not watch files. # Default: "auto" fileWatcherType = "auto" # Symmetric key used to produce signed cookies. If deploying on multiple # replicas, this should be set to the same value across all replicas to ensure # they all share the same secret. # Default: randomly generated secret key. cookieSecret = "a-random-key-appears-here" # If false, will attempt to open a browser window on start. # Default: false unless (1) we are on a Linux box where DISPLAY is unset, or # (2) we are running in the Streamlit Atom plugin. headless = false # Automatically rerun script when the file is modified on disk. # Default: false runOnSave = false # The address where the server will listen for client and browser # connections. Use this if you want to bind the server to a specific address. # If set, the server will only be accessible from this address, and not from # any aliases (like localhost). # Default: (unset) address = # The port where the server will listen for browser connections. # Don't use port 3000 which is reserved for internal development. # Default: 8501 port = 8501 # The base path for the URL where Streamlit should be served from. # Default: "" baseUrlPath = "" # Enables support for Cross-Origin Resource Sharing (CORS) protection, for # added security. # Due to conflicts between CORS and XSRF, if `server.enableXsrfProtection` is # on and `server.enableCORS` is off at the same time, we will prioritize # `server.enableXsrfProtection`. # Default: true enableCORS = true # Enables support for Cross-Site Request Forgery (XSRF) protection, for added # security. # Due to conflicts between CORS and XSRF, if `server.enableXsrfProtection` is # on and `server.enableCORS` is off at the same time, we will prioritize # `server.enableXsrfProtection`. # Default: true enableXsrfProtection = true # Max size, in megabytes, for files uploaded with the file_uploader. # Default: 200 maxUploadSize = 200 # Max size, in megabytes, of messages that can be sent via the WebSocket # connection. # Default: 200 maxMessageSize = 200 # Enables support for websocket compression. # Default: false enableWebsocketCompression = false # Enable serving files from a `static` directory in the running app's # directory. # Default: false enableStaticServing = false # Server certificate file for connecting via HTTPS. # Must be set at the same time as "server.sslKeyFile". # ['DO NOT USE THIS OPTION IN A PRODUCTION ENVIRONMENT. It has not gone through # security audits or performance tests. For the production environment, we # recommend performing SSL termination by the load balancer or the reverse # proxy.'] # sslCertFile = # Cryptographic key file for connecting via HTTPS. # Must be set at the same time as "server.sslCertFile". # ['DO NOT USE THIS OPTION IN A PRODUCTION ENVIRONMENT. It has not gone through # security audits or performance tests. For the production environment, we # recommend performing SSL termination by the load balancer or the reverse # proxy.'] # sslKeyFile = Browser [browser] # Internet address where users should point their browsers in order to # connect to the app. Can be IP address or DNS name and path. # This is used to: # - Set the correct URL for CORS and XSRF protection purposes. # - Show the URL on the terminal # - Open the browser # Default: "localhost" serverAddress = "localhost" # Whether to send usage statistics to Streamlit. # Default: true gatherUsageStats = true # Port where users should point their browsers in order to connect to the # app. # This is used to: # - Set the correct URL for XSRF protection purposes. # - Show the URL on the terminal (part of `streamlit run`). # - Open the browser automatically (part of `streamlit run`). # This option is for advanced use cases. To change the port of your app, use # `server.Port` instead. Don't use port 3000 which is reserved for internal # development. # Default: whatever value is set in server.port. serverPort = 8501 Mapbox [mapbox] # Configure Streamlit to use a custom Mapbox # token for elements like st.pydeck_chart and st.map. # To get a token for yourself, create an account at # https://mapbox.com. It's free (for moderate usage levels)! # Default: "" token = "" Deprecation [deprecation] # Set to false to disable the deprecation warning for using the global pyplot # instance. # Default: true showPyplotGlobalUse = true Theme [theme] # The preset Streamlit theme that your custom theme inherits from. # One of "light" or "dark". # base = # Primary accent color for interactive elements. # primaryColor = # Background color for the main content area. # backgroundColor = # Background color used for the sidebar and most interactive widgets. # secondaryBackgroundColor = # Color used for almost all text. # textColor = # Font family for all text in the app, except code blocks. One of "sans serif", # "serif", or "monospace". # font = Previous: ConfigurationNext: st.set_page_configforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy
https://docs.streamlit.io/develop/api-reference/widgets/st.select_slider#featured-videos
DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceremovePAGE ELEMENTSWrite and magicaddText elementsaddData elementsaddChart elementsaddInput widgetsremoveBUTTONSst.buttonst.download_buttonst.form_submit_buttonlinkst.link_buttonst.page_linkSELECTIONSst.checkboxst.color_pickerst.multiselectst.radiost.selectboxst.select_sliderst.toggleNUMERICst.number_inputst.sliderDATE & TIMEst.date_inputst.time_inputTEXTst.chat_inputlinkst.text_areast.text_inputMEDIA & FILESst.camera_inputst.data_editorlinkst.file_uploaderMedia elementsaddLayouts and containersaddChat elementsaddStatus elementsaddThird-party componentsopen_in_newAPPLICATION LOGICNavigation and pagesaddExecution flowaddCaching and stateaddConnections and secretsaddCustom componentsaddUtilitiesaddConfigurationaddTOOLSApp testingaddCommand lineaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Develop/API reference/Input widgets/st.select_sliderst.select_sliderStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeDisplay a slider widget to select items from a list. This also allows you to render a range slider by passing a two-element tuple or list as the value. The difference between st.select_slider and st.slider is that select_slider accepts any datatype and takes an iterable set of options, while st.slider only accepts numerical or date/time data and takes a range as input. Function signature[source] st.select_slider(label, options=(), value=None, format_func=special_internal_function, key=None, help=None, on_change=None, args=None, kwargs=None, *, disabled=False, label_visibility="visible") Parameters label (str) A short label explaining to the user what this slider is for. The label can optionally contain Markdown and supports the following elements: Bold, Italics, Strikethroughs, Inline Code, Emojis, and Links. This also supports: Emoji shortcodes, such as :+1: and :sunglasses:. For a list of all supported codes, see https://share.streamlit.io/streamlit/emoji-shortcodes. LaTeX expressions, by wrapping them in "$" or "$$" (the "$$" must be on their own lines). Supported LaTeX functions are listed at https://katex.org/docs/supported.html. Colored text and background colors for text, using the syntax :color[text to be colored] and :color-background[text to be colored], respectively. color must be replaced with any of the following supported colors: blue, green, orange, red, violet, gray/grey, rainbow. For example, you can use :orange[your text here] or :blue-background[your text here]. Unsupported elements are unwrapped so only their children (text contents) render. Display unsupported elements as literal characters by backslash-escaping them. E.g. 1\. Not an ordered list. For accessibility reasons, you should never set an empty label (label="") but hide it with label_visibility if needed. In the future, we may disallow empty labels by raising an exception. options (Iterable) Labels for the select options in an Iterable. For example, this can be a list, numpy.ndarray, pandas.Series, pandas.DataFrame, or pandas.Index. For pandas.DataFrame, the first column is used. Each label will be cast to str internally by default. value (a supported type or a tuple/list of supported types or None) The value of the slider when it first renders. If a tuple/list of two values is passed here, then a range slider with those lower and upper bounds is rendered. For example, if set to (1, 10) the slider will have a selectable range between 1 and 10. Defaults to first option. format_func (function) Function to modify the display of the labels from the options. argument. It receives the option as an argument and its output will be cast to str. key (str or int) An optional string or integer to use as the unique key for the widget. If this is omitted, a key will be generated for the widget based on its content. Multiple widgets of the same type may not share the same key. help (str) An optional tooltip that gets displayed next to the select slider. on_change (callable) An optional callback invoked when this select_slider's value changes. args (tuple) An optional tuple of args to pass to the callback. kwargs (dict) An optional dict of kwargs to pass to the callback. disabled (bool) An optional boolean, which disables the select slider if set to True. The default is False. label_visibility ("visible", "hidden", or "collapsed") The visibility of the label. If "hidden", the label doesn't show but there is still empty space for it above the widget (equivalent to label=""). If "collapsed", both the label and the space are removed. Default is "visible". Returns(any value or tuple of any value) The current value of the slider widget. The return type will match the data type of the value parameter. Examples import streamlit as st color = st.select_slider( "Select a color of the rainbow", options=["red", "orange", "yellow", "green", "blue", "indigo", "violet"]) st.write("My favorite color is", color) And here's an example of a range select slider: import streamlit as st start_color, end_color = st.select_slider( "Select a range of color wavelength", options=["red", "orange", "yellow", "green", "blue", "indigo", "violet"], value=("red", "blue")) st.write("You selected wavelengths between", start_color, "and", end_color) Built with Streamlit 🎈Fullscreen open_in_new Featured videos Check out our video on how to use one of Streamlit's core functions, the select slider! 🎈 In the video below, we'll take it a step further and make a double-ended slider. Previous: st.selectboxNext: st.toggleforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy
https://docs.streamlit.io/develop/api-reference/data/st.data_editor#configuring-columns
DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceremovePAGE ELEMENTSWrite and magicaddText elementsaddData elementsremovest.dataframest.data_editorst.column_configaddst.tablest.metricst.jsonChart elementsaddInput widgetsaddMedia elementsaddLayouts and containersaddChat elementsaddStatus elementsaddThird-party componentsopen_in_newAPPLICATION LOGICNavigation and pagesaddExecution flowaddCaching and stateaddConnections and secretsaddCustom componentsaddUtilitiesaddConfigurationaddTOOLSApp testingaddCommand lineaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Develop/API reference/Data elements/st.data_editorstarTipThis page only contains information on the st.data_editor API. For an overview of working with dataframes and to learn more about the data editor's capabilities and limitations, read Dataframes. st.data_editorStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeDisplay a data editor widget. The data editor widget allows you to edit dataframes and many other data structures in a table-like UI. Warning When going from st.experimental_data_editor to st.data_editor in 1.23.0, the data editor's representation in st.session_state was changed. The edited_cells dictionary is now called edited_rows and uses a different format ({0: {"column name": "edited value"}} instead of {"0:1": "edited value"}). You may need to adjust the code if your app uses st.experimental_data_editor in combination with st.session_state. Function signature[source] st.data_editor(data, *, width=None, height=None, use_container_width=False, hide_index=None, column_order=None, column_config=None, num_rows="fixed", disabled=False, key=None, on_change=None, args=None, kwargs=None) Parameters data (pandas.DataFrame, pandas.Series, pandas.Styler, pandas.Index, pyarrow.Table, numpy.ndarray, pyspark.sql.DataFrame, snowflake.snowpark.DataFrame, list, set, tuple, dict, or None) The data to edit in the data editor. Note Styles from pandas.Styler will only be applied to non-editable columns. Mixing data types within a column can make the column uneditable. Additionally, the following data types are not yet supported for editing: complex, list, tuple, bytes, bytearray, memoryview, dict, set, frozenset, fractions.Fraction, pandas.Interval, and pandas.Period. To prevent overflow in JavaScript, columns containing datetime.timedelta and pandas.Timedelta values will default to uneditable but this can be changed through column configuration. width (int or None) Desired width of the data editor expressed in pixels. If None, the width will be automatically determined. height (int or None) Desired height of the data editor expressed in pixels. If None, the height will be automatically determined. use_container_width (bool) If True, set the data editor width to the width of the parent container. This takes precedence over the width argument. Defaults to False. hide_index (bool or None) Whether to hide the index column(s). If None (default), the visibility of index columns is automatically determined based on the data. column_order (Iterable of str or None) Specifies the display order of columns. This also affects which columns are visible. For example, column_order=("col2", "col1") will display 'col2' first, followed by 'col1', and will hide all other non-index columns. If None (default), the order is inherited from the original data structure. column_config (dict or None) Configures how columns are displayed, e.g. their title, visibility, type, or format, as well as editing properties such as min/max value or step. This needs to be a dictionary where each key is a column name and the value is one of: None to hide the column. A string to set the display label of the column. One of the column types defined under st.column_config, e.g. st.column_config.NumberColumn("Dollar values”, format=”$ %d") to show a column as dollar amounts. See more info on the available column types and config options here. To configure the index column(s), use _index as the column name. num_rows ("fixed" or "dynamic") Specifies if the user can add and delete rows in the data editor. If "fixed", the user cannot add or delete rows. If "dynamic", the user can add and delete rows in the data editor, but column sorting is disabled. Defaults to "fixed". disabled (bool or Iterable of str) Controls the editing of columns. If True, editing is disabled for all columns. If an Iterable of column names is provided (e.g., disabled=("col1", "col2")), only the specified columns will be disabled for editing. If False (default), all columns that support editing are editable. key (str) An optional string to use as the unique key for this widget. If this is omitted, a key will be generated for the widget based on its content. Multiple widgets of the same type may not share the same key. on_change (callable) An optional callback invoked when this data_editor's value changes. args (tuple) An optional tuple of args to pass to the callback. kwargs (dict) An optional dict of kwargs to pass to the callback. Returns(pandas.DataFrame, pandas.Series, pyarrow.Table, numpy.ndarray, list, set, tuple, or dict.) The edited data. The edited data is returned in its original data type if it corresponds to any of the supported return types. All other data types are returned as a pandas.DataFrame. Examples import streamlit as st import pandas as pd df = pd.DataFrame( [ {"command": "st.selectbox", "rating": 4, "is_widget": True}, {"command": "st.balloons", "rating": 5, "is_widget": False}, {"command": "st.time_input", "rating": 3, "is_widget": True}, ] ) edited_df = st.data_editor(df) favorite_command = edited_df.loc[edited_df["rating"].idxmax()]["command"] st.markdown(f"Your favorite command is **{favorite_command}** 🎈") Built with Streamlit 🎈Fullscreen open_in_new You can also allow the user to add and delete rows by setting num_rows to "dynamic": import streamlit as st import pandas as pd df = pd.DataFrame( [ {"command": "st.selectbox", "rating": 4, "is_widget": True}, {"command": "st.balloons", "rating": 5, "is_widget": False}, {"command": "st.time_input", "rating": 3, "is_widget": True}, ] ) edited_df = st.data_editor(df, num_rows="dynamic") favorite_command = edited_df.loc[edited_df["rating"].idxmax()]["command"] st.markdown(f"Your favorite command is **{favorite_command}** 🎈") Built with Streamlit 🎈Fullscreen open_in_new Or you can customize the data editor via column_config, hide_index, column_order, or disabled: import pandas as pd import streamlit as st df = pd.DataFrame( [ {"command": "st.selectbox", "rating": 4, "is_widget": True}, {"command": "st.balloons", "rating": 5, "is_widget": False}, {"command": "st.time_input", "rating": 3, "is_widget": True}, ] ) edited_df = st.data_editor( df, column_config={ "command": "Streamlit Command", "rating": st.column_config.NumberColumn( "Your rating", help="How much do you like this command (1-5)?", min_value=1, max_value=5, step=1, format="%d ⭐", ), "is_widget": "Widget ?", }, disabled=["command", "is_widget"], hide_index=True, ) favorite_command = edited_df.loc[edited_df["rating"].idxmax()]["command"] st.markdown(f"Your favorite command is **{favorite_command}** 🎈") Built with Streamlit 🎈Fullscreen open_in_new Configuring columns You can configure the display and editing behavior of columns in st.dataframe and st.data_editor via the Column configuration API. We have developed the API to let you add images, charts, and clickable URLs in dataframe and data editor columns. Additionally, you can make individual columns editable, set columns as categorical and specify which options they can take, hide the index of the dataframe, and much more. Built with Streamlit 🎈Fullscreen open_in_newPrevious: st.dataframeNext: st.column_configforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy
https://docs.streamlit.io/deploy/streamlit-community-cloud/share-your-app#invite-viewers-from-the-share-button
DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudremoveGet startedaddDeploy your appaddManage your appaddShare your appremoveEmbed your appSearch indexabilityShare previewsManage your accountaddTroubleshootingStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Deploy/Streamlit Community Cloud/Share your appShare your app Now that your app is deployed you can easily share it and collaborate on it. But first, let's take a moment and do a little joy dance for getting that app deployed! 🕺💃 Your app is now live at a fixed URL, so go wild and share it with whomever you want. Your app will inherit permissions from your GitHub repo, meaning that if your repo is private your app will be private and if your repo is public your app will be public. If you want to change that you can simply do so from the app settings menu. You are only allowed one private app at a time. If you've deployed from a private repository, you will have to make that app public or delete it before you can deploy another app from a private repository. Only developers can change your app between public and private. Make your app public or private Share your public app Share your private app Make your app public or private If you deployed your app from a public repository, your app will be public by default. If you deployed your app from a private repository, you will need to make the app public if you want to freely share it with the community at large. Set privacy from your app settings Access your App settings and go to the "Sharing" section. Set your app's privacy under "Who can view this app." Select "This app is public and searchable" to make your app public. Select "Only specific people can view this app" to make your app private. Set privacy from the share button From your app at <your-custom-subdomain>.streamlit.app, click "Share" in the upper-right corner. Toggle your app between public and private by clicking "Make this app public". Share your public app Once your app is public, just give anyone your app's URL and they view it! Streamlit Community Cloud has several convenient shortcuts for sharing your app. Share your app on social media From your app at <your-custom-subdomain>.streamlit.app, click "Share" in the upper-right corner. Click "Social" to access convenient social media share buttons. starTipUse the social media sharing buttons to post your app on our forum! We'd love to see what you make and perhaps feature your app as our app of the month. 💖 Invite viewers by email Whether your app is public or private, you can send an email invite to your app directly from Streamlit Community Cloud. This grants the viewer access to analytics for all your public apps and the ability to invite other viewers to your workspace. Developers and invited viewers are identified by their email in analytics instead of appearing anonymously (if they view any of your apps while logged in). Read more about viewers in App analytics. From your app at <your-custom-subdomain>.streamlit.app, click "Share" in the upper-right corner. Enter an email address and click "Invite". Invited users will get a direct link to your app in their inbox. Copy your app's URL You can convenitiently copy your app's URL from the share menu or from your workspace. From your app click "Share" in the upper-right corner then click "Copy link". From your workspace click the overflow menu icon (more_vert) then click "Copy URL". Add a badge to your GitHub repository To help others find and play with your Streamlit app, you can add Streamlit's GitHub badge to your repo. Below is an enlarged example of what the badge looks like. Clicking on the badge takes you to—in this case—Streamlit's Roadmap. Once you deploy your app, you can embed this badge right into your GitHub README.md by adding the following Markdown: [![Streamlit App](https://static.streamlit.io/badges/streamlit_badge_black_white.svg)](https://<your-custom-subdomain>.streamlit.app) push_pinNoteBe sure to replace https://<your-custom-subdomain>.streamlit.app with the URL of your deployed app! Share your private app By default an app deployed from a private repository will be private to the developers in the workspace. A private app will not be visible to anyone else unless you grant them explicit permission. You can grant permission by adding them as a developer on GitHub or by adding them as a viewer on Streamlit Community Cloud. Once you have added someone's email address to your app's viewer list, that person will be able to sign in and view your private app. If their email is associated to a Google account, they will be able to sign in with Google OAuth. Otherwise, they will be able to sign in with single-use, emailed links. Streamlit sends an email invitation with a link to your app every time you invite someone. priority_highImportantWhen you add a viewer to any app in your workspace, they are granted access to analytics for that app as well as analytics for all your public apps. They can also pass these permissions to others by inviting more viewers. All viewers and developers in your workspace are identified by their email in analytics. Furthermore, their emails show in analytics for every app in your workspace and not just apps they are explicitly invited to. Read more about viewers in App analytics Invite viewers from the share button From your app at <your-custom-subdomain>.streamlit.app, click "Share" in the upper-right corner. Enter the email to send an invitation to and click "Invite". Invited users appear in the list below. Invited users will get a direct link to your app in their inbox. To remove a viewer, simply access the share menu as above and click the close next to their name. Invite viewers from your app settings Access your App settings and go to the "Sharing" section. Add or remove users from the list of viewers. Click "Save". Previous: Manage your appNext: Embed your appforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy
https://docs.streamlit.io/knowledge-base/tutorials/build-conversational-apps#add-openai-api-key-to-streamlit-secrets
DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceaddTutorialsremoveExecution flowaddConnect to data sourcesaddMultipage appsaddWork with LLMsremoveBuild a basic LLM chat appBuild an LLM app using LangChainQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Develop/Tutorials/Work with LLMs/Build a basic LLM chat appBuild a basic LLM chat app Introduction The advent of large language models like GPT has revolutionized the ease of developing chat-based applications. Streamlit offers several Chat elements, enabling you to build Graphical User Interfaces (GUIs) for conversational agents or chatbots. Leveraging session state along with these elements allows you to construct anything from a basic chatbot to a more advanced, ChatGPT-like experience using purely Python code. In this tutorial, we'll start by walking through Streamlit's chat elements, st.chat_message and st.chat_input. Then we'll proceed to construct three distinct applications, each showcasing an increasing level of complexity and functionality: First, we'll Build a bot that mirrors your input to get a feel for the chat elements and how they work. We'll also introduce session state and how it can be used to store the chat history. This section will serve as a foundation for the rest of the tutorial. Next, you'll learn how to Build a simple chatbot GUI with streaming. Finally, we'll Build a ChatGPT-like app that leverages session state to remember conversational context, all within less than 50 lines of code. Here's a sneak peek of the LLM-powered chatbot GUI with streaming we'll build in this tutorial: Built with Streamlit 🎈Fullscreen open_in_new Play around with the above demo to get a feel for what we'll build in this tutorial. A few things to note: There's a chat input at the bottom of the screen that's always visible. It contains some placeholder text. You can type in a message and press Enter or click the run button to send it. When you enter a message, it appears as a chat message in the container above. The container is scrollable, so you can scroll up to see previous messages. A default avatar is displayed to your messages' left. The assistant's responses are streamed to the frontend and are displayed with a different default avatar. Before we start building, let's take a closer look at the chat elements we'll use. Chat elements Streamlit offers several commands to help you build conversational apps. These chat elements are designed to be used in conjunction with each other, but you can also use them separately. st.chat_message lets you insert a chat message container into the app so you can display messages from the user or the app. Chat containers can contain other Streamlit elements, including charts, tables, text, and more. st.chat_input lets you display a chat input widget so the user can type in a message. For an overview of the API, check out this video tutorial by Chanin Nantasenamat (@dataprofessor), a Senior Developer Advocate at Streamlit. st.chat_message st.chat_message lets you insert a multi-element chat message container into your app. The returned container can contain any Streamlit element, including charts, tables, text, and more. To add elements to the returned container, you can use with notation. st.chat_message's first parameter is the name of the message author, which can be either "user" or "assistant" to enable preset styling and avatars, like in the demo above. You can also pass in a custom string to use as the author name. Currently, the name is not shown in the UI but is only set as an accessibility label. For accessibility reasons, you should not use an empty string. Here's an minimal example of how to use st.chat_message to display a welcome message: import streamlit as st with st.chat_message("user"): st.write("Hello 👋") Notice the message is displayed with a default avatar and styling since we passed in "user" as the author name. You can also pass in "assistant" as the author name to use a different default avatar and styling, or pass in a custom name and avatar. See the API reference for more details. import streamlit as st import numpy as np with st.chat_message("assistant"): st.write("Hello human") st.bar_chart(np.random.randn(30, 3)) Built with Streamlit 🎈Fullscreen open_in_new While we've used the preferred with notation in the above examples, you can also just call methods directly in the returned objects. The below example is equivalent to the one above: import streamlit as st import numpy as np message = st.chat_message("assistant") message.write("Hello human") message.bar_chart(np.random.randn(30, 3)) So far, we've displayed predefined messages. But what if we want to display messages based on user input? st.chat_input st.chat_input lets you display a chat input widget so the user can type in a message. The returned value is the user's input, which is None if the user hasn't sent a message yet. You can also pass in a default prompt to display in the input widget. Here's an example of how to use st.chat_input to display a chat input widget and show the user's input: import streamlit as st prompt = st.chat_input("Say something") if prompt: st.write(f"User has sent the following prompt: {prompt}") Built with Streamlit 🎈Fullscreen open_in_new Pretty straightforward, right? Now let's combine st.chat_message and st.chat_input to build a bot the mirrors or echoes your input. Build a bot that mirrors your input In this section, we'll build a bot that mirrors or echoes your input. More specifically, the bot will respond to your input with the same message. We'll use st.chat_message to display the user's input and st.chat_input to accept user input. We'll also use session state to store the chat history so we can display it in the chat message container. First, let's think about the different components we'll need to build our bot: Two chat message containers to display messages from the user and the bot, respectively. A chat input widget so the user can type in a message. A way to store the chat history so we can display it in the chat message containers. We can use a list to store the messages, and append to it every time the user or bot sends a message. Each entry in the list will be a dictionary with the following keys: role (the author of the message), and content (the message content). import streamlit as st st.title("Echo Bot") # Initialize chat history if "messages" not in st.session_state: st.session_state.messages = [] # Display chat messages from history on app rerun for message in st.session_state.messages: with st.chat_message(message["role"]): st.markdown(message["content"]) In the above snippet, we've added a title to our app and a for loop to iterate through the chat history and display each message in the chat message container (with the author role and message content). We've also added a check to see if the messages key is in st.session_state. If it's not, we initialize it to an empty list. This is because we'll be adding messages to the list later on, and we don't want to overwrite the list every time the app reruns. Now let's accept user input with st.chat_input, display the user's message in the chat message container, and add it to the chat history. # React to user input if prompt := st.chat_input("What is up?"): # Display user message in chat message container with st.chat_message("user"): st.markdown(prompt) # Add user message to chat history st.session_state.messages.append({"role": "user", "content": prompt}) We used the := operator to assign the user's input to the prompt variable and checked if it's not None in the same line. If the user has sent a message, we display the message in the chat message container and append it to the chat history. All that's left to do is add the chatbot's responses within the if block. We'll use the same logic as before to display the bot's response (which is just the user's prompt) in the chat message container and add it to the history. response = f"Echo: {prompt}" # Display assistant response in chat message container with st.chat_message("assistant"): st.markdown(response) # Add assistant response to chat history st.session_state.messages.append({"role": "assistant", "content": response}) Putting it all together, here's the full code for our simple chatbot GUI and the result: View full codeexpand_moreimport streamlit as st st.title("Echo Bot") # Initialize chat history if "messages" not in st.session_state: st.session_state.messages = [] # Display chat messages from history on app rerun for message in st.session_state.messages: with st.chat_message(message["role"]): st.markdown(message["content"]) # React to user input if prompt := st.chat_input("What is up?"): # Display user message in chat message container st.chat_message("user").markdown(prompt) # Add user message to chat history st.session_state.messages.append({"role": "user", "content": prompt}) response = f"Echo: {prompt}" # Display assistant response in chat message container with st.chat_message("assistant"): st.markdown(response) # Add assistant response to chat history st.session_state.messages.append({"role": "assistant", "content": response}) Built with Streamlit 🎈Fullscreen open_in_new While the above example is very simple, it's a good starting point for building more complex conversational apps. Notice how the bot responds instantly to your input. In the next section, we'll add a delay to simulate the bot "thinking" before responding. Build a simple chatbot GUI with streaming In this section, we'll build a simple chatbot GUI that responds to user input with a random message from a list of pre-determind responses. In the next section, we'll convert this simple toy example into a ChatGPT-like experience using OpenAI. Just like previously, we still require the same components to build our chatbot. Two chat message containers to display messages from the user and the bot, respectively. A chat input widget so the user can type in a message. And a way to store the chat history so we can display it in the chat message containers. Let's just copy the code from the previous section and add a few tweaks to it. import streamlit as st import random import time st.title("Simple chat") # Initialize chat history if "messages" not in st.session_state: st.session_state.messages = [] # Display chat messages from history on app rerun for message in st.session_state.messages: with st.chat_message(message["role"]): st.markdown(message["content"]) # Accept user input if prompt := st.chat_input("What is up?"): # Display user message in chat message container with st.chat_message("user"): st.markdown(prompt) # Add user message to chat history st.session_state.messages.append({"role": "user", "content": prompt}) The only difference so far is we've changed the title of our app and added imports for random and time. We'll use random to randomly select a response from a list of responses and time to add a delay to simulate the chatbot "thinking" before responding. All that's left to do is add the chatbot's responses within the if block. We'll use a list of responses and randomly select one to display. We'll also add a delay to simulate the chatbot "thinking" before responding (or stream its response). Let's make a helper function for this and insert it at the top of our app. # Streamed response emulator def response_generator(): response = random.choice( [ "Hello there! How can I assist you today?", "Hi, human! Is there anything I can help you with?", "Do you need help?", ] ) for word in response.split(): yield word + " " time.sleep(0.05) Back to writing the response in our chat interface, we'll use st.write_stream to write out the streamed response with a typewriter effect. # Display assistant response in chat message container with st.chat_message("assistant"): response = st.write_stream(response_generator()) # Add assistant response to chat history st.session_state.messages.append({"role": "assistant", "content": response}) Above, we've added a placeholder to display the chatbot's response. We've also added a for loop to iterate through the response and display it one word at a time. We've added a delay of 0.05 seconds between each word to simulate the chatbot "thinking" before responding. Finally, we append the chatbot's response to the chat history. As you've probably guessed, this is a naive implementation of streaming. We'll see how to implement streaming with OpenAI in the next section. Putting it all together, here's the full code for our simple chatbot GUI and the result: View full codeexpand_moreimport streamlit as st import random import time # Streamed response emulator def response_generator(): response = random.choice( [ "Hello there! How can I assist you today?", "Hi, human! Is there anything I can help you with?", "Do you need help?", ] ) for word in response.split(): yield word + " " time.sleep(0.05) st.title("Simple chat") # Initialize chat history if "messages" not in st.session_state: st.session_state.messages = [] # Display chat messages from history on app rerun for message in st.session_state.messages: with st.chat_message(message["role"]): st.markdown(message["content"]) # Accept user input if prompt := st.chat_input("What is up?"): # Add user message to chat history st.session_state.messages.append({"role": "user", "content": prompt}) # Display user message in chat message container with st.chat_message("user"): st.markdown(prompt) # Display assistant response in chat message container with st.chat_message("assistant"): response = st.write_stream(response_generator()) # Add assistant response to chat history st.session_state.messages.append({"role": "assistant", "content": response}) Built with Streamlit 🎈Fullscreen open_in_new Play around with the above demo to get a feel for what we've built. It's a very simple chatbot GUI, but it has all the components of a more sophisticated chatbot. In the next section, we'll see how to build a ChatGPT-like app using OpenAI. Build a ChatGPT-like app Now that you've understood the basics of Streamlit's chat elements, let's make a few tweaks to it to build our own ChatGPT-like app. You'll need to install the OpenAI Python library and get an API key to follow along. Install dependencies First let's install the dependencies we'll need for this section: pip install openai streamlit Add OpenAI API key to Streamlit secrets Next, let's add our OpenAI API key to Streamlit secrets. We do this by creating .streamlit/secrets.toml file in our project directory and adding the following lines to it: # .streamlit/secrets.toml OPENAI_API_KEY = "YOUR_API_KEY" Write the app Now let's write the app. We'll use the same code as before, but we'll replace the list of responses with a call to the OpenAI API. We'll also add a few more tweaks to make the app more ChatGPT-like. import streamlit as st from openai import OpenAI st.title("ChatGPT-like clone") # Set OpenAI API key from Streamlit secrets client = OpenAI(api_key=st.secrets["OPENAI_API_KEY"]) # Set a default model if "openai_model" not in st.session_state: st.session_state["openai_model"] = "gpt-3.5-turbo" # Initialize chat history if "messages" not in st.session_state: st.session_state.messages = [] # Display chat messages from history on app rerun for message in st.session_state.messages: with st.chat_message(message["role"]): st.markdown(message["content"]) # Accept user input if prompt := st.chat_input("What is up?"): # Add user message to chat history st.session_state.messages.append({"role": "user", "content": prompt}) # Display user message in chat message container with st.chat_message("user"): st.markdown(prompt) All that's changed is that we've added a default model to st.session_state and set our OpenAI API key from Streamlit secrets. Here's where it gets interesting. We can replace our emulated stream with the model's responses from OpenAI: # Display assistant response in chat message container with st.chat_message("assistant"): stream = client.chat.completions.create( model=st.session_state["openai_model"], messages=[ {"role": m["role"], "content": m["content"]} for m in st.session_state.messages ], stream=True, ) response = st.write_stream(stream) st.session_state.messages.append({"role": "assistant", "content": response}) Above, we've replaced the list of responses with a call to OpenAI().chat.completions.create. We've set stream=True to stream the responses to the frontend. In the API call, we pass the model name we hardcoded in session state and pass the chat history as a list of messages. We also pass the role and content of each message in the chat history. Finally, OpenAI returns a stream of responses (split into chunks of tokens), which we iterate through and display each chunk. Putting it all together, here's the full code for our ChatGPT-like app and the result: View full codeexpand_morefrom openai import OpenAI import streamlit as st st.title("ChatGPT-like clone") client = OpenAI(api_key=st.secrets["OPENAI_API_KEY"]) if "openai_model" not in st.session_state: st.session_state["openai_model"] = "gpt-3.5-turbo" if "messages" not in st.session_state: st.session_state.messages = [] for message in st.session_state.messages: with st.chat_message(message["role"]): st.markdown(message["content"]) if prompt := st.chat_input("What is up?"): st.session_state.messages.append({"role": "user", "content": prompt}) with st.chat_message("user"): st.markdown(prompt) with st.chat_message("assistant"): stream = client.chat.completions.create( model=st.session_state["openai_model"], messages=[ {"role": m["role"], "content": m["content"]} for m in st.session_state.messages ], stream=True, ) response = st.write_stream(stream) st.session_state.messages.append({"role": "assistant", "content": response}) Built with Streamlit 🎈Fullscreen open_in_new Congratulations! You've built your own ChatGPT-like app in less than 50 lines of code. We're very excited to see what you'll build with Streamlit's chat elements. Experiment with different models and tweak the code to build your own conversational apps. If you build something cool, let us know on the Forum or check out some other Generative AI apps for inspiration. 🎈Previous: Work with LLMsNext: Build an LLM app using LangChainforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy
https://docs.streamlit.io/en/0.65.0/api.html#input-widgets
DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceremovePAGE ELEMENTSWrite and magicaddText elementsaddData elementsaddChart elementsaddInput widgetsaddMedia elementsaddLayouts and containersaddChat elementsaddStatus elementsaddThird-party componentsopen_in_newAPPLICATION LOGICNavigation and pagesaddExecution flowaddCaching and stateaddConnections and secretsaddCustom componentsaddUtilitiesaddConfigurationaddTOOLSApp testingaddCommand lineaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Develop/API referenceAPI reference Streamlit makes it easy for you to visualize, mutate, and share data. The API reference is organized by activity type, like displaying data or optimizing performance. Each section includes methods associated with the activity type, including examples. Browse our API below and click to learn more about any of our available commands! 🎈 Display almost anything Write and magic st.writeWrite arguments to the app.st.write("Hello **world**!") st.write(my_data_frame) st.write(my_mpl_figure) st.write_streamWrite generators or streams to the app with a typewriter effect.st.write_stream(my_generator) st.write_stream(my_llm_stream) MagicAny time Streamlit sees either a variable or literal value on its own line, it automatically writes that to your app using st.write"Hello **world**!" my_data_frame my_mpl_figure Text elements MarkdownDisplay string formatted as Markdown.st.markdown("Hello **world**!") TitleDisplay text in title formatting.st.title("The app title") HeaderDisplay text in header formatting.st.header("This is a header") SubheaderDisplay text in subheader formatting.st.subheader("This is a subheader") CaptionDisplay text in small font.st.caption("This is written small caption text") Code blockDisplay a code block with optional syntax highlighting.st.code("a = 1234") EchoDisplay some code in the app, then execute it. Useful for tutorials.with st.echo(): st.write('This code will be printed') LaTeXDisplay mathematical expressions formatted as LaTeX.st.latex("\int a x^2 \,dx") Preformatted textWrite fixed-width and preformatted text.st.text("Hello world") DividerDisplay a horizontal rule.st.divider() Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration! PreviousTagsAdd tags to your Streamlit apps. Created by @gagan3012.st_tags(label='# Enter Keywords:', text='Press enter to add more', value=['Zero', 'One', 'Two'], suggestions=['five', 'six', 'seven', 'eight', 'nine', 'three', 'eleven', 'ten', 'four'], maxtags = 4, key='1') NLUApply text mining on a dataframe. Created by @JohnSnowLabs.nlu.load('sentiment').predict('I love NLU! <3') Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.mention(label="An awesome Streamlit App", icon="streamlit", url="https://extras.streamlit.app",) Annotated textDisplay annotated text in Streamlit apps. Created by @tvst.annotated_text("This ", ("is", "verb"), " some ", ("annotated", "adj"), ("text", "noun"), " for those of ", ("you", "pronoun"), " who ", ("like", "verb"), " this sort of ", ("thing", "noun"), ".") Drawable CanvasProvides a sketching canvas using Fabric.js. Created by @andfanilo.st_canvas(fill_color="rgba(255, 165, 0, 0.3)", stroke_width=stroke_width, stroke_color=stroke_color, background_color=bg_color, background_image=Image.open(bg_image) if bg_image else None, update_streamlit=realtime_update, height=150, drawing_mode=drawing_mode, point_display_radius=point_display_radius if drawing_mode == 'point' else 0, key="canvas",) TagsAdd tags to your Streamlit apps. Created by @gagan3012.st_tags(label='# Enter Keywords:', text='Press enter to add more', value=['Zero', 'One', 'Two'], suggestions=['five', 'six', 'seven', 'eight', 'nine', 'three', 'eleven', 'ten', 'four'], maxtags = 4, key='1') NLUApply text mining on a dataframe. Created by @JohnSnowLabs.nlu.load('sentiment').predict('I love NLU! <3') Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.mention(label="An awesome Streamlit App", icon="streamlit", url="https://extras.streamlit.app",) Annotated textDisplay annotated text in Streamlit apps. Created by @tvst.annotated_text("This ", ("is", "verb"), " some ", ("annotated", "adj"), ("text", "noun"), " for those of ", ("you", "pronoun"), " who ", ("like", "verb"), " this sort of ", ("thing", "noun"), ".") Drawable CanvasProvides a sketching canvas using Fabric.js. Created by @andfanilo.st_canvas(fill_color="rgba(255, 165, 0, 0.3)", stroke_width=stroke_width, stroke_color=stroke_color, background_color=bg_color, background_image=Image.open(bg_image) if bg_image else None, update_streamlit=realtime_update, height=150, drawing_mode=drawing_mode, point_display_radius=point_display_radius if drawing_mode == 'point' else 0, key="canvas",) TagsAdd tags to your Streamlit apps. Created by @gagan3012.st_tags(label='# Enter Keywords:', text='Press enter to add more', value=['Zero', 'One', 'Two'], suggestions=['five', 'six', 'seven', 'eight', 'nine', 'three', 'eleven', 'ten', 'four'], maxtags = 4, key='1') NLUApply text mining on a dataframe. Created by @JohnSnowLabs.nlu.load('sentiment').predict('I love NLU! <3') Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.mention(label="An awesome Streamlit App", icon="streamlit", url="https://extras.streamlit.app",) Next Data elements DataframesDisplay a dataframe as an interactive table.st.dataframe(my_data_frame) Data editorDisplay a data editor widget.edited = st.data_editor(df, num_rows="dynamic") Column configurationConfigure the display and editing behavior of dataframes and data editors.st.column_config.NumberColumn("Price (in USD)", min_value=0, format="$%d") Static tablesDisplay a static table.st.table(my_data_frame) MetricsDisplay a metric in big bold font, with an optional indicator of how the metric changed.st.metric("My metric", 42, 2) Dicts and JSONDisplay object or string as a pretty-printed JSON string.st.json(my_dict) Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration! PreviousImage CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates value = streamlit_image_coordinates("https://placekitten.com/200/300") st.write(value) Plotly EventsMake Plotly charts interactive!. Created by @null-jones.from streamlit_plotly_events import plotly_events fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.metric_cards import style_metric_cards col3.metric(label="No Change", value=5000, delta=0) style_metric_cards() Streamlit AggridImplementation of Ag-Grid component for Streamlit. Created by @PablocFonseca.df = pd.DataFrame({'col1': [1, 2, 3], 'col2': [4, 5, 6]}) grid_return = AgGrid(df, editable=True) new_df = grid_return['data'] Streamlit FoliumStreamlit Component for rendering Folium maps. Created by @randyzwitch.m = folium.Map(location=[39.949610, -75.150282], zoom_start=16) folium.Marker([39.949610, -75.150282], popup="Liberty Bell", tooltip="Liberty Bell").add_to(m) st_data = st_folium(m, width=725) Pandas ProfilingPandas profiling component for Streamlit. Created by @okld.df = pd.read_csv("https://storage.googleapis.com/tf-datasets/titanic/train.csv") pr = df.profile_report() st_profile_report(pr) Image CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates value = streamlit_image_coordinates("https://placekitten.com/200/300") st.write(value) Plotly EventsMake Plotly charts interactive!. Created by @null-jones.from streamlit_plotly_events import plotly_events fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.metric_cards import style_metric_cards col3.metric(label="No Change", value=5000, delta=0) style_metric_cards() Streamlit AggridImplementation of Ag-Grid component for Streamlit. Created by @PablocFonseca.df = pd.DataFrame({'col1': [1, 2, 3], 'col2': [4, 5, 6]}) grid_return = AgGrid(df, editable=True) new_df = grid_return['data'] Streamlit FoliumStreamlit Component for rendering Folium maps. Created by @randyzwitch.m = folium.Map(location=[39.949610, -75.150282], zoom_start=16) folium.Marker([39.949610, -75.150282], popup="Liberty Bell", tooltip="Liberty Bell").add_to(m) st_data = st_folium(m, width=725) Pandas ProfilingPandas profiling component for Streamlit. Created by @okld.df = pd.read_csv("https://storage.googleapis.com/tf-datasets/titanic/train.csv") pr = df.profile_report() st_profile_report(pr) Image CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates value = streamlit_image_coordinates("https://placekitten.com/200/300") st.write(value) Plotly EventsMake Plotly charts interactive!. Created by @null-jones.from streamlit_plotly_events import plotly_events fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.metric_cards import style_metric_cards col3.metric(label="No Change", value=5000, delta=0) style_metric_cards() Next Chart elements Simple area chartsDisplay an area chart.st.area_chart(my_data_frame) Simple bar chartsDisplay a bar chart.st.bar_chart(my_data_frame) Simple line chartsDisplay a line chart.st.line_chart(my_data_frame) Simple scatter chartsDisplay a line chart.st.scatter_chart(my_data_frame) Scatterplots on mapsDisplay a map with points on it.st.map(my_data_frame) MatplotlibDisplay a matplotlib.pyplot figure.st.pyplot(my_mpl_figure) AltairDisplay a chart using the Altair library.st.altair_chart(my_altair_chart) Vega-LiteDisplay a chart using the Vega-Lite library.st.vega_lite_chart(my_vega_lite_chart) PlotlyDisplay an interactive Plotly chart.st.plotly_chart(my_plotly_chart) BokehDisplay an interactive Bokeh chart.st.bokeh_chart(my_bokeh_chart) PyDeckDisplay a chart using the PyDeck library.st.pydeck_chart(my_pydeck_chart) GraphVizDisplay a graph using the dagre-d3 library.st.graphviz_chart(my_graphviz_spec) Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration! PreviousStreamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl("https://assets5.lottiefiles.com/packages/lf20_V9t630.json") st_lottie(lottie_hello, key="hello") Plotly EventsMake Plotly charts interactive!. Created by @null-jones.fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.chart += get_annotations_chart(annotations=[("Mar 01, 2008", "Pretty good day for GOOG"), ("Dec 01, 2007", "Something's going wrong for GOOG & AAPL"), ("Nov 01, 2008", "Market starts again thanks to..."), ("Dec 01, 2009", "Small crash for GOOG after..."),],) st.altair_chart(chart, use_container_width=True) PlostA deceptively simple plotting library for Streamlit. Created by @tvst.import plost plost.line_chart(my_dataframe, x='time', y='stock_value', color='stock_name',) HiPlotHigh dimensional Interactive Plotting. Created by @facebookresearch.data = [{'dropout':0.1, 'lr': 0.001, 'loss': 10.0, 'optimizer': 'SGD'}, {'dropout':0.15, 'lr': 0.01, 'loss': 3.5, 'optimizer': 'Adam'}, {'dropout':0.3, 'lr': 0.1, 'loss': 4.5, 'optimizer': 'Adam'}] hip.Experiment.from_iterable(data).display() EChartsHigh dimensional Interactive Plotting. Created by @andfanilo.from streamlit_echarts import st_echarts st_echarts(options=options) Streamlit FoliumStreamlit Component for rendering Folium maps. Created by @randyzwitch.m = folium.Map(location=[39.949610, -75.150282], zoom_start=16) st_data = st_folium(m, width=725) Spacy-StreamlitspaCy building blocks and visualizers for Streamlit apps. Created by @explosion.models = ["en_core_web_sm", "en_core_web_md"] spacy_streamlit.visualize(models, "Sundar Pichai is the CEO of Google.") Streamlit AgraphA Streamlit Graph Vis, based on react-grah-vis. Created by @ChrisDelClea.from streamlit_agraph import agraph, Node, Edge, Config agraph(nodes=nodes, edges=edges, config=config) Streamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl("https://assets5.lottiefiles.com/packages/lf20_V9t630.json") st_lottie(lottie_hello, key="hello") Plotly EventsMake Plotly charts interactive!. Created by @null-jones.fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.chart += get_annotations_chart(annotations=[("Mar 01, 2008", "Pretty good day for GOOG"), ("Dec 01, 2007", "Something's going wrong for GOOG & AAPL"), ("Nov 01, 2008", "Market starts again thanks to..."), ("Dec 01, 2009", "Small crash for GOOG after..."),],) st.altair_chart(chart, use_container_width=True) PlostA deceptively simple plotting library for Streamlit. Created by @tvst.import plost plost.line_chart(my_dataframe, x='time', y='stock_value', color='stock_name',) HiPlotHigh dimensional Interactive Plotting. Created by @facebookresearch.data = [{'dropout':0.1, 'lr': 0.001, 'loss': 10.0, 'optimizer': 'SGD'}, {'dropout':0.15, 'lr': 0.01, 'loss': 3.5, 'optimizer': 'Adam'}, {'dropout':0.3, 'lr': 0.1, 'loss': 4.5, 'optimizer': 'Adam'}] hip.Experiment.from_iterable(data).display() EChartsHigh dimensional Interactive Plotting. Created by @andfanilo.from streamlit_echarts import st_echarts st_echarts(options=options) Streamlit FoliumStreamlit Component for rendering Folium maps. Created by @randyzwitch.m = folium.Map(location=[39.949610, -75.150282], zoom_start=16) st_data = st_folium(m, width=725) Spacy-StreamlitspaCy building blocks and visualizers for Streamlit apps. Created by @explosion.models = ["en_core_web_sm", "en_core_web_md"] spacy_streamlit.visualize(models, "Sundar Pichai is the CEO of Google.") Streamlit AgraphA Streamlit Graph Vis, based on react-grah-vis. Created by @ChrisDelClea.from streamlit_agraph import agraph, Node, Edge, Config agraph(nodes=nodes, edges=edges, config=config) Streamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl("https://assets5.lottiefiles.com/packages/lf20_V9t630.json") st_lottie(lottie_hello, key="hello") Plotly EventsMake Plotly charts interactive!. Created by @null-jones.fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.chart += get_annotations_chart(annotations=[("Mar 01, 2008", "Pretty good day for GOOG"), ("Dec 01, 2007", "Something's going wrong for GOOG & AAPL"), ("Nov 01, 2008", "Market starts again thanks to..."), ("Dec 01, 2009", "Small crash for GOOG after..."),],) st.altair_chart(chart, use_container_width=True) Next Input widgets ButtonDisplay a button widget.clicked = st.button("Click me") Download buttonDisplay a download button widget.st.download_button("Download file", file) Form buttonDisplay a form submit button. For use with st.form.st.form_submit_button("Sign up") Link buttonDisplay a link button.st.link_button("Go to gallery", url) Page linkDisplay a link to another page in a multipage app.st.page_link("app.py", label="Home", icon="🏠") st.page_link("pages/profile.py", label="My profile") CheckboxDisplay a checkbox widget.selected = st.checkbox("I agree") Color pickerDisplay a color picker widget.color = st.color_picker("Pick a color") MultiselectDisplay a multiselect widget. The multiselect widget starts as empty.choices = st.multiselect("Buy", ["milk", "apples", "potatoes"]) RadioDisplay a radio button widget.choice = st.radio("Pick one", ["cats", "dogs"]) SelectboxDisplay a select widget.choice = st.selectbox("Pick one", ["cats", "dogs"]) Select-sliderDisplay a slider widget to select items from a list.size = st.select_slider("Pick a size", ["S", "M", "L"]) ToggleDisplay a toggle widget.activated = st.toggle("Activate") Number inputDisplay a numeric input widget.choice = st.number_input("Pick a number", 0, 10) SliderDisplay a slider widget.number = st.slider("Pick a number", 0, 100) Date inputDisplay a date input widget.date = st.date_input("Your birthday") Time inputDisplay a time input widget.time = st.time_input("Meeting time") Chat inputDisplay a chat input widget.prompt = st.chat_input("Say something") if prompt: st.write(f"The user has sent: {prompt}") Text-areaDisplay a multi-line text input widget.text = st.text_area("Text to translate") Text inputDisplay a single-line text input widget.name = st.text_input("First name") Data editorDisplay a data editor widget.edited = st.experimental_data_editor(df, num_rows="dynamic") File UploaderDisplay a file uploader widget.data = st.file_uploader("Upload a CSV") Camera inputDisplay a widget that allows users to upload images directly from a camera.image = st.camera_input("Take a picture") Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration! PreviousStreamlit ChatStreamlit Component for a Chatbot UI. Created by @AI-Yash.from streamlit_chat import message message("My message") message("Hello bot!", is_user=True) # align's the message to the right Streamlit Option MenuSelect a single item from a list of options in a menu. Created by @victoryhb.from streamlit_option_menu import option_menu option_menu("Main Menu", ["Home", 'Settings'], icons=['house', 'gear'], menu_icon="cast", default_index=1) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.stoggle import stoggle stoggle( "Click me!", """🥷 Surprise! Here's some additional content""",) Streamlit ElementsCreate a draggable and resizable dashboard in Streamlit. Created by @okls.from streamlit_elements import elements, mui, html with elements("new_element"): mui.Typography("Hello world") TagsAdd tags to your Streamlit apps. Created by @gagan3012.from streamlit_tags import st_tags st_tags(label='# Enter Keywords:', text='Press enter to add more', value=['Zero', 'One', 'Two'], suggestions=['five', 'six', 'seven', 'eight', 'nine', 'three', 'eleven', 'ten', 'four'], maxtags = 4, key='1') StqdmThe simplest way to handle a progress bar in streamlit app. Created by @Wirg.from stqdm import stqdm for _ in stqdm(range(50)): sleep(0.5) TimelineDisplay a Timeline in Streamlit apps using TimelineJS. Created by @innerdoc.from streamlit_timeline import timeline with open('example.json', "r") as f: timeline(f.read(), height=800) Camera input liveAlternative for st.camera_input which returns the webcam images live. Created by @blackary.from camera_input_live import camera_input_live image = camera_input_live() st.image(value) Streamlit AceAce editor component for Streamlit. Created by @okld.from streamlit_ace import st_ace content = st_ace() content Streamlit ChatStreamlit Component for a Chatbot UI. Created by @AI-Yash.from streamlit_chat import message message("My message") message("Hello bot!", is_user=True) # align's the message to the right Streamlit Option MenuSelect a single item from a list of options in a menu. Created by @victoryhb.from streamlit_option_menu import option_menu option_menu("Main Menu", ["Home", 'Settings'], icons=['house', 'gear'], menu_icon="cast", default_index=1) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.stoggle import stoggle stoggle( "Click me!", """🥷 Surprise! Here's some additional content""",) Streamlit ElementsCreate a draggable and resizable dashboard in Streamlit. Created by @okls.from streamlit_elements import elements, mui, html with elements("new_element"): mui.Typography("Hello world") TagsAdd tags to your Streamlit apps. Created by @gagan3012.from streamlit_tags import st_tags st_tags(label='# Enter Keywords:', text='Press enter to add more', value=['Zero', 'One', 'Two'], suggestions=['five', 'six', 'seven', 'eight', 'nine', 'three', 'eleven', 'ten', 'four'], maxtags = 4, key='1') StqdmThe simplest way to handle a progress bar in streamlit app. Created by @Wirg.from stqdm import stqdm for _ in stqdm(range(50)): sleep(0.5) TimelineDisplay a Timeline in Streamlit apps using TimelineJS. Created by @innerdoc.from streamlit_timeline import timeline with open('example.json', "r") as f: timeline(f.read(), height=800) Camera input liveAlternative for st.camera_input which returns the webcam images live. Created by @blackary.from camera_input_live import camera_input_live image = camera_input_live() st.image(value) Streamlit AceAce editor component for Streamlit. Created by @okld.from streamlit_ace import st_ace content = st_ace() content Streamlit ChatStreamlit Component for a Chatbot UI. Created by @AI-Yash.from streamlit_chat import message message("My message") message("Hello bot!", is_user=True) # align's the message to the right Streamlit Option MenuSelect a single item from a list of options in a menu. Created by @victoryhb.from streamlit_option_menu import option_menu option_menu("Main Menu", ["Home", 'Settings'], icons=['house', 'gear'], menu_icon="cast", default_index=1) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.stoggle import stoggle stoggle( "Click me!", """🥷 Surprise! Here's some additional content""",) Next Media elements ImageDisplay an image or list of images.st.image(numpy_array) st.image(image_bytes) st.image(file) st.image("https://example.com/myimage.jpg") AudioDisplay an audio player.st.audio(numpy_array) st.audio(audio_bytes) st.audio(file) st.audio("https://example.com/myaudio.mp3", format="audio/mp3") VideoDisplay a video player.st.video(numpy_array) st.video(video_bytes) st.video(file) st.video("https://example.com/myvideo.mp4", format="video/mp4") Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration! PreviousStreamlit CropperA simple image cropper for Streamlit. Created by @turner-anderson.from streamlit_cropper import st_cropper st_cropper(img, realtime_update=realtime_update, box_color=box_color, aspect_ratio=aspect_ratio) Image CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates streamlit_image_coordinates("https://placekitten.com/200/300") Streamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl("https://assets5.lottiefiles.com/packages/lf20_V9t630.json") st_lottie(lottie_hello, key="hello") Streamlit WebrtcHandling and transmitting real-time video/audio streams with Streamlit. Created by @whitphx.from streamlit_webrtc import webrtc_streamer webrtc_streamer(key="sample") Drawable CanvasProvides a sketching canvas using Fabric.js. Created by @andfanilo.from streamlit_drawable_canvas import st_canvas st_canvas(fill_color="rgba(255, 165, 0, 0.3)", stroke_width=stroke_width, stroke_color=stroke_color, background_color=bg_color, background_image=Image.open(bg_image) if bg_image else None, update_streamlit=realtime_update, height=150, drawing_mode=drawing_mode, point_display_radius=point_display_radius if drawing_mode == 'point' else 0, key="canvas",) Image ComparisonCompare images with a slider using JuxtaposeJS. Created by @fcakyon.from streamlit_image_comparison import image_comparison image_comparison(img1="image1.jpg", img2="image2.jpg",) Streamlit CropperA simple image cropper for Streamlit. Created by @turner-anderson.from streamlit_cropper import st_cropper st_cropper(img, realtime_update=realtime_update, box_color=box_color, aspect_ratio=aspect_ratio) Image CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates streamlit_image_coordinates("https://placekitten.com/200/300") Streamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl("https://assets5.lottiefiles.com/packages/lf20_V9t630.json") st_lottie(lottie_hello, key="hello") Streamlit WebrtcHandling and transmitting real-time video/audio streams with Streamlit. Created by @whitphx.from streamlit_webrtc import webrtc_streamer webrtc_streamer(key="sample") Drawable CanvasProvides a sketching canvas using Fabric.js. Created by @andfanilo.from streamlit_drawable_canvas import st_canvas st_canvas(fill_color="rgba(255, 165, 0, 0.3)", stroke_width=stroke_width, stroke_color=stroke_color, background_color=bg_color, background_image=Image.open(bg_image) if bg_image else None, update_streamlit=realtime_update, height=150, drawing_mode=drawing_mode, point_display_radius=point_display_radius if drawing_mode == 'point' else 0, key="canvas",) Image ComparisonCompare images with a slider using JuxtaposeJS. Created by @fcakyon.from streamlit_image_comparison import image_comparison image_comparison(img1="image1.jpg", img2="image2.jpg",) Streamlit CropperA simple image cropper for Streamlit. Created by @turner-anderson.from streamlit_cropper import st_cropper st_cropper(img, realtime_update=realtime_update, box_color=box_color, aspect_ratio=aspect_ratio) Image CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates streamlit_image_coordinates("https://placekitten.com/200/300") Streamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl("https://assets5.lottiefiles.com/packages/lf20_V9t630.json") st_lottie(lottie_hello, key="hello") Next Layouts and containers ColumnsInsert containers laid out as side-by-side columns.col1, col2 = st.columns(2) col1.write("this is column 1") col2.write("this is column 2") ContainerInsert a multi-element container.c = st.container() st.write("This will show last") c.write("This will show first") c.write("This will show second") Modal dialogsInsert a modal dialog that can rerun independently from the rest of the script.@st.experimental_dialog("Sign up") def email_form(): name = st.text_input("Name") email = st.text_input("Email") EmptyInsert a single-element container.c = st.empty() st.write("This will show last") c.write("This will be replaced") c.write("This will show first") ExpanderInsert a multi-element container that can be expanded/collapsed.with st.expander("Open to see more"): st.write("This is more content") PopoverInsert a multi-element popover container that can be opened/closed.with st.popover("Settings"): st.checkbox("Show completed") SidebarDisplay items in a sidebar.st.sidebar.write("This lives in the sidebar") st.sidebar.button("Click me!") TabsInsert containers separated into tabs.tab1, tab2 = st.tabs(["Tab 1", "Tab2"]) tab1.write("this is tab 1") tab2.write("this is tab 2") Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration!Streamlit ElementsCreate a draggable and resizable dashboard in Streamlit. Created by @okls.from streamlit_elements import elements, mui, html with elements("new_element"): mui.Typography("Hello world") PydanticAuto-generate Streamlit UI from Pydantic Models and Dataclasses. Created by @lukasmasuch.import streamlit_pydantic as sp sp.pydantic_form(key="my_form", model=ExampleModel) Streamlit PagesAn experimental version of Streamlit Multi-Page Apps. Created by @blackary.from st_pages import Page, show_pages, add_page_title show_pages([ Page("streamlit_app.py", "Home", "🏠"), Page("other_pages/page2.py", "Page 2", ":books:"), ]) Chat elements Streamlit provides a few commands to help you build conversational apps. These chat elements are designed to be used in conjunction with each other, but you can also use them separately. st.chat_message lets you insert a chat message container into the app so you can display messages from the user or the app. Chat containers can contain other Streamlit elements, including charts, tables, text, and more. st.chat_input lets you display a chat input widget so the user can type in a message. Chat inputDisplay a chat input widget.prompt = st.chat_input("Say something") if prompt: st.write(f"The user has sent: {prompt}") Chat messageInsert a chat message container.import numpy as np with st.chat_message("user"): st.write("Hello 👋") st.line_chart(np.random.randn(30, 3)) Status containerDisplay output of long-running tasks in a container.with st.status('Running'): do_something_slow() st.write_streamWrite generators or streams to the app with a typewriter effect.st.write_stream(my_generator) st.write_stream(my_llm_stream) Status elements Progress barDisplay a progress bar.for i in range(101): st.progress(i) do_something_slow() SpinnerTemporarily displays a message while executing a block of code.with st.spinner("Please wait..."): do_something_slow() Status containerDisplay output of long-running tasks in a container.with st.status('Running'): do_something_slow() ToastBriefly displays a toast message in the bottom-right corner.st.toast('Butter!', icon='🧈') BalloonsDisplay celebratory balloons!do_something() # Celebrate when all done! st.balloons() SnowflakesDisplay celebratory snowflakes!do_something() # Celebrate when all done! st.snow() Success boxDisplay a success message.st.success("Match found!") Info boxDisplay an informational message.st.info("Dataset is updated every day at midnight.") Warning boxDisplay warning message.st.warning("Unable to fetch image. Skipping...") Error boxDisplay error message.st.error("We encountered an error") Exception outputDisplay an exception.e = RuntimeError("This is an exception of type RuntimeError") st.exception(e) Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration!StqdmThe simplest way to handle a progress bar in streamlit app. Created by @Wirg.from stqdm import stqdm for _ in stqdm(range(50)): sleep(0.5) Custom notification boxA custom notification box with the ability to close it out. Created by @Socvest.from streamlit_custom_notification_box import custom_notification_box styles = {'material-icons':{'color': 'red'}, 'text-icon-link-close-container': {'box-shadow': '#3896de 0px 4px'}, 'notification-text': {'':''}, 'close-button':{'':''}, 'link':{'':''}} custom_notification_box(icon='info', textDisplay='We are almost done with your registration...', externalLink='more info', url='#', styles=styles, key="foo") Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.let_it_rain import rain rain(emoji="🎈", font_size=54, falling_speed=5, animation_length="infinite",) App logic and configuration Navigation and pages Switch pageProgrammatically navigates to a specified page.st.switch_page("pages/my_page.py") Page linkDisplay a link to another page in a multipage app.st.page_link("app.py", label="Home", icon="🏠") st.page_link("pages/profile.py", label="My profile") Execution flow Modal dialogsInsert a modal dialog that can rerun independently from the rest of the script.@st.experimental_dialog("Sign up") def email_form(): name = st.text_input("Name") email = st.text_input("Email") FormsCreate a form that batches elements together with a “Submit" button.with st.form(key='my_form'): name = st.text_input("Name") email = st.text_input("Email") st.form_submit_button("Sign up") Partial rerunsDefine a fragment to rerun independently from the rest of the script.@st.experimental_fragment(run_every="10s") def fragment(): df = get_data() st.line_chart(df) Rerun scriptRerun the script immediately.st.rerun() Stop executionStops execution immediately.st.stop() Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration!AutorefreshForce a refresh without tying up a script. Created by @kmcgrady.from streamlit_autorefresh import st_autorefresh st_autorefresh(interval=2000, limit=100, key="fizzbuzzcounter") PydanticAuto-generate Streamlit UI from Pydantic Models and Dataclasses. Created by @lukasmasuch.import streamlit_pydantic as sp sp.pydantic_form(key="my_form", model=ExampleModel) Streamlit PagesAn experimental version of Streamlit Multi-Page Apps. Created by @blackary.from st_pages import Page, show_pages, add_page_title show_pages([ Page("streamlit_app.py", "Home", "🏠"), Page("other_pages/page2.py", "Page 2", ":books:"), ]) Caching and state Cache dataFunction decorator to cache functions that return data (e.g. dataframe transforms, database queries, ML inference).@st.cache_data def long_function(param1, param2): # Perform expensive computation here or # fetch data from the web here return data Cache resourceFunction decorator to cache functions that return global resources (e.g. database connections, ML models).@st.cache_resource def init_model(): # Return a global resource here return pipeline( "sentiment-analysis", model="distilbert-base-uncased-finetuned-sst-2-english" ) Session stateSession state is a way to share variables between reruns, for each user session.st.session_state['key'] = value Query parametersGet, set, or clear the query parameters that are shown in the browser's URL bar.st.query_params[key] = value st.query_params.clear() Connections and databases Setup your connection Create a connectionConnect to a data source or APIconn = st.connection('pets_db', type='sql') pet_owners = conn.query('select * from pet_owners') st.dataframe(pet_owners) Built-in connections SnowflakeConnectionA connection to Snowflake.conn = st.connection('snowflake') SQLConnectionA connection to a SQL database using SQLAlchemy.conn = st.connection('sql') Build your own connections Connection base classBuild your own connection with BaseConnection.class MyConnection(BaseConnection[myconn.MyConnection]): def _connect(self, **kwargs) -> MyConnection: return myconn.connect(**self._secrets, **kwargs) def query(self, query): return self._instance.query(query) Secrets management Secrets singletonAccess secrets from a local TOML file.key = st.secrets["OpenAI_key"] Secrets fileSave your secrets in a per-project or per-profile TOML file.OpenAI_key = "<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#checkboxcheck
DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceremovePAGE ELEMENTSWrite and magicaddText elementsaddData elementsaddChart elementsaddInput widgetsaddMedia elementsaddLayouts and containersaddChat elementsaddStatus elementsaddThird-party componentsopen_in_newAPPLICATION LOGICNavigation and pagesaddExecution flowaddCaching and stateaddConnections and secretsaddCustom componentsaddUtilitiesaddConfigurationaddTOOLSApp testingremovest.testing.v1.AppTestTesting element classesCommand lineaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Develop/API reference/App testing/Testing element classesTesting element classes st.testing.v1.element_tree.Block The Block class has the same methods and attributes as AppTest. A Block instance represents a container of elements just as AppTest represents the entire app. For example, Block.button will produce a WidgetList of Button in the same manner as AppTest.button. ChatMessage, Column, and Tab all inherit from Block. For all container classes, parameters of the original element can be obtained as properties. For example, ChatMessage.avatar and Tab.label. st.testing.v1.element_tree.ElementStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeElement base class for testing. This class's methods and attributes are universal for all elements implemented in testing. For example, Caption, Code, Text, and Title inherit from Element. All widget classes also inherit from Element, but have additional methods specific to each widget type. See the AppTest class for the full list of supported elements. For all element classes, parameters of the original element can be obtained as properties. For example, Button.label, Caption.help, and Toast.icon. Class description[source] st.testing.v1.element_tree.Element(proto, root) Methods run(*, timeout=None) Run the AppTest script which contains the element. Attributes value The value or contents of the element. st.testing.v1.element_tree.ButtonStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.button and st.form_submit_button. Class description[source] st.testing.v1.element_tree.Button(proto, root) Methods click() Set the value of the button to True. run(*, timeout=None) Run the AppTest script which contains the element. set_value(v) Set the value of the button. Attributes value The value of the button. (bool) st.testing.v1.element_tree.ChatInputStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.chat_input. Class description[source] st.testing.v1.element_tree.ChatInput(proto, root) Methods run(*, timeout=None) Run the AppTest script which contains the element. set_value(v) Set the value of the widget. Attributes value The value of the widget. (str) st.testing.v1.element_tree.CheckboxStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.checkbox. Class description[source] st.testing.v1.element_tree.Checkbox(proto, root) Methods check() Set the value of the widget to True. run(*, timeout=None) Run the AppTest script which contains the element. set_value(v) Set the value of the widget. uncheck() Set the value of the widget to False. Attributes value The value of the widget. (bool) st.testing.v1.element_tree.ColorPickerStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.color_picker. Class description[source] st.testing.v1.element_tree.ColorPicker(proto, root) Methods pick(v) Set the value of the widget as a hex string. May omit the "#" prefix. run(*, timeout=None) Run the AppTest script which contains the element. set_value(v) Set the value of the widget as a hex string. Attributes value The currently selected value as a hex string. (str) st.testing.v1.element_tree.DateInputStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.date_input. Class description[source] st.testing.v1.element_tree.DateInput(proto, root) Methods run(*, timeout=None) Run the AppTest script which contains the element. set_value(v) Set the value of the widget. Attributes value The value of the widget. (date or Tuple of date) st.testing.v1.element_tree.MultiselectStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.multiselect. Class description[source] st.testing.v1.element_tree.Multiselect(proto, root) Methods run(*, timeout=None) Run the AppTest script which contains the element. select(v) Add a selection to the widget. Do nothing if the value is already selected. If testing a multiselect widget with repeated options, use set_value instead. set_value(v) Set the value of the multiselect widget. (list) unselect(v) Remove a selection from the widget. Do nothing if the value is not already selected. If a value is selected multiple times, the first instance is removed. Attributes format_func The widget's formatting function for displaying options. (callable) indices The indices of the currently selected values from the options. (list) value The currently selected values from the options. (list) st.testing.v1.element_tree.NumberInputStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.number_input. Class description[source] st.testing.v1.element_tree.NumberInput(proto, root) Methods decrement() Decrement the st.number_input widget as if the user clicked "-". increment() Increment the st.number_input widget as if the user clicked "+". run(*, timeout=None) Run the AppTest script which contains the element. set_value(v) Set the value of the st.number_input widget. Attributes value Get the current value of the st.number_input widget. st.testing.v1.element_tree.RadioStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.radio. Class description[source] st.testing.v1.element_tree.Radio(proto, root) Methods run(*, timeout=None) Run the AppTest script which contains the element. set_value(v) Set the selection by value. Attributes format_func The widget's formatting function for displaying options. (callable) index The index of the current selection. (int) value The currently selected value from the options. (Any) st.testing.v1.element_tree.SelectSliderStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.select_slider. Class description[source] st.testing.v1.element_tree.SelectSlider(proto, root) Methods run(*, timeout=None) Run the AppTest script which contains the element. set_range(lower, upper) Set the ranged selection by values. set_value(v) Set the (single) selection by value. Attributes format_func The widget's formatting function for displaying options. (callable) value The currently selected value or range. (Any or Sequence of Any) st.testing.v1.element_tree.SelectboxStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.selectbox. Class description[source] st.testing.v1.element_tree.Selectbox(proto, root) Methods run(*, timeout=None) Run the AppTest script which contains the element. select(v) Set the selection by value. select_index(index) Set the selection by index. set_value(v) Set the selection by value. Attributes format_func The widget's formatting function for displaying options. (callable) index The index of the current selection. (int) value The currently selected value from the options. (Any) st.testing.v1.element_tree.SliderStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.slider. Class description[source] st.testing.v1.element_tree.Slider(proto, root) Methods run(*, timeout=None) Run the AppTest script which contains the element. set_range(lower, upper) Set the ranged value of the slider. set_value(v) Set the (single) value of the slider. Attributes value The currently selected value or range. (Any or Sequence of Any) st.testing.v1.element_tree.TextAreaStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.text_area. Class description[source] st.testing.v1.element_tree.TextArea(proto, root) Methods input(v) Set the value of the widget only if the value does not exceed the maximum allowed characters. run(*, timeout=None) Run the AppTest script which contains the element. set_value(v) Set the value of the widget. Attributes value The current value of the widget. (str) st.testing.v1.element_tree.TextInputStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.text_input. Class description[source] st.testing.v1.element_tree.TextInput(proto, root) Methods input(v) Set the value of the widget only if the value does not exceed the maximum allowed characters. run(*, timeout=None) Run the AppTest script which contains the element. set_value(v) Set the value of the widget. Attributes value The current value of the widget. (str) st.testing.v1.element_tree.TimeInputStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.time_input. Class description[source] st.testing.v1.element_tree.TimeInput(proto, root) Methods decrement() Select the previous available time. increment() Select the next available time. run(*, timeout=None) Run the AppTest script which contains the element. set_value(v) Set the value of the widget. Attributes value The current value of the widget. (time) st.testing.v1.element_tree.ToggleStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.toggle. Class description[source] st.testing.v1.element_tree.Toggle(proto, root) Methods run(*, timeout=None) Run the AppTest script which contains the element. set_value(v) Set the value of the widget. Attributes value The current value of the widget. (bool) Previous: st.testing.v1.AppTestNext: Command lineforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy
https://docs.streamlit.io/develop/api-reference/caching-and-state/st.cache_resource#example
DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceremovePAGE ELEMENTSWrite and magicaddText elementsaddData elementsaddChart elementsaddInput widgetsaddMedia elementsaddLayouts and containersaddChat elementsaddStatus elementsaddThird-party componentsopen_in_newAPPLICATION LOGICNavigation and pagesaddExecution flowaddCaching and stateremovest.cache_datast.cache_resourcest.cachedeletest.session_statest.query_paramsst.experimental_get_query_paramsdeletest.experimental_set_query_paramsdeleteConnections and secretsaddCustom componentsaddUtilitiesaddConfigurationaddTOOLSApp testingaddCommand lineaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Develop/API reference/Caching and state/st.cache_resourcestarTipThis page only contains information on the st.cache_resource API. For a deeper dive into caching and how to use it, check out Caching. st.cache_resourceStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeDecorator to cache functions that return global resources (e.g. database connections, ML models). Cached objects are shared across all users, sessions, and reruns. They must be thread-safe because they can be accessed from multiple threads concurrently. If thread safety is an issue, consider using st.session_state to store resources per session instead. You can clear a function's cache with func.clear() or clear the entire cache with st.cache_resource.clear(). To cache data, use st.cache_data instead. Learn more about caching at https://docs.streamlit.io/library/advanced-features/caching. Function signature[source] st.cache_resource(func, *, ttl, max_entries, show_spinner, validate, experimental_allow_widgets, hash_funcs=None) Parameters func (callable) The function that creates the cached resource. Streamlit hashes the function's source code. ttl (float, timedelta, str, or None) The maximum time to keep an entry in the cache. Can be one of: None if cache entries should never expire (default). A number specifying the time in seconds. A string specifying the time in a format supported by Pandas's Timedelta constructor, e.g. "1d", "1.5 days", or "1h23s". A timedelta object from Python's built-in datetime library, e.g. timedelta(days=1). max_entries (int or None) The maximum number of entries to keep in the cache, or None for an unbounded cache. When a new entry is added to a full cache, the oldest cached entry will be removed. Defaults to None. show_spinner (bool or str) Enable the spinner. Default is True to show a spinner when there is a "cache miss" and the cached resource is being created. If string, value of show_spinner param will be used for spinner text. validate (callable or None) An optional validation function for cached data. validate is called each time the cached value is accessed. It receives the cached value as its only parameter and it must return a boolean. If validate returns False, the current cached value is discarded, and the decorated function is called to compute a new value. This is useful e.g. to check the health of database connections. experimental_allow_widgets (bool) Allow widgets to be used in the cached function. Defaults to False. Support for widgets in cached functions is currently experimental. Setting this parameter to True may lead to excessive memory use since the widget value is treated as an additional input parameter to the cache. We may remove support for this option at any time without notice. hash_funcs (dict or None) Mapping of types or fully qualified names to hash functions. This is used to override the behavior of the hasher inside Streamlit's caching mechanism: when the hasher encounters an object, it will first check to see if its type matches a key in this dict and, if so, will use the provided function to generate a hash for it. See below for an example of how this can be used. Example import streamlit as st @st.cache_resource def get_database_session(url): # Create a database session object that points to the URL. return session s1 = get_database_session(SESSION_URL_1) # Actually executes the function, since this is the first time it was # encountered. s2 = get_database_session(SESSION_URL_1) # Does not execute the function. Instead, returns its previously computed # value. This means that now the connection object in s1 is the same as in s2. s3 = get_database_session(SESSION_URL_2) # This is a different URL, so the function executes. By default, all parameters to a cache_resource function must be hashable. Any parameter whose name begins with _ will not be hashed. You can use this as an "escape hatch" for parameters that are not hashable: import streamlit as st @st.cache_resource def get_database_session(_sessionmaker, url): # Create a database connection object that points to the URL. return connection s1 = get_database_session(create_sessionmaker(), DATA_URL_1) # Actually executes the function, since this is the first time it was # encountered. s2 = get_database_session(create_sessionmaker(), DATA_URL_1) # Does not execute the function. Instead, returns its previously computed # value - even though the _sessionmaker parameter was different # in both calls. A cache_resource function's cache can be procedurally cleared: import streamlit as st @st.cache_resource def get_database_session(_sessionmaker, url): # Create a database connection object that points to the URL. return connection fetch_and_clean_data.clear(_sessionmaker, "https://streamlit.io/") # Clear the cached entry for the arguments provided. get_database_session.clear() # Clear all cached entries for this function. To override the default hashing behavior, pass a custom hash function. You can do that by mapping a type (e.g. Person) to a hash function (str) like this: import streamlit as st from pydantic import BaseModel class Person(BaseModel): name: str @st.cache_resource(hash_funcs={Person: str}) def get_person_name(person: Person): return person.name Alternatively, you can map the type's fully-qualified name (e.g. "__main__.Person") to the hash function instead: import streamlit as st from pydantic import BaseModel class Person(BaseModel): name: str @st.cache_resource(hash_funcs={"__main__.Person": str}) def get_person_name(person: Person): return person.name st.cache_resource.clearStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeClear all cache_resource caches. Function signature[source] st.cache_resource.clear() Example In the example below, pressing the "Clear All" button will clear all cache_resource caches. i.e. Clears cached global resources from all functions decorated with @st.cache_resource. import streamlit as st from transformers import BertModel @st.cache_resource def get_database_session(url): # Create a database session object that points to the URL. return session @st.cache_resource def get_model(model_type): # Create a model of the specified type. return BertModel.from_pretrained(model_type) if st.button("Clear All"): # Clears all st.cache_resource caches: st.cache_resource.clear() CachedFunc.clearStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeClear the cached function's associated cache. If no arguments are passed, Streamlit will clear all values cached for the function. If arguments are passed, Streamlit will clear the cached value for these arguments only. Function signature[source] CachedFunc.clear(*args, **kwargs) Parameters *args (Any) Arguments of the cached functions. **kwargs (Any) Keyword arguments of the cached function. Example import streamlit as st import time @st.cache_data def foo(bar): time.sleep(2) st.write(f"Executed foo({bar}).") return bar if st.button("Clear all cached values for `foo`", on_click=foo.clear): foo.clear() if st.button("Clear the cached value of `foo(1)`"): foo.clear(1) foo(1) foo(2) Using Streamlit commands in cached functions Static elements Since version 1.16.0, cached functions can contain Streamlit commands! For example, you can do this: from transformers import pipeline @st.cache_resource def load_model(): model = pipeline("sentiment-analysis") st.success("Loaded NLP model from Hugging Face!") # 👈 Show a success message return model As we know, Streamlit only runs this function if it hasn’t been cached before. On this first run, the st.success message will appear in the app. But what happens on subsequent runs? It still shows up! Streamlit realizes that there is an st. command inside the cached function, saves it during the first run, and replays it on subsequent runs. Replaying static elements works for both caching decorators. You can also use this functionality to cache entire parts of your UI: @st.cache_resource def load_model(): st.header("Data analysis") model = torchvision.models.resnet50(weights=ResNet50_Weights.DEFAULT) st.success("Loaded model!") st.write("Turning on evaluation mode...") model.eval() st.write("Here's the model:") return model Input widgets You can also use interactive input widgets like st.slider or st.text_input in cached functions. Widget replay is an experimental feature at the moment. To enable it, you need to set the experimental_allow_widgets parameter: @st.cache_resource(experimental_allow_widgets=True) # 👈 Set the parameter def load_model(): pretrained = st.checkbox("Use pre-trained model:") # 👈 Add a checkbox model = torchvision.models.resnet50(weights=ResNet50_Weights.DEFAULT, pretrained=pretrained) return model Streamlit treats the checkbox like an additional input parameter to the cached function. If you uncheck it, Streamlit will see if it has already cached the function for this checkbox state. If yes, it will return the cached value. If not, it will rerun the function using the new slider value. Using widgets in cached functions is extremely powerful because it lets you cache entire parts of your app. But it can be dangerous! Since Streamlit treats the widget value as an additional input parameter, it can easily lead to excessive memory usage. Imagine your cached function has five sliders and returns a 100 MB DataFrame. Then we’ll add 100 MB to the cache for every permutation of these five slider values – even if the sliders do not influence the returned data! These additions can make your cache explode very quickly. Please be aware of this limitation if you use widgets in cached functions. We recommend using this feature only for isolated parts of your UI where the widgets directly influence the cached return value. priority_highWarningSupport for widgets in cached functions is currently experimental. We may change or remove it anytime without warning. Please use it with care! push_pinNoteTwo widgets are currently not supported in cached functions: st.file_uploader and st.camera_input. We may support them in the future. Feel free to open a GitHub issue if you need them!Previous: st.cache_dataNext: st.cacheforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy
https://docs.streamlit.io/deploy/streamlit-community-cloud/troubleshooting#general-help
DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudremoveGet startedaddDeploy your appaddManage your appaddShare your appaddManage your accountaddTroubleshootingStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Deploy/Streamlit Community Cloud/TroubleshootingTroubleshooting Sorry to hear you're having issues! Please take a look at some frequently asked questions and issues below. If you cannot find an answer to your issue, please post on our Community forum so that our engineers or community members can help you. Table of contents General help Deploying apps Sharing and accessing apps Data and app security GitHub integration Limitations and known issues General help How can I get help with my app? If you have any questions, feedback, run into any issues, or need to reach us, you can ask on our Community forum. This is best suited for any questions related to the open source library and Community Cloud - debugging code, deployment, resource limits, etc. Deploying apps My repo isn't showing on the Deploy page It's possible it just isn't showing up even though it is already there. Try typing it in. If we don't recognize it, you'll see the message below with a link to click and give access. If for some reason that doesn't work, please try logging out and back in again to make sure the change took effect. And if that doesn't work - please let us know and we'll get you sorted! It won't let me deploy the app To deploy an app for the first time you must have admin-level access to the repo in GitHub. Please check with your administrator to make sure you have that access. If not, please ask them to deploy for the first time (we need this in order to establish webhooks for continuous integration) and from there you can then push updates to the app. I need to set a specific Python version for my app When deploying an app, under advanced settings, you can choose which version of Python you wish your app to use. How do I store files locally? If you want to store your data locally as opposed to in a database, you can store the file in your GitHub repository. Streamlit is just python, so you can read the file using: pandas.read_csv("data.csv") or open("data.csv") starTipIf you have really big or binary data that you change frequently, and git is feeling slow, you might want to check out Git Large File Store (LFS) as a better way to store large files in GitHub. You don't need to make any changes to your app to start using it. If your GitHub repo uses LFS, it will now just work with Streamlit. My app is running into issues while deploying Check your Cloud logs by clicking on the "Manage app" expander in the bottom right corner of your screen. Often the trouble is due to a dependency not being declared. See here for more information on dependency management. If that's not the issue, then please send the logs and warning you are seeing to our Community forum and we'll help get you sorted! My app is hitting resource limits / my app is running very slowly If your app is running slowly or you're hitting the 'Argh' page, we first highly recommend going through and implementing the suggestions in the following blog posts to prevent your app from hitting the resource limits and to detect if your Streamlit app leaks memory: Common app problems: Resource limits 3 steps to fix app memory leaks If you're still having issues, click here to learn more about resource limits. Can I get a custom URL for my app? Yes! You can find instructions for setting a custom subdomain here. Sharing and accessing apps Don't have SSO? No problem! You can sign in to Streamlit with your email address. Click here for step-by-step instructions on how to sign in with email. */} How do I add viewers to my Streamlit apps? Viewer auth allows you to restrict the viewers of your private app. To access your app, users have to authenticate using an email-based passwordless login or Google OAuth. To learn more about how to share your public and private apps with viewers, click here. Do viewers need access to the GitHub repo? Nope! You only need access to the GitHub repo if you want to push changes to the app. What will unauthorized/logged out viewers see when they view my app? A 404 error is displayed to unauthorized viewers to avoid providing any unnecessary information about your app to unintended viewers. Users who satisfy any of the following conditions will see a 404 error when attempting to view your app after you have configured viewer auth: User is not logged in with their primary identity. User is not included in the list of allowed viewers provided in the app settings. User lacks read access to your app's GitHub repo. User has read access to your app's GitHub repo but is not enrolled in Streamlit Community Cloud. I've added someone to the viewer list but they still see a 404 error when attempting to view the app If a user is still seeing a 404 error after their email address has been added to the viewer list, we recommend that you: Check that the user did not log into a different Google account via Single Sign-On (if you have added their work email address to the viewer list, ask the user to check that they are not logged into their personal Google account, and vice versa). Check that the user has navigated to the correct URL. Check that the user's email address has been entered correctly in the viewer list. Reach out on our Community forum and we will be happy to help. Data and app security How will Streamlit secure my data? Streamlit takes a number of industry best-practice measures to ensure your code, data, and apps are all secure. Read more in our Trust and Security memo. How do I set up SSO for my organization? Community Cloud uses Google OAuth, by default. If you use Google for authentication you're all set. Billing and administration The Community Cloud is a free service. You don't have to worry about setting up billing or being charged. GitHub integration Why does Streamlit require additional OAuth scope? In order to deploy your app, Streamlit requires access to your app's source code in GitHub and also the ability to manage the public keys associated with the repositories. The default GitHub OAuth scopes are sufficient to work with apps in public GitHub repositories. However, in order to work with apps in private GitHub repositories, Streamlit requires the additional repo OAuth scope from GitHub. We recognize that this scope provides Streamlit with extra permissions that we do not really need, and which, as people who prize security, we'd rather not even be granted. Alas, we need to work with the APIs we are provided by GitHub. After deploying my private-repo app, I received an email from GitHub saying a new public key was added to my repo. Is this expected? This is the expected behavior. When you try to deploy an app that lives in a private repo, Streamlit Community Cloud needs to get access to that repo somehow. For this, we create a read-only GitHub Deploy Key then access your repo using a public SSH key. When we set this up, GitHub notifies admins of the repo that the key was created as a security measure. What happens when a user's permissions change on GitHub? Once a user is added to a repository on GitHub, it will take at most 15 minutes before they can deploy the app on Cloud. If a user is removed from a repository on GitHub, it will take at most 15 minutes before their permissions to manage the app from that repository are revoked. Limitations and known issues Here are some limitations and known issues that we're actively working to resolve. When you print something to the Cloud logs, you may need to do a sys.stdout.flush() before it shows up. Matplotlib doesn't work well with threads. So if you're using Matplotlib you should wrap your code with locks as shown in the snippet below. This Matplotlib bug is more prominent when you share your app apps since you're more likely to get more concurrent users then. from matplotlib.backends.backend_agg import RendererAgg _lock = RendererAgg.lock with _lock: fig.title('This is a figure)') fig.plot([1,20,3,40]) st.pyplot(fig) All apps are hosted in the United States. This is currently not configurable. Previous: Manage your accountNext: Streamlit in SnowflakeforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy
https://docs.streamlit.io/develop/api-reference/app-testing/testing-element-classes#elementrun
DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceremovePAGE ELEMENTSWrite and magicaddText elementsaddData elementsaddChart elementsaddInput widgetsaddMedia elementsaddLayouts and containersaddChat elementsaddStatus elementsaddThird-party componentsopen_in_newAPPLICATION LOGICNavigation and pagesaddExecution flowaddCaching and stateaddConnections and secretsaddCustom componentsaddUtilitiesaddConfigurationaddTOOLSApp testingremovest.testing.v1.AppTestTesting element classesCommand lineaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Develop/API reference/App testing/Testing element classesTesting element classes st.testing.v1.element_tree.Block The Block class has the same methods and attributes as AppTest. A Block instance represents a container of elements just as AppTest represents the entire app. For example, Block.button will produce a WidgetList of Button in the same manner as AppTest.button. ChatMessage, Column, and Tab all inherit from Block. For all container classes, parameters of the original element can be obtained as properties. For example, ChatMessage.avatar and Tab.label. st.testing.v1.element_tree.ElementStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeElement base class for testing. This class's methods and attributes are universal for all elements implemented in testing. For example, Caption, Code, Text, and Title inherit from Element. All widget classes also inherit from Element, but have additional methods specific to each widget type. See the AppTest class for the full list of supported elements. For all element classes, parameters of the original element can be obtained as properties. For example, Button.label, Caption.help, and Toast.icon. Class description[source] st.testing.v1.element_tree.Element(proto, root) Methods run(*, timeout=None) Run the AppTest script which contains the element. Attributes value The value or contents of the element. st.testing.v1.element_tree.ButtonStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.button and st.form_submit_button. Class description[source] st.testing.v1.element_tree.Button(proto, root) Methods click() Set the value of the button to True. run(*, timeout=None) Run the AppTest script which contains the element. set_value(v) Set the value of the button. Attributes value The value of the button. (bool) st.testing.v1.element_tree.ChatInputStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.chat_input. Class description[source] st.testing.v1.element_tree.ChatInput(proto, root) Methods run(*, timeout=None) Run the AppTest script which contains the element. set_value(v) Set the value of the widget. Attributes value The value of the widget. (str) st.testing.v1.element_tree.CheckboxStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.checkbox. Class description[source] st.testing.v1.element_tree.Checkbox(proto, root) Methods check() Set the value of the widget to True. run(*, timeout=None) Run the AppTest script which contains the element. set_value(v) Set the value of the widget. uncheck() Set the value of the widget to False. Attributes value The value of the widget. (bool) st.testing.v1.element_tree.ColorPickerStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.color_picker. Class description[source] st.testing.v1.element_tree.ColorPicker(proto, root) Methods pick(v) Set the value of the widget as a hex string. May omit the "#" prefix. run(*, timeout=None) Run the AppTest script which contains the element. set_value(v) Set the value of the widget as a hex string. Attributes value The currently selected value as a hex string. (str) st.testing.v1.element_tree.DateInputStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.date_input. Class description[source] st.testing.v1.element_tree.DateInput(proto, root) Methods run(*, timeout=None) Run the AppTest script which contains the element. set_value(v) Set the value of the widget. Attributes value The value of the widget. (date or Tuple of date) st.testing.v1.element_tree.MultiselectStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.multiselect. Class description[source] st.testing.v1.element_tree.Multiselect(proto, root) Methods run(*, timeout=None) Run the AppTest script which contains the element. select(v) Add a selection to the widget. Do nothing if the value is already selected. If testing a multiselect widget with repeated options, use set_value instead. set_value(v) Set the value of the multiselect widget. (list) unselect(v) Remove a selection from the widget. Do nothing if the value is not already selected. If a value is selected multiple times, the first instance is removed. Attributes format_func The widget's formatting function for displaying options. (callable) indices The indices of the currently selected values from the options. (list) value The currently selected values from the options. (list) st.testing.v1.element_tree.NumberInputStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.number_input. Class description[source] st.testing.v1.element_tree.NumberInput(proto, root) Methods decrement() Decrement the st.number_input widget as if the user clicked "-". increment() Increment the st.number_input widget as if the user clicked "+". run(*, timeout=None) Run the AppTest script which contains the element. set_value(v) Set the value of the st.number_input widget. Attributes value Get the current value of the st.number_input widget. st.testing.v1.element_tree.RadioStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.radio. Class description[source] st.testing.v1.element_tree.Radio(proto, root) Methods run(*, timeout=None) Run the AppTest script which contains the element. set_value(v) Set the selection by value. Attributes format_func The widget's formatting function for displaying options. (callable) index The index of the current selection. (int) value The currently selected value from the options. (Any) st.testing.v1.element_tree.SelectSliderStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.select_slider. Class description[source] st.testing.v1.element_tree.SelectSlider(proto, root) Methods run(*, timeout=None) Run the AppTest script which contains the element. set_range(lower, upper) Set the ranged selection by values. set_value(v) Set the (single) selection by value. Attributes format_func The widget's formatting function for displaying options. (callable) value The currently selected value or range. (Any or Sequence of Any) st.testing.v1.element_tree.SelectboxStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.selectbox. Class description[source] st.testing.v1.element_tree.Selectbox(proto, root) Methods run(*, timeout=None) Run the AppTest script which contains the element. select(v) Set the selection by value. select_index(index) Set the selection by index. set_value(v) Set the selection by value. Attributes format_func The widget's formatting function for displaying options. (callable) index The index of the current selection. (int) value The currently selected value from the options. (Any) st.testing.v1.element_tree.SliderStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.slider. Class description[source] st.testing.v1.element_tree.Slider(proto, root) Methods run(*, timeout=None) Run the AppTest script which contains the element. set_range(lower, upper) Set the ranged value of the slider. set_value(v) Set the (single) value of the slider. Attributes value The currently selected value or range. (Any or Sequence of Any) st.testing.v1.element_tree.TextAreaStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.text_area. Class description[source] st.testing.v1.element_tree.TextArea(proto, root) Methods input(v) Set the value of the widget only if the value does not exceed the maximum allowed characters. run(*, timeout=None) Run the AppTest script which contains the element. set_value(v) Set the value of the widget. Attributes value The current value of the widget. (str) st.testing.v1.element_tree.TextInputStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.text_input. Class description[source] st.testing.v1.element_tree.TextInput(proto, root) Methods input(v) Set the value of the widget only if the value does not exceed the maximum allowed characters. run(*, timeout=None) Run the AppTest script which contains the element. set_value(v) Set the value of the widget. Attributes value The current value of the widget. (str) st.testing.v1.element_tree.TimeInputStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.time_input. Class description[source] st.testing.v1.element_tree.TimeInput(proto, root) Methods decrement() Select the previous available time. increment() Select the next available time. run(*, timeout=None) Run the AppTest script which contains the element. set_value(v) Set the value of the widget. Attributes value The current value of the widget. (time) st.testing.v1.element_tree.ToggleStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.toggle. Class description[source] st.testing.v1.element_tree.Toggle(proto, root) Methods run(*, timeout=None) Run the AppTest script which contains the element. set_value(v) Set the value of the widget. Attributes value The current value of the widget. (bool) Previous: st.testing.v1.AppTestNext: Command lineforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy
https://docs.streamlit.io/develop/api-reference/app-testing/testing-element-classes#selectboxvalue
DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceremovePAGE ELEMENTSWrite and magicaddText elementsaddData elementsaddChart elementsaddInput widgetsaddMedia elementsaddLayouts and containersaddChat elementsaddStatus elementsaddThird-party componentsopen_in_newAPPLICATION LOGICNavigation and pagesaddExecution flowaddCaching and stateaddConnections and secretsaddCustom componentsaddUtilitiesaddConfigurationaddTOOLSApp testingremovest.testing.v1.AppTestTesting element classesCommand lineaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Develop/API reference/App testing/Testing element classesTesting element classes st.testing.v1.element_tree.Block The Block class has the same methods and attributes as AppTest. A Block instance represents a container of elements just as AppTest represents the entire app. For example, Block.button will produce a WidgetList of Button in the same manner as AppTest.button. ChatMessage, Column, and Tab all inherit from Block. For all container classes, parameters of the original element can be obtained as properties. For example, ChatMessage.avatar and Tab.label. st.testing.v1.element_tree.ElementStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeElement base class for testing. This class's methods and attributes are universal for all elements implemented in testing. For example, Caption, Code, Text, and Title inherit from Element. All widget classes also inherit from Element, but have additional methods specific to each widget type. See the AppTest class for the full list of supported elements. For all element classes, parameters of the original element can be obtained as properties. For example, Button.label, Caption.help, and Toast.icon. Class description[source] st.testing.v1.element_tree.Element(proto, root) Methods run(*, timeout=None) Run the AppTest script which contains the element. Attributes value The value or contents of the element. st.testing.v1.element_tree.ButtonStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.button and st.form_submit_button. Class description[source] st.testing.v1.element_tree.Button(proto, root) Methods click() Set the value of the button to True. run(*, timeout=None) Run the AppTest script which contains the element. set_value(v) Set the value of the button. Attributes value The value of the button. (bool) st.testing.v1.element_tree.ChatInputStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.chat_input. Class description[source] st.testing.v1.element_tree.ChatInput(proto, root) Methods run(*, timeout=None) Run the AppTest script which contains the element. set_value(v) Set the value of the widget. Attributes value The value of the widget. (str) st.testing.v1.element_tree.CheckboxStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.checkbox. Class description[source] st.testing.v1.element_tree.Checkbox(proto, root) Methods check() Set the value of the widget to True. run(*, timeout=None) Run the AppTest script which contains the element. set_value(v) Set the value of the widget. uncheck() Set the value of the widget to False. Attributes value The value of the widget. (bool) st.testing.v1.element_tree.ColorPickerStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.color_picker. Class description[source] st.testing.v1.element_tree.ColorPicker(proto, root) Methods pick(v) Set the value of the widget as a hex string. May omit the "#" prefix. run(*, timeout=None) Run the AppTest script which contains the element. set_value(v) Set the value of the widget as a hex string. Attributes value The currently selected value as a hex string. (str) st.testing.v1.element_tree.DateInputStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.date_input. Class description[source] st.testing.v1.element_tree.DateInput(proto, root) Methods run(*, timeout=None) Run the AppTest script which contains the element. set_value(v) Set the value of the widget. Attributes value The value of the widget. (date or Tuple of date) st.testing.v1.element_tree.MultiselectStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.multiselect. Class description[source] st.testing.v1.element_tree.Multiselect(proto, root) Methods run(*, timeout=None) Run the AppTest script which contains the element. select(v) Add a selection to the widget. Do nothing if the value is already selected. If testing a multiselect widget with repeated options, use set_value instead. set_value(v) Set the value of the multiselect widget. (list) unselect(v) Remove a selection from the widget. Do nothing if the value is not already selected. If a value is selected multiple times, the first instance is removed. Attributes format_func The widget's formatting function for displaying options. (callable) indices The indices of the currently selected values from the options. (list) value The currently selected values from the options. (list) st.testing.v1.element_tree.NumberInputStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.number_input. Class description[source] st.testing.v1.element_tree.NumberInput(proto, root) Methods decrement() Decrement the st.number_input widget as if the user clicked "-". increment() Increment the st.number_input widget as if the user clicked "+". run(*, timeout=None) Run the AppTest script which contains the element. set_value(v) Set the value of the st.number_input widget. Attributes value Get the current value of the st.number_input widget. st.testing.v1.element_tree.RadioStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.radio. Class description[source] st.testing.v1.element_tree.Radio(proto, root) Methods run(*, timeout=None) Run the AppTest script which contains the element. set_value(v) Set the selection by value. Attributes format_func The widget's formatting function for displaying options. (callable) index The index of the current selection. (int) value The currently selected value from the options. (Any) st.testing.v1.element_tree.SelectSliderStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.select_slider. Class description[source] st.testing.v1.element_tree.SelectSlider(proto, root) Methods run(*, timeout=None) Run the AppTest script which contains the element. set_range(lower, upper) Set the ranged selection by values. set_value(v) Set the (single) selection by value. Attributes format_func The widget's formatting function for displaying options. (callable) value The currently selected value or range. (Any or Sequence of Any) st.testing.v1.element_tree.SelectboxStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.selectbox. Class description[source] st.testing.v1.element_tree.Selectbox(proto, root) Methods run(*, timeout=None) Run the AppTest script which contains the element. select(v) Set the selection by value. select_index(index) Set the selection by index. set_value(v) Set the selection by value. Attributes format_func The widget's formatting function for displaying options. (callable) index The index of the current selection. (int) value The currently selected value from the options. (Any) st.testing.v1.element_tree.SliderStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.slider. Class description[source] st.testing.v1.element_tree.Slider(proto, root) Methods run(*, timeout=None) Run the AppTest script which contains the element. set_range(lower, upper) Set the ranged value of the slider. set_value(v) Set the (single) value of the slider. Attributes value The currently selected value or range. (Any or Sequence of Any) st.testing.v1.element_tree.TextAreaStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.text_area. Class description[source] st.testing.v1.element_tree.TextArea(proto, root) Methods input(v) Set the value of the widget only if the value does not exceed the maximum allowed characters. run(*, timeout=None) Run the AppTest script which contains the element. set_value(v) Set the value of the widget. Attributes value The current value of the widget. (str) st.testing.v1.element_tree.TextInputStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.text_input. Class description[source] st.testing.v1.element_tree.TextInput(proto, root) Methods input(v) Set the value of the widget only if the value does not exceed the maximum allowed characters. run(*, timeout=None) Run the AppTest script which contains the element. set_value(v) Set the value of the widget. Attributes value The current value of the widget. (str) st.testing.v1.element_tree.TimeInputStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.time_input. Class description[source] st.testing.v1.element_tree.TimeInput(proto, root) Methods decrement() Select the previous available time. increment() Select the next available time. run(*, timeout=None) Run the AppTest script which contains the element. set_value(v) Set the value of the widget. Attributes value The current value of the widget. (time) st.testing.v1.element_tree.ToggleStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.toggle. Class description[source] st.testing.v1.element_tree.Toggle(proto, root) Methods run(*, timeout=None) Run the AppTest script which contains the element. set_value(v) Set the value of the widget. Attributes value The current value of the widget. (bool) Previous: st.testing.v1.AppTestNext: Command lineforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy
https://docs.streamlit.io/get-started/fundamentals/additional-features#theming
DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsremoveBasic conceptsAdvanced conceptsAdditional featuresSummaryFirst stepsaddcodeDevelopConceptsaddAPI referenceaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Get started/Fundamentals/Additional featuresAdditional Streamlit features So you've read all about Streamlit's Basic concepts and gotten a taste of caching and Session State in Advanced concepts. But what about the bells and whistles? Here's a quick look at some extra features to take your app to the next level. Theming Streamlit supports Light and Dark themes out of the box. Streamlit will first check if the user viewing an app has a Light or Dark mode preference set by their operating system and browser. If so, then that preference will be used. Otherwise, the Light theme is applied by default. You can also change the active theme from "⋮" → "Settings". Want to add your own theme to an app? The "Settings" menu has a theme editor accessible by clicking on "Edit active theme". You can use this editor to try out different colors and see your app update live. When you're happy with your work, themes can be saved by setting config options in the [theme] config section. After you've defined a theme for your app, it will appear as "Custom Theme" in the theme selector and will be applied by default instead of the included Light and Dark themes. More information about the options available when defining a theme can be found in the theme option documentation. push_pinNoteThe theme editor menu is available only in local development. If you've deployed your app using Streamlit Community Cloud, the "Edit active theme" button will no longer be displayed in the "Settings" menu. starTipAnother way to experiment with different theme colors is to turn on the "Run on save" option, edit your config.toml file, and watch as your app reruns with the new theme colors applied. Pages As apps grow large, it becomes useful to organize them into multiple pages. This makes the app easier to manage as a developer and easier to navigate as a user. Streamlit provides a frictionless way to create multipage apps. We designed this feature so that building a multipage app is as easy as building a single-page app! Just add more pages to an existing app as follows: In the folder containing your main script, create a new pages folder. Let’s say your main script is named main_page.py. Add new .py files in the pages folder to add more pages to your app. Run streamlit run main_page.py as usual. That’s it! The main_page.py script will now correspond to the main page of your app. And you’ll see the other scripts from the pages folder in the sidebar page selector. The pages are listed according to filename (without file extensions and disregarding underscores). For example: main_page.pyimport streamlit as st st.markdown("# Main page 🎈") st.sidebar.markdown("# Main page 🎈") pages/page_2.pyimport streamlit as st st.markdown("# Page 2 ❄️") st.sidebar.markdown("# Page 2 ❄️") pages/page_3.pyimport streamlit as st st.markdown("# Page 3 🎉") st.sidebar.markdown("# Page 3 🎉") Now run streamlit run main_page.py and view your shiny new multipage app! Our documentation on Multipage apps teaches you how to add pages to your app, including how to define pages, structure and run multipage apps, and navigate between pages. Once you understand the basics, create your first multipage app! Custom components If you can't find the right component within the Streamlit library, try out custom components to extend Streamlit's built-in functionality. Explore and browse through popular, community-created components in the Components gallery. If you dabble in frontend development, you can build your own custom component with Streamlit's components API. Static file serving As you learned in Streamlit fundamentals, Streamlit runs a server that clients connect to. That means viewers of your app don't have direct access to the files which are local to your app. Most of the time, this doesn't matter because Streamlt commands handle that for you. When you use st.image(<path-to-image>) your Streamlit server will access the file and handle the necessary hosting so your app viewers can see it. However, if you want a direct URL to an image or file you'll need to host it. This requires setting the correct configuration and placing your hosted files in a directory named static. For example, your project could look like: your-project/ ├── static/ │ └── my_hosted-image.png └── streamlit_app.py To learn more, read our guide on Static file serving. App testing Good development hygeine includes testing your code. Automated testing allows you to write higher quality code, faster! Streamlit has a built-in testing framework that let's you build tests easily. Use your favorite testing framework to run your tests. We like pytest. When you test a Streamlit app, you simulate running the app, declare user input, and inspect the results. You can use GitHub workflows to automate your tests and get instant alerts about breaking changes. Learn more in our guide to App testing.Previous: Advanced conceptsNext: SummaryforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy
https://docs.streamlit.io/deploy/streamlit-community-cloud/manage-your-account/update-your-email#how-to-update-your-email
DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudremoveGet startedaddDeploy your appaddManage your appaddShare your appaddManage your accountremoveSign in & sign outWorkspace settingsManage your GitHub connectionUpdate your emailDelete your accountTroubleshootingStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Deploy/Streamlit Community Cloud/Manage your account/Update your emailUpdate your email If you wish to update your email on Streamlit Community Cloud, you can do so via your Workspace settings. Updating your email changes the primary identity of your account. Once updated, if your account's email is associated with a Google account, you can sign in with Google OAuth. Otherwise, you through emailed links. The latter involves typing in your email, after which we'll send you a unique, single-use link (valid for 15 minutes). If you are signed in to GitHub and don't already have a primary identity on your account, see Connect Google to your account. How to update your email Sign in to Streamlit Community Cloud at share.streamlit.io. Click "Settings" in the page's top-right corner. Click "Update email" within the "Linked accounts" section. Enter your new email and click "Update email." You'll see a confirmation dialog asking you to check your email for a confirmation link. Click "Done." Your account settings will show "Update pending" until you complete the next step. Check your inbox for an email from Streamlit containing a "Change email" button and a confirmation link. This one-time link expires in 15 minutes. Click either one to confirm your new email address for Streamlit Community Cloud. Before doing so, ensure you access the link from the same browser session where you are logged in to Streamlit Community Cloud. priority_highImportantIf you access the confirmation link from a browser session where you are not logged in to Streamlit Community Cloud, the confirmation link will not complete the process. You will be prompted to sign in. If you try to sign in with your new email, you will create a second account instead. See Troubleshooting. A confirmation will display to confirm your email update is complete! 🎈 Resend your confirmation link If your confirmation link expires, don't worry! You can resend it by following these steps: Sign in to Streamlit Community Cloud at share.streamlit.io and click "Settings" in the page's top-right corner. Click "Update pending" Click "Resend email" Continue from step 4 of How to update your email. Troubleshooting If you click the confirmation link in a browser session where you are not signed in, you will be informed that "Sign in is required." If you try to sign in with your new email, you will create a second account instead. You cannot resend your confirmation link while you have this second account. If you accidentally created a second account, you can follow the steps to Delete your account to get rid of the duplicate. Afterwards, Resend your confirmation link from your first account. Connect Google to your account If you signed up with GitHub and did not create a primary identity, your workspace will show a warning icon in the upper right corner. Click "Settings" to access your workspace settings. When you access your workspace settings, a warning is displayed: "You are not signed in with a primary identity account." Click "Sign in with Google" and follow Google's authentication prompts. Your account now has both a primary identity and source control account. Previous: Manage your GitHub connectionNext: Delete your accountforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy
https://docs.streamlit.io/develop/api-reference/charts/st.altair_chart#annotating-charts
DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceremovePAGE ELEMENTSWrite and magicaddText elementsaddData elementsaddChart elementsremoveSIMPLEst.area_chartst.bar_chartst.line_chartst.mapst.scatter_chartADVANCEDst.altair_chartst.bokeh_chartst.graphviz_chartst.plotly_chartst.pydeck_chartst.pyplotst.vega_lite_chartInput widgetsaddMedia elementsaddLayouts and containersaddChat elementsaddStatus elementsaddThird-party componentsopen_in_newAPPLICATION LOGICNavigation and pagesaddExecution flowaddCaching and stateaddConnections and secretsaddCustom componentsaddUtilitiesaddConfigurationaddTOOLSApp testingaddCommand lineaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Develop/API reference/Chart elements/st.altair_chartst.altair_chartStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeDisplay a chart using the Altair library. Function signature[source] st.altair_chart(altair_chart, use_container_width=False, theme="streamlit") Parameters altair_chart (altair.Chart) The Altair chart object to display. use_container_width (bool) If True, set the chart width to the column width. This takes precedence over Altair's native width value. theme ("streamlit" or None) The theme of the chart. Currently, we only support "streamlit" for the Streamlit defined design or None to fallback to the default behavior of the library. Example import streamlit as st import pandas as pd import numpy as np import altair as alt chart_data = pd.DataFrame(np.random.randn(20, 3), columns=["a", "b", "c"]) c = ( alt.Chart(chart_data) .mark_circle() .encode(x="a", y="b", size="c", color="c", tooltip=["a", "b", "c"]) ) st.altair_chart(c, use_container_width=True) Built with Streamlit 🎈Fullscreen open_in_new Examples of Altair charts can be found at https://altair-viz.github.io/gallery/. Theming Altair charts are displayed using the Streamlit theme by default. This theme is sleek, user-friendly, and incorporates Streamlit's color palette. The added benefit is that your charts better integrate with the rest of your app's design. The Streamlit theme is available from Streamlit 1.16.0 through the theme="streamlit" keyword argument. To disable it, and use Altair's native theme, use theme=None instead. Let's look at an example of charts with the Streamlit theme and the native Altair theme: import altair as alt from vega_datasets import data source = data.cars() chart = alt.Chart(source).mark_circle().encode( x='Horsepower', y='Miles_per_Gallon', color='Origin', ).interactive() tab1, tab2 = st.tabs(["Streamlit theme (default)", "Altair native theme"]) with tab1: # Use the Streamlit theme. # This is the default. So you can also omit the theme argument. st.altair_chart(chart, theme="streamlit", use_container_width=True) with tab2: # Use the native Altair theme. st.altair_chart(chart, theme=None, use_container_width=True) Click the tabs in the interactive app below to see the charts with the Streamlit theme enabled and disabled. Built with Streamlit 🎈Fullscreen open_in_new If you're wondering if your own customizations will still be taken into account, don't worry! You can still make changes to your chart configurations. In other words, although we now enable the Streamlit theme by default, you can overwrite it with custom colors or fonts. For example, if you want a chart line to be green instead of the default red, you can do it! Here's an example of an Altair chart where manual color passing is done and reflected: See the codeexpand_moreimport altair as alt import streamlit as st from vega_datasets import data source = data.seattle_weather() scale = alt.Scale( domain=["sun", "fog", "drizzle", "rain", "snow"], range=["#e7ba52", "#a7a7a7", "#aec7e8", "#1f77b4", "#9467bd"], ) color = alt.Color("weather:N", scale=scale) # We create two selections: # - a brush that is active on the top panel # - a multi-click that is active on the bottom panel brush = alt.selection_interval(encodings=["x"]) click = alt.selection_multi(encodings=["color"]) # Top panel is scatter plot of temperature vs time points = ( alt.Chart() .mark_point() .encode( alt.X("monthdate(date):T", title="Date"), alt.Y( "temp_max:Q", title="Maximum Daily Temperature (C)", scale=alt.Scale(domain=[-5, 40]), ), color=alt.condition(brush, color, alt.value("lightgray")), size=alt.Size("precipitation:Q", scale=alt.Scale(range=[5, 200])), ) .properties(width=550, height=300) .add_selection(brush) .transform_filter(click) ) # Bottom panel is a bar chart of weather type bars = ( alt.Chart() .mark_bar() .encode( x="count()", y="weather:N", color=alt.condition(click, color, alt.value("lightgray")), ) .transform_filter(brush) .properties( width=550, ) .add_selection(click) ) chart = alt.vconcat(points, bars, data=source, title="Seattle Weather: 2012-2015") tab1, tab2 = st.tabs(["Streamlit theme (default)", "Altair native theme"]) with tab1: st.altair_chart(chart, theme="streamlit", use_container_width=True) with tab2: st.altair_chart(chart, theme=None, use_container_width=True) Notice how the custom colors are still reflected in the chart, even when the Streamlit theme is enabled 👇 Built with Streamlit 🎈Fullscreen open_in_new For many more examples of Altair charts with and without the Streamlit theme, check out the altair.streamlit.app. Annotating charts Altair also allows you to annotate your charts with text, images, and emojis. You can do this by creating layered charts, which let you overlay two different charts on top of each other. The idea is to use the first chart to show the data, and the second chart to show the annotations. The second chart can then be overlaid on top of the first chart using the + operator to create a layered chart. Let's walk through an example of annotating a time-series chart with text and an emoji. Step 1: Create the base chart In this example, we create a time-series chart to track the evolution of stock prices. The chart is interactive and contains a multi-line tooltip. Click here to learn more about multi-line tooltips in Altair. First, we import the required libraries and load the example stocks dataset using the vega_datasets package: import altair as alt import pandas as pd import streamlit as st from vega_datasets import data # We use @st.cache_data to keep the dataset in cache @st.cache_data def get_data(): source = data.stocks() source = source[source.date.gt("2004-01-01")] return source source = get_data() Next, we define a function get_chart() to create the interactive time-series chart of the stock prices with a multi-line tooltip. The x-axis represents the date, and the y-axis represents the stock price. We then invoke get_chart() that takes the stock prices dataframe as an input and returns a chart object. This is going to be our base chart on which we will overlay the annotations in Step 2. # Define the base time-series chart. def get_chart(data): hover = alt.selection_single( fields=["date"], nearest=True, on="mouseover", empty="none", ) lines = ( alt.Chart(data, title="Evolution of stock prices") .mark_line() .encode( x="date", y="price", color="symbol", ) ) # Draw points on the line, and highlight based on selection points = lines.transform_filter(hover).mark_circle(size=65) # Draw a rule at the location of the selection tooltips = ( alt.Chart(data) .mark_rule() .encode( x="yearmonthdate(date)", y="price", opacity=alt.condition(hover, alt.value(0.3), alt.value(0)), tooltip=[ alt.Tooltip("date", title="Date"), alt.Tooltip("price", title="Price (USD)"), ], ) .add_selection(hover) ) return (lines + points + tooltips).interactive() chart = get_chart(source) Step 2: Annotate the chart Now that we have our first chart that shows the data, we can annotate it with text and an emoji. Let's overlay the ⬇ emoji on top of the time-series chart at specifc points of interest. We want users to hover over the ⬇ emoji to see the associated annotation text. For simplicity, let's annotate four specific dates and set the height of the annotations at constant value of 10. starTipYou can vary the horizontal and vertical postions of the annotations by replacing the hard-coded values with the output of Streamlit widgets! Click here to jump to a live example below, and develop an intuition for the ideal horizontal and vertical positions of the annotations by playing with Streamlit widgets. To do so, we create a dataframe annotations_df containing the dates, annotation text, and the height of the annotations: # Add annotations ANNOTATIONS = [ ("Mar 01, 2008", "Pretty good day for GOOG"), ("Dec 01, 2007", "Something's going wrong for GOOG & AAPL"), ("Nov 01, 2008", "Market starts again thanks to..."), ("Dec 01, 2009", "Small crash for GOOG after..."), ] annotations_df = pd.DataFrame(ANNOTATIONS, columns=["date", "event"]) annotations_df.date = pd.to_datetime(annotations_df.date) annotations_df["y"] = 10 Using this dataframe, we create a scatter plot with the x-axis representing the date, and the y-axis representing the height of the annotation. The data point at the specific date and height is represented by the ⬇ emoji, using Altair's mark_text() mark. The annotation text is displayed as a tooltip when users hover over the ⬇ emoji. This is achieved using Altair's encode() method to map the event column containing the annotation text to the visual attribute ⬇ of the plot. annotation_layer = ( alt.Chart(annotations_df) .mark_text(size=20, text="⬇", dx=-8, dy=-10, align="left") .encode( x="date:T", y=alt.Y("y:Q"), tooltip=["event"], ) .interactive() ) Finally, we overlay the annotations on top of the base chart using the + operator to create the final layered chart! 🎈 st.altair_chart( (chart + annotation_layer).interactive(), use_container_width=True ) To use images instead of emojis, replace the line containing .mark_text() with .mark_image(), and replace image_url below with the URL of the image: .mark_image( width=12, height=12, url="image_url", ) Interactive example Now that you've learned how to annotate charts, the sky's the limit! We've extended the above example to let you interactively paste your favorite emoji and set its position on the chart with Streamlit widgets. 👇 Built with Streamlit 🎈Fullscreen open_in_newPrevious: st.scatter_chartNext: st.bokeh_chartforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy
https://docs.streamlit.io/en/latest/api.html#app-testing
DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceremovePAGE ELEMENTSWrite and magicaddText elementsaddData elementsaddChart elementsaddInput widgetsaddMedia elementsaddLayouts and containersaddChat elementsaddStatus elementsaddThird-party componentsopen_in_newAPPLICATION LOGICNavigation and pagesaddExecution flowaddCaching and stateaddConnections and secretsaddCustom componentsaddUtilitiesaddConfigurationaddTOOLSApp testingaddCommand lineaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Develop/API referenceAPI reference Streamlit makes it easy for you to visualize, mutate, and share data. The API reference is organized by activity type, like displaying data or optimizing performance. Each section includes methods associated with the activity type, including examples. Browse our API below and click to learn more about any of our available commands! 🎈 Display almost anything Write and magic st.writeWrite arguments to the app.st.write("Hello **world**!") st.write(my_data_frame) st.write(my_mpl_figure) st.write_streamWrite generators or streams to the app with a typewriter effect.st.write_stream(my_generator) st.write_stream(my_llm_stream) MagicAny time Streamlit sees either a variable or literal value on its own line, it automatically writes that to your app using st.write"Hello **world**!" my_data_frame my_mpl_figure Text elements MarkdownDisplay string formatted as Markdown.st.markdown("Hello **world**!") TitleDisplay text in title formatting.st.title("The app title") HeaderDisplay text in header formatting.st.header("This is a header") SubheaderDisplay text in subheader formatting.st.subheader("This is a subheader") CaptionDisplay text in small font.st.caption("This is written small caption text") Code blockDisplay a code block with optional syntax highlighting.st.code("a = 1234") EchoDisplay some code in the app, then execute it. Useful for tutorials.with st.echo(): st.write('This code will be printed') LaTeXDisplay mathematical expressions formatted as LaTeX.st.latex("\int a x^2 \,dx") Preformatted textWrite fixed-width and preformatted text.st.text("Hello world") DividerDisplay a horizontal rule.st.divider() Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration! PreviousTagsAdd tags to your Streamlit apps. Created by @gagan3012.st_tags(label='# Enter Keywords:', text='Press enter to add more', value=['Zero', 'One', 'Two'], suggestions=['five', 'six', 'seven', 'eight', 'nine', 'three', 'eleven', 'ten', 'four'], maxtags = 4, key='1') NLUApply text mining on a dataframe. Created by @JohnSnowLabs.nlu.load('sentiment').predict('I love NLU! <3') Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.mention(label="An awesome Streamlit App", icon="streamlit", url="https://extras.streamlit.app",) Annotated textDisplay annotated text in Streamlit apps. Created by @tvst.annotated_text("This ", ("is", "verb"), " some ", ("annotated", "adj"), ("text", "noun"), " for those of ", ("you", "pronoun"), " who ", ("like", "verb"), " this sort of ", ("thing", "noun"), ".") Drawable CanvasProvides a sketching canvas using Fabric.js. Created by @andfanilo.st_canvas(fill_color="rgba(255, 165, 0, 0.3)", stroke_width=stroke_width, stroke_color=stroke_color, background_color=bg_color, background_image=Image.open(bg_image) if bg_image else None, update_streamlit=realtime_update, height=150, drawing_mode=drawing_mode, point_display_radius=point_display_radius if drawing_mode == 'point' else 0, key="canvas",) TagsAdd tags to your Streamlit apps. Created by @gagan3012.st_tags(label='# Enter Keywords:', text='Press enter to add more', value=['Zero', 'One', 'Two'], suggestions=['five', 'six', 'seven', 'eight', 'nine', 'three', 'eleven', 'ten', 'four'], maxtags = 4, key='1') NLUApply text mining on a dataframe. Created by @JohnSnowLabs.nlu.load('sentiment').predict('I love NLU! <3') Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.mention(label="An awesome Streamlit App", icon="streamlit", url="https://extras.streamlit.app",) Annotated textDisplay annotated text in Streamlit apps. Created by @tvst.annotated_text("This ", ("is", "verb"), " some ", ("annotated", "adj"), ("text", "noun"), " for those of ", ("you", "pronoun"), " who ", ("like", "verb"), " this sort of ", ("thing", "noun"), ".") Drawable CanvasProvides a sketching canvas using Fabric.js. Created by @andfanilo.st_canvas(fill_color="rgba(255, 165, 0, 0.3)", stroke_width=stroke_width, stroke_color=stroke_color, background_color=bg_color, background_image=Image.open(bg_image) if bg_image else None, update_streamlit=realtime_update, height=150, drawing_mode=drawing_mode, point_display_radius=point_display_radius if drawing_mode == 'point' else 0, key="canvas",) TagsAdd tags to your Streamlit apps. Created by @gagan3012.st_tags(label='# Enter Keywords:', text='Press enter to add more', value=['Zero', 'One', 'Two'], suggestions=['five', 'six', 'seven', 'eight', 'nine', 'three', 'eleven', 'ten', 'four'], maxtags = 4, key='1') NLUApply text mining on a dataframe. Created by @JohnSnowLabs.nlu.load('sentiment').predict('I love NLU! <3') Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.mention(label="An awesome Streamlit App", icon="streamlit", url="https://extras.streamlit.app",) Next Data elements DataframesDisplay a dataframe as an interactive table.st.dataframe(my_data_frame) Data editorDisplay a data editor widget.edited = st.data_editor(df, num_rows="dynamic") Column configurationConfigure the display and editing behavior of dataframes and data editors.st.column_config.NumberColumn("Price (in USD)", min_value=0, format="$%d") Static tablesDisplay a static table.st.table(my_data_frame) MetricsDisplay a metric in big bold font, with an optional indicator of how the metric changed.st.metric("My metric", 42, 2) Dicts and JSONDisplay object or string as a pretty-printed JSON string.st.json(my_dict) Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration! PreviousImage CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates value = streamlit_image_coordinates("https://placekitten.com/200/300") st.write(value) Plotly EventsMake Plotly charts interactive!. Created by @null-jones.from streamlit_plotly_events import plotly_events fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.metric_cards import style_metric_cards col3.metric(label="No Change", value=5000, delta=0) style_metric_cards() Streamlit AggridImplementation of Ag-Grid component for Streamlit. Created by @PablocFonseca.df = pd.DataFrame({'col1': [1, 2, 3], 'col2': [4, 5, 6]}) grid_return = AgGrid(df, editable=True) new_df = grid_return['data'] Streamlit FoliumStreamlit Component for rendering Folium maps. Created by @randyzwitch.m = folium.Map(location=[39.949610, -75.150282], zoom_start=16) folium.Marker([39.949610, -75.150282], popup="Liberty Bell", tooltip="Liberty Bell").add_to(m) st_data = st_folium(m, width=725) Pandas ProfilingPandas profiling component for Streamlit. Created by @okld.df = pd.read_csv("https://storage.googleapis.com/tf-datasets/titanic/train.csv") pr = df.profile_report() st_profile_report(pr) Image CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates value = streamlit_image_coordinates("https://placekitten.com/200/300") st.write(value) Plotly EventsMake Plotly charts interactive!. Created by @null-jones.from streamlit_plotly_events import plotly_events fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.metric_cards import style_metric_cards col3.metric(label="No Change", value=5000, delta=0) style_metric_cards() Streamlit AggridImplementation of Ag-Grid component for Streamlit. Created by @PablocFonseca.df = pd.DataFrame({'col1': [1, 2, 3], 'col2': [4, 5, 6]}) grid_return = AgGrid(df, editable=True) new_df = grid_return['data'] Streamlit FoliumStreamlit Component for rendering Folium maps. Created by @randyzwitch.m = folium.Map(location=[39.949610, -75.150282], zoom_start=16) folium.Marker([39.949610, -75.150282], popup="Liberty Bell", tooltip="Liberty Bell").add_to(m) st_data = st_folium(m, width=725) Pandas ProfilingPandas profiling component for Streamlit. Created by @okld.df = pd.read_csv("https://storage.googleapis.com/tf-datasets/titanic/train.csv") pr = df.profile_report() st_profile_report(pr) Image CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates value = streamlit_image_coordinates("https://placekitten.com/200/300") st.write(value) Plotly EventsMake Plotly charts interactive!. Created by @null-jones.from streamlit_plotly_events import plotly_events fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.metric_cards import style_metric_cards col3.metric(label="No Change", value=5000, delta=0) style_metric_cards() Next Chart elements Simple area chartsDisplay an area chart.st.area_chart(my_data_frame) Simple bar chartsDisplay a bar chart.st.bar_chart(my_data_frame) Simple line chartsDisplay a line chart.st.line_chart(my_data_frame) Simple scatter chartsDisplay a line chart.st.scatter_chart(my_data_frame) Scatterplots on mapsDisplay a map with points on it.st.map(my_data_frame) MatplotlibDisplay a matplotlib.pyplot figure.st.pyplot(my_mpl_figure) AltairDisplay a chart using the Altair library.st.altair_chart(my_altair_chart) Vega-LiteDisplay a chart using the Vega-Lite library.st.vega_lite_chart(my_vega_lite_chart) PlotlyDisplay an interactive Plotly chart.st.plotly_chart(my_plotly_chart) BokehDisplay an interactive Bokeh chart.st.bokeh_chart(my_bokeh_chart) PyDeckDisplay a chart using the PyDeck library.st.pydeck_chart(my_pydeck_chart) GraphVizDisplay a graph using the dagre-d3 library.st.graphviz_chart(my_graphviz_spec) Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration! PreviousStreamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl("https://assets5.lottiefiles.com/packages/lf20_V9t630.json") st_lottie(lottie_hello, key="hello") Plotly EventsMake Plotly charts interactive!. Created by @null-jones.fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.chart += get_annotations_chart(annotations=[("Mar 01, 2008", "Pretty good day for GOOG"), ("Dec 01, 2007", "Something's going wrong for GOOG & AAPL"), ("Nov 01, 2008", "Market starts again thanks to..."), ("Dec 01, 2009", "Small crash for GOOG after..."),],) st.altair_chart(chart, use_container_width=True) PlostA deceptively simple plotting library for Streamlit. Created by @tvst.import plost plost.line_chart(my_dataframe, x='time', y='stock_value', color='stock_name',) HiPlotHigh dimensional Interactive Plotting. Created by @facebookresearch.data = [{'dropout':0.1, 'lr': 0.001, 'loss': 10.0, 'optimizer': 'SGD'}, {'dropout':0.15, 'lr': 0.01, 'loss': 3.5, 'optimizer': 'Adam'}, {'dropout':0.3, 'lr': 0.1, 'loss': 4.5, 'optimizer': 'Adam'}] hip.Experiment.from_iterable(data).display() EChartsHigh dimensional Interactive Plotting. Created by @andfanilo.from streamlit_echarts import st_echarts st_echarts(options=options) Streamlit FoliumStreamlit Component for rendering Folium maps. Created by @randyzwitch.m = folium.Map(location=[39.949610, -75.150282], zoom_start=16) st_data = st_folium(m, width=725) Spacy-StreamlitspaCy building blocks and visualizers for Streamlit apps. Created by @explosion.models = ["en_core_web_sm", "en_core_web_md"] spacy_streamlit.visualize(models, "Sundar Pichai is the CEO of Google.") Streamlit AgraphA Streamlit Graph Vis, based on react-grah-vis. Created by @ChrisDelClea.from streamlit_agraph import agraph, Node, Edge, Config agraph(nodes=nodes, edges=edges, config=config) Streamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl("https://assets5.lottiefiles.com/packages/lf20_V9t630.json") st_lottie(lottie_hello, key="hello") Plotly EventsMake Plotly charts interactive!. Created by @null-jones.fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.chart += get_annotations_chart(annotations=[("Mar 01, 2008", "Pretty good day for GOOG"), ("Dec 01, 2007", "Something's going wrong for GOOG & AAPL"), ("Nov 01, 2008", "Market starts again thanks to..."), ("Dec 01, 2009", "Small crash for GOOG after..."),],) st.altair_chart(chart, use_container_width=True) PlostA deceptively simple plotting library for Streamlit. Created by @tvst.import plost plost.line_chart(my_dataframe, x='time', y='stock_value', color='stock_name',) HiPlotHigh dimensional Interactive Plotting. Created by @facebookresearch.data = [{'dropout':0.1, 'lr': 0.001, 'loss': 10.0, 'optimizer': 'SGD'}, {'dropout':0.15, 'lr': 0.01, 'loss': 3.5, 'optimizer': 'Adam'}, {'dropout':0.3, 'lr': 0.1, 'loss': 4.5, 'optimizer': 'Adam'}] hip.Experiment.from_iterable(data).display() EChartsHigh dimensional Interactive Plotting. Created by @andfanilo.from streamlit_echarts import st_echarts st_echarts(options=options) Streamlit FoliumStreamlit Component for rendering Folium maps. Created by @randyzwitch.m = folium.Map(location=[39.949610, -75.150282], zoom_start=16) st_data = st_folium(m, width=725) Spacy-StreamlitspaCy building blocks and visualizers for Streamlit apps. Created by @explosion.models = ["en_core_web_sm", "en_core_web_md"] spacy_streamlit.visualize(models, "Sundar Pichai is the CEO of Google.") Streamlit AgraphA Streamlit Graph Vis, based on react-grah-vis. Created by @ChrisDelClea.from streamlit_agraph import agraph, Node, Edge, Config agraph(nodes=nodes, edges=edges, config=config) Streamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl("https://assets5.lottiefiles.com/packages/lf20_V9t630.json") st_lottie(lottie_hello, key="hello") Plotly EventsMake Plotly charts interactive!. Created by @null-jones.fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.chart += get_annotations_chart(annotations=[("Mar 01, 2008", "Pretty good day for GOOG"), ("Dec 01, 2007", "Something's going wrong for GOOG & AAPL"), ("Nov 01, 2008", "Market starts again thanks to..."), ("Dec 01, 2009", "Small crash for GOOG after..."),],) st.altair_chart(chart, use_container_width=True) Next Input widgets ButtonDisplay a button widget.clicked = st.button("Click me") Download buttonDisplay a download button widget.st.download_button("Download file", file) Form buttonDisplay a form submit button. For use with st.form.st.form_submit_button("Sign up") Link buttonDisplay a link button.st.link_button("Go to gallery", url) Page linkDisplay a link to another page in a multipage app.st.page_link("app.py", label="Home", icon="🏠") st.page_link("pages/profile.py", label="My profile") CheckboxDisplay a checkbox widget.selected = st.checkbox("I agree") Color pickerDisplay a color picker widget.color = st.color_picker("Pick a color") MultiselectDisplay a multiselect widget. The multiselect widget starts as empty.choices = st.multiselect("Buy", ["milk", "apples", "potatoes"]) RadioDisplay a radio button widget.choice = st.radio("Pick one", ["cats", "dogs"]) SelectboxDisplay a select widget.choice = st.selectbox("Pick one", ["cats", "dogs"]) Select-sliderDisplay a slider widget to select items from a list.size = st.select_slider("Pick a size", ["S", "M", "L"]) ToggleDisplay a toggle widget.activated = st.toggle("Activate") Number inputDisplay a numeric input widget.choice = st.number_input("Pick a number", 0, 10) SliderDisplay a slider widget.number = st.slider("Pick a number", 0, 100) Date inputDisplay a date input widget.date = st.date_input("Your birthday") Time inputDisplay a time input widget.time = st.time_input("Meeting time") Chat inputDisplay a chat input widget.prompt = st.chat_input("Say something") if prompt: st.write(f"The user has sent: {prompt}") Text-areaDisplay a multi-line text input widget.text = st.text_area("Text to translate") Text inputDisplay a single-line text input widget.name = st.text_input("First name") Data editorDisplay a data editor widget.edited = st.experimental_data_editor(df, num_rows="dynamic") File UploaderDisplay a file uploader widget.data = st.file_uploader("Upload a CSV") Camera inputDisplay a widget that allows users to upload images directly from a camera.image = st.camera_input("Take a picture") Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration! PreviousStreamlit ChatStreamlit Component for a Chatbot UI. Created by @AI-Yash.from streamlit_chat import message message("My message") message("Hello bot!", is_user=True) # align's the message to the right Streamlit Option MenuSelect a single item from a list of options in a menu. Created by @victoryhb.from streamlit_option_menu import option_menu option_menu("Main Menu", ["Home", 'Settings'], icons=['house', 'gear'], menu_icon="cast", default_index=1) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.stoggle import stoggle stoggle( "Click me!", """🥷 Surprise! Here's some additional content""",) Streamlit ElementsCreate a draggable and resizable dashboard in Streamlit. Created by @okls.from streamlit_elements import elements, mui, html with elements("new_element"): mui.Typography("Hello world") TagsAdd tags to your Streamlit apps. Created by @gagan3012.from streamlit_tags import st_tags st_tags(label='# Enter Keywords:', text='Press enter to add more', value=['Zero', 'One', 'Two'], suggestions=['five', 'six', 'seven', 'eight', 'nine', 'three', 'eleven', 'ten', 'four'], maxtags = 4, key='1') StqdmThe simplest way to handle a progress bar in streamlit app. Created by @Wirg.from stqdm import stqdm for _ in stqdm(range(50)): sleep(0.5) TimelineDisplay a Timeline in Streamlit apps using TimelineJS. Created by @innerdoc.from streamlit_timeline import timeline with open('example.json', "r") as f: timeline(f.read(), height=800) Camera input liveAlternative for st.camera_input which returns the webcam images live. Created by @blackary.from camera_input_live import camera_input_live image = camera_input_live() st.image(value) Streamlit AceAce editor component for Streamlit. Created by @okld.from streamlit_ace import st_ace content = st_ace() content Streamlit ChatStreamlit Component for a Chatbot UI. Created by @AI-Yash.from streamlit_chat import message message("My message") message("Hello bot!", is_user=True) # align's the message to the right Streamlit Option MenuSelect a single item from a list of options in a menu. Created by @victoryhb.from streamlit_option_menu import option_menu option_menu("Main Menu", ["Home", 'Settings'], icons=['house', 'gear'], menu_icon="cast", default_index=1) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.stoggle import stoggle stoggle( "Click me!", """🥷 Surprise! Here's some additional content""",) Streamlit ElementsCreate a draggable and resizable dashboard in Streamlit. Created by @okls.from streamlit_elements import elements, mui, html with elements("new_element"): mui.Typography("Hello world") TagsAdd tags to your Streamlit apps. Created by @gagan3012.from streamlit_tags import st_tags st_tags(label='# Enter Keywords:', text='Press enter to add more', value=['Zero', 'One', 'Two'], suggestions=['five', 'six', 'seven', 'eight', 'nine', 'three', 'eleven', 'ten', 'four'], maxtags = 4, key='1') StqdmThe simplest way to handle a progress bar in streamlit app. Created by @Wirg.from stqdm import stqdm for _ in stqdm(range(50)): sleep(0.5) TimelineDisplay a Timeline in Streamlit apps using TimelineJS. Created by @innerdoc.from streamlit_timeline import timeline with open('example.json', "r") as f: timeline(f.read(), height=800) Camera input liveAlternative for st.camera_input which returns the webcam images live. Created by @blackary.from camera_input_live import camera_input_live image = camera_input_live() st.image(value) Streamlit AceAce editor component for Streamlit. Created by @okld.from streamlit_ace import st_ace content = st_ace() content Streamlit ChatStreamlit Component for a Chatbot UI. Created by @AI-Yash.from streamlit_chat import message message("My message") message("Hello bot!", is_user=True) # align's the message to the right Streamlit Option MenuSelect a single item from a list of options in a menu. Created by @victoryhb.from streamlit_option_menu import option_menu option_menu("Main Menu", ["Home", 'Settings'], icons=['house', 'gear'], menu_icon="cast", default_index=1) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.stoggle import stoggle stoggle( "Click me!", """🥷 Surprise! Here's some additional content""",) Next Media elements ImageDisplay an image or list of images.st.image(numpy_array) st.image(image_bytes) st.image(file) st.image("https://example.com/myimage.jpg") AudioDisplay an audio player.st.audio(numpy_array) st.audio(audio_bytes) st.audio(file) st.audio("https://example.com/myaudio.mp3", format="audio/mp3") VideoDisplay a video player.st.video(numpy_array) st.video(video_bytes) st.video(file) st.video("https://example.com/myvideo.mp4", format="video/mp4") Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration! PreviousStreamlit CropperA simple image cropper for Streamlit. Created by @turner-anderson.from streamlit_cropper import st_cropper st_cropper(img, realtime_update=realtime_update, box_color=box_color, aspect_ratio=aspect_ratio) Image CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates streamlit_image_coordinates("https://placekitten.com/200/300") Streamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl("https://assets5.lottiefiles.com/packages/lf20_V9t630.json") st_lottie(lottie_hello, key="hello") Streamlit WebrtcHandling and transmitting real-time video/audio streams with Streamlit. Created by @whitphx.from streamlit_webrtc import webrtc_streamer webrtc_streamer(key="sample") Drawable CanvasProvides a sketching canvas using Fabric.js. Created by @andfanilo.from streamlit_drawable_canvas import st_canvas st_canvas(fill_color="rgba(255, 165, 0, 0.3)", stroke_width=stroke_width, stroke_color=stroke_color, background_color=bg_color, background_image=Image.open(bg_image) if bg_image else None, update_streamlit=realtime_update, height=150, drawing_mode=drawing_mode, point_display_radius=point_display_radius if drawing_mode == 'point' else 0, key="canvas",) Image ComparisonCompare images with a slider using JuxtaposeJS. Created by @fcakyon.from streamlit_image_comparison import image_comparison image_comparison(img1="image1.jpg", img2="image2.jpg",) Streamlit CropperA simple image cropper for Streamlit. Created by @turner-anderson.from streamlit_cropper import st_cropper st_cropper(img, realtime_update=realtime_update, box_color=box_color, aspect_ratio=aspect_ratio) Image CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates streamlit_image_coordinates("https://placekitten.com/200/300") Streamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl("https://assets5.lottiefiles.com/packages/lf20_V9t630.json") st_lottie(lottie_hello, key="hello") Streamlit WebrtcHandling and transmitting real-time video/audio streams with Streamlit. Created by @whitphx.from streamlit_webrtc import webrtc_streamer webrtc_streamer(key="sample") Drawable CanvasProvides a sketching canvas using Fabric.js. Created by @andfanilo.from streamlit_drawable_canvas import st_canvas st_canvas(fill_color="rgba(255, 165, 0, 0.3)", stroke_width=stroke_width, stroke_color=stroke_color, background_color=bg_color, background_image=Image.open(bg_image) if bg_image else None, update_streamlit=realtime_update, height=150, drawing_mode=drawing_mode, point_display_radius=point_display_radius if drawing_mode == 'point' else 0, key="canvas",) Image ComparisonCompare images with a slider using JuxtaposeJS. Created by @fcakyon.from streamlit_image_comparison import image_comparison image_comparison(img1="image1.jpg", img2="image2.jpg",) Streamlit CropperA simple image cropper for Streamlit. Created by @turner-anderson.from streamlit_cropper import st_cropper st_cropper(img, realtime_update=realtime_update, box_color=box_color, aspect_ratio=aspect_ratio) Image CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates streamlit_image_coordinates("https://placekitten.com/200/300") Streamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl("https://assets5.lottiefiles.com/packages/lf20_V9t630.json") st_lottie(lottie_hello, key="hello") Next Layouts and containers ColumnsInsert containers laid out as side-by-side columns.col1, col2 = st.columns(2) col1.write("this is column 1") col2.write("this is column 2") ContainerInsert a multi-element container.c = st.container() st.write("This will show last") c.write("This will show first") c.write("This will show second") Modal dialogsInsert a modal dialog that can rerun independently from the rest of the script.@st.experimental_dialog("Sign up") def email_form(): name = st.text_input("Name") email = st.text_input("Email") EmptyInsert a single-element container.c = st.empty() st.write("This will show last") c.write("This will be replaced") c.write("This will show first") ExpanderInsert a multi-element container that can be expanded/collapsed.with st.expander("Open to see more"): st.write("This is more content") PopoverInsert a multi-element popover container that can be opened/closed.with st.popover("Settings"): st.checkbox("Show completed") SidebarDisplay items in a sidebar.st.sidebar.write("This lives in the sidebar") st.sidebar.button("Click me!") TabsInsert containers separated into tabs.tab1, tab2 = st.tabs(["Tab 1", "Tab2"]) tab1.write("this is tab 1") tab2.write("this is tab 2") Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration!Streamlit ElementsCreate a draggable and resizable dashboard in Streamlit. Created by @okls.from streamlit_elements import elements, mui, html with elements("new_element"): mui.Typography("Hello world") PydanticAuto-generate Streamlit UI from Pydantic Models and Dataclasses. Created by @lukasmasuch.import streamlit_pydantic as sp sp.pydantic_form(key="my_form", model=ExampleModel) Streamlit PagesAn experimental version of Streamlit Multi-Page Apps. Created by @blackary.from st_pages import Page, show_pages, add_page_title show_pages([ Page("streamlit_app.py", "Home", "🏠"), Page("other_pages/page2.py", "Page 2", ":books:"), ]) Chat elements Streamlit provides a few commands to help you build conversational apps. These chat elements are designed to be used in conjunction with each other, but you can also use them separately. st.chat_message lets you insert a chat message container into the app so you can display messages from the user or the app. Chat containers can contain other Streamlit elements, including charts, tables, text, and more. st.chat_input lets you display a chat input widget so the user can type in a message. Chat inputDisplay a chat input widget.prompt = st.chat_input("Say something") if prompt: st.write(f"The user has sent: {prompt}") Chat messageInsert a chat message container.import numpy as np with st.chat_message("user"): st.write("Hello 👋") st.line_chart(np.random.randn(30, 3)) Status containerDisplay output of long-running tasks in a container.with st.status('Running'): do_something_slow() st.write_streamWrite generators or streams to the app with a typewriter effect.st.write_stream(my_generator) st.write_stream(my_llm_stream) Status elements Progress barDisplay a progress bar.for i in range(101): st.progress(i) do_something_slow() SpinnerTemporarily displays a message while executing a block of code.with st.spinner("Please wait..."): do_something_slow() Status containerDisplay output of long-running tasks in a container.with st.status('Running'): do_something_slow() ToastBriefly displays a toast message in the bottom-right corner.st.toast('Butter!', icon='🧈') BalloonsDisplay celebratory balloons!do_something() # Celebrate when all done! st.balloons() SnowflakesDisplay celebratory snowflakes!do_something() # Celebrate when all done! st.snow() Success boxDisplay a success message.st.success("Match found!") Info boxDisplay an informational message.st.info("Dataset is updated every day at midnight.") Warning boxDisplay warning message.st.warning("Unable to fetch image. Skipping...") Error boxDisplay error message.st.error("We encountered an error") Exception outputDisplay an exception.e = RuntimeError("This is an exception of type RuntimeError") st.exception(e) Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration!StqdmThe simplest way to handle a progress bar in streamlit app. Created by @Wirg.from stqdm import stqdm for _ in stqdm(range(50)): sleep(0.5) Custom notification boxA custom notification box with the ability to close it out. Created by @Socvest.from streamlit_custom_notification_box import custom_notification_box styles = {'material-icons':{'color': 'red'}, 'text-icon-link-close-container': {'box-shadow': '#3896de 0px 4px'}, 'notification-text': {'':''}, 'close-button':{'':''}, 'link':{'':''}} custom_notification_box(icon='info', textDisplay='We are almost done with your registration...', externalLink='more info', url='#', styles=styles, key="foo") Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.let_it_rain import rain rain(emoji="🎈", font_size=54, falling_speed=5, animation_length="infinite",) App logic and configuration Navigation and pages Switch pageProgrammatically navigates to a specified page.st.switch_page("pages/my_page.py") Page linkDisplay a link to another page in a multipage app.st.page_link("app.py", label="Home", icon="🏠") st.page_link("pages/profile.py", label="My profile") Execution flow Modal dialogsInsert a modal dialog that can rerun independently from the rest of the script.@st.experimental_dialog("Sign up") def email_form(): name = st.text_input("Name") email = st.text_input("Email") FormsCreate a form that batches elements together with a “Submit" button.with st.form(key='my_form'): name = st.text_input("Name") email = st.text_input("Email") st.form_submit_button("Sign up") Partial rerunsDefine a fragment to rerun independently from the rest of the script.@st.experimental_fragment(run_every="10s") def fragment(): df = get_data() st.line_chart(df) Rerun scriptRerun the script immediately.st.rerun() Stop executionStops execution immediately.st.stop() Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration!AutorefreshForce a refresh without tying up a script. Created by @kmcgrady.from streamlit_autorefresh import st_autorefresh st_autorefresh(interval=2000, limit=100, key="fizzbuzzcounter") PydanticAuto-generate Streamlit UI from Pydantic Models and Dataclasses. Created by @lukasmasuch.import streamlit_pydantic as sp sp.pydantic_form(key="my_form", model=ExampleModel) Streamlit PagesAn experimental version of Streamlit Multi-Page Apps. Created by @blackary.from st_pages import Page, show_pages, add_page_title show_pages([ Page("streamlit_app.py", "Home", "🏠"), Page("other_pages/page2.py", "Page 2", ":books:"), ]) Caching and state Cache dataFunction decorator to cache functions that return data (e.g. dataframe transforms, database queries, ML inference).@st.cache_data def long_function(param1, param2): # Perform expensive computation here or # fetch data from the web here return data Cache resourceFunction decorator to cache functions that return global resources (e.g. database connections, ML models).@st.cache_resource def init_model(): # Return a global resource here return pipeline( "sentiment-analysis", model="distilbert-base-uncased-finetuned-sst-2-english" ) Session stateSession state is a way to share variables between reruns, for each user session.st.session_state['key'] = value Query parametersGet, set, or clear the query parameters that are shown in the browser's URL bar.st.query_params[key] = value st.query_params.clear() Connections and databases Setup your connection Create a connectionConnect to a data source or APIconn = st.connection('pets_db', type='sql') pet_owners = conn.query('select * from pet_owners') st.dataframe(pet_owners) Built-in connections SnowflakeConnectionA connection to Snowflake.conn = st.connection('snowflake') SQLConnectionA connection to a SQL database using SQLAlchemy.conn = st.connection('sql') Build your own connections Connection base classBuild your own connection with BaseConnection.class MyConnection(BaseConnection[myconn.MyConnection]): def _connect(self, **kwargs) -> MyConnection: return myconn.connect(**self._secrets, **kwargs) def query(self, query): return self._instance.query(query) Secrets management Secrets singletonAccess secrets from a local TOML file.key = st.secrets["OpenAI_key"] Secrets fileSave your secrets in a per-project or per-profile TOML file.OpenAI_key = "<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/knowledge-base/deploy/unable-to-edit-or-delete-apps-in-streamlit-community-cloud-after-modifying-github-username
DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Knowledge base/Deployment issues/Unable to edit or delete apps in Streamlit Community Cloud after modifying GitHub usernameUnable to edit or delete apps in Streamlit Community Cloud after modifying GitHub username Problem After updating the GitHub username, apps cannot be edited or deleted from Streamlit Community Cloud. Solution Support can delete your old applications that were deployed before updating the GitHub username. Once deleted, you can redeploy the applications using the new GitHub username. Please contact Support with a list of the URLs for the apps you need to be deleted. Previous: Upgrade the Streamlit version of your app on Streamlit Community CloudNext: Huh. This is isn't supposed to happen message after trying to log inforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy
https://docs.streamlit.io/en/0.71.0/api.html#custom-components
DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceremovePAGE ELEMENTSWrite and magicaddText elementsaddData elementsaddChart elementsaddInput widgetsaddMedia elementsaddLayouts and containersaddChat elementsaddStatus elementsaddThird-party componentsopen_in_newAPPLICATION LOGICNavigation and pagesaddExecution flowaddCaching and stateaddConnections and secretsaddCustom componentsaddUtilitiesaddConfigurationaddTOOLSApp testingaddCommand lineaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Develop/API referenceAPI reference Streamlit makes it easy for you to visualize, mutate, and share data. The API reference is organized by activity type, like displaying data or optimizing performance. Each section includes methods associated with the activity type, including examples. Browse our API below and click to learn more about any of our available commands! 🎈 Display almost anything Write and magic st.writeWrite arguments to the app.st.write("Hello **world**!") st.write(my_data_frame) st.write(my_mpl_figure) st.write_streamWrite generators or streams to the app with a typewriter effect.st.write_stream(my_generator) st.write_stream(my_llm_stream) MagicAny time Streamlit sees either a variable or literal value on its own line, it automatically writes that to your app using st.write"Hello **world**!" my_data_frame my_mpl_figure Text elements MarkdownDisplay string formatted as Markdown.st.markdown("Hello **world**!") TitleDisplay text in title formatting.st.title("The app title") HeaderDisplay text in header formatting.st.header("This is a header") SubheaderDisplay text in subheader formatting.st.subheader("This is a subheader") CaptionDisplay text in small font.st.caption("This is written small caption text") Code blockDisplay a code block with optional syntax highlighting.st.code("a = 1234") EchoDisplay some code in the app, then execute it. Useful for tutorials.with st.echo(): st.write('This code will be printed') LaTeXDisplay mathematical expressions formatted as LaTeX.st.latex("\int a x^2 \,dx") Preformatted textWrite fixed-width and preformatted text.st.text("Hello world") DividerDisplay a horizontal rule.st.divider() Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration! PreviousTagsAdd tags to your Streamlit apps. Created by @gagan3012.st_tags(label='# Enter Keywords:', text='Press enter to add more', value=['Zero', 'One', 'Two'], suggestions=['five', 'six', 'seven', 'eight', 'nine', 'three', 'eleven', 'ten', 'four'], maxtags = 4, key='1') NLUApply text mining on a dataframe. Created by @JohnSnowLabs.nlu.load('sentiment').predict('I love NLU! <3') Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.mention(label="An awesome Streamlit App", icon="streamlit", url="https://extras.streamlit.app",) Annotated textDisplay annotated text in Streamlit apps. Created by @tvst.annotated_text("This ", ("is", "verb"), " some ", ("annotated", "adj"), ("text", "noun"), " for those of ", ("you", "pronoun"), " who ", ("like", "verb"), " this sort of ", ("thing", "noun"), ".") Drawable CanvasProvides a sketching canvas using Fabric.js. Created by @andfanilo.st_canvas(fill_color="rgba(255, 165, 0, 0.3)", stroke_width=stroke_width, stroke_color=stroke_color, background_color=bg_color, background_image=Image.open(bg_image) if bg_image else None, update_streamlit=realtime_update, height=150, drawing_mode=drawing_mode, point_display_radius=point_display_radius if drawing_mode == 'point' else 0, key="canvas",) TagsAdd tags to your Streamlit apps. Created by @gagan3012.st_tags(label='# Enter Keywords:', text='Press enter to add more', value=['Zero', 'One', 'Two'], suggestions=['five', 'six', 'seven', 'eight', 'nine', 'three', 'eleven', 'ten', 'four'], maxtags = 4, key='1') NLUApply text mining on a dataframe. Created by @JohnSnowLabs.nlu.load('sentiment').predict('I love NLU! <3') Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.mention(label="An awesome Streamlit App", icon="streamlit", url="https://extras.streamlit.app",) Annotated textDisplay annotated text in Streamlit apps. Created by @tvst.annotated_text("This ", ("is", "verb"), " some ", ("annotated", "adj"), ("text", "noun"), " for those of ", ("you", "pronoun"), " who ", ("like", "verb"), " this sort of ", ("thing", "noun"), ".") Drawable CanvasProvides a sketching canvas using Fabric.js. Created by @andfanilo.st_canvas(fill_color="rgba(255, 165, 0, 0.3)", stroke_width=stroke_width, stroke_color=stroke_color, background_color=bg_color, background_image=Image.open(bg_image) if bg_image else None, update_streamlit=realtime_update, height=150, drawing_mode=drawing_mode, point_display_radius=point_display_radius if drawing_mode == 'point' else 0, key="canvas",) TagsAdd tags to your Streamlit apps. Created by @gagan3012.st_tags(label='# Enter Keywords:', text='Press enter to add more', value=['Zero', 'One', 'Two'], suggestions=['five', 'six', 'seven', 'eight', 'nine', 'three', 'eleven', 'ten', 'four'], maxtags = 4, key='1') NLUApply text mining on a dataframe. Created by @JohnSnowLabs.nlu.load('sentiment').predict('I love NLU! <3') Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.mention(label="An awesome Streamlit App", icon="streamlit", url="https://extras.streamlit.app",) Next Data elements DataframesDisplay a dataframe as an interactive table.st.dataframe(my_data_frame) Data editorDisplay a data editor widget.edited = st.data_editor(df, num_rows="dynamic") Column configurationConfigure the display and editing behavior of dataframes and data editors.st.column_config.NumberColumn("Price (in USD)", min_value=0, format="$%d") Static tablesDisplay a static table.st.table(my_data_frame) MetricsDisplay a metric in big bold font, with an optional indicator of how the metric changed.st.metric("My metric", 42, 2) Dicts and JSONDisplay object or string as a pretty-printed JSON string.st.json(my_dict) Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration! PreviousImage CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates value = streamlit_image_coordinates("https://placekitten.com/200/300") st.write(value) Plotly EventsMake Plotly charts interactive!. Created by @null-jones.from streamlit_plotly_events import plotly_events fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.metric_cards import style_metric_cards col3.metric(label="No Change", value=5000, delta=0) style_metric_cards() Streamlit AggridImplementation of Ag-Grid component for Streamlit. Created by @PablocFonseca.df = pd.DataFrame({'col1': [1, 2, 3], 'col2': [4, 5, 6]}) grid_return = AgGrid(df, editable=True) new_df = grid_return['data'] Streamlit FoliumStreamlit Component for rendering Folium maps. Created by @randyzwitch.m = folium.Map(location=[39.949610, -75.150282], zoom_start=16) folium.Marker([39.949610, -75.150282], popup="Liberty Bell", tooltip="Liberty Bell").add_to(m) st_data = st_folium(m, width=725) Pandas ProfilingPandas profiling component for Streamlit. Created by @okld.df = pd.read_csv("https://storage.googleapis.com/tf-datasets/titanic/train.csv") pr = df.profile_report() st_profile_report(pr) Image CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates value = streamlit_image_coordinates("https://placekitten.com/200/300") st.write(value) Plotly EventsMake Plotly charts interactive!. Created by @null-jones.from streamlit_plotly_events import plotly_events fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.metric_cards import style_metric_cards col3.metric(label="No Change", value=5000, delta=0) style_metric_cards() Streamlit AggridImplementation of Ag-Grid component for Streamlit. Created by @PablocFonseca.df = pd.DataFrame({'col1': [1, 2, 3], 'col2': [4, 5, 6]}) grid_return = AgGrid(df, editable=True) new_df = grid_return['data'] Streamlit FoliumStreamlit Component for rendering Folium maps. Created by @randyzwitch.m = folium.Map(location=[39.949610, -75.150282], zoom_start=16) folium.Marker([39.949610, -75.150282], popup="Liberty Bell", tooltip="Liberty Bell").add_to(m) st_data = st_folium(m, width=725) Pandas ProfilingPandas profiling component for Streamlit. Created by @okld.df = pd.read_csv("https://storage.googleapis.com/tf-datasets/titanic/train.csv") pr = df.profile_report() st_profile_report(pr) Image CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates value = streamlit_image_coordinates("https://placekitten.com/200/300") st.write(value) Plotly EventsMake Plotly charts interactive!. Created by @null-jones.from streamlit_plotly_events import plotly_events fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.metric_cards import style_metric_cards col3.metric(label="No Change", value=5000, delta=0) style_metric_cards() Next Chart elements Simple area chartsDisplay an area chart.st.area_chart(my_data_frame) Simple bar chartsDisplay a bar chart.st.bar_chart(my_data_frame) Simple line chartsDisplay a line chart.st.line_chart(my_data_frame) Simple scatter chartsDisplay a line chart.st.scatter_chart(my_data_frame) Scatterplots on mapsDisplay a map with points on it.st.map(my_data_frame) MatplotlibDisplay a matplotlib.pyplot figure.st.pyplot(my_mpl_figure) AltairDisplay a chart using the Altair library.st.altair_chart(my_altair_chart) Vega-LiteDisplay a chart using the Vega-Lite library.st.vega_lite_chart(my_vega_lite_chart) PlotlyDisplay an interactive Plotly chart.st.plotly_chart(my_plotly_chart) BokehDisplay an interactive Bokeh chart.st.bokeh_chart(my_bokeh_chart) PyDeckDisplay a chart using the PyDeck library.st.pydeck_chart(my_pydeck_chart) GraphVizDisplay a graph using the dagre-d3 library.st.graphviz_chart(my_graphviz_spec) Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration! PreviousStreamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl("https://assets5.lottiefiles.com/packages/lf20_V9t630.json") st_lottie(lottie_hello, key="hello") Plotly EventsMake Plotly charts interactive!. Created by @null-jones.fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.chart += get_annotations_chart(annotations=[("Mar 01, 2008", "Pretty good day for GOOG"), ("Dec 01, 2007", "Something's going wrong for GOOG & AAPL"), ("Nov 01, 2008", "Market starts again thanks to..."), ("Dec 01, 2009", "Small crash for GOOG after..."),],) st.altair_chart(chart, use_container_width=True) PlostA deceptively simple plotting library for Streamlit. Created by @tvst.import plost plost.line_chart(my_dataframe, x='time', y='stock_value', color='stock_name',) HiPlotHigh dimensional Interactive Plotting. Created by @facebookresearch.data = [{'dropout':0.1, 'lr': 0.001, 'loss': 10.0, 'optimizer': 'SGD'}, {'dropout':0.15, 'lr': 0.01, 'loss': 3.5, 'optimizer': 'Adam'}, {'dropout':0.3, 'lr': 0.1, 'loss': 4.5, 'optimizer': 'Adam'}] hip.Experiment.from_iterable(data).display() EChartsHigh dimensional Interactive Plotting. Created by @andfanilo.from streamlit_echarts import st_echarts st_echarts(options=options) Streamlit FoliumStreamlit Component for rendering Folium maps. Created by @randyzwitch.m = folium.Map(location=[39.949610, -75.150282], zoom_start=16) st_data = st_folium(m, width=725) Spacy-StreamlitspaCy building blocks and visualizers for Streamlit apps. Created by @explosion.models = ["en_core_web_sm", "en_core_web_md"] spacy_streamlit.visualize(models, "Sundar Pichai is the CEO of Google.") Streamlit AgraphA Streamlit Graph Vis, based on react-grah-vis. Created by @ChrisDelClea.from streamlit_agraph import agraph, Node, Edge, Config agraph(nodes=nodes, edges=edges, config=config) Streamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl("https://assets5.lottiefiles.com/packages/lf20_V9t630.json") st_lottie(lottie_hello, key="hello") Plotly EventsMake Plotly charts interactive!. Created by @null-jones.fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.chart += get_annotations_chart(annotations=[("Mar 01, 2008", "Pretty good day for GOOG"), ("Dec 01, 2007", "Something's going wrong for GOOG & AAPL"), ("Nov 01, 2008", "Market starts again thanks to..."), ("Dec 01, 2009", "Small crash for GOOG after..."),],) st.altair_chart(chart, use_container_width=True) PlostA deceptively simple plotting library for Streamlit. Created by @tvst.import plost plost.line_chart(my_dataframe, x='time', y='stock_value', color='stock_name',) HiPlotHigh dimensional Interactive Plotting. Created by @facebookresearch.data = [{'dropout':0.1, 'lr': 0.001, 'loss': 10.0, 'optimizer': 'SGD'}, {'dropout':0.15, 'lr': 0.01, 'loss': 3.5, 'optimizer': 'Adam'}, {'dropout':0.3, 'lr': 0.1, 'loss': 4.5, 'optimizer': 'Adam'}] hip.Experiment.from_iterable(data).display() EChartsHigh dimensional Interactive Plotting. Created by @andfanilo.from streamlit_echarts import st_echarts st_echarts(options=options) Streamlit FoliumStreamlit Component for rendering Folium maps. Created by @randyzwitch.m = folium.Map(location=[39.949610, -75.150282], zoom_start=16) st_data = st_folium(m, width=725) Spacy-StreamlitspaCy building blocks and visualizers for Streamlit apps. Created by @explosion.models = ["en_core_web_sm", "en_core_web_md"] spacy_streamlit.visualize(models, "Sundar Pichai is the CEO of Google.") Streamlit AgraphA Streamlit Graph Vis, based on react-grah-vis. Created by @ChrisDelClea.from streamlit_agraph import agraph, Node, Edge, Config agraph(nodes=nodes, edges=edges, config=config) Streamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl("https://assets5.lottiefiles.com/packages/lf20_V9t630.json") st_lottie(lottie_hello, key="hello") Plotly EventsMake Plotly charts interactive!. Created by @null-jones.fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.chart += get_annotations_chart(annotations=[("Mar 01, 2008", "Pretty good day for GOOG"), ("Dec 01, 2007", "Something's going wrong for GOOG & AAPL"), ("Nov 01, 2008", "Market starts again thanks to..."), ("Dec 01, 2009", "Small crash for GOOG after..."),],) st.altair_chart(chart, use_container_width=True) Next Input widgets ButtonDisplay a button widget.clicked = st.button("Click me") Download buttonDisplay a download button widget.st.download_button("Download file", file) Form buttonDisplay a form submit button. For use with st.form.st.form_submit_button("Sign up") Link buttonDisplay a link button.st.link_button("Go to gallery", url) Page linkDisplay a link to another page in a multipage app.st.page_link("app.py", label="Home", icon="🏠") st.page_link("pages/profile.py", label="My profile") CheckboxDisplay a checkbox widget.selected = st.checkbox("I agree") Color pickerDisplay a color picker widget.color = st.color_picker("Pick a color") MultiselectDisplay a multiselect widget. The multiselect widget starts as empty.choices = st.multiselect("Buy", ["milk", "apples", "potatoes"]) RadioDisplay a radio button widget.choice = st.radio("Pick one", ["cats", "dogs"]) SelectboxDisplay a select widget.choice = st.selectbox("Pick one", ["cats", "dogs"]) Select-sliderDisplay a slider widget to select items from a list.size = st.select_slider("Pick a size", ["S", "M", "L"]) ToggleDisplay a toggle widget.activated = st.toggle("Activate") Number inputDisplay a numeric input widget.choice = st.number_input("Pick a number", 0, 10) SliderDisplay a slider widget.number = st.slider("Pick a number", 0, 100) Date inputDisplay a date input widget.date = st.date_input("Your birthday") Time inputDisplay a time input widget.time = st.time_input("Meeting time") Chat inputDisplay a chat input widget.prompt = st.chat_input("Say something") if prompt: st.write(f"The user has sent: {prompt}") Text-areaDisplay a multi-line text input widget.text = st.text_area("Text to translate") Text inputDisplay a single-line text input widget.name = st.text_input("First name") Data editorDisplay a data editor widget.edited = st.experimental_data_editor(df, num_rows="dynamic") File UploaderDisplay a file uploader widget.data = st.file_uploader("Upload a CSV") Camera inputDisplay a widget that allows users to upload images directly from a camera.image = st.camera_input("Take a picture") Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration! PreviousStreamlit ChatStreamlit Component for a Chatbot UI. Created by @AI-Yash.from streamlit_chat import message message("My message") message("Hello bot!", is_user=True) # align's the message to the right Streamlit Option MenuSelect a single item from a list of options in a menu. Created by @victoryhb.from streamlit_option_menu import option_menu option_menu("Main Menu", ["Home", 'Settings'], icons=['house', 'gear'], menu_icon="cast", default_index=1) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.stoggle import stoggle stoggle( "Click me!", """🥷 Surprise! Here's some additional content""",) Streamlit ElementsCreate a draggable and resizable dashboard in Streamlit. Created by @okls.from streamlit_elements import elements, mui, html with elements("new_element"): mui.Typography("Hello world") TagsAdd tags to your Streamlit apps. Created by @gagan3012.from streamlit_tags import st_tags st_tags(label='# Enter Keywords:', text='Press enter to add more', value=['Zero', 'One', 'Two'], suggestions=['five', 'six', 'seven', 'eight', 'nine', 'three', 'eleven', 'ten', 'four'], maxtags = 4, key='1') StqdmThe simplest way to handle a progress bar in streamlit app. Created by @Wirg.from stqdm import stqdm for _ in stqdm(range(50)): sleep(0.5) TimelineDisplay a Timeline in Streamlit apps using TimelineJS. Created by @innerdoc.from streamlit_timeline import timeline with open('example.json', "r") as f: timeline(f.read(), height=800) Camera input liveAlternative for st.camera_input which returns the webcam images live. Created by @blackary.from camera_input_live import camera_input_live image = camera_input_live() st.image(value) Streamlit AceAce editor component for Streamlit. Created by @okld.from streamlit_ace import st_ace content = st_ace() content Streamlit ChatStreamlit Component for a Chatbot UI. Created by @AI-Yash.from streamlit_chat import message message("My message") message("Hello bot!", is_user=True) # align's the message to the right Streamlit Option MenuSelect a single item from a list of options in a menu. Created by @victoryhb.from streamlit_option_menu import option_menu option_menu("Main Menu", ["Home", 'Settings'], icons=['house', 'gear'], menu_icon="cast", default_index=1) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.stoggle import stoggle stoggle( "Click me!", """🥷 Surprise! Here's some additional content""",) Streamlit ElementsCreate a draggable and resizable dashboard in Streamlit. Created by @okls.from streamlit_elements import elements, mui, html with elements("new_element"): mui.Typography("Hello world") TagsAdd tags to your Streamlit apps. Created by @gagan3012.from streamlit_tags import st_tags st_tags(label='# Enter Keywords:', text='Press enter to add more', value=['Zero', 'One', 'Two'], suggestions=['five', 'six', 'seven', 'eight', 'nine', 'three', 'eleven', 'ten', 'four'], maxtags = 4, key='1') StqdmThe simplest way to handle a progress bar in streamlit app. Created by @Wirg.from stqdm import stqdm for _ in stqdm(range(50)): sleep(0.5) TimelineDisplay a Timeline in Streamlit apps using TimelineJS. Created by @innerdoc.from streamlit_timeline import timeline with open('example.json', "r") as f: timeline(f.read(), height=800) Camera input liveAlternative for st.camera_input which returns the webcam images live. Created by @blackary.from camera_input_live import camera_input_live image = camera_input_live() st.image(value) Streamlit AceAce editor component for Streamlit. Created by @okld.from streamlit_ace import st_ace content = st_ace() content Streamlit ChatStreamlit Component for a Chatbot UI. Created by @AI-Yash.from streamlit_chat import message message("My message") message("Hello bot!", is_user=True) # align's the message to the right Streamlit Option MenuSelect a single item from a list of options in a menu. Created by @victoryhb.from streamlit_option_menu import option_menu option_menu("Main Menu", ["Home", 'Settings'], icons=['house', 'gear'], menu_icon="cast", default_index=1) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.stoggle import stoggle stoggle( "Click me!", """🥷 Surprise! Here's some additional content""",) Next Media elements ImageDisplay an image or list of images.st.image(numpy_array) st.image(image_bytes) st.image(file) st.image("https://example.com/myimage.jpg") AudioDisplay an audio player.st.audio(numpy_array) st.audio(audio_bytes) st.audio(file) st.audio("https://example.com/myaudio.mp3", format="audio/mp3") VideoDisplay a video player.st.video(numpy_array) st.video(video_bytes) st.video(file) st.video("https://example.com/myvideo.mp4", format="video/mp4") Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration! PreviousStreamlit CropperA simple image cropper for Streamlit. Created by @turner-anderson.from streamlit_cropper import st_cropper st_cropper(img, realtime_update=realtime_update, box_color=box_color, aspect_ratio=aspect_ratio) Image CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates streamlit_image_coordinates("https://placekitten.com/200/300") Streamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl("https://assets5.lottiefiles.com/packages/lf20_V9t630.json") st_lottie(lottie_hello, key="hello") Streamlit WebrtcHandling and transmitting real-time video/audio streams with Streamlit. Created by @whitphx.from streamlit_webrtc import webrtc_streamer webrtc_streamer(key="sample") Drawable CanvasProvides a sketching canvas using Fabric.js. Created by @andfanilo.from streamlit_drawable_canvas import st_canvas st_canvas(fill_color="rgba(255, 165, 0, 0.3)", stroke_width=stroke_width, stroke_color=stroke_color, background_color=bg_color, background_image=Image.open(bg_image) if bg_image else None, update_streamlit=realtime_update, height=150, drawing_mode=drawing_mode, point_display_radius=point_display_radius if drawing_mode == 'point' else 0, key="canvas",) Image ComparisonCompare images with a slider using JuxtaposeJS. Created by @fcakyon.from streamlit_image_comparison import image_comparison image_comparison(img1="image1.jpg", img2="image2.jpg",) Streamlit CropperA simple image cropper for Streamlit. Created by @turner-anderson.from streamlit_cropper import st_cropper st_cropper(img, realtime_update=realtime_update, box_color=box_color, aspect_ratio=aspect_ratio) Image CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates streamlit_image_coordinates("https://placekitten.com/200/300") Streamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl("https://assets5.lottiefiles.com/packages/lf20_V9t630.json") st_lottie(lottie_hello, key="hello") Streamlit WebrtcHandling and transmitting real-time video/audio streams with Streamlit. Created by @whitphx.from streamlit_webrtc import webrtc_streamer webrtc_streamer(key="sample") Drawable CanvasProvides a sketching canvas using Fabric.js. Created by @andfanilo.from streamlit_drawable_canvas import st_canvas st_canvas(fill_color="rgba(255, 165, 0, 0.3)", stroke_width=stroke_width, stroke_color=stroke_color, background_color=bg_color, background_image=Image.open(bg_image) if bg_image else None, update_streamlit=realtime_update, height=150, drawing_mode=drawing_mode, point_display_radius=point_display_radius if drawing_mode == 'point' else 0, key="canvas",) Image ComparisonCompare images with a slider using JuxtaposeJS. Created by @fcakyon.from streamlit_image_comparison import image_comparison image_comparison(img1="image1.jpg", img2="image2.jpg",) Streamlit CropperA simple image cropper for Streamlit. Created by @turner-anderson.from streamlit_cropper import st_cropper st_cropper(img, realtime_update=realtime_update, box_color=box_color, aspect_ratio=aspect_ratio) Image CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates streamlit_image_coordinates("https://placekitten.com/200/300") Streamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl("https://assets5.lottiefiles.com/packages/lf20_V9t630.json") st_lottie(lottie_hello, key="hello") Next Layouts and containers ColumnsInsert containers laid out as side-by-side columns.col1, col2 = st.columns(2) col1.write("this is column 1") col2.write("this is column 2") ContainerInsert a multi-element container.c = st.container() st.write("This will show last") c.write("This will show first") c.write("This will show second") Modal dialogsInsert a modal dialog that can rerun independently from the rest of the script.@st.experimental_dialog("Sign up") def email_form(): name = st.text_input("Name") email = st.text_input("Email") EmptyInsert a single-element container.c = st.empty() st.write("This will show last") c.write("This will be replaced") c.write("This will show first") ExpanderInsert a multi-element container that can be expanded/collapsed.with st.expander("Open to see more"): st.write("This is more content") PopoverInsert a multi-element popover container that can be opened/closed.with st.popover("Settings"): st.checkbox("Show completed") SidebarDisplay items in a sidebar.st.sidebar.write("This lives in the sidebar") st.sidebar.button("Click me!") TabsInsert containers separated into tabs.tab1, tab2 = st.tabs(["Tab 1", "Tab2"]) tab1.write("this is tab 1") tab2.write("this is tab 2") Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration!Streamlit ElementsCreate a draggable and resizable dashboard in Streamlit. Created by @okls.from streamlit_elements import elements, mui, html with elements("new_element"): mui.Typography("Hello world") PydanticAuto-generate Streamlit UI from Pydantic Models and Dataclasses. Created by @lukasmasuch.import streamlit_pydantic as sp sp.pydantic_form(key="my_form", model=ExampleModel) Streamlit PagesAn experimental version of Streamlit Multi-Page Apps. Created by @blackary.from st_pages import Page, show_pages, add_page_title show_pages([ Page("streamlit_app.py", "Home", "🏠"), Page("other_pages/page2.py", "Page 2", ":books:"), ]) Chat elements Streamlit provides a few commands to help you build conversational apps. These chat elements are designed to be used in conjunction with each other, but you can also use them separately. st.chat_message lets you insert a chat message container into the app so you can display messages from the user or the app. Chat containers can contain other Streamlit elements, including charts, tables, text, and more. st.chat_input lets you display a chat input widget so the user can type in a message. Chat inputDisplay a chat input widget.prompt = st.chat_input("Say something") if prompt: st.write(f"The user has sent: {prompt}") Chat messageInsert a chat message container.import numpy as np with st.chat_message("user"): st.write("Hello 👋") st.line_chart(np.random.randn(30, 3)) Status containerDisplay output of long-running tasks in a container.with st.status('Running'): do_something_slow() st.write_streamWrite generators or streams to the app with a typewriter effect.st.write_stream(my_generator) st.write_stream(my_llm_stream) Status elements Progress barDisplay a progress bar.for i in range(101): st.progress(i) do_something_slow() SpinnerTemporarily displays a message while executing a block of code.with st.spinner("Please wait..."): do_something_slow() Status containerDisplay output of long-running tasks in a container.with st.status('Running'): do_something_slow() ToastBriefly displays a toast message in the bottom-right corner.st.toast('Butter!', icon='🧈') BalloonsDisplay celebratory balloons!do_something() # Celebrate when all done! st.balloons() SnowflakesDisplay celebratory snowflakes!do_something() # Celebrate when all done! st.snow() Success boxDisplay a success message.st.success("Match found!") Info boxDisplay an informational message.st.info("Dataset is updated every day at midnight.") Warning boxDisplay warning message.st.warning("Unable to fetch image. Skipping...") Error boxDisplay error message.st.error("We encountered an error") Exception outputDisplay an exception.e = RuntimeError("This is an exception of type RuntimeError") st.exception(e) Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration!StqdmThe simplest way to handle a progress bar in streamlit app. Created by @Wirg.from stqdm import stqdm for _ in stqdm(range(50)): sleep(0.5) Custom notification boxA custom notification box with the ability to close it out. Created by @Socvest.from streamlit_custom_notification_box import custom_notification_box styles = {'material-icons':{'color': 'red'}, 'text-icon-link-close-container': {'box-shadow': '#3896de 0px 4px'}, 'notification-text': {'':''}, 'close-button':{'':''}, 'link':{'':''}} custom_notification_box(icon='info', textDisplay='We are almost done with your registration...', externalLink='more info', url='#', styles=styles, key="foo") Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.let_it_rain import rain rain(emoji="🎈", font_size=54, falling_speed=5, animation_length="infinite",) App logic and configuration Navigation and pages Switch pageProgrammatically navigates to a specified page.st.switch_page("pages/my_page.py") Page linkDisplay a link to another page in a multipage app.st.page_link("app.py", label="Home", icon="🏠") st.page_link("pages/profile.py", label="My profile") Execution flow Modal dialogsInsert a modal dialog that can rerun independently from the rest of the script.@st.experimental_dialog("Sign up") def email_form(): name = st.text_input("Name") email = st.text_input("Email") FormsCreate a form that batches elements together with a “Submit" button.with st.form(key='my_form'): name = st.text_input("Name") email = st.text_input("Email") st.form_submit_button("Sign up") Partial rerunsDefine a fragment to rerun independently from the rest of the script.@st.experimental_fragment(run_every="10s") def fragment(): df = get_data() st.line_chart(df) Rerun scriptRerun the script immediately.st.rerun() Stop executionStops execution immediately.st.stop() Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration!AutorefreshForce a refresh without tying up a script. Created by @kmcgrady.from streamlit_autorefresh import st_autorefresh st_autorefresh(interval=2000, limit=100, key="fizzbuzzcounter") PydanticAuto-generate Streamlit UI from Pydantic Models and Dataclasses. Created by @lukasmasuch.import streamlit_pydantic as sp sp.pydantic_form(key="my_form", model=ExampleModel) Streamlit PagesAn experimental version of Streamlit Multi-Page Apps. Created by @blackary.from st_pages import Page, show_pages, add_page_title show_pages([ Page("streamlit_app.py", "Home", "🏠"), Page("other_pages/page2.py", "Page 2", ":books:"), ]) Caching and state Cache dataFunction decorator to cache functions that return data (e.g. dataframe transforms, database queries, ML inference).@st.cache_data def long_function(param1, param2): # Perform expensive computation here or # fetch data from the web here return data Cache resourceFunction decorator to cache functions that return global resources (e.g. database connections, ML models).@st.cache_resource def init_model(): # Return a global resource here return pipeline( "sentiment-analysis", model="distilbert-base-uncased-finetuned-sst-2-english" ) Session stateSession state is a way to share variables between reruns, for each user session.st.session_state['key'] = value Query parametersGet, set, or clear the query parameters that are shown in the browser's URL bar.st.query_params[key] = value st.query_params.clear() Connections and databases Setup your connection Create a connectionConnect to a data source or APIconn = st.connection('pets_db', type='sql') pet_owners = conn.query('select * from pet_owners') st.dataframe(pet_owners) Built-in connections SnowflakeConnectionA connection to Snowflake.conn = st.connection('snowflake') SQLConnectionA connection to a SQL database using SQLAlchemy.conn = st.connection('sql') Build your own connections Connection base classBuild your own connection with BaseConnection.class MyConnection(BaseConnection[myconn.MyConnection]): def _connect(self, **kwargs) -> MyConnection: return myconn.connect(**self._secrets, **kwargs) def query(self, query): return self._instance.query(query) Secrets management Secrets singletonAccess secrets from a local TOML file.key = st.secrets["OpenAI_key"] Secrets fileSave your secrets in a per-project or per-profile TOML file.OpenAI_key = "<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/st.testing.v1.apptest#apptestlatex
DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceremovePAGE ELEMENTSWrite and magicaddText elementsaddData elementsaddChart elementsaddInput widgetsaddMedia elementsaddLayouts and containersaddChat elementsaddStatus elementsaddThird-party componentsopen_in_newAPPLICATION LOGICNavigation and pagesaddExecution flowaddCaching and stateaddConnections and secretsaddCustom componentsaddUtilitiesaddConfigurationaddTOOLSApp testingremovest.testing.v1.AppTestTesting element classesCommand lineaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Develop/API reference/App testing/st.testing.v1.AppTest The AppTest class st.testing.v1.AppTestStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA simulated Streamlit app to check the correctness of displayed elements and outputs. An instance of AppTest simulates a running Streamlit app. This class provides methods to set up, manipulate, and inspect the app contents via API instead of a browser UI. It can be used to write automated tests of an app in various scenarios. These can then be run using a tool like pytest. AppTest can be initialized by one of three class methods: st.testing.v1.AppTest.from_file (recommended) st.testing.v1.AppTest.from_string st.testing.v1.AppTest.from_function Once initialized, Session State and widget values can be updated and the script can be run. Unlike an actual live-running Streamlit app, you need to call AppTest.run() explicitly to re-run the app after changing a widget value. Switching pages also requires an explicit, follow-up call to AppTest.run(). AppTest enables developers to build tests on their app as-is, in the familiar python test format, without major refactoring or abstracting out logic to be tested separately from the UI. Tests can run quickly with very low overhead. A typical pattern is to build a suite of tests for an app that ensure consistent functionality as the app evolves, and run the tests locally and/or in a CI environment like Github Actions. Note AppTest only supports testing a single page of an app per instance. For multipage apps, each page will need to be tested separately. No methods exist to programatically switch pages within AppTest. Class description[source] st.testing.v1.AppTest(script_path, *, default_timeout, args=None, kwargs=None) Methods get(element_type) Get elements or widgets of the specified type. run(*, timeout=None) Run the script from the current state. switch_page(page_path) Switch to another page of the app. Attributes secrets (dict[str, Any]) Dictionary of secrets to be used the simulated app. Use dict-like syntax to set secret values for the simulated app. session_state (SafeSessionState) Session State for the simulated app. SafeSessionState object supports read and write operations as usual for Streamlit apps. query_params (dict[str, Any]) Dictionary of query parameters to be used by the simluated app. Use dict-like syntax to set query_params values for the simulated app. button Sequence of all st.button and st.form_submit_button widgets. caption Sequence of all st.caption elements. chat_input Sequence of all st.chat_input widgets. chat_message Sequence of all st.chat_message elements. checkbox Sequence of all st.checkbox widgets. code Sequence of all st.code elements. color_picker Sequence of all st.color_picker widgets. columns Sequence of all columns within st.columns elements. dataframe Sequence of all st.dataframe elements. date_input Sequence of all st.date_input widgets. divider Sequence of all st.divider elements. error Sequence of all st.error elements. exception Sequence of all st.exception elements. expander Sequence of all st.expander elements. header Sequence of all st.header elements. info Sequence of all st.info elements. json Sequence of all st.json elements. latex Sequence of all st.latex elements. main Sequence of elements within the main body of the app. markdown Sequence of all st.markdown elements. metric Sequence of all st.metric elements. multiselect Sequence of all st.multiselect widgets. number_input Sequence of all st.number_input widgets. radio Sequence of all st.radio widgets. select_slider Sequence of all st.select_slider widgets. selectbox Sequence of all st.selectbox widgets. sidebar Sequence of all elements within st.sidebar. slider Sequence of all st.slider widgets. status Sequence of all st.status elements. subheader Sequence of all st.subheader elements. success Sequence of all st.success elements. table Sequence of all st.table elements. tabs Sequence of all tabs within st.tabs elements. text Sequence of all st.text elements. text_area Sequence of all st.text_area widgets. text_input Sequence of all st.text_input widgets. time_input Sequence of all st.time_input widgets. title Sequence of all st.title elements. toast Sequence of all st.toast elements. toggle Sequence of all st.toggle widgets. warning Sequence of all st.warning elements. Initialize a simulated app using AppTest AppTest.from_fileStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeCreate an instance of AppTest to simulate an app page defined within a file. This option is most convenient for CI workflows and testing of published apps. The script must be executable on its own and so must contain all necessary imports. Function signature[source] AppTest.from_file(cls, script_path, *, default_timeout=3) Parameters script_path (str) Path to a script file. The path should be absolute or relative to the file calling .from_file. default_timeout (float) Default time in seconds before a script run is timed out. Can be overridden for individual .run() calls. Returns(AppTest) A simulated Streamlit app for testing. The simulated app can be executed via .run(). AppTest.from_stringStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeCreate an instance of AppTest to simulate an app page defined within a string. This is useful for testing short scripts that fit comfortably as an inline string in the test itself, without having to create a separate file for it. The script must be executable on its own and so must contain all necessary imports. Function signature[source] AppTest.from_string(cls, script, *, default_timeout=3) Parameters script (str) The string contents of the script to be run. default_timeout (float) Default time in seconds before a script run is timed out. Can be overridden for individual .run() calls. Returns(AppTest) A simulated Streamlit app for testing. The simulated app can be executed via .run(). AppTest.from_functionStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeCreate an instance of AppTest to simulate an app page defined within a function. This is similar to AppTest.from_string(), but more convenient to write with IDE assistance. The script must be executable on its own and so must contain all necessary imports. Function signature[source] AppTest.from_function(cls, script, *, default_timeout=3, args=None, kwargs=None) Parameters script (Callable) A function whose body will be used as a script. Must be runnable in isolation, so it must include any necessary imports. default_timeout (float) Default time in seconds before a script run is timed out. Can be overridden for individual .run() calls. args (tuple) An optional tuple of args to pass to the script function. kwargs (dict) An optional dict of kwargs to pass to the script function. Returns(AppTest) A simulated Streamlit app for testing. The simulated app can be executed via .run(). Run an AppTest script AppTest.runStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeRun the script from the current state. This is equivalent to manually rerunning the app or the rerun that occurs upon user interaction. AppTest.run() must be manually called after updating a widget value or switching pages as script reruns do not occur automatically as they do for live-running Streamlit apps. Function signature[source] AppTest.run(*, timeout=None) Parameters timeout (null) The maximum number of seconds to run the script. None means use the default timeout set for the instance of AppTest. Returns(AppTest) self AppTest.switch_pageStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSwitch to another page of the app. This method does not automatically rerun the app. Use a follow-up call to AppTest.run() to obtain the elements on the selected page. Function signature[source] AppTest.switch_page(page_path) Parameters page_path (str) Path of the page to switch to. The path must be relative to the main script's location (e.g. "pages/my_page.py"). Returns(AppTest) self Get AppTest script elements The main value of AppTest is providing an API to programmatically inspect and interact with the elements and widgets produced by a running Streamlit app. Using the AppTest.<element type> properties or AppTest.get() method returns a collection of all the elements or widgets of the specified type that would have been displayed by running the app. Note that you can also retrieve elements within a specific container in the same way - first retrieve the container, then retrieve the elements just in that container. AppTest.getStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeGet elements or widgets of the specified type. This method returns the collection of all elements or widgets of the specified type on the current page. Retrieve a specific element by using its index (order on page) or key lookup. Function signature[source] AppTest.get(element_type) Parameters element_type (str) An element attribute of AppTest. For example, "button", "caption", or "chat_input". Returns(Sequence of Elements) Sequence of elements of the given type. Individual elements can be accessed from a Sequence by index (order on the page). When getting and element_type that is a widget, individual widgets can be accessed by key. For example, at.get("text")[0] for the first st.text element or at.get("slider")(key="my_key") for the st.slider widget with a given key. AppTest.buttonStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.button and st.form_submit_button widgets. Function signature[source] AppTest.button Returns(WidgetList of Button) Sequence of all st.button and st.form_submit_button widgets. Individual widgets can be accessed from a WidgetList by index (order on the page) or key. For example, at.button[0] for the first widget or at.button(key="my_key") for a widget with a given key. AppTest.captionStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.caption elements. Function signature[source] AppTest.caption Returns(ElementList of Caption) Sequence of all st.caption elements. Individual elements can be accessed from an ElementList by index (order on the page). For example, at.caption[0] for the first element. Caption is an extension of the Element class. AppTest.chat_inputStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.chat_input widgets. Function signature[source] AppTest.chat_input Returns(WidgetList of ChatInput) Sequence of all st.chat_input widgets. Individual widgets can be accessed from a WidgetList by index (order on the page) or key. For example, at.chat_input[0] for the first widget or at.chat_input(key="my_key") for a widget with a given key. AppTest.chat_messageStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.chat_message elements. Function signature[source] AppTest.chat_message Returns(Sequence of ChatMessage) Sequence of all st.chat_message elements. Individual elements can be accessed from an ElementList by index (order on the page). For example, at.chat_message[0] for the first element. ChatMessage is an extension of the Block class. AppTest.checkboxStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.checkbox widgets. Function signature[source] AppTest.checkbox Returns(WidgetList of Checkbox) Sequence of all st.checkbox widgets. Individual widgets can be accessed from a WidgetList by index (order on the page) or key. For example, at.checkbox[0] for the first widget or at.checkbox(key="my_key") for a widget with a given key. AppTest.codeStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.code elements. Function signature[source] AppTest.code Returns(ElementList of Code) Sequence of all st.code elements. Individual elements can be accessed from an ElementList by index (order on the page). For example, at.code[0] for the first element. Code is an extension of the Element class. AppTest.color_pickerStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.color_picker widgets. Function signature[source] AppTest.color_picker Returns(WidgetList of ColorPicker) Sequence of all st.color_picker widgets. Individual widgets can be accessed from a WidgetList by index (order on the page) or key. For example, at.color_picker[0] for the first widget or at.color_picker(key="my_key") for a widget with a given key. AppTest.columnsStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all columns within st.columns elements. Each column within a single st.columns will be returned as a separate Column in the Sequence. Function signature[source] AppTest.columns Returns(Sequence of Column) Sequence of all columns within st.columns elements. Individual columns can be accessed from an ElementList by index (order on the page). For example, at.columns[0] for the first column. Column is an extension of the Block class. AppTest.dataframeStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.dataframe elements. Function signature[source] AppTest.dataframe Returns(ElementList of Dataframe) Sequence of all st.dataframe elements. Individual elements can be accessed from an ElementList by index (order on the page). For example, at.dataframe[0] for the first element. Dataframe is an extension of the Element class. AppTest.date_inputStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.date_input widgets. Function signature[source] AppTest.date_input Returns(WidgetList of DateInput) Sequence of all st.date_input widgets. Individual widgets can be accessed from a WidgetList by index (order on the page) or key. For example, at.date_input[0] for the first widget or at.date_input(key="my_key") for a widget with a given key. AppTest.dividerStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.divider elements. Function signature[source] AppTest.divider Returns(ElementList of Divider) Sequence of all st.divider elements. Individual elements can be accessed from an ElementList by index (order on the page). For example, at.divider[0] for the first element. Divider is an extension of the Element class. AppTest.errorStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.error elements. Function signature[source] AppTest.error Returns(ElementList of Error) Sequence of all st.error elements. Individual elements can be accessed from an ElementList by index (order on the page). For example, at.error[0] for the first element. Error is an extension of the Element class. AppTest.exceptionStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.exception elements. Function signature[source] AppTest.exception Returns(ElementList of Exception) Sequence of all st.exception elements. Individual elements can be accessed from an ElementList by index (order on the page). For example, at.exception[0] for the first element. Exception is an extension of the Element class. AppTest.expanderStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.expander elements. Function signature[source] AppTest.expander Returns(Sequence of Expandable) Sequence of all st.expander elements. Individual elements can be accessed from a Sequence by index (order on the page). For example, at.expander[0] for the first element. Expandable is an extension of the Block class. AppTest.headerStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.header elements. Function signature[source] AppTest.header Returns(ElementList of Header) Sequence of all st.header elements. Individual elements can be accessed from an ElementList by index (order on the page). For example, at.header[0] for the first element. Header is an extension of the Element class. AppTest.infoStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.info elements. Function signature[source] AppTest.info Returns(ElementList of Info) Sequence of all st.info elements. Individual elements can be accessed from an ElementList by index (order on the page). For example, at.info[0] for the first element. Info is an extension of the Element class. AppTest.jsonStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.json elements. Function signature[source] AppTest.json Returns(ElementList of Json) Sequence of all st.json elements. Individual elements can be accessed from an ElementList by index (order on the page). For example, at.json[0] for the first element. Json is an extension of the Element class. AppTest.latexStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.latex elements. Function signature[source] AppTest.latex Returns(ElementList of Latex) Sequence of all st.latex elements. Individual elements can be accessed from an ElementList by index (order on the page). For example, at.latex[0] for the first element. Latex is an extension of the Element class. AppTest.mainStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of elements within the main body of the app. Function signature[source] AppTest.main Returns(Block) A container of elements. Block can be queried for elements in the same manner as AppTest. For example, Block.checkbox will return all st.checkbox within the associated container. AppTest.markdownStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.markdown elements. Function signature[source] AppTest.markdown Returns(ElementList of Markdown) Sequence of all st.markdown elements. Individual elements can be accessed from an ElementList by index (order on the page). For example, at.markdown[0] for the first element. Markdown is an extension of the Element class. AppTest.metricStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.metric elements. Function signature[source] AppTest.metric Returns(ElementList of Metric) Sequence of all st.metric elements. Individual elements can be accessed from an ElementList by index (order on the page). For example, at.metric[0] for the first element. Metric is an extension of the Element class. AppTest.multiselectStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.multiselect widgets. Function signature[source] AppTest.multiselect Returns(WidgetList of Multiselect) Sequence of all st.multiselect widgets. Individual widgets can be accessed from a WidgetList by index (order on the page) or key. For example, at.multiselect[0] for the first widget or at.multiselect(key="my_key") for a widget with a given key. AppTest.number_inputStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.number_input widgets. Function signature[source] AppTest.number_input Returns(WidgetList of NumberInput) Sequence of all st.number_input widgets. Individual widgets can be accessed from a WidgetList by index (order on the page) or key. For example, at.number_input[0] for the first widget or at.number_input(key="my_key") for a widget with a given key. AppTest.radioStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.radio widgets. Function signature[source] AppTest.radio Returns(WidgetList of Radio) Sequence of all st.radio widgets. Individual widgets can be accessed from a WidgetList by index (order on the page) or key. For example, at.radio[0] for the first widget or at.radio(key="my_key") for a widget with a given key. AppTest.select_sliderStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.select_slider widgets. Function signature[source] AppTest.select_slider Returns(WidgetList of SelectSlider) Sequence of all st.select_slider widgets. Individual widgets can be accessed from a WidgetList by index (order on the page) or key. For example, at.select_slider[0] for the first widget or at.select_slider(key="my_key") for a widget with a given key. AppTest.selectboxStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.selectbox widgets. Function signature[source] AppTest.selectbox Returns(WidgetList of Selectbox) Sequence of all st.selectbox widgets. Individual widgets can be accessed from a WidgetList by index (order on the page) or key. For example, at.selectbox[0] for the first widget or at.selectbox(key="my_key") for a widget with a given key. AppTest.sidebarStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all elements within st.sidebar. Function signature[source] AppTest.sidebar Returns(Block) A container of elements. Block can be queried for elements in the same manner as AppTest. For example, Block.checkbox will return all st.checkbox within the associated container. AppTest.sliderStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.slider widgets. Function signature[source] AppTest.slider Returns(WidgetList of Slider) Sequence of all st.slider widgets. Individual widgets can be accessed from a WidgetList by index (order on the page) or key. For example, at.slider[0] for the first widget or at.slider(key="my_key") for a widget with a given key. AppTest.subheaderStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.subheader elements. Function signature[source] AppTest.subheader Returns(ElementList of Subheader) Sequence of all st.subheader elements. Individual elements can be accessed from an ElementList by index (order on the page). For example, at.subheader[0] for the first element. Subheader is an extension of the Element class. AppTest.successStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.success elements. Function signature[source] AppTest.success Returns(ElementList of Success) Sequence of all st.success elements. Individual elements can be accessed from an ElementList by index (order on the page). For example, at.success[0] for the first element. Success is an extension of the Element class. AppTest.statusStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.status elements. Function signature[source] AppTest.status Returns(Sequence of Status) Sequence of all st.status elements. Individual elements can be accessed from a Sequence by index (order on the page). For example, at.status[0] for the first element. Status is an extension of the Block class. AppTest.tableStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.table elements. Function signature[source] AppTest.table Returns(ElementList of Table) Sequence of all st.table elements. Individual elements can be accessed from an ElementList by index (order on the page). For example, at.table[0] for the first element. Table is an extension of the Element class. AppTest.tabsStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all tabs within st.tabs elements. Each tab within a single st.tabs will be returned as a separate Tab in the Sequence. Additionally, the tab labels are forwarded to each Tab element as a property. For example, st.tabs("A","B") will yield two Tab objects, with Tab.label returning "A" and "B", respectively. Function signature[source] AppTest.tabs Returns(Sequence of Tab) Sequence of all tabs within st.tabs elements. Individual tabs can be accessed from an ElementList by index (order on the page). For example, at.tabs[0] for the first tab. Tab is an extension of the Block class. AppTest.textStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.text elements. Function signature[source] AppTest.text Returns(ElementList of Text) Sequence of all st.text elements. Individual elements can be accessed from an ElementList by index (order on the page). For example, at.text[0] for the first element. Text is an extension of the Element class. AppTest.text_areaStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.text_area widgets. Function signature[source] AppTest.text_area Returns(WidgetList of TextArea) Sequence of all st.text_area widgets. Individual widgets can be accessed from a WidgetList by index (order on the page) or key. For example, at.text_area[0] for the first widget or at.text_area(key="my_key") for a widget with a given key. AppTest.text_inputStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.text_input widgets. Function signature[source] AppTest.text_input Returns(WidgetList of TextInput) Sequence of all st.text_input widgets. Individual widgets can be accessed from a WidgetList by index (order on the page) or key. For example, at.text_input[0] for the first widget or at.text_input(key="my_key") for a widget with a given key. AppTest.time_inputStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.time_input widgets. Function signature[source] AppTest.time_input Returns(WidgetList of TimeInput) Sequence of all st.time_input widgets. Individual widgets can be accessed from a WidgetList by index (order on the page) or key. For example, at.time_input[0] for the first widget or at.time_input(key="my_key") for a widget with a given key. AppTest.titleStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.title elements. Function signature[source] AppTest.title Returns(ElementList of Title) Sequence of all st.title elements. Individual elements can be accessed from an ElementList by index (order on the page). For example, at.title[0] for the first element. Title is an extension of the Element class. AppTest.toastStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.toast elements. Function signature[source] AppTest.toast Returns(ElementList of Toast) Sequence of all st.toast elements. Individual elements can be accessed from an ElementList by index (order on the page). For example, at.toast[0] for the first element. Toast is an extension of the Element class. AppTest.toggleStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.toggle widgets. Function signature[source] AppTest.toggle Returns(WidgetList of Toggle) Sequence of all st.toggle widgets. Individual widgets can be accessed from a WidgetList by index (order on the page) or key. For example, at.toggle[0] for the first widget or at.toggle(key="my_key") for a widget with a given key. AppTest.warningStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSequence of all st.warning elements. Function signature[source] AppTest.warning Returns(ElementList of Warning) Sequence of all st.warning elements. Individual elements can be accessed from an ElementList by index (order on the page). For example, at.warning[0] for the first element. Warning is an extension of the Element class. Previous: App testingNext: Testing element classesforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy
https://docs.streamlit.io/develop/concepts/design/custom-classes#example-what-happens-when-you-define-the-same-class-twice
DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsremoveCOREArchitecture & executionaddMultipage appsaddApp designremoveAnimate & update elementsButton behavior and examplesDataframesUsing custom classesWorking with timezonesADDITIONALConnections and secretsaddCustom componentsaddConfiguration and themingaddApp testingaddAPI referenceaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Develop/Concepts/App design/Using custom classesUsing custom Python classes in your Streamlit app If you are building a complex Streamlit app or working with existing code, you may have custom Python classes defined in your script. Common examples include the following: Defining a @dataclass to store related data within your app. Defining an Enum class to represent a fixed set of options or values. Defining custom interfaces to external services or databases not covered by st.connection. Because Streamlit reruns your script after every user interaction, custom classes may be redefined multiple times within the same Streamlit session. This may result in unwanted effects, especially with class and instance comparisons. Read on to understand this common pitfall and how to avoid it. We begin by covering some general-purpose patterns you can use for different types of custom classes, and follow with a few more technical details explaining why this matters. Finally, we go into more detail about Using Enum classes specifically, and describe a configuration option which can make them more convenient. Patterns to define your custom classes Pattern 1: Define your class in a separate module This is the recommended, general solution. If possible, move class definitions into their own module file and import them into your app script. As long as you are not editing the file where your class is defined, Streamlit will not re-import it with each rerun. Therefore, if a class is defined in an external file and imported into your script, the class will not be redefined during the session. Example: Move your class definition Try running the following Streamlit app where MyClass is defined within the page's script. isinstance() will return True on the first script run then return False on each rerun thereafter. # app.py import streamlit as st # MyClass gets redefined every time app.py reruns class MyClass: def __init__(self, var1, var2): self.var1 = var1 self.var2 = var2 if "my_instance" not in st.session_state: st.session_state.my_instance = MyClass("foo", "bar") # Displays True on the first run then False on every rerun st.write(isinstance(st.session_state.my_instance, MyClass)) st.button("Rerun") If you move the class definition out of app.py into another file, you can make isinstance() consistently return True. Consider the following file structure: myproject/ ├── my_class.py └── app.py # my_class.py class MyClass: def __init__(self, var1, var2): self.var1 = var1 self.var2 = var2 # app.py import streamlit as st from my_class import MyClass # MyClass doesn't get redefined with each rerun if "my_instance" not in st.session_state: st.session_state.my_instance = MyClass("foo", "bar") # Displays True on every rerun st.write(isinstance(st.session_state.my_instance, MyClass)) st.button("Rerun") Streamlit only reloads code in imported modules when it detects the code has changed. Thus, if you are actively editing the file where your class is defined, you may need to stop and restart your Streamlit server to avoid an undesirable class redefinition mid-session. Pattern 2: Force your class to compare internal values For classes that store data (like dataclasses), you may be more interested in comparing the internally stored values rather than the class itself. If you define a custom __eq__ method, you can force comparisons to be made on the internally stored values. Example: Define __eq__ Try running the following Streamlit app and observe how the comparison is True on the first run then False on every rerun thereafter. import streamlit as st from dataclasses import dataclass @dataclass class MyDataclass: var1: int var2: float if "my_dataclass" not in st.session_state: st.session_state.my_dataclass = MyDataclass(1, 5.5) # Displays True on the first run the False on every rerun st.session_state.my_dataclass == MyDataclass(1, 5.5) st.button("Rerun") Since MyDataclass gets redefined with each rerun, the instance stored in Session State will not be equal to any instance defined in a later script run. You can fix this by forcing a comparison of internal values as follows: import streamlit as st from dataclasses import dataclass @dataclass class MyDataclass: var1: int var2: float def __eq__(self, other): # An instance of MyDataclass is equal to another object if the object # contains the same fields with the same values return (self.var1, self.var2) == (other.var1, other.var2) if "my_dataclass" not in st.session_state: st.session_state.my_dataclass = MyDataclass(1, 5.5) # Displays True on every rerun st.session_state.my_dataclass == MyDataclass(1, 5.5) st.button("Rerun") The default Python __eq__ implementation for a regular class or @dataclass depends on the in-memory ID of the class or class instance. To avoid problems in Streamlit, your custom __eq__ method should not depend the type() of self and other. Pattern 3: Store your class as serialized data Another option for classes that store data is to define serialization and deserialization methods like to_str and from_str for your class. You can use these to store class instance data in st.session_state rather than storing the class instance itself. Similar to pattern 2, this is a way to force comparison of the internal data and bypass the changing in-memory IDs. Example: Save your class instance as a string Using the same example from pattern 2, this can be done as follows: import streamlit as st from dataclasses import dataclass @dataclass class MyDataclass: var1: int var2: float def to_str(self): return f"{self.var1},{self.var2}" @classmethod def from_str(cls, serial_str): values = serial_str.split(",") var1 = int(values[0]) var2 = float(values[1]) return cls(var1, var2) if "my_dataclass" not in st.session_state: st.session_state.my_dataclass = MyDataclass(1, 5.5).to_str() # Displays True on every rerun MyDataclass.from_str(st.session_state.my_dataclass) == MyDataclass(1, 5.5) st.button("Rerun") Pattern 4: Use caching to preserve your class For classes that are used as resources (database connections, state managers, APIs), consider using the cached singleton pattern. Use @st.cache_resource to decorate a @staticmethod of your class to generate a single, cached instance of the class. For example: import streamlit as st class MyResource: def __init__(self, api_url: str): self._url = api_url @st.cache_resource(ttl=300) @staticmethod def get_resource_manager(api_url: str): return MyResource(api_url) # This is cached until Session State is cleared or 5 minutes has elapsed. resource_manager = MyResource.get_resource_manager("http://example.com/api/") When you use one of Streamlit's caching decorators on a function, Streamlit doesn't use the function object to look up cached values. Instead, Streamlit's caching decorators index return values using the function's qualified name and module. So, even though Streamlit redefines MyResource with each script run, st.cache_resource is unaffected by this. get_resource_manager() will return its cached value with each rerun, until the value expires. Understanding how Python defines and compares classes So what's really happening here? We'll consider a simple example to illustrate why this is a pitfall. Feel free to skip this section if you don't want to deal more details. You can jump ahead to learn about Using Enum classes. Example: What happens when you define the same class twice? Set aside Streamlit for a moment and think about this simple Python script: from dataclasses import dataclass @dataclass class Student: student_id: int name: str Marshall_A = Student(1, "Marshall") Marshall_B = Student(1, "Marshall") # This is True (because a dataclass will compare two of its instances by value) Marshall_A == Marshall_B # Redefine the class @dataclass class Student: student_id: int name: str Marshall_C = Student(1, "Marshall") # This is False Marshall_A == Marshall_C In this example, the dataclass Student is defined twice. All three Marshalls have the same internal values. If you compare Marshall_A and Marshall_B they will be equal because they were both created from the first definition of Student. However, if you compare Marshall_A and Marshall_C they will not be equal because Marshall_C was created from the second definition of Student. Even though both Student dataclasses are defined exactly the same, they have differnt in-memory IDs and are therefore different. What's happening in Streamlit? In Streamlit, you probably don't have the same class written twice in your page script. However, the rerun logic of Streamlit creates the same effect. Let's use the above example for an analogy. If you define a class in one script run and save an instance in Session State, then a later rerun will redefine the class and you may end up comparing a Mashall_C in your rerun to a Marshall_A in Session State. Since widgets rely on Session State under the hood, this is where things can get confusing. How Streamlit widgets store options Several Streamlit UI elements, such as st.selectbox or st.radio, accept multiple-choice options via an options argument. The user of your application can typically select one or more of these options. The selected value is returned by the widget function. For example: number = st.selectbox("Pick a number, any number", options=[1, 2, 3]) # number == whatever value the user has selected from the UI. When you call a function like st.selectbox and pass an Iterable to options, the Iterable and current selection are saved into a hidden portion of Session State called the Widget Metadata. When the user of your application interacts with the st.selectbox widget, the broswer sends the index of their selection to your Streamlit server. This index is used to determine which values from the original options list, saved in the Widget Metadata from the previous page execution, are returned to your application. The key detail is that the value returned by st.selectbox (or similar widget function) is from an Iterable saved in Session State during a previous execution of the page, NOT the values passed to options on the current execution. There are a number of architectural reasons why Streamlit is designed this way, which we won't go into here. However, this is how we end up comparing instances of different classes when we think we are comparing instances of the same class. A pathological example The above explanation might be a bit confusing, so here's a pathological example to illustrate the idea. import streamlit as st from dataclasses import dataclass @dataclass class Student: student_id: int name: str Marshall_A = Student(1, "Marshall") if "B" not in st.session_state: st.session_state.B = Student(1, "Marshall") Marshall_B = st.session_state.B options = [Marshall_A,Marshall_B] selected = st.selectbox("Pick", options) # This comparison does not return expected results: selected == Marshall_A # This comparison evaluates as expected: selected == Marshall_B As a final note, we used @dataclass in the example for this section to illustrate a point, but in fact it is possible to encounter these same problems with classes, in general. Any class which checks class identity inside of a comparison operator—such as __eq__ or __gt__—can exhibit these issues. Using Enum classes in Streamlit The Enum class from the Python standard library is a powerful way to define custom symbolic names that can be used as options for st.multiselect or st.selectbox in place of str values. For example, you might add the following to your streamlit page: from enum import Enum import streamlit as st # class syntax class Color(Enum): RED = 1 GREEN = 2 BLUE = 3 selected_colors = set(st.multiselect("Pick colors", options=Color)) if selected_colors == {Color.RED, Color.GREEN}: st.write("Hooray, you found the color YELLOW!") If you're using the latest version of Streamlit, this Streamlit page will work as it appears it should. When a user picks both Color.RED and Color.GREEN, they are shown the special message. However, if you've read the rest of this page you might notice something tricky going on. Specifically, the Enum class Color gets redefined every time this script is run. In Python, if you define two Enum classes with the same class name, members, and values, the classes and their members are still considered unique from each other. This should cause the above if condition to always evaluate to False. In any script rerun, the Color values returned by st.multiselect would be of a different class than the Color defined in that script run. If you run the snippet above with Streamlit version 1.28.0 or less, you will not be able see the special message. Thankfully, as of version 1.29.0, Streamlit introduced a configuration option to greatly simplify the problem. That's where the enabled-by-default enumCoercion configuration option comes in. Understanding the enumCoercion configuration option When enumCoercion is enabled, Streamlit tries to recognize when you are using an element like st.multiselect or st.selectbox with a set of Enum members as options. If Streamlit detects this, it will convert the widget's returned values to members of the Enum class defined in the latest script run. This is something we call automatic Enum coercion. This behavior is configurable via the enumCoercion setting in your Streamlit config.toml file. It is enabled by default, and may be disabled or set to a stricter set of matching criteria. If you find that you still encounter issues with enumCoercion enabled, consider using the custom class patterns described above, such as moving your Enum class definition to a separate module file.Previous: DataframesNext: Working with timezonesforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy
https://docs.streamlit.io/develop/api-reference/caching-and-state/st.experimental_singleton#widget-replay-disabled
DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceremovePAGE ELEMENTSWrite and magicaddText elementsaddData elementsaddChart elementsaddInput widgetsaddMedia elementsaddLayouts and containersaddChat elementsaddStatus elementsaddThird-party componentsopen_in_newAPPLICATION LOGICNavigation and pagesaddExecution flowaddCaching and stateremovest.cache_datast.cache_resourcest.cachedeletest.session_statest.query_paramsst.experimental_get_query_paramsdeletest.experimental_set_query_paramsdeleteConnections and secretsaddCustom componentsaddUtilitiesaddConfigurationaddTOOLSApp testingaddCommand lineaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Develop/API reference/Caching and state/st.experimental_singletonpriority_highImportantThis is an experimental feature. Experimental features and their APIs may change or be removed at any time. To learn more, click here. st.experimental_singletonStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakedeleteDeprecation noticest.experimental_singleton was deprecated in version 1.18.0. Use st.cache_resource instead. Learn more in Caching.Decorator to cache functions that return global resources (e.g. database connections, ML models). Cached objects are shared across all users, sessions, and reruns. They must be thread-safe because they can be accessed from multiple threads concurrently. If thread safety is an issue, consider using st.session_state to store resources per session instead. You can clear a function's cache with func.clear() or clear the entire cache with st.cache_resource.clear(). To cache data, use st.cache_data instead. Learn more about caching at https://docs.streamlit.io/library/advanced-features/caching. Function signature[source] st.experimental_singleton(func, *, ttl, max_entries, show_spinner, validate, experimental_allow_widgets, hash_funcs=None) Parameters func (callable) The function that creates the cached resource. Streamlit hashes the function's source code. ttl (float, timedelta, str, or None) The maximum time to keep an entry in the cache. Can be one of: None if cache entries should never expire (default). A number specifying the time in seconds. A string specifying the time in a format supported by Pandas's Timedelta constructor, e.g. "1d", "1.5 days", or "1h23s". A timedelta object from Python's built-in datetime library, e.g. timedelta(days=1). max_entries (int or None) The maximum number of entries to keep in the cache, or None for an unbounded cache. When a new entry is added to a full cache, the oldest cached entry will be removed. Defaults to None. show_spinner (bool or str) Enable the spinner. Default is True to show a spinner when there is a "cache miss" and the cached resource is being created. If string, value of show_spinner param will be used for spinner text. validate (callable or None) An optional validation function for cached data. validate is called each time the cached value is accessed. It receives the cached value as its only parameter and it must return a boolean. If validate returns False, the current cached value is discarded, and the decorated function is called to compute a new value. This is useful e.g. to check the health of database connections. experimental_allow_widgets (bool) Allow widgets to be used in the cached function. Defaults to False. Support for widgets in cached functions is currently experimental. Setting this parameter to True may lead to excessive memory use since the widget value is treated as an additional input parameter to the cache. We may remove support for this option at any time without notice. hash_funcs (dict or None) Mapping of types or fully qualified names to hash functions. This is used to override the behavior of the hasher inside Streamlit's caching mechanism: when the hasher encounters an object, it will first check to see if its type matches a key in this dict and, if so, will use the provided function to generate a hash for it. See below for an example of how this can be used. Example import streamlit as st @st.cache_resource def get_database_session(url): # Create a database session object that points to the URL. return session s1 = get_database_session(SESSION_URL_1) # Actually executes the function, since this is the first time it was # encountered. s2 = get_database_session(SESSION_URL_1) # Does not execute the function. Instead, returns its previously computed # value. This means that now the connection object in s1 is the same as in s2. s3 = get_database_session(SESSION_URL_2) # This is a different URL, so the function executes. By default, all parameters to a cache_resource function must be hashable. Any parameter whose name begins with _ will not be hashed. You can use this as an "escape hatch" for parameters that are not hashable: import streamlit as st @st.cache_resource def get_database_session(_sessionmaker, url): # Create a database connection object that points to the URL. return connection s1 = get_database_session(create_sessionmaker(), DATA_URL_1) # Actually executes the function, since this is the first time it was # encountered. s2 = get_database_session(create_sessionmaker(), DATA_URL_1) # Does not execute the function. Instead, returns its previously computed # value - even though the _sessionmaker parameter was different # in both calls. A cache_resource function's cache can be procedurally cleared: import streamlit as st @st.cache_resource def get_database_session(_sessionmaker, url): # Create a database connection object that points to the URL. return connection fetch_and_clean_data.clear(_sessionmaker, "https://streamlit.io/") # Clear the cached entry for the arguments provided. get_database_session.clear() # Clear all cached entries for this function. To override the default hashing behavior, pass a custom hash function. You can do that by mapping a type (e.g. Person) to a hash function (str) like this: import streamlit as st from pydantic import BaseModel class Person(BaseModel): name: str @st.cache_resource(hash_funcs={Person: str}) def get_person_name(person: Person): return person.name Alternatively, you can map the type's fully-qualified name (e.g. "__main__.Person") to the hash function instead: import streamlit as st from pydantic import BaseModel class Person(BaseModel): name: str @st.cache_resource(hash_funcs={"__main__.Person": str}) def get_person_name(person: Person): return person.name st.experimental_singleton.clearStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakedeleteDeprecation noticest.experimental_singleton.clear was deprecated in version 1.18.0. Use st.cache_resource.clear instead. Learn more in Caching.Clear all cache_resource caches. Function signature[source] st.experimental_singleton.clear() Example In the example below, pressing the "Clear All" button will clear all singleton caches. i.e. Clears cached singleton objects from all functions decorated with @st.experimental_singleton. import streamlit as st from transformers import BertModel @st.experimental_singleton def get_database_session(url): # Create a database session object that points to the URL. return session @st.experimental_singleton def get_model(model_type): # Create a model of the specified type. return BertModel.from_pretrained(model_type) if st.button("Clear All"): # Clears all singleton caches: st.experimental_singleton.clear() Validating the cache The @st.experimental_singleton decorator is used to cache the output of a function, so that it only needs to be executed once. This can improve performance in certain situations, such as when a function takes a long time to execute or makes a network request. However, in some cases, the cached output may become invalid over time, such as when a database connection times out. To handle this, the @st.experimental_singleton decorator supports an optional validate parameter, which accepts a validation function that is called each time the cached output is accessed. If the validation function returns False, the cached output is discarded and the decorated function is executed again. Best Practices Use the validate parameter when the cached output may become invalid over time, such as when a database connection or an API key expires. Use the validate parameter judiciously, as it will add an additional overhead of calling the validation function each time the cached output is accessed. Make sure that the validation function is as fast as possible, as it will be called each time the cached output is accessed. Consider to validate cached data periodically, instead of each time it is accessed, to mitigate the performance impact. Handle errors that may occur during validation and provide a fallback mechanism if the validation fails. Replay static st elements in cache-decorated functions Functions decorated with @st.experimental_singleton can contain static st elements. When a cache-decorated function is executed, we record the element and block messages produced, so the elements will appear in the app even when execution of the function is skipped because the result was cached. In the example below, the @st.experimental_singleton decorator is used to cache the execution of the get_model function, that returns a 🤗 Hugging Face Transformers model. Notice the cached function also contains a st.bar_chart command, which will be replayed when the function is skipped because the result was cached. import numpy as np import pandas as pd import streamlit as st from transformers import AutoModel @st.experimental_singleton def get_model(model_type): # Contains a static element st.bar_chart st.bar_chart( np.random.rand(10, 1) ) # This will be recorded and displayed even when the function is skipped # Create a model of the specified type return AutoModel.from_pretrained(model_type) bert_model = get_model("distilbert-base-uncased") st.help(bert_model) # Display the model's docstring Supported static st elements in cache-decorated functions include: st.alert st.altair_chart st.area_chart st.audio st.bar_chart st.ballons st.bokeh_chart st.caption st.code st.components.v1.html st.components.v1.iframe st.container st.dataframe st.echo st.empty st.error st.exception st.expander st.experimental_get_query_params st.experimental_set_query_params st.form st.form_submit_button st.graphviz_chart st.help st.image st.info st.json st.latex st.line_chart st.markdown st.metric st.plotly_chart st.progress st.pydeck_chart st.snow st.spinner st.success st.table st.text st.vega_lite_chart st.video st.warning Replay input widgets in cache-decorated functions In addition to static elements, functions decorated with @st.experimental_singleton can also contain input widgets! Replaying input widgets is disabled by default. To enable it, you can set the experimental_allow_widgets parameter for @st.experimental_singleton to True. The example below enables widget replaying, and shows the use of a checkbox widget within a cache-decorated function. import streamlit as st # Enable widget replay @st.experimental_singleton(experimental_allow_widgets=True) def func(): # Contains an input widget st.checkbox("Works!") func() If the cache decorated function contains input widgets, but experimental_allow_widgets is set to False or unset, Streamlit will throw a CachedStFunctionWarning, like the one below: import streamlit as st # Widget replay is disabled by default @st.experimental_singleton def func(): # Streamlit will throw a CachedStFunctionWarning st.checkbox("Doesn't work") func() How widget replay works Let's demystify how widget replay in cache-decorated functions works and gain a conceptual understanding. Widget values are treated as additional inputs to the function, and are used to determine whether the function should be executed or not. Consider the following example: import streamlit as st @st.experimental_singleton(experimental_allow_widgets=True) def plus_one(x): y = x + 1 if st.checkbox("Nuke the value 💥"): st.write("Value was nuked, returning 0") y = 0 return y st.write(plus_one(2)) The plus_one function takes an integer x as input, and returns x + 1. The function also contains a checkbox widget, which is used to "nuke" the value of x. i.e. the return value of plus_one depends on the state of the checkbox: if it is checked, the function returns 0, otherwise it returns 3. In order to know which value the cache should return (in case of a cache hit), Streamlit treats the checkbox state (checked / unchecked) as an additional input to the function plus_one (just like x). If the user checks the checkbox (thereby changing its state), we look up the cache for the same value of x (2) and the same checkbox state (checked). If the cache contains a value for this combination of inputs, we return it. Otherwise, we execute the function and store the result in the cache. Let's now understand how enabling and disabling widget replay changes the behavior of the function. Widget replay disabled Widgets in cached functions throw a CachedStFunctionWarning and are ignored. Other static elements in cached functions replay as expected. Widget replay enabled Widgets in cached functions don't lead to a warning, and are replayed as expected. Interacting with a widget in a cached function will cause the function to be executed again, and the cache to be updated. Widgets in cached functions retain their state across reruns. Each unique combination of widget values is treated as a separate input to the function, and is used to determine whether the function should be executed or not. i.e. Each unique combination of widget values has its own cache entry; the cached function runs the first time and the saved value is used afterwards. Calling a cached function multiple times in one script run with the same arguments triggers a DuplicateWidgetID error. If the arguments to a cached function change, widgets from that function that render again retain their state. Changing the source code of a cached function invalidates the cache. Both st.experimental_singleton and st.experimental_memo support widget replay. Fundamentally, the behavior of a function with (supported) widgets in it doesn't change when it is decorated with @st.experimental_singleton or @st.experimental_memo. The only difference is that the function is only executed when we detect a cache "miss". Supported widgets All input widgets are supported in cache-decorated functions. The following is an exhaustive list of supported widgets: st.button st.camera_input st.checkbox st.color_picker st.date_input st.download_button st.file_uploader st.multiselect st.number_input st.radio st.selectbox st.select_slider st.slider st.text_area st.text_input st.time_input Previous: st.experimental_memoNext: st.session_stateforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy
https://docs.streamlit.io/develop/quick-reference/cheat-sheet#placeholders-help-and-options
DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceaddTutorialsaddQuick referenceremoveCheat sheetRelease notesPre-release featuresRoadmapopen_in_newweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Develop/Quick reference/Cheat sheetStreamlit API cheat sheet This is a summary of the docs, as of Streamlit v1.34.0. Install & Importpip install streamlit streamlit run first_app.py # Import convention >>> import streamlit as st Pre-release featurespip uninstall streamlit pip install streamlit-nightly --upgrade Learn more about experimental featuresCommand linestreamlit --help streamlit run your_script.py streamlit hello streamlit config show streamlit cache clear streamlit docs streamlit --version Magic commands# Magic commands implicitly # call st.write(). "_This_ is some **Markdown***" my_variable "dataframe:", my_data_frame Display textst.write("Most objects") # df, err, func, keras! st.write(["st", "is <", 3]) # see * st.write_stream(my_generator) st.write_stream(my_llm_stream) st.text("Fixed width text") st.markdown("_Markdown_") # see * st.latex(r""" e^{i\pi} + 1 = 0 """) st.title("My title") st.header("My header") st.subheader("My sub") st.code("for i in range(8): foo()") * optional kwarg unsafe_allow_html = True Display datast.dataframe(my_dataframe) st.table(data.iloc[0:10]) st.json({"foo":"bar","fu":"ba"}) st.metric("My metric", 42, 2) Display mediast.image("./header.png") st.audio(data) st.video(data) st.video(data, subtitles="./subs.vtt") Display chartsst.area_chart(df) st.bar_chart(df) st.line_chart(df) st.map(df) st.scatter_chart(df) st.altair_chart(chart) st.bokeh_chart(fig) st.graphviz_chart(fig) st.plotly_chart(fig) st.pydeck_chart(chart) st.pyplot(fig) st.vega_lite_chart(df) Add widgets to sidebar# Just add it after st.sidebar: >>> a = st.sidebar.radio("Select one:", [1, 2]) # Or use "with" notation: >>> with st.sidebar: >>> st.radio("Select one:", [1, 2]) Columns# Two equal columns: >>> col1, col2 = st.columns(2) >>> col1.write("This is column 1") >>> col2.write("This is column 2") # Three different columns: >>> col1, col2, col3 = st.columns([3, 1, 1]) # col1 is larger. # You can also use "with" notation: >>> with col1: >>> st.radio("Select one:", [1, 2]) Tabs# Insert containers separated into tabs: >>> tab1, tab2 = st.tabs(["Tab 1", "Tab2"]) >>> tab1.write("this is tab 1") >>> tab2.write("this is tab 2") # You can also use "with" notation: >>> with tab1: >>> st.radio("Select one:", [1, 2]) Expandable containers>>> expand = st.expander("My label") >>> expand.write("Inside the expander.") >>> pop = st.popover("Button label") >>> pop.checkbox("Show all") # You can also use "with" notation: >>> with expand: >>> st.radio("Select one:", [1, 2]) Control flow# Stop execution immediately: st.stop() # Rerun script immediately: st.rerun() # Navigate to another page: st.switch_page("pages/my_page.py") # Group multiple widgets: >>> with st.form(key="my_form"): >>> username = st.text_input("Username") >>> password = st.text_input("Password") >>> st.form_submit_button("Login") # Define a dialog function >>> @st.experimental_dialog("Welcome!") >>> def modal_dialog(): >>> st.write("Hello") >>> >>> modal_dialog() # Define a fragment >>> @st.experimental_fragment >>> def fragment_function(): >>> df = get_data() >>> st.line_chart(df) >>> st.button("Update") >>> >>> fragment_function() Display interactive widgetsst.button("Click me") st.download_button("Download file", data) st.link_button("Go to gallery", url) st.page_link("app.py", label="Home") st.data_editor("Edit data", data) st.checkbox("I agree") st.toggle("Enable") st.radio("Pick one", ["cats", "dogs"]) st.selectbox("Pick one", ["cats", "dogs"]) st.multiselect("Buy", ["milk", "apples", "potatoes"]) st.slider("Pick a number", 0, 100) st.select_slider("Pick a size", ["S", "M", "L"]) st.text_input("First name") st.number_input("Pick a number", 0, 10) st.text_area("Text to translate") st.date_input("Your birthday") st.time_input("Meeting time") st.file_uploader("Upload a CSV") st.camera_input("Take a picture") st.color_picker("Pick a color") # Use widgets' returned values in variables: >>> for i in range(int(st.number_input("Num:"))): >>> foo() >>> if st.sidebar.selectbox("I:",["f"]) == "f": >>> b() >>> my_slider_val = st.slider("Quinn Mallory", 1, 88) >>> st.write(slider_val) # Disable widgets to remove interactivity: >>> st.slider("Pick a number", 0, 100, disabled=True) Build chat-based apps# Insert a chat message container. >>> with st.chat_message("user"): >>> st.write("Hello 👋") >>> st.line_chart(np.random.randn(30, 3)) # Display a chat input widget at the bottom of the app. >>> st.chat_input("Say something") # Display a chat input widget inline. >>> with st.container(): >>> st.chat_input("Say something") Learn how to Build a basic LLM chat appMutate data# Add rows to a dataframe after # showing it. >>> element = st.dataframe(df1) >>> element.add_rows(df2) # Add rows to a chart after # showing it. >>> element = st.line_chart(df1) >>> element.add_rows(df2) Display code>>> with st.echo(): >>> st.write("Code will be executed and printed") Placeholders, help, and options# Replace any single element. >>> element = st.empty() >>> element.line_chart(...) >>> element.text_input(...) # Replaces previous. # Insert out of order. >>> elements = st.container() >>> elements.line_chart(...) >>> st.write("Hello") >>> elements.text_input(...) # Appears above "Hello". st.help(pandas.DataFrame) st.get_option(key) st.set_option(key, value) st.set_page_config(layout="wide") st.query_params[key] st.query_params.from_dict(params_dict) st.query_params.get_all(key) st.query_params.clear() st.html("<p>Hi!</p>") Connect to data sourcesst.connection("pets_db", type="sql") conn = st.connection("sql") conn = st.connection("snowflake") >>> class MyConnection(BaseConnection[myconn.MyConnection]): >>> def _connect(self, **kwargs) -> MyConnection: >>> return myconn.connect(**self._secrets, **kwargs) >>> def query(self, query): >>> return self._instance.query(query) Optimize performanceCache data objects# E.g. Dataframe computation, storing downloaded data, etc. >>> @st.cache_data ... def foo(bar): ... # Do something expensive and return data ... return data # Executes foo >>> d1 = foo(ref1) # Does not execute foo # Returns cached item by value, d1 == d2 >>> d2 = foo(ref1) # Different arg, so function foo executes >>> d3 = foo(ref2) # Clear the cached value for foo(ref1) >>> foo.clear(ref1) # Clear all cached entries for this function >>> foo.clear() # Clear values from *all* in-memory or on-disk cached functions >>> st.cache_data.clear() Cache global resources# E.g. TensorFlow session, database connection, etc. >>> @st.cache_resource ... def foo(bar): ... # Create and return a non-data object ... return session # Executes foo >>> s1 = foo(ref1) # Does not execute foo # Returns cached item by reference, s1 == s2 >>> s2 = foo(ref1) # Different arg, so function foo executes >>> s3 = foo(ref2) # Clear the cached value for foo(ref1) >>> foo.clear(ref1) # Clear all cached entries for this function >>> foo.clear() # Clear all global resources from cache >>> st.cache_resource.clear() Deprecated caching>>> @st.cache ... def foo(bar): ... # Do something expensive in here... ... return data >>> # Executes foo >>> d1 = foo(ref1) >>> # Does not execute foo >>> # Returns cached item by reference, d1 == d2 >>> d2 = foo(ref1) >>> # Different arg, so function foo executes >>> d3 = foo(ref2) Display progress and status# Show a spinner during a process >>> with st.spinner(text="In progress"): >>> time.sleep(3) >>> st.success("Done") # Show and update progress bar >>> bar = st.progress(50) >>> time.sleep(3) >>> bar.progress(100) >>> with st.status("Authenticating...") as s: >>> time.sleep(2) >>> st.write("Some long response.") >>> s.update(label="Response") st.balloons() st.snow() st.toast("Warming up...") st.error("Error message") st.warning("Warning message") st.info("Info message") st.success("Success message") st.exception(e) Personalize apps for users# Show different content based on the user's email address. >>> if st.user.email == "jane@email.com": >>> display_jane_content() >>> elif st.user.email == "adam@foocorp.io": >>> display_adam_content() >>> else: >>> st.write("Please contact us to get access!") Previous: Quick referenceNext: Release notesforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy
https://docs.streamlit.io/get-started/tutorials/create-an-app#draw-a-histogram
DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsremoveCreate an appCreate a multipage appcodeDevelopConceptsaddAPI referenceaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Get started/First steps/Create an appCreate an app If you've made it this far, chances are you've installed Streamlit and run through the basics in Basic concepts and Advanced concepts. If not, now is a good time to take a look. The easiest way to learn how to use Streamlit is to try things out yourself. As you read through this guide, test each method. As long as your app is running, every time you add a new element to your script and save, Streamlit's UI will ask if you'd like to rerun the app and view the changes. This allows you to work in a fast interactive loop: you write some code, save it, review the output, write some more, and so on, until you're happy with the results. The goal is to use Streamlit to create an interactive app for your data or model and along the way to use Streamlit to review, debug, perfect, and share your code. In this guide, you're going to use Streamlit's core features to create an interactive app; exploring a public Uber dataset for pickups and drop-offs in New York City. When you're finished, you'll know how to fetch and cache data, draw charts, plot information on a map, and use interactive widgets, like a slider, to filter results. starTipIf you'd like to skip ahead and see everything at once, the complete script is available below. Create your first app Streamlit is more than just a way to make data apps, it’s also a community of creators that share their apps and ideas and help each other make their work better. Please come join us on the community forum. We love to hear your questions, ideas, and help you work through your bugs — stop by today! The first step is to create a new Python script. Let's call it uber_pickups.py. Open uber_pickups.py in your favorite IDE or text editor, then add these lines: import streamlit as st import pandas as pd import numpy as np Every good app has a title, so let's add one: st.title('Uber pickups in NYC') Now it's time to run Streamlit from the command line: streamlit run uber_pickups.py Running a Streamlit app is no different than any other Python script. Whenever you need to view the app, you can use this command. starTipDid you know you can also pass a URL to streamlit run? This is great when combined with GitHub Gists. For example:streamlit run https://raw.githubusercontent.com/streamlit/demo-uber-nyc-pickups/master/streamlit_app.py As usual, the app should automatically open in a new tab in your browser. Fetch some data Now that you have an app, the next thing you'll need to do is fetch the Uber dataset for pickups and drop-offs in New York City. Let's start by writing a function to load the data. Add this code to your script: DATE_COLUMN = 'date/time' DATA_URL = ('https://s3-us-west-2.amazonaws.com/' 'streamlit-demo-data/uber-raw-data-sep14.csv.gz') def load_data(nrows): data = pd.read_csv(DATA_URL, nrows=nrows) lowercase = lambda x: str(x).lower() data.rename(lowercase, axis='columns', inplace=True) data[DATE_COLUMN] = pd.to_datetime(data[DATE_COLUMN]) return data You'll notice that load_data is a plain old function that downloads some data, puts it in a Pandas dataframe, and converts the date column from text to datetime. The function accepts a single parameter (nrows), which specifies the number of rows that you want to load into the dataframe. Now let's test the function and review the output. Below your function, add these lines: # Create a text element and let the reader know the data is loading. data_load_state = st.text('Loading data...') # Load 10,000 rows of data into the dataframe. data = load_data(10000) # Notify the reader that the data was successfully loaded. data_load_state.text('Loading data...done!') You'll see a few buttons in the upper-right corner of your app asking if you'd like to rerun the app. Choose Always rerun, and you'll see your changes automatically each time you save. Ok, that's underwhelming... It turns out that it takes a long time to download data, and load 10,000 lines into a dataframe. Converting the date column into datetime isn’t a quick job either. You don’t want to reload the data each time the app is updated – luckily Streamlit allows you to cache the data. Effortless caching Try adding @st.cache_data before the load_data declaration: @st.cache_data def load_data(nrows): Then save the script, and Streamlit will automatically rerun your app. Since this is the first time you’re running the script with @st.cache_data, you won't see anything change. Let’s tweak your file a little bit more so that you can see the power of caching. Replace the line data_load_state.text('Loading data...done!') with this: data_load_state.text("Done! (using st.cache_data)") Now save. See how the line you added appeared immediately? If you take a step back for a second, this is actually quite amazing. Something magical is happening behind the scenes, and it only takes one line of code to activate it. How's it work? Let's take a few minutes to discuss how @st.cache_data actually works. When you mark a function with Streamlit’s cache annotation, it tells Streamlit that whenever the function is called that it should check two things: The input parameters you used for the function call. The code inside the function. If this is the first time Streamlit has seen both these items, with these exact values, and in this exact combination, it runs the function and stores the result in a local cache. The next time the function is called, if the two values haven't changed, then Streamlit knows it can skip executing the function altogether. Instead, it reads the output from the local cache and passes it on to the caller -- like magic. "But, wait a second," you’re saying to yourself, "this sounds too good to be true. What are the limitations of all this awesomesauce?" Well, there are a few: Streamlit will only check for changes within the current working directory. If you upgrade a Python library, Streamlit's cache will only notice this if that library is installed inside your working directory. If your function is not deterministic (that is, its output depends on random numbers), or if it pulls data from an external time-varying source (for example, a live stock market ticker service) the cached value will be none-the-wiser. Lastly, you should avoid mutating the output of a function cached with st.cache_data since cached values are stored by reference. While these limitations are important to keep in mind, they tend not to be an issue a surprising amount of the time. Those times, this cache is really transformational. starTipWhenever you have a long-running computation in your code, consider refactoring it so you can use @st.cache_data, if possible. Please read Caching for more details. Now that you know how caching with Streamlit works, let’s get back to the Uber pickup data. Inspect the raw data It's always a good idea to take a look at the raw data you're working with before you start working with it. Let's add a subheader and a printout of the raw data to the app: st.subheader('Raw data') st.write(data) In the Basic concepts guide you learned that st.write will render almost anything you pass to it. In this case, you're passing in a dataframe and it's rendering as an interactive table. st.write tries to do the right thing based on the data type of the input. If it isn't doing what you expect you can use a specialized command like st.dataframe instead. For a full list, see API reference. Draw a histogram Now that you've had a chance to take a look at the dataset and observe what's available, let's take things a step further and draw a histogram to see what Uber's busiest hours are in New York City. To start, let's add a subheader just below the raw data section: st.subheader('Number of pickups by hour') Use NumPy to generate a histogram that breaks down pickup times binned by hour: hist_values = np.histogram( data[DATE_COLUMN].dt.hour, bins=24, range=(0,24))[0] Now, let's use Streamlit's st.bar_chart() method to draw this histogram. st.bar_chart(hist_values) Save your script. This histogram should show up in your app right away. After a quick review, it looks like the busiest time is 17:00 (5 P.M.). To draw this diagram we used Streamlit's native bar_chart() method, but it's important to know that Streamlit supports more complex charting libraries like Altair, Bokeh, Plotly, Matplotlib and more. For a full list, see supported charting libraries. Plot data on a map Using a histogram with Uber's dataset helped us determine what the busiest times are for pickups, but what if we wanted to figure out where pickups were concentrated throughout the city. While you could use a bar chart to show this data, it wouldn't be easy to interpret unless you were intimately familiar with latitudinal and longitudinal coordinates in the city. To show pickup concentration, let's use Streamlit st.map() function to overlay the data on a map of New York City. Add a subheader for the section: st.subheader('Map of all pickups') Use the st.map() function to plot the data: st.map(data) Save your script. The map is fully interactive. Give it a try by panning or zooming in a bit. After drawing your histogram, you determined that the busiest hour for Uber pickups was 17:00. Let's redraw the map to show the concentration of pickups at 17:00. Locate the following code snippet: st.subheader('Map of all pickups') st.map(data) Replace it with: hour_to_filter = 17 filtered_data = data[data[DATE_COLUMN].dt.hour == hour_to_filter] st.subheader(f'Map of all pickups at {hour_to_filter}:00') st.map(filtered_data) You should see the data update instantly. To draw this map we used the st.map function that's built into Streamlit, but if you'd like to visualize complex map data, we encourage you to take a look at the st.pydeck_chart. Filter results with a slider In the last section, when you drew the map, the time used to filter results was hardcoded into the script, but what if we wanted to let a reader dynamically filter the data in real time? Using Streamlit's widgets you can. Let's add a slider to the app with the st.slider() method. Locate hour_to_filter and replace it with this code snippet: hour_to_filter = st.slider('hour', 0, 23, 17) # min: 0h, max: 23h, default: 17h Use the slider and watch the map update in real time. Use a button to toggle data Sliders are just one way to dynamically change the composition of your app. Let's use the st.checkbox function to add a checkbox to your app. We'll use this checkbox to show/hide the raw data table at the top of your app. Locate these lines: st.subheader('Raw data') st.write(data) Replace these lines with the following code: if st.checkbox('Show raw data'): st.subheader('Raw data') st.write(data) We're sure you've got your own ideas. When you're done with this tutorial, check out all the widgets that Streamlit exposes in our API Reference. Let's put it all together That's it, you've made it to the end. Here's the complete script for our interactive app. starTipIf you've skipped ahead, after you've created your script, the command to run Streamlit is streamlit run [app name]. import streamlit as st import pandas as pd import numpy as np st.title('Uber pickups in NYC') DATE_COLUMN = 'date/time' DATA_URL = ('https://s3-us-west-2.amazonaws.com/' 'streamlit-demo-data/uber-raw-data-sep14.csv.gz') @st.cache_data def load_data(nrows): data = pd.read_csv(DATA_URL, nrows=nrows) lowercase = lambda x: str(x).lower() data.rename(lowercase, axis='columns', inplace=True) data[DATE_COLUMN] = pd.to_datetime(data[DATE_COLUMN]) return data data_load_state = st.text('Loading data...') data = load_data(10000) data_load_state.text("Done! (using st.cache_data)") if st.checkbox('Show raw data'): st.subheader('Raw data') st.write(data) st.subheader('Number of pickups by hour') hist_values = np.histogram(data[DATE_COLUMN].dt.hour, bins=24, range=(0,24))[0] st.bar_chart(hist_values) # Some number in the range 0-23 hour_to_filter = st.slider('hour', 0, 23, 17) filtered_data = data[data[DATE_COLUMN].dt.hour == hour_to_filter] st.subheader('Map of all pickups at %s:00' % hour_to_filter) st.map(filtered_data) Share your app After you’ve built a Streamlit app, it's time to share it! To show it off to the world you can use Streamlit Community Cloud to deploy, manage, and share your app for free. It works in 3 simple steps: Put your app in a public GitHub repo (and make sure it has a requirements.txt!) Sign into share.streamlit.io Click 'Deploy an app' and then paste in your GitHub URL That's it! 🎈 You now have a publicly deployed app that you can share with the world. Click to learn more about how to use Streamlit Community Cloud. Get help That's it for getting started, now you can go and build your own apps! If you run into difficulties here are a few things you can do. Check out our community forum and post a question Quick help from command line with streamlit help Go through our Knowledge Base for tips, step-by-step tutorials, and articles that answer your questions about creating and deploying Streamlit apps. Read more documentation! Check out: Concepts for things like caching, theming, and adding statefulness to apps. API reference for examples of every Streamlit command. Previous: First stepsNext: Create a multipage appforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy
https://docs.streamlit.io/knowledge-base/using-streamlit/sanity-checks#check-4-is-your-browser-caching-your-app-too-aggressively
DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Knowledge base/FAQ/Sanity checksSanity checks If you're having problems running your Streamlit app, here are a few things to try out. Check #0: Are you using a Streamlit-supported version of Python? Streamlit will maintain backwards-compatibility with earlier Python versions as practical, guaranteeing compatibility with at least the last three minor versions of Python 3. As new versions of Python are released, we will try to be compatible with the new version as soon as possible, though frequently we are at the mercy of other Python packages to support these new versions as well. Streamlit currently supports versions 3.8, 3.9, 3.10, 3.11, and 3.12 of Python. Check #1: Is Streamlit running? On a Mac or Linux machine, type this on the terminal: ps -Al | grep streamlit If you don't see streamlit run in the output (or streamlit hello, if that's the command you ran) then the Streamlit server is not running. So re-run your command and see if the bug goes away. Check #2: Is this an already-fixed Streamlit bug? We try to fix bugs quickly, so many times a problem will go away when you upgrade Streamlit. So the first thing to try when having an issue is upgrading to the latest version of Streamlit: pip install --upgrade streamlit streamlit version ...and then verify that the version number printed corresponds to the version number displayed on PyPI. Try reproducing the issue now. If not fixed, keep reading on. Check #3: Are you running the correct Streamlit binary? Let's check whether your Python environment is set up correctly. Edit the Streamlit script where you're experiencing your issue, comment everything out, and add these lines instead: import streamlit as st st.write(st.__version__) ...then call streamlit run on your script and make sure it says the same version as above. If not the same version, check out these instructions for some sure-fire ways to set up your environment. Check #4: Is your browser caching your app too aggressively? There are two easy ways to check this: Load your app in a browser then press Ctrl-Shift-R or ⌘-Shift-R to do a hard refresh (Chrome/Firefox). As a test, run Streamlit on another port. This way the browser starts the page with a brand new cache. For that, pass the --server.port argument to Streamlit on the command line: streamlit run my_app.py --server.port=9876 Check #5: Is this a Streamlit regression? If you've upgraded to the latest version of Streamlit and things aren't working, you can downgrade at any time using this command: pip install --upgrade streamlit==1.0.0 ...where 1.0.0 is the version you'd like to downgrade to. See Changelog for a complete list of Streamlit versions. Check #6 [Windows]: Is Python added to your PATH? When installed by downloading from python.org, Python is not automatically added to the Windows system PATH. Because of this, you may get error messages like the following: Command Prompt: C:\Users\streamlit> streamlit hello 'streamlit' is not recognized as an internal or external command, operable program or batch file. PowerShell: PS C:\Users\streamlit> streamlit hello streamlit : The term 'streamlit' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again. At line:1 char:1 + streamlit hello + ~~~~~~~~~ + CategoryInfo : ObjectNotFound: (streamlit:String) [], CommandNotFoundException + FullyQualifiedErrorId : CommandNotFoundException To resolve this issue, add Python to the Windows system PATH. After adding Python to your Windows PATH, you should then be able to follow the instructions in our Get Started section. Check #7 [Windows]: Do you need Build Tools for Visual Studio installed? Streamlit includes pyarrow as an install dependency. Occasionally, when trying to install Streamlit from PyPI, you may see errors such as the following: Using cached pyarrow-1.0.1.tar.gz (1.3 MB) Installing build dependencies ... error ERROR: Command errored out with exit status 1: command: 'c:\users\streamlit\appdata\local\programs\python\python38-32\python.exe' 'c:\users\streamlit\appdata\local\programs\python\python38-32\lib\site-packages\pip' install --ignore-installed --no-user --prefix 'C:\Users\streamlit\AppData\Local\Temp\pip-build-env-s7owjrle\overlay' --no-warn-script-location --no-binary :none: --only-binary :none: -i https://pypi.org/simple -- 'cython >= 0.29' 'numpy==1.14.5; python_version<'"'"'3.8'"'"'' 'numpy==1.16.0; python_version>='"'"'3.8'"'"'' setuptools setuptools_scm wheel cwd: None Complete output (319 lines): Running setup.py install for numpy: finished with status 'error' ERROR: Command errored out with exit status 1: command: 'c:\users\streamlit\appdata\local\programs\python\python38-32\python.exe' -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'C:\\Users\\streamlit\\AppData\\Local\\Temp\\pip-install-0jwfwx_u\\numpy\\setup.py'"'"'; __file__='"'"'C:\\Users\\streamlit\\AppData\\Local\\Temp\\pip-install-0jwfwx_u\\numpy\\setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' install --record 'C:\Users\streamlit\AppData\Local\Temp\pip-record-eys4l2gc\install-record.txt' --single-version-externally-managed --prefix 'C:\Users\streamlit\AppData\Local\Temp\pip-build-env-s7owjrle\overlay' --compile --install-headers 'C:\Users\streamlit\AppData\Local\Temp\pip-build-env-s7owjrle\overlay\Include\numpy' cwd: C:\Users\streamlit\AppData\Local\Temp\pip-install-0jwfwx_u\numpy\ Complete output (298 lines): blas_opt_info: blas_mkl_info: No module named 'numpy.distutils._msvccompiler' in numpy.distutils; trying from distutils customize MSVCCompiler libraries mkl_rt not found in ['c:\\users\\streamlit\\appdata\\local\\programs\\python\\python38-32\\lib', 'C:\\', 'c:\\users\\streamlit\\appdata\\local\\programs\\python\\python38-32\\libs'] NOT AVAILABLE blis_info: No module named 'numpy.distutils._msvccompiler' in numpy.distutils; trying from distutils customize MSVCCompiler libraries blis not found in ['c:\\users\\streamlit\\appdata\\local\\programs\\python\\python38-32\\lib', 'C:\\', 'c:\\users\\streamlit\\appdata\\local\\programs\\python\\python38-32\\libs'] NOT AVAILABLE # <truncated for brevity> # c:\users\streamlit\appdata\local\programs\python\python38-32\lib\distutils\dist.py:274: UserWarning: Unknown distribution option: 'define_macros' warnings.warn(msg) running install running build running config_cc unifing config_cc, config, build_clib, build_ext, build commands --compiler options running config_fc unifing config_fc, config, build_clib, build_ext, build commands --fcompiler options running build_src build_src building py_modules sources creating build creating build\src.win32-3.8 creating build\src.win32-3.8\numpy creating build\src.win32-3.8\numpy\distutils building library "npymath" sources No module named 'numpy.distutils._msvccompiler' in numpy.distutils; trying from distutils error: Microsoft Visual C++ 14.0 is required. Get it with "Build Tools for Visual Studio": https://visualstudio.microsoft.com/downloads/ ---------------------------------------- ERROR: Command errored out with exit status 1: 'c:\users\streamlit\appdata\local\programs\python\python38-32\python.exe' -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'C:\\Users\\streamlit\\AppData\\Local\\Temp\\pip-install-0jwfwx_u\\numpy\\setup.py'"'"'; __file__='"'"'C:\\Users\\streamlit\\AppData\\Local\\Temp\\pip-install-0jwfwx_u\\numpy\\setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' install --record 'C:\Users\streamlit\AppData\Local\Temp\pip-record-eys4l2gc\install-record.txt' --single-version-externally-managed --prefix 'C:\Users\streamlit\AppData\Local\Temp\pip-build-env-s7owjrle\overlay' --compile --install-headers 'C:\Users\streamlit\AppData\Local\Temp\pip-build-env-s7owjrle\overlay\Include\numpy' Check the logs for full command output. ---------------------------------------- This error indicates that Python is trying to compile certain libraries during install, but it cannot find the proper compilers on your system, as reflected by the line error: Microsoft Visual C++ 14.0 is required. Get it with "Build Tools for Visual Studio". Installing Build Tools for Visual Studio should resolve this issue.Previous: How do you retrieve the filename of a file uploaded with st.file_uploader?Next: How can I make Streamlit watch for changes in other modules I'm importing in my app?forumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy
https://docs.streamlit.io/develop/api-reference/caching-and-state/st.cache_data#input-widgets
DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceremovePAGE ELEMENTSWrite and magicaddText elementsaddData elementsaddChart elementsaddInput widgetsaddMedia elementsaddLayouts and containersaddChat elementsaddStatus elementsaddThird-party componentsopen_in_newAPPLICATION LOGICNavigation and pagesaddExecution flowaddCaching and stateremovest.cache_datast.cache_resourcest.cachedeletest.session_statest.query_paramsst.experimental_get_query_paramsdeletest.experimental_set_query_paramsdeleteConnections and secretsaddCustom componentsaddUtilitiesaddConfigurationaddTOOLSApp testingaddCommand lineaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Develop/API reference/Caching and state/st.cache_datastarTipThis page only contains information on the st.cache_data API. For a deeper dive into caching and how to use it, check out Caching. st.cache_dataStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeDecorator to cache functions that return data (e.g. dataframe transforms, database queries, ML inference). Cached objects are stored in "pickled" form, which means that the return value of a cached function must be pickleable. Each caller of the cached function gets its own copy of the cached data. You can clear a function's cache with func.clear() or clear the entire cache with st.cache_data.clear(). To cache global resources, use st.cache_resource instead. Learn more about caching at https://docs.streamlit.io/library/advanced-features/caching. Function signature[source] st.cache_data(func=None, *, ttl, max_entries, show_spinner, persist, experimental_allow_widgets, hash_funcs=None) Parameters func (callable) The function to cache. Streamlit hashes the function's source code. ttl (float, timedelta, str, or None) The maximum time to keep an entry in the cache. Can be one of: None if cache entries should never expire (default). A number specifying the time in seconds. A string specifying the time in a format supported by Pandas's Timedelta constructor, e.g. "1d", "1.5 days", or "1h23s". A timedelta object from Python's built-in datetime library, e.g. timedelta(days=1). Note that ttl will be ignored if persist="disk" or persist=True. max_entries (int or None) The maximum number of entries to keep in the cache, or None for an unbounded cache. When a new entry is added to a full cache, the oldest cached entry will be removed. Defaults to None. show_spinner (bool or str) Enable the spinner. Default is True to show a spinner when there is a "cache miss" and the cached data is being created. If string, value of show_spinner param will be used for spinner text. persist ("disk", bool, or None) Optional location to persist cached data to. Passing "disk" (or True) will persist the cached data to the local disk. None (or False) will disable persistence. The default is None. experimental_allow_widgets (bool) Allow widgets to be used in the cached function. Defaults to False. Support for widgets in cached functions is currently experimental. Setting this parameter to True may lead to excessive memory use since the widget value is treated as an additional input parameter to the cache. We may remove support for this option at any time without notice. hash_funcs (dict or None) Mapping of types or fully qualified names to hash functions. This is used to override the behavior of the hasher inside Streamlit's caching mechanism: when the hasher encounters an object, it will first check to see if its type matches a key in this dict and, if so, will use the provided function to generate a hash for it. See below for an example of how this can be used. Example import streamlit as st @st.cache_data def fetch_and_clean_data(url): # Fetch data from URL here, and then clean it up. return data d1 = fetch_and_clean_data(DATA_URL_1) # Actually executes the function, since this is the first time it was # encountered. d2 = fetch_and_clean_data(DATA_URL_1) # Does not execute the function. Instead, returns its previously computed # value. This means that now the data in d1 is the same as in d2. d3 = fetch_and_clean_data(DATA_URL_2) # This is a different URL, so the function executes. To set the persist parameter, use this command as follows: import streamlit as st @st.cache_data(persist="disk") def fetch_and_clean_data(url): # Fetch data from URL here, and then clean it up. return data By default, all parameters to a cached function must be hashable. Any parameter whose name begins with _ will not be hashed. You can use this as an "escape hatch" for parameters that are not hashable: import streamlit as st @st.cache_data def fetch_and_clean_data(_db_connection, num_rows): # Fetch data from _db_connection here, and then clean it up. return data connection = make_database_connection() d1 = fetch_and_clean_data(connection, num_rows=10) # Actually executes the function, since this is the first time it was # encountered. another_connection = make_database_connection() d2 = fetch_and_clean_data(another_connection, num_rows=10) # Does not execute the function. Instead, returns its previously computed # value - even though the _database_connection parameter was different # in both calls. A cached function's cache can be procedurally cleared: import streamlit as st @st.cache_data def fetch_and_clean_data(_db_connection, num_rows): # Fetch data from _db_connection here, and then clean it up. return data fetch_and_clean_data.clear(_db_connection, 50) # Clear the cached entry for the arguments provided. fetch_and_clean_data.clear() # Clear all cached entries for this function. To override the default hashing behavior, pass a custom hash function. You can do that by mapping a type (e.g. datetime.datetime) to a hash function (lambda dt: dt.isoformat()) like this: import streamlit as st import datetime @st.cache_data(hash_funcs={datetime.datetime: lambda dt: dt.isoformat()}) def convert_to_utc(dt: datetime.datetime): return dt.astimezone(datetime.timezone.utc) Alternatively, you can map the type's fully-qualified name (e.g. "datetime.datetime") to the hash function instead: import streamlit as st import datetime @st.cache_data(hash_funcs={"datetime.datetime": lambda dt: dt.isoformat()}) def convert_to_utc(dt: datetime.datetime): return dt.astimezone(datetime.timezone.utc) priority_highWarningst.cache_data implicitly uses the pickle module, which is known to be insecure. Anything your cached function returns is pickled and stored, then unpickled on retrieval. Ensure your cached functions return trusted values because it is possible to construct malicious pickle data that will execute arbitrary code during unpickling. Never load data that could have come from an untrusted source in an unsafe mode or that could have been tampered with. Only load data you trust. st.cache_data.clearStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeClear all in-memory and on-disk data caches. Function signature[source] st.cache_data.clear() Example In the example below, pressing the "Clear All" button will clear memoized values from all functions decorated with @st.cache_data. import streamlit as st @st.cache_data def square(x): return x**2 @st.cache_data def cube(x): return x**3 if st.button("Clear All"): # Clear values from *all* all in-memory and on-disk data caches: # i.e. clear values from both square and cube st.cache_data.clear() CachedFunc.clearStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeClear the cached function's associated cache. If no arguments are passed, Streamlit will clear all values cached for the function. If arguments are passed, Streamlit will clear the cached value for these arguments only. Function signature[source] CachedFunc.clear(*args, **kwargs) Parameters *args (Any) Arguments of the cached functions. **kwargs (Any) Keyword arguments of the cached function. Example import streamlit as st import time @st.cache_data def foo(bar): time.sleep(2) st.write(f"Executed foo({bar}).") return bar if st.button("Clear all cached values for `foo`", on_click=foo.clear): foo.clear() if st.button("Clear the cached value of `foo(1)`"): foo.clear(1) foo(1) foo(2) Using Streamlit commands in cached functions Static elements Since version 1.16.0, cached functions can contain Streamlit commands! For example, you can do this: @st.cache_data def get_api_data(): data = api.get(...) st.success("Fetched data from API!") # 👈 Show a success message return data As we know, Streamlit only runs this function if it hasn’t been cached before. On this first run, the st.success message will appear in the app. But what happens on subsequent runs? It still shows up! Streamlit realizes that there is an st. command inside the cached function, saves it during the first run, and replays it on subsequent runs. Replaying static elements works for both caching decorators. You can also use this functionality to cache entire parts of your UI: @st.cache_data def show_data(): st.header("Data analysis") data = api.get(...) st.success("Fetched data from API!") st.write("Here is a plot of the data:") st.line_chart(data) st.write("And here is the raw data:") st.dataframe(data) Input widgets You can also use interactive input widgets like st.slider or st.text_input in cached functions. Widget replay is an experimental feature at the moment. To enable it, you need to set the experimental_allow_widgets parameter: @st.cache_data(experimental_allow_widgets=True) # 👈 Set the parameter def get_data(): num_rows = st.slider("Number of rows to get") # 👈 Add a slider data = api.get(..., num_rows) return data Streamlit treats the slider like an additional input parameter to the cached function. If you change the slider position, Streamlit will see if it has already cached the function for this slider value. If yes, it will return the cached value. If not, it will rerun the function using the new slider value. Using widgets in cached functions is extremely powerful because it lets you cache entire parts of your app. But it can be dangerous! Since Streamlit treats the widget value as an additional input parameter, it can easily lead to excessive memory usage. Imagine your cached function has five sliders and returns a 100 MB DataFrame. Then we’ll add 100 MB to the cache for every permutation of these five slider values – even if the sliders do not influence the returned data! These additions can make your cache explode very quickly. Please be aware of this limitation if you use widgets in cached functions. We recommend using this feature only for isolated parts of your UI where the widgets directly influence the cached return value. priority_highWarningSupport for widgets in cached functions is currently experimental. We may change or remove it anytime without warning. Please use it with care! push_pinNoteTwo widgets are currently not supported in cached functions: st.file_uploader and st.camera_input. We may support them in the future. Feel free to open a GitHub issue if you need them!Previous: Caching and stateNext: st.cache_resourceforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy
https://docs.streamlit.io/deploy/streamlit-community-cloud/deploy-your-app#advanced-settings-for-deployment
DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudremoveGet startedaddDeploy your appremoveApp dependenciesSecrets managementManage your appaddShare your appaddManage your accountaddTroubleshootingStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Deploy/Streamlit Community Cloud/Deploy your appDeploy your app Streamlit Community Cloud lets you deploy your apps in just one click, and most apps will deploy in only a few minutes. If you don't have an app ready to deploy, fork or clone one from our App gallery — you can find apps for machine learning, data visualization, data exploration, A/B testing and more. You can also fork and deploy samples straight from the New app button. Once you've deployed your app, check out how you can Edit your app with GitHub Codespaces. push_pinNoteIf you want to deploy your app on a different cloud service, check out the Deploy Streamlit apps article in our Knowledge Base. Add your app to GitHub Streamlit Community Cloud launches apps directly from your GitHub repo, so your app code and dependencies need to be on GitHub before you try to deploy your app. For more information on how to specify dependencies, see App dependencies. Your directory structure should look similar to this: your-repository/ ├── your_app.py └── requirements.txt If you are including any custom Configuration or Theming, make sure your config file is saved relative to the root of your repo. Within your repo, your config file should be named .streamlit/config.toml. your-repository/ ├── .streamlit/ │ └── config.toml ├── your_app.py └── requirements.txt priority_highImportantAlthough you can deploy multiple apps from the same repository, there can be only one configuration file. Deploy your app From your workspace at share.streamlit.io, click "New app" from the upper-right corner of your workspace. Fill in your repo, branch, and file path. As a shortcut, you can also click "Paste GitHub URL" to paste a link directly to your_app.py on GitHub. An app URL with a random hash is prefilled but you can change this to a custom subdomain instead. In the example below, the app would be deployed to https://red-balloon.streamlit.app/. You can always change your subdomain later. See more about Custom subdomains at the end of this page. Advanced settings for deployment push_pinNoteStreamlit Community Cloud supports all released versions of Python that are still receiving security updates. Streamlit Community Cloud defaults to version 3.9. You can select a version of your choice from the "Python version" dropdown in the "Advanced settings" modal. If an app is running a version of Python that becomes unsupported, it will be forcibly upgraded to the oldest, supported version of Python and may break. (Optional) If you are connecting to a data source or want to specify the Python version for your app, you can do that by clicking "Advanced settings" before you deploy the app. Learn more about Secrets management. Watch your app launch Your app is now deploying and you can watch while it launches. Most apps take only a couple of minutes to deploy, but if your app has a lot of dependencies it may take longer to deploy the first time. After the initial deployment, any change that does not touch your dependencies should show up immediately. push_pinNoteThe Streamlit Community Cloud logs on the right hand side of your app are only viewable to users with developer access to your repository. These logs help you debug any issues with the app. Learn more about Streamlit Community Cloud logs. Your app URL That's it — you're done! Your app now has a unique subdomain URL that you can share with others. Read more about how to Share your app with viewers. Unique subdomains If the "Custom subdomain (optional)" field is blank when you deploy your app, a URL is assigned following a structure based on your GitHub repo. The URL begins with your GitHub username or organization owning your repo, followed by your repo name, app path, and a short hash. If you deploy from a branch other than main or master, the URL also includes the branch name. https://[GitHub username or organization]-[repo name]-[app path]-[branch name]-[short hash].streamlit.app For example, this is an app deployed from the streamlit organization. The repo is demo-self-driving and the app name is streamlit_app.py in the root directory. The branch name is master and therefore not included. https://streamlit-demo-self-driving-streamlit-app-8jya0g.streamlit.app Custom subdomains Setting a custom subdomain makes it much easier to share your app since you can choose something memorable. Whether you set a custom subdomain during deployment or later, your app's URL will appear as: https://<your-custom-subdomain>.streamlit.app To view or customize your app subdomain from the dashboard: Click the overflow icon (more_vert) to the app's right and select "Settings". View the "General" tab in the App settings modal. Your app's unique subdomain will appear here. Pick a custom subdomain between 6 and 63 characters in length for your app's URL and hit "Save". It's that simple! You can then access your app by visiting your customized URL 🎉. If a custom subdomain is not available (e.g. because it's already taken), you'll see an error message like this: Previous: Get startedNext: App dependenciesforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy