Link
stringlengths
37
191
Text
stringlengths
916
46.2k
https://docs.streamlit.io/develop/api-reference/#built-in-connections
DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceremovePAGE ELEMENTSWrite and magicaddText elementsaddData elementsaddChart elementsaddInput widgetsaddMedia elementsaddLayouts and containersaddChat elementsaddStatus elementsaddThird-party componentsopen_in_newAPPLICATION LOGICNavigation and pagesaddExecution flowaddCaching and stateaddConnections and secretsaddCustom componentsaddUtilitiesaddConfigurationaddTOOLSApp testingaddCommand lineaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Develop/API referenceAPI reference Streamlit makes it easy for you to visualize, mutate, and share data. The API reference is organized by activity type, like displaying data or optimizing performance. Each section includes methods associated with the activity type, including examples. Browse our API below and click to learn more about any of our available commands! 🎈 Display almost anything Write and magic st.writeWrite arguments to the app.st.write("Hello **world**!") st.write(my_data_frame) st.write(my_mpl_figure) st.write_streamWrite generators or streams to the app with a typewriter effect.st.write_stream(my_generator) st.write_stream(my_llm_stream) MagicAny time Streamlit sees either a variable or literal value on its own line, it automatically writes that to your app using st.write"Hello **world**!" my_data_frame my_mpl_figure Text elements MarkdownDisplay string formatted as Markdown.st.markdown("Hello **world**!") TitleDisplay text in title formatting.st.title("The app title") HeaderDisplay text in header formatting.st.header("This is a header") SubheaderDisplay text in subheader formatting.st.subheader("This is a subheader") CaptionDisplay text in small font.st.caption("This is written small caption text") Code blockDisplay a code block with optional syntax highlighting.st.code("a = 1234") EchoDisplay some code in the app, then execute it. Useful for tutorials.with st.echo(): st.write('This code will be printed') LaTeXDisplay mathematical expressions formatted as LaTeX.st.latex("\int a x^2 \,dx") Preformatted textWrite fixed-width and preformatted text.st.text("Hello world") DividerDisplay a horizontal rule.st.divider() Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration! PreviousTagsAdd tags to your Streamlit apps. Created by @gagan3012.st_tags(label='# Enter Keywords:', text='Press enter to add more', value=['Zero', 'One', 'Two'], suggestions=['five', 'six', 'seven', 'eight', 'nine', 'three', 'eleven', 'ten', 'four'], maxtags = 4, key='1') NLUApply text mining on a dataframe. Created by @JohnSnowLabs.nlu.load('sentiment').predict('I love NLU! <3') Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.mention(label="An awesome Streamlit App", icon="streamlit", url="https://extras.streamlit.app",) Annotated textDisplay annotated text in Streamlit apps. Created by @tvst.annotated_text("This ", ("is", "verb"), " some ", ("annotated", "adj"), ("text", "noun"), " for those of ", ("you", "pronoun"), " who ", ("like", "verb"), " this sort of ", ("thing", "noun"), ".") Drawable CanvasProvides a sketching canvas using Fabric.js. Created by @andfanilo.st_canvas(fill_color="rgba(255, 165, 0, 0.3)", stroke_width=stroke_width, stroke_color=stroke_color, background_color=bg_color, background_image=Image.open(bg_image) if bg_image else None, update_streamlit=realtime_update, height=150, drawing_mode=drawing_mode, point_display_radius=point_display_radius if drawing_mode == 'point' else 0, key="canvas",) TagsAdd tags to your Streamlit apps. Created by @gagan3012.st_tags(label='# Enter Keywords:', text='Press enter to add more', value=['Zero', 'One', 'Two'], suggestions=['five', 'six', 'seven', 'eight', 'nine', 'three', 'eleven', 'ten', 'four'], maxtags = 4, key='1') NLUApply text mining on a dataframe. Created by @JohnSnowLabs.nlu.load('sentiment').predict('I love NLU! <3') Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.mention(label="An awesome Streamlit App", icon="streamlit", url="https://extras.streamlit.app",) Annotated textDisplay annotated text in Streamlit apps. Created by @tvst.annotated_text("This ", ("is", "verb"), " some ", ("annotated", "adj"), ("text", "noun"), " for those of ", ("you", "pronoun"), " who ", ("like", "verb"), " this sort of ", ("thing", "noun"), ".") Drawable CanvasProvides a sketching canvas using Fabric.js. Created by @andfanilo.st_canvas(fill_color="rgba(255, 165, 0, 0.3)", stroke_width=stroke_width, stroke_color=stroke_color, background_color=bg_color, background_image=Image.open(bg_image) if bg_image else None, update_streamlit=realtime_update, height=150, drawing_mode=drawing_mode, point_display_radius=point_display_radius if drawing_mode == 'point' else 0, key="canvas",) TagsAdd tags to your Streamlit apps. Created by @gagan3012.st_tags(label='# Enter Keywords:', text='Press enter to add more', value=['Zero', 'One', 'Two'], suggestions=['five', 'six', 'seven', 'eight', 'nine', 'three', 'eleven', 'ten', 'four'], maxtags = 4, key='1') NLUApply text mining on a dataframe. Created by @JohnSnowLabs.nlu.load('sentiment').predict('I love NLU! <3') Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.mention(label="An awesome Streamlit App", icon="streamlit", url="https://extras.streamlit.app",) Next Data elements DataframesDisplay a dataframe as an interactive table.st.dataframe(my_data_frame) Data editorDisplay a data editor widget.edited = st.data_editor(df, num_rows="dynamic") Column configurationConfigure the display and editing behavior of dataframes and data editors.st.column_config.NumberColumn("Price (in USD)", min_value=0, format="$%d") Static tablesDisplay a static table.st.table(my_data_frame) MetricsDisplay a metric in big bold font, with an optional indicator of how the metric changed.st.metric("My metric", 42, 2) Dicts and JSONDisplay object or string as a pretty-printed JSON string.st.json(my_dict) Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration! PreviousImage CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates value = streamlit_image_coordinates("https://placekitten.com/200/300") st.write(value) Plotly EventsMake Plotly charts interactive!. Created by @null-jones.from streamlit_plotly_events import plotly_events fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.metric_cards import style_metric_cards col3.metric(label="No Change", value=5000, delta=0) style_metric_cards() Streamlit AggridImplementation of Ag-Grid component for Streamlit. Created by @PablocFonseca.df = pd.DataFrame({'col1': [1, 2, 3], 'col2': [4, 5, 6]}) grid_return = AgGrid(df, editable=True) new_df = grid_return['data'] Streamlit FoliumStreamlit Component for rendering Folium maps. Created by @randyzwitch.m = folium.Map(location=[39.949610, -75.150282], zoom_start=16) folium.Marker([39.949610, -75.150282], popup="Liberty Bell", tooltip="Liberty Bell").add_to(m) st_data = st_folium(m, width=725) Pandas ProfilingPandas profiling component for Streamlit. Created by @okld.df = pd.read_csv("https://storage.googleapis.com/tf-datasets/titanic/train.csv") pr = df.profile_report() st_profile_report(pr) Image CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates value = streamlit_image_coordinates("https://placekitten.com/200/300") st.write(value) Plotly EventsMake Plotly charts interactive!. Created by @null-jones.from streamlit_plotly_events import plotly_events fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.metric_cards import style_metric_cards col3.metric(label="No Change", value=5000, delta=0) style_metric_cards() Streamlit AggridImplementation of Ag-Grid component for Streamlit. Created by @PablocFonseca.df = pd.DataFrame({'col1': [1, 2, 3], 'col2': [4, 5, 6]}) grid_return = AgGrid(df, editable=True) new_df = grid_return['data'] Streamlit FoliumStreamlit Component for rendering Folium maps. Created by @randyzwitch.m = folium.Map(location=[39.949610, -75.150282], zoom_start=16) folium.Marker([39.949610, -75.150282], popup="Liberty Bell", tooltip="Liberty Bell").add_to(m) st_data = st_folium(m, width=725) Pandas ProfilingPandas profiling component for Streamlit. Created by @okld.df = pd.read_csv("https://storage.googleapis.com/tf-datasets/titanic/train.csv") pr = df.profile_report() st_profile_report(pr) Image CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates value = streamlit_image_coordinates("https://placekitten.com/200/300") st.write(value) Plotly EventsMake Plotly charts interactive!. Created by @null-jones.from streamlit_plotly_events import plotly_events fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.metric_cards import style_metric_cards col3.metric(label="No Change", value=5000, delta=0) style_metric_cards() Next Chart elements Simple area chartsDisplay an area chart.st.area_chart(my_data_frame) Simple bar chartsDisplay a bar chart.st.bar_chart(my_data_frame) Simple line chartsDisplay a line chart.st.line_chart(my_data_frame) Simple scatter chartsDisplay a line chart.st.scatter_chart(my_data_frame) Scatterplots on mapsDisplay a map with points on it.st.map(my_data_frame) MatplotlibDisplay a matplotlib.pyplot figure.st.pyplot(my_mpl_figure) AltairDisplay a chart using the Altair library.st.altair_chart(my_altair_chart) Vega-LiteDisplay a chart using the Vega-Lite library.st.vega_lite_chart(my_vega_lite_chart) PlotlyDisplay an interactive Plotly chart.st.plotly_chart(my_plotly_chart) BokehDisplay an interactive Bokeh chart.st.bokeh_chart(my_bokeh_chart) PyDeckDisplay a chart using the PyDeck library.st.pydeck_chart(my_pydeck_chart) GraphVizDisplay a graph using the dagre-d3 library.st.graphviz_chart(my_graphviz_spec) Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration! PreviousStreamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl("https://assets5.lottiefiles.com/packages/lf20_V9t630.json") st_lottie(lottie_hello, key="hello") Plotly EventsMake Plotly charts interactive!. Created by @null-jones.fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.chart += get_annotations_chart(annotations=[("Mar 01, 2008", "Pretty good day for GOOG"), ("Dec 01, 2007", "Something's going wrong for GOOG & AAPL"), ("Nov 01, 2008", "Market starts again thanks to..."), ("Dec 01, 2009", "Small crash for GOOG after..."),],) st.altair_chart(chart, use_container_width=True) PlostA deceptively simple plotting library for Streamlit. Created by @tvst.import plost plost.line_chart(my_dataframe, x='time', y='stock_value', color='stock_name',) HiPlotHigh dimensional Interactive Plotting. Created by @facebookresearch.data = [{'dropout':0.1, 'lr': 0.001, 'loss': 10.0, 'optimizer': 'SGD'}, {'dropout':0.15, 'lr': 0.01, 'loss': 3.5, 'optimizer': 'Adam'}, {'dropout':0.3, 'lr': 0.1, 'loss': 4.5, 'optimizer': 'Adam'}] hip.Experiment.from_iterable(data).display() EChartsHigh dimensional Interactive Plotting. Created by @andfanilo.from streamlit_echarts import st_echarts st_echarts(options=options) Streamlit FoliumStreamlit Component for rendering Folium maps. Created by @randyzwitch.m = folium.Map(location=[39.949610, -75.150282], zoom_start=16) st_data = st_folium(m, width=725) Spacy-StreamlitspaCy building blocks and visualizers for Streamlit apps. Created by @explosion.models = ["en_core_web_sm", "en_core_web_md"] spacy_streamlit.visualize(models, "Sundar Pichai is the CEO of Google.") Streamlit AgraphA Streamlit Graph Vis, based on react-grah-vis. Created by @ChrisDelClea.from streamlit_agraph import agraph, Node, Edge, Config agraph(nodes=nodes, edges=edges, config=config) Streamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl("https://assets5.lottiefiles.com/packages/lf20_V9t630.json") st_lottie(lottie_hello, key="hello") Plotly EventsMake Plotly charts interactive!. Created by @null-jones.fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.chart += get_annotations_chart(annotations=[("Mar 01, 2008", "Pretty good day for GOOG"), ("Dec 01, 2007", "Something's going wrong for GOOG & AAPL"), ("Nov 01, 2008", "Market starts again thanks to..."), ("Dec 01, 2009", "Small crash for GOOG after..."),],) st.altair_chart(chart, use_container_width=True) PlostA deceptively simple plotting library for Streamlit. Created by @tvst.import plost plost.line_chart(my_dataframe, x='time', y='stock_value', color='stock_name',) HiPlotHigh dimensional Interactive Plotting. Created by @facebookresearch.data = [{'dropout':0.1, 'lr': 0.001, 'loss': 10.0, 'optimizer': 'SGD'}, {'dropout':0.15, 'lr': 0.01, 'loss': 3.5, 'optimizer': 'Adam'}, {'dropout':0.3, 'lr': 0.1, 'loss': 4.5, 'optimizer': 'Adam'}] hip.Experiment.from_iterable(data).display() EChartsHigh dimensional Interactive Plotting. Created by @andfanilo.from streamlit_echarts import st_echarts st_echarts(options=options) Streamlit FoliumStreamlit Component for rendering Folium maps. Created by @randyzwitch.m = folium.Map(location=[39.949610, -75.150282], zoom_start=16) st_data = st_folium(m, width=725) Spacy-StreamlitspaCy building blocks and visualizers for Streamlit apps. Created by @explosion.models = ["en_core_web_sm", "en_core_web_md"] spacy_streamlit.visualize(models, "Sundar Pichai is the CEO of Google.") Streamlit AgraphA Streamlit Graph Vis, based on react-grah-vis. Created by @ChrisDelClea.from streamlit_agraph import agraph, Node, Edge, Config agraph(nodes=nodes, edges=edges, config=config) Streamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl("https://assets5.lottiefiles.com/packages/lf20_V9t630.json") st_lottie(lottie_hello, key="hello") Plotly EventsMake Plotly charts interactive!. Created by @null-jones.fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.chart += get_annotations_chart(annotations=[("Mar 01, 2008", "Pretty good day for GOOG"), ("Dec 01, 2007", "Something's going wrong for GOOG & AAPL"), ("Nov 01, 2008", "Market starts again thanks to..."), ("Dec 01, 2009", "Small crash for GOOG after..."),],) st.altair_chart(chart, use_container_width=True) Next Input widgets ButtonDisplay a button widget.clicked = st.button("Click me") Download buttonDisplay a download button widget.st.download_button("Download file", file) Form buttonDisplay a form submit button. For use with st.form.st.form_submit_button("Sign up") Link buttonDisplay a link button.st.link_button("Go to gallery", url) Page linkDisplay a link to another page in a multipage app.st.page_link("app.py", label="Home", icon="🏠") st.page_link("pages/profile.py", label="My profile") CheckboxDisplay a checkbox widget.selected = st.checkbox("I agree") Color pickerDisplay a color picker widget.color = st.color_picker("Pick a color") MultiselectDisplay a multiselect widget. The multiselect widget starts as empty.choices = st.multiselect("Buy", ["milk", "apples", "potatoes"]) RadioDisplay a radio button widget.choice = st.radio("Pick one", ["cats", "dogs"]) SelectboxDisplay a select widget.choice = st.selectbox("Pick one", ["cats", "dogs"]) Select-sliderDisplay a slider widget to select items from a list.size = st.select_slider("Pick a size", ["S", "M", "L"]) ToggleDisplay a toggle widget.activated = st.toggle("Activate") Number inputDisplay a numeric input widget.choice = st.number_input("Pick a number", 0, 10) SliderDisplay a slider widget.number = st.slider("Pick a number", 0, 100) Date inputDisplay a date input widget.date = st.date_input("Your birthday") Time inputDisplay a time input widget.time = st.time_input("Meeting time") Chat inputDisplay a chat input widget.prompt = st.chat_input("Say something") if prompt: st.write(f"The user has sent: {prompt}") Text-areaDisplay a multi-line text input widget.text = st.text_area("Text to translate") Text inputDisplay a single-line text input widget.name = st.text_input("First name") Data editorDisplay a data editor widget.edited = st.experimental_data_editor(df, num_rows="dynamic") File UploaderDisplay a file uploader widget.data = st.file_uploader("Upload a CSV") Camera inputDisplay a widget that allows users to upload images directly from a camera.image = st.camera_input("Take a picture") Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration! PreviousStreamlit ChatStreamlit Component for a Chatbot UI. Created by @AI-Yash.from streamlit_chat import message message("My message") message("Hello bot!", is_user=True) # align's the message to the right Streamlit Option MenuSelect a single item from a list of options in a menu. Created by @victoryhb.from streamlit_option_menu import option_menu option_menu("Main Menu", ["Home", 'Settings'], icons=['house', 'gear'], menu_icon="cast", default_index=1) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.stoggle import stoggle stoggle( "Click me!", """🥷 Surprise! Here's some additional content""",) Streamlit ElementsCreate a draggable and resizable dashboard in Streamlit. Created by @okls.from streamlit_elements import elements, mui, html with elements("new_element"): mui.Typography("Hello world") TagsAdd tags to your Streamlit apps. Created by @gagan3012.from streamlit_tags import st_tags st_tags(label='# Enter Keywords:', text='Press enter to add more', value=['Zero', 'One', 'Two'], suggestions=['five', 'six', 'seven', 'eight', 'nine', 'three', 'eleven', 'ten', 'four'], maxtags = 4, key='1') StqdmThe simplest way to handle a progress bar in streamlit app. Created by @Wirg.from stqdm import stqdm for _ in stqdm(range(50)): sleep(0.5) TimelineDisplay a Timeline in Streamlit apps using TimelineJS. Created by @innerdoc.from streamlit_timeline import timeline with open('example.json', "r") as f: timeline(f.read(), height=800) Camera input liveAlternative for st.camera_input which returns the webcam images live. Created by @blackary.from camera_input_live import camera_input_live image = camera_input_live() st.image(value) Streamlit AceAce editor component for Streamlit. Created by @okld.from streamlit_ace import st_ace content = st_ace() content Streamlit ChatStreamlit Component for a Chatbot UI. Created by @AI-Yash.from streamlit_chat import message message("My message") message("Hello bot!", is_user=True) # align's the message to the right Streamlit Option MenuSelect a single item from a list of options in a menu. Created by @victoryhb.from streamlit_option_menu import option_menu option_menu("Main Menu", ["Home", 'Settings'], icons=['house', 'gear'], menu_icon="cast", default_index=1) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.stoggle import stoggle stoggle( "Click me!", """🥷 Surprise! Here's some additional content""",) Streamlit ElementsCreate a draggable and resizable dashboard in Streamlit. Created by @okls.from streamlit_elements import elements, mui, html with elements("new_element"): mui.Typography("Hello world") TagsAdd tags to your Streamlit apps. Created by @gagan3012.from streamlit_tags import st_tags st_tags(label='# Enter Keywords:', text='Press enter to add more', value=['Zero', 'One', 'Two'], suggestions=['five', 'six', 'seven', 'eight', 'nine', 'three', 'eleven', 'ten', 'four'], maxtags = 4, key='1') StqdmThe simplest way to handle a progress bar in streamlit app. Created by @Wirg.from stqdm import stqdm for _ in stqdm(range(50)): sleep(0.5) TimelineDisplay a Timeline in Streamlit apps using TimelineJS. Created by @innerdoc.from streamlit_timeline import timeline with open('example.json', "r") as f: timeline(f.read(), height=800) Camera input liveAlternative for st.camera_input which returns the webcam images live. Created by @blackary.from camera_input_live import camera_input_live image = camera_input_live() st.image(value) Streamlit AceAce editor component for Streamlit. Created by @okld.from streamlit_ace import st_ace content = st_ace() content Streamlit ChatStreamlit Component for a Chatbot UI. Created by @AI-Yash.from streamlit_chat import message message("My message") message("Hello bot!", is_user=True) # align's the message to the right Streamlit Option MenuSelect a single item from a list of options in a menu. Created by @victoryhb.from streamlit_option_menu import option_menu option_menu("Main Menu", ["Home", 'Settings'], icons=['house', 'gear'], menu_icon="cast", default_index=1) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.stoggle import stoggle stoggle( "Click me!", """🥷 Surprise! Here's some additional content""",) Next Media elements ImageDisplay an image or list of images.st.image(numpy_array) st.image(image_bytes) st.image(file) st.image("https://example.com/myimage.jpg") AudioDisplay an audio player.st.audio(numpy_array) st.audio(audio_bytes) st.audio(file) st.audio("https://example.com/myaudio.mp3", format="audio/mp3") VideoDisplay a video player.st.video(numpy_array) st.video(video_bytes) st.video(file) st.video("https://example.com/myvideo.mp4", format="video/mp4") Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration! PreviousStreamlit CropperA simple image cropper for Streamlit. Created by @turner-anderson.from streamlit_cropper import st_cropper st_cropper(img, realtime_update=realtime_update, box_color=box_color, aspect_ratio=aspect_ratio) Image CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates streamlit_image_coordinates("https://placekitten.com/200/300") Streamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl("https://assets5.lottiefiles.com/packages/lf20_V9t630.json") st_lottie(lottie_hello, key="hello") Streamlit WebrtcHandling and transmitting real-time video/audio streams with Streamlit. Created by @whitphx.from streamlit_webrtc import webrtc_streamer webrtc_streamer(key="sample") Drawable CanvasProvides a sketching canvas using Fabric.js. Created by @andfanilo.from streamlit_drawable_canvas import st_canvas st_canvas(fill_color="rgba(255, 165, 0, 0.3)", stroke_width=stroke_width, stroke_color=stroke_color, background_color=bg_color, background_image=Image.open(bg_image) if bg_image else None, update_streamlit=realtime_update, height=150, drawing_mode=drawing_mode, point_display_radius=point_display_radius if drawing_mode == 'point' else 0, key="canvas",) Image ComparisonCompare images with a slider using JuxtaposeJS. Created by @fcakyon.from streamlit_image_comparison import image_comparison image_comparison(img1="image1.jpg", img2="image2.jpg",) Streamlit CropperA simple image cropper for Streamlit. Created by @turner-anderson.from streamlit_cropper import st_cropper st_cropper(img, realtime_update=realtime_update, box_color=box_color, aspect_ratio=aspect_ratio) Image CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates streamlit_image_coordinates("https://placekitten.com/200/300") Streamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl("https://assets5.lottiefiles.com/packages/lf20_V9t630.json") st_lottie(lottie_hello, key="hello") Streamlit WebrtcHandling and transmitting real-time video/audio streams with Streamlit. Created by @whitphx.from streamlit_webrtc import webrtc_streamer webrtc_streamer(key="sample") Drawable CanvasProvides a sketching canvas using Fabric.js. Created by @andfanilo.from streamlit_drawable_canvas import st_canvas st_canvas(fill_color="rgba(255, 165, 0, 0.3)", stroke_width=stroke_width, stroke_color=stroke_color, background_color=bg_color, background_image=Image.open(bg_image) if bg_image else None, update_streamlit=realtime_update, height=150, drawing_mode=drawing_mode, point_display_radius=point_display_radius if drawing_mode == 'point' else 0, key="canvas",) Image ComparisonCompare images with a slider using JuxtaposeJS. Created by @fcakyon.from streamlit_image_comparison import image_comparison image_comparison(img1="image1.jpg", img2="image2.jpg",) Streamlit CropperA simple image cropper for Streamlit. Created by @turner-anderson.from streamlit_cropper import st_cropper st_cropper(img, realtime_update=realtime_update, box_color=box_color, aspect_ratio=aspect_ratio) Image CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates streamlit_image_coordinates("https://placekitten.com/200/300") Streamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl("https://assets5.lottiefiles.com/packages/lf20_V9t630.json") st_lottie(lottie_hello, key="hello") Next Layouts and containers ColumnsInsert containers laid out as side-by-side columns.col1, col2 = st.columns(2) col1.write("this is column 1") col2.write("this is column 2") ContainerInsert a multi-element container.c = st.container() st.write("This will show last") c.write("This will show first") c.write("This will show second") Modal dialogsInsert a modal dialog that can rerun independently from the rest of the script.@st.experimental_dialog("Sign up") def email_form(): name = st.text_input("Name") email = st.text_input("Email") EmptyInsert a single-element container.c = st.empty() st.write("This will show last") c.write("This will be replaced") c.write("This will show first") ExpanderInsert a multi-element container that can be expanded/collapsed.with st.expander("Open to see more"): st.write("This is more content") PopoverInsert a multi-element popover container that can be opened/closed.with st.popover("Settings"): st.checkbox("Show completed") SidebarDisplay items in a sidebar.st.sidebar.write("This lives in the sidebar") st.sidebar.button("Click me!") TabsInsert containers separated into tabs.tab1, tab2 = st.tabs(["Tab 1", "Tab2"]) tab1.write("this is tab 1") tab2.write("this is tab 2") Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration!Streamlit ElementsCreate a draggable and resizable dashboard in Streamlit. Created by @okls.from streamlit_elements import elements, mui, html with elements("new_element"): mui.Typography("Hello world") PydanticAuto-generate Streamlit UI from Pydantic Models and Dataclasses. Created by @lukasmasuch.import streamlit_pydantic as sp sp.pydantic_form(key="my_form", model=ExampleModel) Streamlit PagesAn experimental version of Streamlit Multi-Page Apps. Created by @blackary.from st_pages import Page, show_pages, add_page_title show_pages([ Page("streamlit_app.py", "Home", "🏠"), Page("other_pages/page2.py", "Page 2", ":books:"), ]) Chat elements Streamlit provides a few commands to help you build conversational apps. These chat elements are designed to be used in conjunction with each other, but you can also use them separately. st.chat_message lets you insert a chat message container into the app so you can display messages from the user or the app. Chat containers can contain other Streamlit elements, including charts, tables, text, and more. st.chat_input lets you display a chat input widget so the user can type in a message. Chat inputDisplay a chat input widget.prompt = st.chat_input("Say something") if prompt: st.write(f"The user has sent: {prompt}") Chat messageInsert a chat message container.import numpy as np with st.chat_message("user"): st.write("Hello 👋") st.line_chart(np.random.randn(30, 3)) Status containerDisplay output of long-running tasks in a container.with st.status('Running'): do_something_slow() st.write_streamWrite generators or streams to the app with a typewriter effect.st.write_stream(my_generator) st.write_stream(my_llm_stream) Status elements Progress barDisplay a progress bar.for i in range(101): st.progress(i) do_something_slow() SpinnerTemporarily displays a message while executing a block of code.with st.spinner("Please wait..."): do_something_slow() Status containerDisplay output of long-running tasks in a container.with st.status('Running'): do_something_slow() ToastBriefly displays a toast message in the bottom-right corner.st.toast('Butter!', icon='🧈') BalloonsDisplay celebratory balloons!do_something() # Celebrate when all done! st.balloons() SnowflakesDisplay celebratory snowflakes!do_something() # Celebrate when all done! st.snow() Success boxDisplay a success message.st.success("Match found!") Info boxDisplay an informational message.st.info("Dataset is updated every day at midnight.") Warning boxDisplay warning message.st.warning("Unable to fetch image. Skipping...") Error boxDisplay error message.st.error("We encountered an error") Exception outputDisplay an exception.e = RuntimeError("This is an exception of type RuntimeError") st.exception(e) Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration!StqdmThe simplest way to handle a progress bar in streamlit app. Created by @Wirg.from stqdm import stqdm for _ in stqdm(range(50)): sleep(0.5) Custom notification boxA custom notification box with the ability to close it out. Created by @Socvest.from streamlit_custom_notification_box import custom_notification_box styles = {'material-icons':{'color': 'red'}, 'text-icon-link-close-container': {'box-shadow': '#3896de 0px 4px'}, 'notification-text': {'':''}, 'close-button':{'':''}, 'link':{'':''}} custom_notification_box(icon='info', textDisplay='We are almost done with your registration...', externalLink='more info', url='#', styles=styles, key="foo") Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.let_it_rain import rain rain(emoji="🎈", font_size=54, falling_speed=5, animation_length="infinite",) App logic and configuration Navigation and pages Switch pageProgrammatically navigates to a specified page.st.switch_page("pages/my_page.py") Page linkDisplay a link to another page in a multipage app.st.page_link("app.py", label="Home", icon="🏠") st.page_link("pages/profile.py", label="My profile") Execution flow Modal dialogsInsert a modal dialog that can rerun independently from the rest of the script.@st.experimental_dialog("Sign up") def email_form(): name = st.text_input("Name") email = st.text_input("Email") FormsCreate a form that batches elements together with a “Submit" button.with st.form(key='my_form'): name = st.text_input("Name") email = st.text_input("Email") st.form_submit_button("Sign up") Partial rerunsDefine a fragment to rerun independently from the rest of the script.@st.experimental_fragment(run_every="10s") def fragment(): df = get_data() st.line_chart(df) Rerun scriptRerun the script immediately.st.rerun() Stop executionStops execution immediately.st.stop() Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration!AutorefreshForce a refresh without tying up a script. Created by @kmcgrady.from streamlit_autorefresh import st_autorefresh st_autorefresh(interval=2000, limit=100, key="fizzbuzzcounter") PydanticAuto-generate Streamlit UI from Pydantic Models and Dataclasses. Created by @lukasmasuch.import streamlit_pydantic as sp sp.pydantic_form(key="my_form", model=ExampleModel) Streamlit PagesAn experimental version of Streamlit Multi-Page Apps. Created by @blackary.from st_pages import Page, show_pages, add_page_title show_pages([ Page("streamlit_app.py", "Home", "🏠"), Page("other_pages/page2.py", "Page 2", ":books:"), ]) Caching and state Cache dataFunction decorator to cache functions that return data (e.g. dataframe transforms, database queries, ML inference).@st.cache_data def long_function(param1, param2): # Perform expensive computation here or # fetch data from the web here return data Cache resourceFunction decorator to cache functions that return global resources (e.g. database connections, ML models).@st.cache_resource def init_model(): # Return a global resource here return pipeline( "sentiment-analysis", model="distilbert-base-uncased-finetuned-sst-2-english" ) Session stateSession state is a way to share variables between reruns, for each user session.st.session_state['key'] = value Query parametersGet, set, or clear the query parameters that are shown in the browser's URL bar.st.query_params[key] = value st.query_params.clear() Connections and databases Setup your connection Create a connectionConnect to a data source or APIconn = st.connection('pets_db', type='sql') pet_owners = conn.query('select * from pet_owners') st.dataframe(pet_owners) Built-in connections SnowflakeConnectionA connection to Snowflake.conn = st.connection('snowflake') SQLConnectionA connection to a SQL database using SQLAlchemy.conn = st.connection('sql') Build your own connections Connection base classBuild your own connection with BaseConnection.class MyConnection(BaseConnection[myconn.MyConnection]): def _connect(self, **kwargs) -> MyConnection: return myconn.connect(**self._secrets, **kwargs) def query(self, query): return self._instance.query(query) Secrets management Secrets singletonAccess secrets from a local TOML file.key = st.secrets["OpenAI_key"] Secrets fileSave your secrets in a per-project or per-profile TOML file.OpenAI_key = "<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/buttons#show-a-temporary-message-with-a-button
DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsremoveCOREArchitecture & executionaddMultipage appsaddApp designremoveAnimate & update elementsButton behavior and examplesDataframesUsing custom classesWorking with timezonesADDITIONALConnections and secretsaddCustom componentsaddConfiguration and themingaddApp testingaddAPI referenceaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Develop/Concepts/App design/Button behavior and examplesButton behavior and examples Summary Buttons created with st.button do not retain state. They return True on the script rerun resulting from their click and immediately return to False on the next script rerun. If a displayed element is nested inside if st.button('Click me'):, the element will be visible when the button is clicked and disappear as soon as the user takes their next action. This is because the script reruns and the button return value becomes False. In this guide, we will illustrate the use of buttons and explain common misconceptions. Read on to see a variety of examples that expand on st.button using st.session_state. Anti-patterns are included at the end. Go ahead and pull up your favorite code editor so you can streamlit run the examples as you read. Check out Streamlit's Basic concepts if you haven't run your own Streamlit scripts yet. When to use if st.button() When code is conditioned on a button's value, it will execute once in response to the button being clicked and not again (until the button is clicked again). Good to nest inside buttons: Transient messages that immediately disappear. Once-per-click processes that saves data to session state, a file, or a database. Bad to nest inside buttons: Displayed items that should persist as the user continues. Other widgets which cause the script to rerun when used. Processes that neither modify session state nor write to a file/database.* * This can be appropriate when disposable results are desired. If you have a "Validate" button, that could be a process conditioned directly on a button. It could be used to create an alert to say 'Valid' or 'Invalid' with no need to keep that info. Common logic with buttons Show a temporary message with a button If you want to give the user a quick button to check if an entry is valid, but not keep that check displayed as the user continues. In this example, a user can click a button to check if their animal string is in the animal_shelter list. When the user clicks "Check availability" they will see "We have that animal!" or "We don't have that animal." If they change the animal in st.text_input, the script reruns and the message disappears until they click "Check availability" again. import streamlit as st animal_shelter = ['cat', 'dog', 'rabbit', 'bird'] animal = st.text_input('Type an animal') if st.button('Check availability'): have_it = animal.lower() in animal_shelter 'We have that animal!' if have_it else 'We don\'t have that animal.' Note: The above example uses magic to render the message on the frontend. Stateful button If you want a clicked button to continue to be True, create a value in st.session_state and use the button to set that value to True in a callback. import streamlit as st if 'clicked' not in st.session_state: st.session_state.clicked = False def click_button(): st.session_state.clicked = True st.button('Click me', on_click=click_button) if st.session_state.clicked: # The message and nested widget will remain on the page st.write('Button clicked!') st.slider('Select a value') Toggle button If you want a button to work like a toggle switch, consider using st.checkbox. Otherwise, you can use a button with a callback function to reverse a boolean value saved in st.session_state. In this example, we use st.button to toggle another widget on and off. By displaying st.slider conditionally on a value in st.session_state, the user can interact with the slider without it disappearing. import streamlit as st if 'button' not in st.session_state: st.session_state.button = False def click_button(): st.session_state.button = not st.session_state.button st.button('Click me', on_click=click_button) if st.session_state.button: # The message and nested widget will remain on the page st.write('Button is on!') st.slider('Select a value') else: st.write('Button is off!') Alternatively, you can use the value in st.session_state on the slider's disabled parameter. import streamlit as st if 'button' not in st.session_state: st.session_state.button = False def click_button(): st.session_state.button = not st.session_state.button st.button('Click me', on_click=click_button) st.slider('Select a value', disabled=st.session_state.button) Buttons to continue or control stages of a process Another alternative to nesting content inside a button is to use a value in st.session_state that designates the "step" or "stage" of a process. In this example, we have four stages in our script: Before the user begins. User enters their name. User chooses a color. User gets a thank-you message. A button at the beginning advances the stage from 0 to 1. A button at the end resets the stage from 3 to 0. The other widgets used in stage 1 and 2 have callbacks to set the stage. If you have a process with dependant steps and want to keep previous stages visible, such a callback forces a user to retrace subsequent stages if they change an earlier widget. import streamlit as st if 'stage' not in st.session_state: st.session_state.stage = 0 def set_state(i): st.session_state.stage = i if st.session_state.stage == 0: st.button('Begin', on_click=set_state, args=[1]) if st.session_state.stage >= 1: name = st.text_input('Name', on_change=set_state, args=[2]) if st.session_state.stage >= 2: st.write(f'Hello {name}!') color = st.selectbox( 'Pick a Color', [None, 'red', 'orange', 'green', 'blue', 'violet'], on_change=set_state, args=[3] ) if color is None: set_state(2) if st.session_state.stage >= 3: st.write(f':{color}[Thank you!]') st.button('Start Over', on_click=set_state, args=[0]) Buttons to modify st.session_state If you modify st.session_state inside of a button, you must consider where that button is within the script. A slight problem In this example, we access st.session_state.name both before and after the buttons which modify it. When a button ("Jane" or "John") is clicked, the script reruns. The info displayed before the buttons lags behind the info written after the button. The data in st.session_state before the button is not updated. When the script executes the button function, that is when the conditional code to update st.session_state creates the change. Thus, this change is reflected after the button. import streamlit as st import pandas as pd if 'name' not in st.session_state: st.session_state['name'] = 'John Doe' st.header(st.session_state['name']) if st.button('Jane'): st.session_state['name'] = 'Jane Doe' if st.button('John'): st.session_state['name'] = 'John Doe' st.header(st.session_state['name']) Logic used in a callback Callbacks are a clean way to modify st.session_state. Callbacks are executed as a prefix to the script rerunning, so the position of the button relative to accessing data is not important. import streamlit as st import pandas as pd if 'name' not in st.session_state: st.session_state['name'] = 'John Doe' def change_name(name): st.session_state['name'] = name st.header(st.session_state['name']) st.button('Jane', on_click=change_name, args=['Jane Doe']) st.button('John', on_click=change_name, args=['John Doe']) st.header(st.session_state['name']) Logic nested in a button with a rerun Although callbacks are often preferred to avoid extra reruns, our first 'John Doe'/'Jane Doe' example can be modified by adding st.rerun instead. If you need to acces data in st.session_state before the button that modifies it, you can include st.rerun to rerun the script after the change has been committed. This means the script will rerun twice when a button is clicked. import streamlit as st import pandas as pd if 'name' not in st.session_state: st.session_state['name'] = 'John Doe' st.header(st.session_state['name']) if st.button('Jane'): st.session_state['name'] = 'Jane Doe' st.rerun() if st.button('John'): st.session_state['name'] = 'John Doe' st.rerun() st.header(st.session_state['name']) Buttons to modify or reset other widgets When a button is used to modify or reset another widget, it is the same as the above examples to modify st.session_state. However, an extra consideration exists: you cannot modify a key-value pair in st.session_state if the widget with that key has already been rendered on the page for the current script run. priority_highImportantDon't do this!import streamlit as st st.text_input('Name', key='name') # These buttons will error because their nested code changes # a widget's state after that widget within the script. if st.button('Clear name'): st.session_state.name = '' if st.button('Streamlit!'): st.session_state.name = ('Streamlit') Option 1: Use a key for the button and put the logic before the widget If you assign a key to a button, you can condition code on a button's state by using its value in st.session_state. This means that logic depending on your button can be in your script before that button. In the following example, we use the .get() method on st.session_state because the keys for the buttons will not exist when the script runs for the first time. The .get() method will return False if it can't find the key. Otherwise, it will return the value of the key. import streamlit as st # Use the get method since the keys won't be in session_state # on the first script run if st.session_state.get('clear'): st.session_state['name'] = '' if st.session_state.get('streamlit'): st.session_state['name'] = 'Streamlit' st.text_input('Name', key='name') st.button('Clear name', key='clear') st.button('Streamlit!', key='streamlit') Option 2: Use a callback import streamlit as st st.text_input('Name', key='name') def set_name(name): st.session_state.name = name st.button('Clear name', on_click=set_name, args=['']) st.button('Streamlit!', on_click=set_name, args=['Streamlit']) Option 3: Use containers By using st.container you can have widgets appear in different orders in your script and frontend view (webpage). import streamlit as st begin = st.container() if st.button('Clear name'): st.session_state.name = '' if st.button('Streamlit!'): st.session_state.name = ('Streamlit') # The widget is second in logic, but first in display begin.text_input('Name', key='name') Buttons to add other widgets dynamically When dynamically adding widgets to the page, make sure to use an index to keep the keys unique and avoid a DuplicateWidgetID error. In this example, we define a function display_input_row which renders a row of widgets. That function accepts an index as a parameter. The widgets rendered by display_input_row use index within their keys so that dispaly_input_row can be executed multiple times on a single script rerun without repeating any widget keys. import streamlit as st def display_input_row(index): left, middle, right = st.columns(3) left.text_input('First', key=f'first_{index}') middle.text_input('Middle', key=f'middle_{index}') right.text_input('Last', key=f'last_{index}') if 'rows' not in st.session_state: st.session_state['rows'] = 0 def increase_rows(): st.session_state['rows'] += 1 st.button('Add person', on_click=increase_rows) for i in range(st.session_state['rows']): display_input_row(i) # Show the results st.subheader('People') for i in range(st.session_state['rows']): st.write( f'Person {i+1}:', st.session_state[f'first_{i}'], st.session_state[f'middle_{i}'], st.session_state[f'last_{i}'] ) Buttons to handle expensive or file-writing processes When you have expensive processes, set them to run upon clicking a button and save the results into st.session_state. This allows you to keep accessing the results of the process without re-executing it unnecessarily. This is especially helpful for processes that save to disk or write to a database. In this example, we have an expensive_process that depends on two parameters: option and add. Functionally, add changes the output, but option does not—option is there to provide a parameter import streamlit as st import pandas as pd import time def expensive_process(option, add): with st.spinner('Processing...'): time.sleep(5) df = pd.DataFrame({'A': [1, 2, 3], 'B': [4, 5, 6], 'C':[7, 8, 9]}) + add return (df, add) cols = st.columns(2) option = cols[0].selectbox('Select a number', options=['1', '2', '3']) add = cols[1].number_input('Add a number', min_value=0, max_value=10) if 'processed' not in st.session_state: st.session_state.processed = {} # Process and save results if st.button('Process'): result = expensive_process(option, add) st.session_state.processed[option] = result if option in st.session_state.processed: st.write(f'Option {option} processed with add {add}') st.write(st.session_state.processed[option][0]) Astute observers may think, "This feels a little like caching." We are only saving results relative to one parameter, but the pattern could easily be expanded to save results relative to both parameters. In that sense, yes, it has some similarities to caching, but also some important differences. When you save results in st.session_state, the results are only available to the current user in their current session. If you use st.cache_data instead, the results are available to all users across all sessions. Furthermore, if you want to update a saved result, you have to clear all saved results for that function to do so. Anti-patterns Here are some simplified examples of how buttons can go wrong. Be on the lookout for these common mistakes. Buttons nested inside buttons import streamlit as st if st.button('Button 1'): st.write('Button 1 was clicked') if st.button('Button 2'): # This will never be executed. st.write('Button 2 was clicked') Other widgets nested inside buttons import streamlit as st if st.button('Sign up'): name = st.text_input('Name') if name: # This will never be executed. st.success(f'Welcome {name}') Nesting a process inside a button without saving to session state import streamlit as st import pandas as pd file = st.file_uploader("Upload a file", type="csv") if st.button('Get data'): df = pd.read_csv(file) # This display will go away with the user's next action. st.write(df) if st.button('Save'): # This will always error. df.to_csv('data.csv') Previous: Animate & update elementsNext: DataframesforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy
https://docs.streamlit.io/knowledge-base/deploy/invoking-python-subprocess-deployed-streamlit-app#invoking-a-python-subprocess-in-a-deployed-streamlit-app
DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Knowledge base/Deployment issues/Invoking a Python subprocess in a deployed Streamlit appInvoking a Python subprocess in a deployed Streamlit app Problem Let's suppose you want to invoke a subprocess to run a Python script script.py in your deployed Streamlit app streamlit_app.py. For example, the machine learning library Ludwig is run using a command-line interface, or maybe you want to run a bash script or similar type of process from Python. You have tried the following, but run into dependency issues for script.py, even though you have specified your Python dependencies in a requirements file: # streamlit_app.py import streamlit as st import subprocess subprocess.run(["python", "script.py"]) Solution When you run the above code block, you will get the version of Python that is on the system path—not necessarily the Python executable installed in the virtual environment that the Streamlit code is running under. The solution is to detect the Python executable directly with sys.executable: # streamlit_app.py import streamlit as st import subprocess import sys subprocess.run([f"{sys.executable}", "script.py"]) This ensures that script.py is running under the same Python executable as your Streamlit code—where your Python dependencies are installed. Relevant links https://stackoverflow.com/questions/69947867/run-portion-of-python-code-in-parallel-from-a-streamlit-app/69948545#69948545 https://discuss.streamlit.io/t/modulenotfounderror-no-module-named-cv2-streamlit/18319/3?u=snehankekre https://docs.python.org/3/library/sys.html#sys.executable Previous: How do I increase the upload limit of st.file_uploader on Streamlit Community Cloud?Next: Organizing your apps with workspaces on Streamlit Community CloudforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy
https://docs.streamlit.io/get-started/fundamentals/additional-features#custom-components
DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsremoveBasic conceptsAdvanced conceptsAdditional featuresSummaryFirst stepsaddcodeDevelopConceptsaddAPI referenceaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Get started/Fundamentals/Additional featuresAdditional Streamlit features So you've read all about Streamlit's Basic concepts and gotten a taste of caching and Session State in Advanced concepts. But what about the bells and whistles? Here's a quick look at some extra features to take your app to the next level. Theming Streamlit supports Light and Dark themes out of the box. Streamlit will first check if the user viewing an app has a Light or Dark mode preference set by their operating system and browser. If so, then that preference will be used. Otherwise, the Light theme is applied by default. You can also change the active theme from "⋮" → "Settings". Want to add your own theme to an app? The "Settings" menu has a theme editor accessible by clicking on "Edit active theme". You can use this editor to try out different colors and see your app update live. When you're happy with your work, themes can be saved by setting config options in the [theme] config section. After you've defined a theme for your app, it will appear as "Custom Theme" in the theme selector and will be applied by default instead of the included Light and Dark themes. More information about the options available when defining a theme can be found in the theme option documentation. push_pinNoteThe theme editor menu is available only in local development. If you've deployed your app using Streamlit Community Cloud, the "Edit active theme" button will no longer be displayed in the "Settings" menu. starTipAnother way to experiment with different theme colors is to turn on the "Run on save" option, edit your config.toml file, and watch as your app reruns with the new theme colors applied. Pages As apps grow large, it becomes useful to organize them into multiple pages. This makes the app easier to manage as a developer and easier to navigate as a user. Streamlit provides a frictionless way to create multipage apps. We designed this feature so that building a multipage app is as easy as building a single-page app! Just add more pages to an existing app as follows: In the folder containing your main script, create a new pages folder. Let’s say your main script is named main_page.py. Add new .py files in the pages folder to add more pages to your app. Run streamlit run main_page.py as usual. That’s it! The main_page.py script will now correspond to the main page of your app. And you’ll see the other scripts from the pages folder in the sidebar page selector. The pages are listed according to filename (without file extensions and disregarding underscores). For example: main_page.pyimport streamlit as st st.markdown("# Main page 🎈") st.sidebar.markdown("# Main page 🎈") pages/page_2.pyimport streamlit as st st.markdown("# Page 2 ❄️") st.sidebar.markdown("# Page 2 ❄️") pages/page_3.pyimport streamlit as st st.markdown("# Page 3 🎉") st.sidebar.markdown("# Page 3 🎉") Now run streamlit run main_page.py and view your shiny new multipage app! Our documentation on Multipage apps teaches you how to add pages to your app, including how to define pages, structure and run multipage apps, and navigate between pages. Once you understand the basics, create your first multipage app! Custom components If you can't find the right component within the Streamlit library, try out custom components to extend Streamlit's built-in functionality. Explore and browse through popular, community-created components in the Components gallery. If you dabble in frontend development, you can build your own custom component with Streamlit's components API. Static file serving As you learned in Streamlit fundamentals, Streamlit runs a server that clients connect to. That means viewers of your app don't have direct access to the files which are local to your app. Most of the time, this doesn't matter because Streamlt commands handle that for you. When you use st.image(<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/en/0.72.0/api.html#chat-elements
DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceremovePAGE ELEMENTSWrite and magicaddText elementsaddData elementsaddChart elementsaddInput widgetsaddMedia elementsaddLayouts and containersaddChat elementsaddStatus elementsaddThird-party componentsopen_in_newAPPLICATION LOGICNavigation and pagesaddExecution flowaddCaching and stateaddConnections and secretsaddCustom componentsaddUtilitiesaddConfigurationaddTOOLSApp testingaddCommand lineaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Develop/API referenceAPI reference Streamlit makes it easy for you to visualize, mutate, and share data. The API reference is organized by activity type, like displaying data or optimizing performance. Each section includes methods associated with the activity type, including examples. Browse our API below and click to learn more about any of our available commands! 🎈 Display almost anything Write and magic st.writeWrite arguments to the app.st.write("Hello **world**!") st.write(my_data_frame) st.write(my_mpl_figure) st.write_streamWrite generators or streams to the app with a typewriter effect.st.write_stream(my_generator) st.write_stream(my_llm_stream) MagicAny time Streamlit sees either a variable or literal value on its own line, it automatically writes that to your app using st.write"Hello **world**!" my_data_frame my_mpl_figure Text elements MarkdownDisplay string formatted as Markdown.st.markdown("Hello **world**!") TitleDisplay text in title formatting.st.title("The app title") HeaderDisplay text in header formatting.st.header("This is a header") SubheaderDisplay text in subheader formatting.st.subheader("This is a subheader") CaptionDisplay text in small font.st.caption("This is written small caption text") Code blockDisplay a code block with optional syntax highlighting.st.code("a = 1234") EchoDisplay some code in the app, then execute it. Useful for tutorials.with st.echo(): st.write('This code will be printed') LaTeXDisplay mathematical expressions formatted as LaTeX.st.latex("\int a x^2 \,dx") Preformatted textWrite fixed-width and preformatted text.st.text("Hello world") DividerDisplay a horizontal rule.st.divider() Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration! PreviousTagsAdd tags to your Streamlit apps. Created by @gagan3012.st_tags(label='# Enter Keywords:', text='Press enter to add more', value=['Zero', 'One', 'Two'], suggestions=['five', 'six', 'seven', 'eight', 'nine', 'three', 'eleven', 'ten', 'four'], maxtags = 4, key='1') NLUApply text mining on a dataframe. Created by @JohnSnowLabs.nlu.load('sentiment').predict('I love NLU! <3') Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.mention(label="An awesome Streamlit App", icon="streamlit", url="https://extras.streamlit.app",) Annotated textDisplay annotated text in Streamlit apps. Created by @tvst.annotated_text("This ", ("is", "verb"), " some ", ("annotated", "adj"), ("text", "noun"), " for those of ", ("you", "pronoun"), " who ", ("like", "verb"), " this sort of ", ("thing", "noun"), ".") Drawable CanvasProvides a sketching canvas using Fabric.js. Created by @andfanilo.st_canvas(fill_color="rgba(255, 165, 0, 0.3)", stroke_width=stroke_width, stroke_color=stroke_color, background_color=bg_color, background_image=Image.open(bg_image) if bg_image else None, update_streamlit=realtime_update, height=150, drawing_mode=drawing_mode, point_display_radius=point_display_radius if drawing_mode == 'point' else 0, key="canvas",) TagsAdd tags to your Streamlit apps. Created by @gagan3012.st_tags(label='# Enter Keywords:', text='Press enter to add more', value=['Zero', 'One', 'Two'], suggestions=['five', 'six', 'seven', 'eight', 'nine', 'three', 'eleven', 'ten', 'four'], maxtags = 4, key='1') NLUApply text mining on a dataframe. Created by @JohnSnowLabs.nlu.load('sentiment').predict('I love NLU! <3') Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.mention(label="An awesome Streamlit App", icon="streamlit", url="https://extras.streamlit.app",) Annotated textDisplay annotated text in Streamlit apps. Created by @tvst.annotated_text("This ", ("is", "verb"), " some ", ("annotated", "adj"), ("text", "noun"), " for those of ", ("you", "pronoun"), " who ", ("like", "verb"), " this sort of ", ("thing", "noun"), ".") Drawable CanvasProvides a sketching canvas using Fabric.js. Created by @andfanilo.st_canvas(fill_color="rgba(255, 165, 0, 0.3)", stroke_width=stroke_width, stroke_color=stroke_color, background_color=bg_color, background_image=Image.open(bg_image) if bg_image else None, update_streamlit=realtime_update, height=150, drawing_mode=drawing_mode, point_display_radius=point_display_radius if drawing_mode == 'point' else 0, key="canvas",) TagsAdd tags to your Streamlit apps. Created by @gagan3012.st_tags(label='# Enter Keywords:', text='Press enter to add more', value=['Zero', 'One', 'Two'], suggestions=['five', 'six', 'seven', 'eight', 'nine', 'three', 'eleven', 'ten', 'four'], maxtags = 4, key='1') NLUApply text mining on a dataframe. Created by @JohnSnowLabs.nlu.load('sentiment').predict('I love NLU! <3') Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.mention(label="An awesome Streamlit App", icon="streamlit", url="https://extras.streamlit.app",) Next Data elements DataframesDisplay a dataframe as an interactive table.st.dataframe(my_data_frame) Data editorDisplay a data editor widget.edited = st.data_editor(df, num_rows="dynamic") Column configurationConfigure the display and editing behavior of dataframes and data editors.st.column_config.NumberColumn("Price (in USD)", min_value=0, format="$%d") Static tablesDisplay a static table.st.table(my_data_frame) MetricsDisplay a metric in big bold font, with an optional indicator of how the metric changed.st.metric("My metric", 42, 2) Dicts and JSONDisplay object or string as a pretty-printed JSON string.st.json(my_dict) Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration! PreviousImage CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates value = streamlit_image_coordinates("https://placekitten.com/200/300") st.write(value) Plotly EventsMake Plotly charts interactive!. Created by @null-jones.from streamlit_plotly_events import plotly_events fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.metric_cards import style_metric_cards col3.metric(label="No Change", value=5000, delta=0) style_metric_cards() Streamlit AggridImplementation of Ag-Grid component for Streamlit. Created by @PablocFonseca.df = pd.DataFrame({'col1': [1, 2, 3], 'col2': [4, 5, 6]}) grid_return = AgGrid(df, editable=True) new_df = grid_return['data'] Streamlit FoliumStreamlit Component for rendering Folium maps. Created by @randyzwitch.m = folium.Map(location=[39.949610, -75.150282], zoom_start=16) folium.Marker([39.949610, -75.150282], popup="Liberty Bell", tooltip="Liberty Bell").add_to(m) st_data = st_folium(m, width=725) Pandas ProfilingPandas profiling component for Streamlit. Created by @okld.df = pd.read_csv("https://storage.googleapis.com/tf-datasets/titanic/train.csv") pr = df.profile_report() st_profile_report(pr) Image CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates value = streamlit_image_coordinates("https://placekitten.com/200/300") st.write(value) Plotly EventsMake Plotly charts interactive!. Created by @null-jones.from streamlit_plotly_events import plotly_events fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.metric_cards import style_metric_cards col3.metric(label="No Change", value=5000, delta=0) style_metric_cards() Streamlit AggridImplementation of Ag-Grid component for Streamlit. Created by @PablocFonseca.df = pd.DataFrame({'col1': [1, 2, 3], 'col2': [4, 5, 6]}) grid_return = AgGrid(df, editable=True) new_df = grid_return['data'] Streamlit FoliumStreamlit Component for rendering Folium maps. Created by @randyzwitch.m = folium.Map(location=[39.949610, -75.150282], zoom_start=16) folium.Marker([39.949610, -75.150282], popup="Liberty Bell", tooltip="Liberty Bell").add_to(m) st_data = st_folium(m, width=725) Pandas ProfilingPandas profiling component for Streamlit. Created by @okld.df = pd.read_csv("https://storage.googleapis.com/tf-datasets/titanic/train.csv") pr = df.profile_report() st_profile_report(pr) Image CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates value = streamlit_image_coordinates("https://placekitten.com/200/300") st.write(value) Plotly EventsMake Plotly charts interactive!. Created by @null-jones.from streamlit_plotly_events import plotly_events fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.metric_cards import style_metric_cards col3.metric(label="No Change", value=5000, delta=0) style_metric_cards() Next Chart elements Simple area chartsDisplay an area chart.st.area_chart(my_data_frame) Simple bar chartsDisplay a bar chart.st.bar_chart(my_data_frame) Simple line chartsDisplay a line chart.st.line_chart(my_data_frame) Simple scatter chartsDisplay a line chart.st.scatter_chart(my_data_frame) Scatterplots on mapsDisplay a map with points on it.st.map(my_data_frame) MatplotlibDisplay a matplotlib.pyplot figure.st.pyplot(my_mpl_figure) AltairDisplay a chart using the Altair library.st.altair_chart(my_altair_chart) Vega-LiteDisplay a chart using the Vega-Lite library.st.vega_lite_chart(my_vega_lite_chart) PlotlyDisplay an interactive Plotly chart.st.plotly_chart(my_plotly_chart) BokehDisplay an interactive Bokeh chart.st.bokeh_chart(my_bokeh_chart) PyDeckDisplay a chart using the PyDeck library.st.pydeck_chart(my_pydeck_chart) GraphVizDisplay a graph using the dagre-d3 library.st.graphviz_chart(my_graphviz_spec) Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration! PreviousStreamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl("https://assets5.lottiefiles.com/packages/lf20_V9t630.json") st_lottie(lottie_hello, key="hello") Plotly EventsMake Plotly charts interactive!. Created by @null-jones.fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.chart += get_annotations_chart(annotations=[("Mar 01, 2008", "Pretty good day for GOOG"), ("Dec 01, 2007", "Something's going wrong for GOOG & AAPL"), ("Nov 01, 2008", "Market starts again thanks to..."), ("Dec 01, 2009", "Small crash for GOOG after..."),],) st.altair_chart(chart, use_container_width=True) PlostA deceptively simple plotting library for Streamlit. Created by @tvst.import plost plost.line_chart(my_dataframe, x='time', y='stock_value', color='stock_name',) HiPlotHigh dimensional Interactive Plotting. Created by @facebookresearch.data = [{'dropout':0.1, 'lr': 0.001, 'loss': 10.0, 'optimizer': 'SGD'}, {'dropout':0.15, 'lr': 0.01, 'loss': 3.5, 'optimizer': 'Adam'}, {'dropout':0.3, 'lr': 0.1, 'loss': 4.5, 'optimizer': 'Adam'}] hip.Experiment.from_iterable(data).display() EChartsHigh dimensional Interactive Plotting. Created by @andfanilo.from streamlit_echarts import st_echarts st_echarts(options=options) Streamlit FoliumStreamlit Component for rendering Folium maps. Created by @randyzwitch.m = folium.Map(location=[39.949610, -75.150282], zoom_start=16) st_data = st_folium(m, width=725) Spacy-StreamlitspaCy building blocks and visualizers for Streamlit apps. Created by @explosion.models = ["en_core_web_sm", "en_core_web_md"] spacy_streamlit.visualize(models, "Sundar Pichai is the CEO of Google.") Streamlit AgraphA Streamlit Graph Vis, based on react-grah-vis. Created by @ChrisDelClea.from streamlit_agraph import agraph, Node, Edge, Config agraph(nodes=nodes, edges=edges, config=config) Streamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl("https://assets5.lottiefiles.com/packages/lf20_V9t630.json") st_lottie(lottie_hello, key="hello") Plotly EventsMake Plotly charts interactive!. Created by @null-jones.fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.chart += get_annotations_chart(annotations=[("Mar 01, 2008", "Pretty good day for GOOG"), ("Dec 01, 2007", "Something's going wrong for GOOG & AAPL"), ("Nov 01, 2008", "Market starts again thanks to..."), ("Dec 01, 2009", "Small crash for GOOG after..."),],) st.altair_chart(chart, use_container_width=True) PlostA deceptively simple plotting library for Streamlit. Created by @tvst.import plost plost.line_chart(my_dataframe, x='time', y='stock_value', color='stock_name',) HiPlotHigh dimensional Interactive Plotting. Created by @facebookresearch.data = [{'dropout':0.1, 'lr': 0.001, 'loss': 10.0, 'optimizer': 'SGD'}, {'dropout':0.15, 'lr': 0.01, 'loss': 3.5, 'optimizer': 'Adam'}, {'dropout':0.3, 'lr': 0.1, 'loss': 4.5, 'optimizer': 'Adam'}] hip.Experiment.from_iterable(data).display() EChartsHigh dimensional Interactive Plotting. Created by @andfanilo.from streamlit_echarts import st_echarts st_echarts(options=options) Streamlit FoliumStreamlit Component for rendering Folium maps. Created by @randyzwitch.m = folium.Map(location=[39.949610, -75.150282], zoom_start=16) st_data = st_folium(m, width=725) Spacy-StreamlitspaCy building blocks and visualizers for Streamlit apps. Created by @explosion.models = ["en_core_web_sm", "en_core_web_md"] spacy_streamlit.visualize(models, "Sundar Pichai is the CEO of Google.") Streamlit AgraphA Streamlit Graph Vis, based on react-grah-vis. Created by @ChrisDelClea.from streamlit_agraph import agraph, Node, Edge, Config agraph(nodes=nodes, edges=edges, config=config) Streamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl("https://assets5.lottiefiles.com/packages/lf20_V9t630.json") st_lottie(lottie_hello, key="hello") Plotly EventsMake Plotly charts interactive!. Created by @null-jones.fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.chart += get_annotations_chart(annotations=[("Mar 01, 2008", "Pretty good day for GOOG"), ("Dec 01, 2007", "Something's going wrong for GOOG & AAPL"), ("Nov 01, 2008", "Market starts again thanks to..."), ("Dec 01, 2009", "Small crash for GOOG after..."),],) st.altair_chart(chart, use_container_width=True) Next Input widgets ButtonDisplay a button widget.clicked = st.button("Click me") Download buttonDisplay a download button widget.st.download_button("Download file", file) Form buttonDisplay a form submit button. For use with st.form.st.form_submit_button("Sign up") Link buttonDisplay a link button.st.link_button("Go to gallery", url) Page linkDisplay a link to another page in a multipage app.st.page_link("app.py", label="Home", icon="🏠") st.page_link("pages/profile.py", label="My profile") CheckboxDisplay a checkbox widget.selected = st.checkbox("I agree") Color pickerDisplay a color picker widget.color = st.color_picker("Pick a color") MultiselectDisplay a multiselect widget. The multiselect widget starts as empty.choices = st.multiselect("Buy", ["milk", "apples", "potatoes"]) RadioDisplay a radio button widget.choice = st.radio("Pick one", ["cats", "dogs"]) SelectboxDisplay a select widget.choice = st.selectbox("Pick one", ["cats", "dogs"]) Select-sliderDisplay a slider widget to select items from a list.size = st.select_slider("Pick a size", ["S", "M", "L"]) ToggleDisplay a toggle widget.activated = st.toggle("Activate") Number inputDisplay a numeric input widget.choice = st.number_input("Pick a number", 0, 10) SliderDisplay a slider widget.number = st.slider("Pick a number", 0, 100) Date inputDisplay a date input widget.date = st.date_input("Your birthday") Time inputDisplay a time input widget.time = st.time_input("Meeting time") Chat inputDisplay a chat input widget.prompt = st.chat_input("Say something") if prompt: st.write(f"The user has sent: {prompt}") Text-areaDisplay a multi-line text input widget.text = st.text_area("Text to translate") Text inputDisplay a single-line text input widget.name = st.text_input("First name") Data editorDisplay a data editor widget.edited = st.experimental_data_editor(df, num_rows="dynamic") File UploaderDisplay a file uploader widget.data = st.file_uploader("Upload a CSV") Camera inputDisplay a widget that allows users to upload images directly from a camera.image = st.camera_input("Take a picture") Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration! PreviousStreamlit ChatStreamlit Component for a Chatbot UI. Created by @AI-Yash.from streamlit_chat import message message("My message") message("Hello bot!", is_user=True) # align's the message to the right Streamlit Option MenuSelect a single item from a list of options in a menu. Created by @victoryhb.from streamlit_option_menu import option_menu option_menu("Main Menu", ["Home", 'Settings'], icons=['house', 'gear'], menu_icon="cast", default_index=1) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.stoggle import stoggle stoggle( "Click me!", """🥷 Surprise! Here's some additional content""",) Streamlit ElementsCreate a draggable and resizable dashboard in Streamlit. Created by @okls.from streamlit_elements import elements, mui, html with elements("new_element"): mui.Typography("Hello world") TagsAdd tags to your Streamlit apps. Created by @gagan3012.from streamlit_tags import st_tags st_tags(label='# Enter Keywords:', text='Press enter to add more', value=['Zero', 'One', 'Two'], suggestions=['five', 'six', 'seven', 'eight', 'nine', 'three', 'eleven', 'ten', 'four'], maxtags = 4, key='1') StqdmThe simplest way to handle a progress bar in streamlit app. Created by @Wirg.from stqdm import stqdm for _ in stqdm(range(50)): sleep(0.5) TimelineDisplay a Timeline in Streamlit apps using TimelineJS. Created by @innerdoc.from streamlit_timeline import timeline with open('example.json', "r") as f: timeline(f.read(), height=800) Camera input liveAlternative for st.camera_input which returns the webcam images live. Created by @blackary.from camera_input_live import camera_input_live image = camera_input_live() st.image(value) Streamlit AceAce editor component for Streamlit. Created by @okld.from streamlit_ace import st_ace content = st_ace() content Streamlit ChatStreamlit Component for a Chatbot UI. Created by @AI-Yash.from streamlit_chat import message message("My message") message("Hello bot!", is_user=True) # align's the message to the right Streamlit Option MenuSelect a single item from a list of options in a menu. Created by @victoryhb.from streamlit_option_menu import option_menu option_menu("Main Menu", ["Home", 'Settings'], icons=['house', 'gear'], menu_icon="cast", default_index=1) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.stoggle import stoggle stoggle( "Click me!", """🥷 Surprise! Here's some additional content""",) Streamlit ElementsCreate a draggable and resizable dashboard in Streamlit. Created by @okls.from streamlit_elements import elements, mui, html with elements("new_element"): mui.Typography("Hello world") TagsAdd tags to your Streamlit apps. Created by @gagan3012.from streamlit_tags import st_tags st_tags(label='# Enter Keywords:', text='Press enter to add more', value=['Zero', 'One', 'Two'], suggestions=['five', 'six', 'seven', 'eight', 'nine', 'three', 'eleven', 'ten', 'four'], maxtags = 4, key='1') StqdmThe simplest way to handle a progress bar in streamlit app. Created by @Wirg.from stqdm import stqdm for _ in stqdm(range(50)): sleep(0.5) TimelineDisplay a Timeline in Streamlit apps using TimelineJS. Created by @innerdoc.from streamlit_timeline import timeline with open('example.json', "r") as f: timeline(f.read(), height=800) Camera input liveAlternative for st.camera_input which returns the webcam images live. Created by @blackary.from camera_input_live import camera_input_live image = camera_input_live() st.image(value) Streamlit AceAce editor component for Streamlit. Created by @okld.from streamlit_ace import st_ace content = st_ace() content Streamlit ChatStreamlit Component for a Chatbot UI. Created by @AI-Yash.from streamlit_chat import message message("My message") message("Hello bot!", is_user=True) # align's the message to the right Streamlit Option MenuSelect a single item from a list of options in a menu. Created by @victoryhb.from streamlit_option_menu import option_menu option_menu("Main Menu", ["Home", 'Settings'], icons=['house', 'gear'], menu_icon="cast", default_index=1) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.stoggle import stoggle stoggle( "Click me!", """🥷 Surprise! Here's some additional content""",) Next Media elements ImageDisplay an image or list of images.st.image(numpy_array) st.image(image_bytes) st.image(file) st.image("https://example.com/myimage.jpg") AudioDisplay an audio player.st.audio(numpy_array) st.audio(audio_bytes) st.audio(file) st.audio("https://example.com/myaudio.mp3", format="audio/mp3") VideoDisplay a video player.st.video(numpy_array) st.video(video_bytes) st.video(file) st.video("https://example.com/myvideo.mp4", format="video/mp4") Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration! PreviousStreamlit CropperA simple image cropper for Streamlit. Created by @turner-anderson.from streamlit_cropper import st_cropper st_cropper(img, realtime_update=realtime_update, box_color=box_color, aspect_ratio=aspect_ratio) Image CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates streamlit_image_coordinates("https://placekitten.com/200/300") Streamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl("https://assets5.lottiefiles.com/packages/lf20_V9t630.json") st_lottie(lottie_hello, key="hello") Streamlit WebrtcHandling and transmitting real-time video/audio streams with Streamlit. Created by @whitphx.from streamlit_webrtc import webrtc_streamer webrtc_streamer(key="sample") Drawable CanvasProvides a sketching canvas using Fabric.js. Created by @andfanilo.from streamlit_drawable_canvas import st_canvas st_canvas(fill_color="rgba(255, 165, 0, 0.3)", stroke_width=stroke_width, stroke_color=stroke_color, background_color=bg_color, background_image=Image.open(bg_image) if bg_image else None, update_streamlit=realtime_update, height=150, drawing_mode=drawing_mode, point_display_radius=point_display_radius if drawing_mode == 'point' else 0, key="canvas",) Image ComparisonCompare images with a slider using JuxtaposeJS. Created by @fcakyon.from streamlit_image_comparison import image_comparison image_comparison(img1="image1.jpg", img2="image2.jpg",) Streamlit CropperA simple image cropper for Streamlit. Created by @turner-anderson.from streamlit_cropper import st_cropper st_cropper(img, realtime_update=realtime_update, box_color=box_color, aspect_ratio=aspect_ratio) Image CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates streamlit_image_coordinates("https://placekitten.com/200/300") Streamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl("https://assets5.lottiefiles.com/packages/lf20_V9t630.json") st_lottie(lottie_hello, key="hello") Streamlit WebrtcHandling and transmitting real-time video/audio streams with Streamlit. Created by @whitphx.from streamlit_webrtc import webrtc_streamer webrtc_streamer(key="sample") Drawable CanvasProvides a sketching canvas using Fabric.js. Created by @andfanilo.from streamlit_drawable_canvas import st_canvas st_canvas(fill_color="rgba(255, 165, 0, 0.3)", stroke_width=stroke_width, stroke_color=stroke_color, background_color=bg_color, background_image=Image.open(bg_image) if bg_image else None, update_streamlit=realtime_update, height=150, drawing_mode=drawing_mode, point_display_radius=point_display_radius if drawing_mode == 'point' else 0, key="canvas",) Image ComparisonCompare images with a slider using JuxtaposeJS. Created by @fcakyon.from streamlit_image_comparison import image_comparison image_comparison(img1="image1.jpg", img2="image2.jpg",) Streamlit CropperA simple image cropper for Streamlit. Created by @turner-anderson.from streamlit_cropper import st_cropper st_cropper(img, realtime_update=realtime_update, box_color=box_color, aspect_ratio=aspect_ratio) Image CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates streamlit_image_coordinates("https://placekitten.com/200/300") Streamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl("https://assets5.lottiefiles.com/packages/lf20_V9t630.json") st_lottie(lottie_hello, key="hello") Next Layouts and containers ColumnsInsert containers laid out as side-by-side columns.col1, col2 = st.columns(2) col1.write("this is column 1") col2.write("this is column 2") ContainerInsert a multi-element container.c = st.container() st.write("This will show last") c.write("This will show first") c.write("This will show second") Modal dialogsInsert a modal dialog that can rerun independently from the rest of the script.@st.experimental_dialog("Sign up") def email_form(): name = st.text_input("Name") email = st.text_input("Email") EmptyInsert a single-element container.c = st.empty() st.write("This will show last") c.write("This will be replaced") c.write("This will show first") ExpanderInsert a multi-element container that can be expanded/collapsed.with st.expander("Open to see more"): st.write("This is more content") PopoverInsert a multi-element popover container that can be opened/closed.with st.popover("Settings"): st.checkbox("Show completed") SidebarDisplay items in a sidebar.st.sidebar.write("This lives in the sidebar") st.sidebar.button("Click me!") TabsInsert containers separated into tabs.tab1, tab2 = st.tabs(["Tab 1", "Tab2"]) tab1.write("this is tab 1") tab2.write("this is tab 2") Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration!Streamlit ElementsCreate a draggable and resizable dashboard in Streamlit. Created by @okls.from streamlit_elements import elements, mui, html with elements("new_element"): mui.Typography("Hello world") PydanticAuto-generate Streamlit UI from Pydantic Models and Dataclasses. Created by @lukasmasuch.import streamlit_pydantic as sp sp.pydantic_form(key="my_form", model=ExampleModel) Streamlit PagesAn experimental version of Streamlit Multi-Page Apps. Created by @blackary.from st_pages import Page, show_pages, add_page_title show_pages([ Page("streamlit_app.py", "Home", "🏠"), Page("other_pages/page2.py", "Page 2", ":books:"), ]) Chat elements Streamlit provides a few commands to help you build conversational apps. These chat elements are designed to be used in conjunction with each other, but you can also use them separately. st.chat_message lets you insert a chat message container into the app so you can display messages from the user or the app. Chat containers can contain other Streamlit elements, including charts, tables, text, and more. st.chat_input lets you display a chat input widget so the user can type in a message. Chat inputDisplay a chat input widget.prompt = st.chat_input("Say something") if prompt: st.write(f"The user has sent: {prompt}") Chat messageInsert a chat message container.import numpy as np with st.chat_message("user"): st.write("Hello 👋") st.line_chart(np.random.randn(30, 3)) Status containerDisplay output of long-running tasks in a container.with st.status('Running'): do_something_slow() st.write_streamWrite generators or streams to the app with a typewriter effect.st.write_stream(my_generator) st.write_stream(my_llm_stream) Status elements Progress barDisplay a progress bar.for i in range(101): st.progress(i) do_something_slow() SpinnerTemporarily displays a message while executing a block of code.with st.spinner("Please wait..."): do_something_slow() Status containerDisplay output of long-running tasks in a container.with st.status('Running'): do_something_slow() ToastBriefly displays a toast message in the bottom-right corner.st.toast('Butter!', icon='🧈') BalloonsDisplay celebratory balloons!do_something() # Celebrate when all done! st.balloons() SnowflakesDisplay celebratory snowflakes!do_something() # Celebrate when all done! st.snow() Success boxDisplay a success message.st.success("Match found!") Info boxDisplay an informational message.st.info("Dataset is updated every day at midnight.") Warning boxDisplay warning message.st.warning("Unable to fetch image. Skipping...") Error boxDisplay error message.st.error("We encountered an error") Exception outputDisplay an exception.e = RuntimeError("This is an exception of type RuntimeError") st.exception(e) Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration!StqdmThe simplest way to handle a progress bar in streamlit app. Created by @Wirg.from stqdm import stqdm for _ in stqdm(range(50)): sleep(0.5) Custom notification boxA custom notification box with the ability to close it out. Created by @Socvest.from streamlit_custom_notification_box import custom_notification_box styles = {'material-icons':{'color': 'red'}, 'text-icon-link-close-container': {'box-shadow': '#3896de 0px 4px'}, 'notification-text': {'':''}, 'close-button':{'':''}, 'link':{'':''}} custom_notification_box(icon='info', textDisplay='We are almost done with your registration...', externalLink='more info', url='#', styles=styles, key="foo") Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.let_it_rain import rain rain(emoji="🎈", font_size=54, falling_speed=5, animation_length="infinite",) App logic and configuration Navigation and pages Switch pageProgrammatically navigates to a specified page.st.switch_page("pages/my_page.py") Page linkDisplay a link to another page in a multipage app.st.page_link("app.py", label="Home", icon="🏠") st.page_link("pages/profile.py", label="My profile") Execution flow Modal dialogsInsert a modal dialog that can rerun independently from the rest of the script.@st.experimental_dialog("Sign up") def email_form(): name = st.text_input("Name") email = st.text_input("Email") FormsCreate a form that batches elements together with a “Submit" button.with st.form(key='my_form'): name = st.text_input("Name") email = st.text_input("Email") st.form_submit_button("Sign up") Partial rerunsDefine a fragment to rerun independently from the rest of the script.@st.experimental_fragment(run_every="10s") def fragment(): df = get_data() st.line_chart(df) Rerun scriptRerun the script immediately.st.rerun() Stop executionStops execution immediately.st.stop() Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration!AutorefreshForce a refresh without tying up a script. Created by @kmcgrady.from streamlit_autorefresh import st_autorefresh st_autorefresh(interval=2000, limit=100, key="fizzbuzzcounter") PydanticAuto-generate Streamlit UI from Pydantic Models and Dataclasses. Created by @lukasmasuch.import streamlit_pydantic as sp sp.pydantic_form(key="my_form", model=ExampleModel) Streamlit PagesAn experimental version of Streamlit Multi-Page Apps. Created by @blackary.from st_pages import Page, show_pages, add_page_title show_pages([ Page("streamlit_app.py", "Home", "🏠"), Page("other_pages/page2.py", "Page 2", ":books:"), ]) Caching and state Cache dataFunction decorator to cache functions that return data (e.g. dataframe transforms, database queries, ML inference).@st.cache_data def long_function(param1, param2): # Perform expensive computation here or # fetch data from the web here return data Cache resourceFunction decorator to cache functions that return global resources (e.g. database connections, ML models).@st.cache_resource def init_model(): # Return a global resource here return pipeline( "sentiment-analysis", model="distilbert-base-uncased-finetuned-sst-2-english" ) Session stateSession state is a way to share variables between reruns, for each user session.st.session_state['key'] = value Query parametersGet, set, or clear the query parameters that are shown in the browser's URL bar.st.query_params[key] = value st.query_params.clear() Connections and databases Setup your connection Create a connectionConnect to a data source or APIconn = st.connection('pets_db', type='sql') pet_owners = conn.query('select * from pet_owners') st.dataframe(pet_owners) Built-in connections SnowflakeConnectionA connection to Snowflake.conn = st.connection('snowflake') SQLConnectionA connection to a SQL database using SQLAlchemy.conn = st.connection('sql') Build your own connections Connection base classBuild your own connection with BaseConnection.class MyConnection(BaseConnection[myconn.MyConnection]): def _connect(self, **kwargs) -> MyConnection: return myconn.connect(**self._secrets, **kwargs) def query(self, query): return self._instance.query(query) Secrets management Secrets singletonAccess secrets from a local TOML file.key = st.secrets["OpenAI_key"] Secrets fileSave your secrets in a per-project or per-profile TOML file.OpenAI_key = "<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/en/0.75.0/api.html#utilities-and-user-info
DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceremovePAGE ELEMENTSWrite and magicaddText elementsaddData elementsaddChart elementsaddInput widgetsaddMedia elementsaddLayouts and containersaddChat elementsaddStatus elementsaddThird-party componentsopen_in_newAPPLICATION LOGICNavigation and pagesaddExecution flowaddCaching and stateaddConnections and secretsaddCustom componentsaddUtilitiesaddConfigurationaddTOOLSApp testingaddCommand lineaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Develop/API referenceAPI reference Streamlit makes it easy for you to visualize, mutate, and share data. The API reference is organized by activity type, like displaying data or optimizing performance. Each section includes methods associated with the activity type, including examples. Browse our API below and click to learn more about any of our available commands! 🎈 Display almost anything Write and magic st.writeWrite arguments to the app.st.write("Hello **world**!") st.write(my_data_frame) st.write(my_mpl_figure) st.write_streamWrite generators or streams to the app with a typewriter effect.st.write_stream(my_generator) st.write_stream(my_llm_stream) MagicAny time Streamlit sees either a variable or literal value on its own line, it automatically writes that to your app using st.write"Hello **world**!" my_data_frame my_mpl_figure Text elements MarkdownDisplay string formatted as Markdown.st.markdown("Hello **world**!") TitleDisplay text in title formatting.st.title("The app title") HeaderDisplay text in header formatting.st.header("This is a header") SubheaderDisplay text in subheader formatting.st.subheader("This is a subheader") CaptionDisplay text in small font.st.caption("This is written small caption text") Code blockDisplay a code block with optional syntax highlighting.st.code("a = 1234") EchoDisplay some code in the app, then execute it. Useful for tutorials.with st.echo(): st.write('This code will be printed') LaTeXDisplay mathematical expressions formatted as LaTeX.st.latex("\int a x^2 \,dx") Preformatted textWrite fixed-width and preformatted text.st.text("Hello world") DividerDisplay a horizontal rule.st.divider() Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration! PreviousTagsAdd tags to your Streamlit apps. Created by @gagan3012.st_tags(label='# Enter Keywords:', text='Press enter to add more', value=['Zero', 'One', 'Two'], suggestions=['five', 'six', 'seven', 'eight', 'nine', 'three', 'eleven', 'ten', 'four'], maxtags = 4, key='1') NLUApply text mining on a dataframe. Created by @JohnSnowLabs.nlu.load('sentiment').predict('I love NLU! <3') Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.mention(label="An awesome Streamlit App", icon="streamlit", url="https://extras.streamlit.app",) Annotated textDisplay annotated text in Streamlit apps. Created by @tvst.annotated_text("This ", ("is", "verb"), " some ", ("annotated", "adj"), ("text", "noun"), " for those of ", ("you", "pronoun"), " who ", ("like", "verb"), " this sort of ", ("thing", "noun"), ".") Drawable CanvasProvides a sketching canvas using Fabric.js. Created by @andfanilo.st_canvas(fill_color="rgba(255, 165, 0, 0.3)", stroke_width=stroke_width, stroke_color=stroke_color, background_color=bg_color, background_image=Image.open(bg_image) if bg_image else None, update_streamlit=realtime_update, height=150, drawing_mode=drawing_mode, point_display_radius=point_display_radius if drawing_mode == 'point' else 0, key="canvas",) TagsAdd tags to your Streamlit apps. Created by @gagan3012.st_tags(label='# Enter Keywords:', text='Press enter to add more', value=['Zero', 'One', 'Two'], suggestions=['five', 'six', 'seven', 'eight', 'nine', 'three', 'eleven', 'ten', 'four'], maxtags = 4, key='1') NLUApply text mining on a dataframe. Created by @JohnSnowLabs.nlu.load('sentiment').predict('I love NLU! <3') Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.mention(label="An awesome Streamlit App", icon="streamlit", url="https://extras.streamlit.app",) Annotated textDisplay annotated text in Streamlit apps. Created by @tvst.annotated_text("This ", ("is", "verb"), " some ", ("annotated", "adj"), ("text", "noun"), " for those of ", ("you", "pronoun"), " who ", ("like", "verb"), " this sort of ", ("thing", "noun"), ".") Drawable CanvasProvides a sketching canvas using Fabric.js. Created by @andfanilo.st_canvas(fill_color="rgba(255, 165, 0, 0.3)", stroke_width=stroke_width, stroke_color=stroke_color, background_color=bg_color, background_image=Image.open(bg_image) if bg_image else None, update_streamlit=realtime_update, height=150, drawing_mode=drawing_mode, point_display_radius=point_display_radius if drawing_mode == 'point' else 0, key="canvas",) TagsAdd tags to your Streamlit apps. Created by @gagan3012.st_tags(label='# Enter Keywords:', text='Press enter to add more', value=['Zero', 'One', 'Two'], suggestions=['five', 'six', 'seven', 'eight', 'nine', 'three', 'eleven', 'ten', 'four'], maxtags = 4, key='1') NLUApply text mining on a dataframe. Created by @JohnSnowLabs.nlu.load('sentiment').predict('I love NLU! <3') Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.mention(label="An awesome Streamlit App", icon="streamlit", url="https://extras.streamlit.app",) Next Data elements DataframesDisplay a dataframe as an interactive table.st.dataframe(my_data_frame) Data editorDisplay a data editor widget.edited = st.data_editor(df, num_rows="dynamic") Column configurationConfigure the display and editing behavior of dataframes and data editors.st.column_config.NumberColumn("Price (in USD)", min_value=0, format="$%d") Static tablesDisplay a static table.st.table(my_data_frame) MetricsDisplay a metric in big bold font, with an optional indicator of how the metric changed.st.metric("My metric", 42, 2) Dicts and JSONDisplay object or string as a pretty-printed JSON string.st.json(my_dict) Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration! PreviousImage CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates value = streamlit_image_coordinates("https://placekitten.com/200/300") st.write(value) Plotly EventsMake Plotly charts interactive!. Created by @null-jones.from streamlit_plotly_events import plotly_events fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.metric_cards import style_metric_cards col3.metric(label="No Change", value=5000, delta=0) style_metric_cards() Streamlit AggridImplementation of Ag-Grid component for Streamlit. Created by @PablocFonseca.df = pd.DataFrame({'col1': [1, 2, 3], 'col2': [4, 5, 6]}) grid_return = AgGrid(df, editable=True) new_df = grid_return['data'] Streamlit FoliumStreamlit Component for rendering Folium maps. Created by @randyzwitch.m = folium.Map(location=[39.949610, -75.150282], zoom_start=16) folium.Marker([39.949610, -75.150282], popup="Liberty Bell", tooltip="Liberty Bell").add_to(m) st_data = st_folium(m, width=725) Pandas ProfilingPandas profiling component for Streamlit. Created by @okld.df = pd.read_csv("https://storage.googleapis.com/tf-datasets/titanic/train.csv") pr = df.profile_report() st_profile_report(pr) Image CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates value = streamlit_image_coordinates("https://placekitten.com/200/300") st.write(value) Plotly EventsMake Plotly charts interactive!. Created by @null-jones.from streamlit_plotly_events import plotly_events fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.metric_cards import style_metric_cards col3.metric(label="No Change", value=5000, delta=0) style_metric_cards() Streamlit AggridImplementation of Ag-Grid component for Streamlit. Created by @PablocFonseca.df = pd.DataFrame({'col1': [1, 2, 3], 'col2': [4, 5, 6]}) grid_return = AgGrid(df, editable=True) new_df = grid_return['data'] Streamlit FoliumStreamlit Component for rendering Folium maps. Created by @randyzwitch.m = folium.Map(location=[39.949610, -75.150282], zoom_start=16) folium.Marker([39.949610, -75.150282], popup="Liberty Bell", tooltip="Liberty Bell").add_to(m) st_data = st_folium(m, width=725) Pandas ProfilingPandas profiling component for Streamlit. Created by @okld.df = pd.read_csv("https://storage.googleapis.com/tf-datasets/titanic/train.csv") pr = df.profile_report() st_profile_report(pr) Image CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates value = streamlit_image_coordinates("https://placekitten.com/200/300") st.write(value) Plotly EventsMake Plotly charts interactive!. Created by @null-jones.from streamlit_plotly_events import plotly_events fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.metric_cards import style_metric_cards col3.metric(label="No Change", value=5000, delta=0) style_metric_cards() Next Chart elements Simple area chartsDisplay an area chart.st.area_chart(my_data_frame) Simple bar chartsDisplay a bar chart.st.bar_chart(my_data_frame) Simple line chartsDisplay a line chart.st.line_chart(my_data_frame) Simple scatter chartsDisplay a line chart.st.scatter_chart(my_data_frame) Scatterplots on mapsDisplay a map with points on it.st.map(my_data_frame) MatplotlibDisplay a matplotlib.pyplot figure.st.pyplot(my_mpl_figure) AltairDisplay a chart using the Altair library.st.altair_chart(my_altair_chart) Vega-LiteDisplay a chart using the Vega-Lite library.st.vega_lite_chart(my_vega_lite_chart) PlotlyDisplay an interactive Plotly chart.st.plotly_chart(my_plotly_chart) BokehDisplay an interactive Bokeh chart.st.bokeh_chart(my_bokeh_chart) PyDeckDisplay a chart using the PyDeck library.st.pydeck_chart(my_pydeck_chart) GraphVizDisplay a graph using the dagre-d3 library.st.graphviz_chart(my_graphviz_spec) Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration! PreviousStreamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl("https://assets5.lottiefiles.com/packages/lf20_V9t630.json") st_lottie(lottie_hello, key="hello") Plotly EventsMake Plotly charts interactive!. Created by @null-jones.fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.chart += get_annotations_chart(annotations=[("Mar 01, 2008", "Pretty good day for GOOG"), ("Dec 01, 2007", "Something's going wrong for GOOG & AAPL"), ("Nov 01, 2008", "Market starts again thanks to..."), ("Dec 01, 2009", "Small crash for GOOG after..."),],) st.altair_chart(chart, use_container_width=True) PlostA deceptively simple plotting library for Streamlit. Created by @tvst.import plost plost.line_chart(my_dataframe, x='time', y='stock_value', color='stock_name',) HiPlotHigh dimensional Interactive Plotting. Created by @facebookresearch.data = [{'dropout':0.1, 'lr': 0.001, 'loss': 10.0, 'optimizer': 'SGD'}, {'dropout':0.15, 'lr': 0.01, 'loss': 3.5, 'optimizer': 'Adam'}, {'dropout':0.3, 'lr': 0.1, 'loss': 4.5, 'optimizer': 'Adam'}] hip.Experiment.from_iterable(data).display() EChartsHigh dimensional Interactive Plotting. Created by @andfanilo.from streamlit_echarts import st_echarts st_echarts(options=options) Streamlit FoliumStreamlit Component for rendering Folium maps. Created by @randyzwitch.m = folium.Map(location=[39.949610, -75.150282], zoom_start=16) st_data = st_folium(m, width=725) Spacy-StreamlitspaCy building blocks and visualizers for Streamlit apps. Created by @explosion.models = ["en_core_web_sm", "en_core_web_md"] spacy_streamlit.visualize(models, "Sundar Pichai is the CEO of Google.") Streamlit AgraphA Streamlit Graph Vis, based on react-grah-vis. Created by @ChrisDelClea.from streamlit_agraph import agraph, Node, Edge, Config agraph(nodes=nodes, edges=edges, config=config) Streamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl("https://assets5.lottiefiles.com/packages/lf20_V9t630.json") st_lottie(lottie_hello, key="hello") Plotly EventsMake Plotly charts interactive!. Created by @null-jones.fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.chart += get_annotations_chart(annotations=[("Mar 01, 2008", "Pretty good day for GOOG"), ("Dec 01, 2007", "Something's going wrong for GOOG & AAPL"), ("Nov 01, 2008", "Market starts again thanks to..."), ("Dec 01, 2009", "Small crash for GOOG after..."),],) st.altair_chart(chart, use_container_width=True) PlostA deceptively simple plotting library for Streamlit. Created by @tvst.import plost plost.line_chart(my_dataframe, x='time', y='stock_value', color='stock_name',) HiPlotHigh dimensional Interactive Plotting. Created by @facebookresearch.data = [{'dropout':0.1, 'lr': 0.001, 'loss': 10.0, 'optimizer': 'SGD'}, {'dropout':0.15, 'lr': 0.01, 'loss': 3.5, 'optimizer': 'Adam'}, {'dropout':0.3, 'lr': 0.1, 'loss': 4.5, 'optimizer': 'Adam'}] hip.Experiment.from_iterable(data).display() EChartsHigh dimensional Interactive Plotting. Created by @andfanilo.from streamlit_echarts import st_echarts st_echarts(options=options) Streamlit FoliumStreamlit Component for rendering Folium maps. Created by @randyzwitch.m = folium.Map(location=[39.949610, -75.150282], zoom_start=16) st_data = st_folium(m, width=725) Spacy-StreamlitspaCy building blocks and visualizers for Streamlit apps. Created by @explosion.models = ["en_core_web_sm", "en_core_web_md"] spacy_streamlit.visualize(models, "Sundar Pichai is the CEO of Google.") Streamlit AgraphA Streamlit Graph Vis, based on react-grah-vis. Created by @ChrisDelClea.from streamlit_agraph import agraph, Node, Edge, Config agraph(nodes=nodes, edges=edges, config=config) Streamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl("https://assets5.lottiefiles.com/packages/lf20_V9t630.json") st_lottie(lottie_hello, key="hello") Plotly EventsMake Plotly charts interactive!. Created by @null-jones.fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.chart += get_annotations_chart(annotations=[("Mar 01, 2008", "Pretty good day for GOOG"), ("Dec 01, 2007", "Something's going wrong for GOOG & AAPL"), ("Nov 01, 2008", "Market starts again thanks to..."), ("Dec 01, 2009", "Small crash for GOOG after..."),],) st.altair_chart(chart, use_container_width=True) Next Input widgets ButtonDisplay a button widget.clicked = st.button("Click me") Download buttonDisplay a download button widget.st.download_button("Download file", file) Form buttonDisplay a form submit button. For use with st.form.st.form_submit_button("Sign up") Link buttonDisplay a link button.st.link_button("Go to gallery", url) Page linkDisplay a link to another page in a multipage app.st.page_link("app.py", label="Home", icon="🏠") st.page_link("pages/profile.py", label="My profile") CheckboxDisplay a checkbox widget.selected = st.checkbox("I agree") Color pickerDisplay a color picker widget.color = st.color_picker("Pick a color") MultiselectDisplay a multiselect widget. The multiselect widget starts as empty.choices = st.multiselect("Buy", ["milk", "apples", "potatoes"]) RadioDisplay a radio button widget.choice = st.radio("Pick one", ["cats", "dogs"]) SelectboxDisplay a select widget.choice = st.selectbox("Pick one", ["cats", "dogs"]) Select-sliderDisplay a slider widget to select items from a list.size = st.select_slider("Pick a size", ["S", "M", "L"]) ToggleDisplay a toggle widget.activated = st.toggle("Activate") Number inputDisplay a numeric input widget.choice = st.number_input("Pick a number", 0, 10) SliderDisplay a slider widget.number = st.slider("Pick a number", 0, 100) Date inputDisplay a date input widget.date = st.date_input("Your birthday") Time inputDisplay a time input widget.time = st.time_input("Meeting time") Chat inputDisplay a chat input widget.prompt = st.chat_input("Say something") if prompt: st.write(f"The user has sent: {prompt}") Text-areaDisplay a multi-line text input widget.text = st.text_area("Text to translate") Text inputDisplay a single-line text input widget.name = st.text_input("First name") Data editorDisplay a data editor widget.edited = st.experimental_data_editor(df, num_rows="dynamic") File UploaderDisplay a file uploader widget.data = st.file_uploader("Upload a CSV") Camera inputDisplay a widget that allows users to upload images directly from a camera.image = st.camera_input("Take a picture") Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration! PreviousStreamlit ChatStreamlit Component for a Chatbot UI. Created by @AI-Yash.from streamlit_chat import message message("My message") message("Hello bot!", is_user=True) # align's the message to the right Streamlit Option MenuSelect a single item from a list of options in a menu. Created by @victoryhb.from streamlit_option_menu import option_menu option_menu("Main Menu", ["Home", 'Settings'], icons=['house', 'gear'], menu_icon="cast", default_index=1) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.stoggle import stoggle stoggle( "Click me!", """🥷 Surprise! Here's some additional content""",) Streamlit ElementsCreate a draggable and resizable dashboard in Streamlit. Created by @okls.from streamlit_elements import elements, mui, html with elements("new_element"): mui.Typography("Hello world") TagsAdd tags to your Streamlit apps. Created by @gagan3012.from streamlit_tags import st_tags st_tags(label='# Enter Keywords:', text='Press enter to add more', value=['Zero', 'One', 'Two'], suggestions=['five', 'six', 'seven', 'eight', 'nine', 'three', 'eleven', 'ten', 'four'], maxtags = 4, key='1') StqdmThe simplest way to handle a progress bar in streamlit app. Created by @Wirg.from stqdm import stqdm for _ in stqdm(range(50)): sleep(0.5) TimelineDisplay a Timeline in Streamlit apps using TimelineJS. Created by @innerdoc.from streamlit_timeline import timeline with open('example.json', "r") as f: timeline(f.read(), height=800) Camera input liveAlternative for st.camera_input which returns the webcam images live. Created by @blackary.from camera_input_live import camera_input_live image = camera_input_live() st.image(value) Streamlit AceAce editor component for Streamlit. Created by @okld.from streamlit_ace import st_ace content = st_ace() content Streamlit ChatStreamlit Component for a Chatbot UI. Created by @AI-Yash.from streamlit_chat import message message("My message") message("Hello bot!", is_user=True) # align's the message to the right Streamlit Option MenuSelect a single item from a list of options in a menu. Created by @victoryhb.from streamlit_option_menu import option_menu option_menu("Main Menu", ["Home", 'Settings'], icons=['house', 'gear'], menu_icon="cast", default_index=1) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.stoggle import stoggle stoggle( "Click me!", """🥷 Surprise! Here's some additional content""",) Streamlit ElementsCreate a draggable and resizable dashboard in Streamlit. Created by @okls.from streamlit_elements import elements, mui, html with elements("new_element"): mui.Typography("Hello world") TagsAdd tags to your Streamlit apps. Created by @gagan3012.from streamlit_tags import st_tags st_tags(label='# Enter Keywords:', text='Press enter to add more', value=['Zero', 'One', 'Two'], suggestions=['five', 'six', 'seven', 'eight', 'nine', 'three', 'eleven', 'ten', 'four'], maxtags = 4, key='1') StqdmThe simplest way to handle a progress bar in streamlit app. Created by @Wirg.from stqdm import stqdm for _ in stqdm(range(50)): sleep(0.5) TimelineDisplay a Timeline in Streamlit apps using TimelineJS. Created by @innerdoc.from streamlit_timeline import timeline with open('example.json', "r") as f: timeline(f.read(), height=800) Camera input liveAlternative for st.camera_input which returns the webcam images live. Created by @blackary.from camera_input_live import camera_input_live image = camera_input_live() st.image(value) Streamlit AceAce editor component for Streamlit. Created by @okld.from streamlit_ace import st_ace content = st_ace() content Streamlit ChatStreamlit Component for a Chatbot UI. Created by @AI-Yash.from streamlit_chat import message message("My message") message("Hello bot!", is_user=True) # align's the message to the right Streamlit Option MenuSelect a single item from a list of options in a menu. Created by @victoryhb.from streamlit_option_menu import option_menu option_menu("Main Menu", ["Home", 'Settings'], icons=['house', 'gear'], menu_icon="cast", default_index=1) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.stoggle import stoggle stoggle( "Click me!", """🥷 Surprise! Here's some additional content""",) Next Media elements ImageDisplay an image or list of images.st.image(numpy_array) st.image(image_bytes) st.image(file) st.image("https://example.com/myimage.jpg") AudioDisplay an audio player.st.audio(numpy_array) st.audio(audio_bytes) st.audio(file) st.audio("https://example.com/myaudio.mp3", format="audio/mp3") VideoDisplay a video player.st.video(numpy_array) st.video(video_bytes) st.video(file) st.video("https://example.com/myvideo.mp4", format="video/mp4") Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration! PreviousStreamlit CropperA simple image cropper for Streamlit. Created by @turner-anderson.from streamlit_cropper import st_cropper st_cropper(img, realtime_update=realtime_update, box_color=box_color, aspect_ratio=aspect_ratio) Image CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates streamlit_image_coordinates("https://placekitten.com/200/300") Streamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl("https://assets5.lottiefiles.com/packages/lf20_V9t630.json") st_lottie(lottie_hello, key="hello") Streamlit WebrtcHandling and transmitting real-time video/audio streams with Streamlit. Created by @whitphx.from streamlit_webrtc import webrtc_streamer webrtc_streamer(key="sample") Drawable CanvasProvides a sketching canvas using Fabric.js. Created by @andfanilo.from streamlit_drawable_canvas import st_canvas st_canvas(fill_color="rgba(255, 165, 0, 0.3)", stroke_width=stroke_width, stroke_color=stroke_color, background_color=bg_color, background_image=Image.open(bg_image) if bg_image else None, update_streamlit=realtime_update, height=150, drawing_mode=drawing_mode, point_display_radius=point_display_radius if drawing_mode == 'point' else 0, key="canvas",) Image ComparisonCompare images with a slider using JuxtaposeJS. Created by @fcakyon.from streamlit_image_comparison import image_comparison image_comparison(img1="image1.jpg", img2="image2.jpg",) Streamlit CropperA simple image cropper for Streamlit. Created by @turner-anderson.from streamlit_cropper import st_cropper st_cropper(img, realtime_update=realtime_update, box_color=box_color, aspect_ratio=aspect_ratio) Image CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates streamlit_image_coordinates("https://placekitten.com/200/300") Streamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl("https://assets5.lottiefiles.com/packages/lf20_V9t630.json") st_lottie(lottie_hello, key="hello") Streamlit WebrtcHandling and transmitting real-time video/audio streams with Streamlit. Created by @whitphx.from streamlit_webrtc import webrtc_streamer webrtc_streamer(key="sample") Drawable CanvasProvides a sketching canvas using Fabric.js. Created by @andfanilo.from streamlit_drawable_canvas import st_canvas st_canvas(fill_color="rgba(255, 165, 0, 0.3)", stroke_width=stroke_width, stroke_color=stroke_color, background_color=bg_color, background_image=Image.open(bg_image) if bg_image else None, update_streamlit=realtime_update, height=150, drawing_mode=drawing_mode, point_display_radius=point_display_radius if drawing_mode == 'point' else 0, key="canvas",) Image ComparisonCompare images with a slider using JuxtaposeJS. Created by @fcakyon.from streamlit_image_comparison import image_comparison image_comparison(img1="image1.jpg", img2="image2.jpg",) Streamlit CropperA simple image cropper for Streamlit. Created by @turner-anderson.from streamlit_cropper import st_cropper st_cropper(img, realtime_update=realtime_update, box_color=box_color, aspect_ratio=aspect_ratio) Image CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates streamlit_image_coordinates("https://placekitten.com/200/300") Streamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl("https://assets5.lottiefiles.com/packages/lf20_V9t630.json") st_lottie(lottie_hello, key="hello") Next Layouts and containers ColumnsInsert containers laid out as side-by-side columns.col1, col2 = st.columns(2) col1.write("this is column 1") col2.write("this is column 2") ContainerInsert a multi-element container.c = st.container() st.write("This will show last") c.write("This will show first") c.write("This will show second") Modal dialogsInsert a modal dialog that can rerun independently from the rest of the script.@st.experimental_dialog("Sign up") def email_form(): name = st.text_input("Name") email = st.text_input("Email") EmptyInsert a single-element container.c = st.empty() st.write("This will show last") c.write("This will be replaced") c.write("This will show first") ExpanderInsert a multi-element container that can be expanded/collapsed.with st.expander("Open to see more"): st.write("This is more content") PopoverInsert a multi-element popover container that can be opened/closed.with st.popover("Settings"): st.checkbox("Show completed") SidebarDisplay items in a sidebar.st.sidebar.write("This lives in the sidebar") st.sidebar.button("Click me!") TabsInsert containers separated into tabs.tab1, tab2 = st.tabs(["Tab 1", "Tab2"]) tab1.write("this is tab 1") tab2.write("this is tab 2") Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration!Streamlit ElementsCreate a draggable and resizable dashboard in Streamlit. Created by @okls.from streamlit_elements import elements, mui, html with elements("new_element"): mui.Typography("Hello world") PydanticAuto-generate Streamlit UI from Pydantic Models and Dataclasses. Created by @lukasmasuch.import streamlit_pydantic as sp sp.pydantic_form(key="my_form", model=ExampleModel) Streamlit PagesAn experimental version of Streamlit Multi-Page Apps. Created by @blackary.from st_pages import Page, show_pages, add_page_title show_pages([ Page("streamlit_app.py", "Home", "🏠"), Page("other_pages/page2.py", "Page 2", ":books:"), ]) Chat elements Streamlit provides a few commands to help you build conversational apps. These chat elements are designed to be used in conjunction with each other, but you can also use them separately. st.chat_message lets you insert a chat message container into the app so you can display messages from the user or the app. Chat containers can contain other Streamlit elements, including charts, tables, text, and more. st.chat_input lets you display a chat input widget so the user can type in a message. Chat inputDisplay a chat input widget.prompt = st.chat_input("Say something") if prompt: st.write(f"The user has sent: {prompt}") Chat messageInsert a chat message container.import numpy as np with st.chat_message("user"): st.write("Hello 👋") st.line_chart(np.random.randn(30, 3)) Status containerDisplay output of long-running tasks in a container.with st.status('Running'): do_something_slow() st.write_streamWrite generators or streams to the app with a typewriter effect.st.write_stream(my_generator) st.write_stream(my_llm_stream) Status elements Progress barDisplay a progress bar.for i in range(101): st.progress(i) do_something_slow() SpinnerTemporarily displays a message while executing a block of code.with st.spinner("Please wait..."): do_something_slow() Status containerDisplay output of long-running tasks in a container.with st.status('Running'): do_something_slow() ToastBriefly displays a toast message in the bottom-right corner.st.toast('Butter!', icon='🧈') BalloonsDisplay celebratory balloons!do_something() # Celebrate when all done! st.balloons() SnowflakesDisplay celebratory snowflakes!do_something() # Celebrate when all done! st.snow() Success boxDisplay a success message.st.success("Match found!") Info boxDisplay an informational message.st.info("Dataset is updated every day at midnight.") Warning boxDisplay warning message.st.warning("Unable to fetch image. Skipping...") Error boxDisplay error message.st.error("We encountered an error") Exception outputDisplay an exception.e = RuntimeError("This is an exception of type RuntimeError") st.exception(e) Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration!StqdmThe simplest way to handle a progress bar in streamlit app. Created by @Wirg.from stqdm import stqdm for _ in stqdm(range(50)): sleep(0.5) Custom notification boxA custom notification box with the ability to close it out. Created by @Socvest.from streamlit_custom_notification_box import custom_notification_box styles = {'material-icons':{'color': 'red'}, 'text-icon-link-close-container': {'box-shadow': '#3896de 0px 4px'}, 'notification-text': {'':''}, 'close-button':{'':''}, 'link':{'':''}} custom_notification_box(icon='info', textDisplay='We are almost done with your registration...', externalLink='more info', url='#', styles=styles, key="foo") Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.let_it_rain import rain rain(emoji="🎈", font_size=54, falling_speed=5, animation_length="infinite",) App logic and configuration Navigation and pages Switch pageProgrammatically navigates to a specified page.st.switch_page("pages/my_page.py") Page linkDisplay a link to another page in a multipage app.st.page_link("app.py", label="Home", icon="🏠") st.page_link("pages/profile.py", label="My profile") Execution flow Modal dialogsInsert a modal dialog that can rerun independently from the rest of the script.@st.experimental_dialog("Sign up") def email_form(): name = st.text_input("Name") email = st.text_input("Email") FormsCreate a form that batches elements together with a “Submit" button.with st.form(key='my_form'): name = st.text_input("Name") email = st.text_input("Email") st.form_submit_button("Sign up") Partial rerunsDefine a fragment to rerun independently from the rest of the script.@st.experimental_fragment(run_every="10s") def fragment(): df = get_data() st.line_chart(df) Rerun scriptRerun the script immediately.st.rerun() Stop executionStops execution immediately.st.stop() Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration!AutorefreshForce a refresh without tying up a script. Created by @kmcgrady.from streamlit_autorefresh import st_autorefresh st_autorefresh(interval=2000, limit=100, key="fizzbuzzcounter") PydanticAuto-generate Streamlit UI from Pydantic Models and Dataclasses. Created by @lukasmasuch.import streamlit_pydantic as sp sp.pydantic_form(key="my_form", model=ExampleModel) Streamlit PagesAn experimental version of Streamlit Multi-Page Apps. Created by @blackary.from st_pages import Page, show_pages, add_page_title show_pages([ Page("streamlit_app.py", "Home", "🏠"), Page("other_pages/page2.py", "Page 2", ":books:"), ]) Caching and state Cache dataFunction decorator to cache functions that return data (e.g. dataframe transforms, database queries, ML inference).@st.cache_data def long_function(param1, param2): # Perform expensive computation here or # fetch data from the web here return data Cache resourceFunction decorator to cache functions that return global resources (e.g. database connections, ML models).@st.cache_resource def init_model(): # Return a global resource here return pipeline( "sentiment-analysis", model="distilbert-base-uncased-finetuned-sst-2-english" ) Session stateSession state is a way to share variables between reruns, for each user session.st.session_state['key'] = value Query parametersGet, set, or clear the query parameters that are shown in the browser's URL bar.st.query_params[key] = value st.query_params.clear() Connections and databases Setup your connection Create a connectionConnect to a data source or APIconn = st.connection('pets_db', type='sql') pet_owners = conn.query('select * from pet_owners') st.dataframe(pet_owners) Built-in connections SnowflakeConnectionA connection to Snowflake.conn = st.connection('snowflake') SQLConnectionA connection to a SQL database using SQLAlchemy.conn = st.connection('sql') Build your own connections Connection base classBuild your own connection with BaseConnection.class MyConnection(BaseConnection[myconn.MyConnection]): def _connect(self, **kwargs) -> MyConnection: return myconn.connect(**self._secrets, **kwargs) def query(self, query): return self._instance.query(query) Secrets management Secrets singletonAccess secrets from a local TOML file.key = st.secrets["OpenAI_key"] Secrets fileSave your secrets in a per-project or per-profile TOML file.OpenAI_key = "<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/share-apps-with-viewers-outside-organization#share-your-app-on-social-media
DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudremoveGet startedaddDeploy your appaddManage your appaddShare your appremoveEmbed your appSearch indexabilityShare previewsManage your accountaddTroubleshootingStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Deploy/Streamlit Community Cloud/Share your appShare your app Now that your app is deployed you can easily share it and collaborate on it. But first, let's take a moment and do a little joy dance for getting that app deployed! 🕺💃 Your app is now live at a fixed URL, so go wild and share it with whomever you want. Your app will inherit permissions from your GitHub repo, meaning that if your repo is private your app will be private and if your repo is public your app will be public. If you want to change that you can simply do so from the app settings menu. You are only allowed one private app at a time. If you've deployed from a private repository, you will have to make that app public or delete it before you can deploy another app from a private repository. Only developers can change your app between public and private. Make your app public or private Share your public app Share your private app Make your app public or private If you deployed your app from a public repository, your app will be public by default. If you deployed your app from a private repository, you will need to make the app public if you want to freely share it with the community at large. Set privacy from your app settings Access your App settings and go to the "Sharing" section. Set your app's privacy under "Who can view this app." Select "This app is public and searchable" to make your app public. Select "Only specific people can view this app" to make your app private. Set privacy from the share button From your app at <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/deploy/sign-in-without-sso#sign-in-with-google
DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudremoveGet startedaddDeploy your appaddManage your appaddShare your appaddManage your accountremoveSign in & sign outWorkspace settingsManage your GitHub connectionUpdate your emailDelete your accountTroubleshootingStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Deploy/Streamlit Community Cloud/Manage your account/Sign in & sign outSign in & sign out Once you've created your account, you can sign in to share.streamlit.io and follow the steps below. Sign in with Google Visit share.streamlit.io and click "Continue with Google". Enter your Google account credentials. If your account is already linked to GitHub, you may be immediately prompted to sign in with GitHub. Once you have signed in, you can Explore your workspace!. 🎈 Sign in with GitHub Visit share.streamlit.io and click "Continue with GitHub". Enter your GitHub credentials. Once you have signed in to GitHub, you can Explore your workspace!. 🎈 Sign in with Email Visit share.streamlit.io and enter the email you used to create your Streamlit Community Cloud account. Click "Continue with email". You will see a confirmation message asking you to check your email. Check your inbox for an email with the subject "Sign in to Streamlit Cloud". Click the link in the email to sign in to Streamlit Community Cloud. Note that this link will expire in 15 minutes and can only be used once. Once you click the link in your email, you can Explore your workspace!. 🎈 Sign out of your account From your workspace, click on your workspace name in the upper-right corner. Click "Sign out". Previous: Manage your accountNext: Workspace settingsforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy
https://docs.streamlit.io/deploy/tutorials/kubernetes#introduction
DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsremoveDockerKubernetesschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Deploy/Other platforms/KubernetesDeploy Streamlit using Kubernetes Introduction So you have an amazing app and you want to start sharing it with other people, what do you do? You have a few options. First, where do you want to run your Streamlit app, and how do you want to access it? On your corporate network - Most corporate networks are closed to the outside world. You typically use a VPN to log onto your corporate network and access resources there. You could run your Streamlit app on a server in your corporate network for security reasons, to ensure that only folks internal to your company can access it. On the cloud - If you'd like to access your Streamlit app from outside of a corporate network, or share your app with folks outside of your home network or laptop, you might choose this option. In this case, it'll depend on your hosting provider. We have community-submitted guides from Heroku, AWS, and other providers. Wherever you decide to deploy your app, you will first need to containerize it. This guide walks you through using Kubernetes to deploy your app. If you prefer Docker see Deploy Streamlit using Docker. Prerequisites Install Docker Engine Install the gcloud CLI Install Docker Engine If you haven't already done so, install Docker on your server. Docker provides .deb and .rpm packages from many Linux distributions, including: Debian Ubuntu Verify that Docker Engine is installed correctly by running the hello-world Docker image: sudo docker run hello-world starTipFollow Docker's official post-installation steps for Linux to run Docker as a non-root user, so that you don't have to preface the docker command with sudo. Install the gcloud CLI In this guide, we will orchestrate Docker containers with Kubernetes and host docker images on the Google Container Registry (GCR). As GCR is a Google-supported Docker registry, we need to register gcloud as the Docker credential helper. Follow the official documentation to Install the gcloud CLI and initialize it. Create a Docker container We need to create a docker container which contains all the dependencies and the application code. Below you can see the entrypoint, i.e. the command run when the container starts, and the Dockerfile definition. Create an entrypoint script Create a run.sh script containing the following: #!/bin/bash APP_PID= stopRunningProcess() { # Based on https://linuxconfig.org/how-to-propagate-a-signal-to-child-processes-from-a-bash-script if test ! "${APP_PID}" = '' && ps -p ${APP_PID} > /dev/null ; then > /proc/1/fd/1 echo "Stopping ${COMMAND_PATH} which is running with process ID ${APP_PID}" kill -TERM ${APP_PID} > /proc/1/fd/1 echo "Waiting for ${COMMAND_PATH} to process SIGTERM signal" wait ${APP_PID} > /proc/1/fd/1 echo "All processes have stopped running" else > /proc/1/fd/1 echo "${COMMAND_PATH} was not started when the signal was sent or it has already been stopped" fi } trap stopRunningProcess EXIT TERM source ${VIRTUAL_ENV}/bin/activate streamlit run ${HOME}/app/streamlit_app.py & APP_ID=${!} wait ${APP_ID} Create a Dockerfile Docker builds images by reading the instructions from a Dockerfile. A Dockerfile is a text document that contains all the commands a user could call on the command line to assemble an image. Learn more in the Dockerfile reference. The docker build command builds an image from a Dockerfile. The docker run command first creates a container over the specified image, and then starts it using the specified command. Here's an example Dockerfile that you can add to the root of your directory. FROM python:3.8-slim RUN groupadd --gid 1000 appuser \ && useradd --uid 1000 --gid 1000 -ms /bin/bash appuser RUN pip3 install --no-cache-dir --upgrade \ pip \ virtualenv RUN apt-get update && apt-get install -y \ build-essential \ software-properties-common \ git USER appuser WORKDIR /home/appuser RUN git clone https://github.com/streamlit/streamlit-example.git app ENV VIRTUAL_ENV=/home/appuser/venv RUN virtualenv ${VIRTUAL_ENV} RUN . ${VIRTUAL_ENV}/bin/activate && pip install -r app/requirements.txt EXPOSE 8501 COPY run.sh /home/appuser ENTRYPOINT ["./run.sh"] priority_highImportantAs mentioned in Development flow, for Streamlit version 1.10.0 and higher, Streamlit apps cannot be run from the root directory of Linux distributions. Your main script should live in a directory other than the root directory. If you try to run a Streamlit app from the root directory, Streamlit will throw a FileNotFoundError: [Errno 2] No such file or directory error. For more information, see GitHub issue #5239.If you are using Streamlit version 1.10.0 or higher, you must set the WORKDIR to a directory other than the root directory. For example, you can set the WORKDIR to /home/appuser as shown in the example Dockerfile above. Build a Docker image Put the above files (run.sh and Dockerfile) in the same folder and build the docker image: docker build --platform linux/amd64 -t gcr.io/$GCP_PROJECT_ID/k8s-streamlit:test . priority_highImportantReplace $GCP_PROJECT_ID in the above command with the name of your Google Cloud project. Upload the Docker image to a container registry The next step is to upload the Docker image to a container registry. In this example, we will use the Google Container Registry (GCR). Start by enabling the Container Registry API. Sign in to Google Cloud and navigate to your project’s Container Registry and click Enable. We can now build the Docker image from the previous step and push it to our project’s GCR. Be sure to replace $GCP_PROJECT_ID in the docker push command with the name of your project: gcloud auth configure-docker docker push gcr.io/$GCP_PROJECT_ID/k8s-streamlit:test Create a Kubernetes deployment For this step you will need a: Running Kubernetes service Custom domain for which you can generate a TLS certificate DNS service where you can configure your custom domain to point to the application IP As the image was uploaded to the container registry in the previous step, we can run it in Kubernetes using the below configurations. Install and run Kubernetes Make sure your Kubernetes client, kubectl, is installed and running on your machine. Configure a Google OAuth Client and oauth2-proxy For configuring the Google OAuth Client, please see Google Auth Provider. Configure oauth2-proxy to use the desired OAuth Provider Configuration and update the oath2-proxy config in the config map. The below configuration contains a ouath2-proxy sidecar container which handles the authentication with Google. You can learn more from the oauth2-proxy repository. Create a Kubernetes configuration file Create a YAML configuration file named k8s-streamlit.yaml: apiVersion: v1 kind: ConfigMap metadata: name: streamlit-configmap data: oauth2-proxy.cfg: |- http_address = "0.0.0.0:4180" upstreams = ["http://127.0.0.1:8501/"] email_domains = ["*"] client_id = "<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/knowledge-base/dependencies/install-package-not-pypi-conda-available-github#specify-a-tag
DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Knowledge base/Installing dependencies/How to install a package not on PyPI or Conda but available on GitHubHow to install a package not on PyPI/Conda but available on GitHub Overview Are you trying to deploy your app to Streamlit Community Cloud, but don't know how to specify a Python dependency in your requirements file that is available on a public GitHub repo but not any package index like PyPI or Conda? If so, continue reading to find out how! Let's suppose you want to install SomePackage and its Python dependencies from GitHub, a hosting service for the popular version control system (VCS) Git. And suppose SomePackage is found at the the following URL: https://github.com/SomePackage.git. pip (via requirements.txt) supports installing from GitHub. This support requires a working executable to be available (for Git). It is used through a URL prefix: git+. Specify the GitHub web URL To install SomePackage, innclude the following in your requirements.txt file: git+https://github.com/SomePackage#egg=SomePackage You can even specify a "git ref" such as branch name, a commit hash or a tag name, as shown in the examples below. Specify a Git branch name Install SomePackage by specifying a branch name such as main, master, develop, etc, in requirements.txt: git+https://github.com/SomePackage.git@main#egg=SomePackage Specify a commit hash Install SomePackage by specifying a commit hash in requirements.txt: git+https://github.com/SomePackage.git@eb40b4ff6f7c5c1e4366cgfg0671291bge918#egg=SomePackage Specify a tag Install SomePackage by specifying a tag in requirements.txt: git+https://github.com/SomePackage.git@v1.1.0#egg=SomePackage Limitations It is currently not possible to install private packages from private GitHub repos using the URI form: git+https://{token}@github.com/user/project.git@{version} where version is a tag, a branch, or a commit. And token is a personal access token with read only permissions. Streamlit Community Cloud only supports installing public packages from public GitHub repos.Previous: Installing dependenciesNext: ImportError libGL.so.1 cannot open shared object file No such file or directoryforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy
https://docs.streamlit.io/develop/tutorials/databases/tableau
DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceaddTutorialsremoveExecution flowaddConnect to data sourcesremoveAWS S3BigQueryDeta BaseFirestoreopen_in_newGoogle Cloud StorageMicrosoft SQL ServerMongoDBMySQLNeonPostgreSQLPrivate Google SheetPublic Google SheetSnowflakeSupabaseTableauTiDBTigerGraphMultipage appsaddWork with LLMsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Develop/Tutorials/Connect to data sources/TableauConnect Streamlit to Tableau Introduction This guide explains how to securely access data on Tableau from Streamlit Community Cloud. It uses the tableauserverclient library and Streamlit's Secrets management. Create a Tableau site push_pinNoteIf you already have a database that you want to use, feel free to skip to the next step. For simplicity, we are using the cloud version of Tableau here but this guide works equally well for self-hosted deployments. First, sign up for Tableau Online or log in. Create a workbook or run one of the example workbooks under "Dashboard Starters". Create personal access tokens While the Tableau API allows authentication via username and password, you should use personal access tokens for a production app. Go to your Tableau Online homepage, create an access token and note down the token name and secret. push_pinNotePersonal access tokens will expire if not used after 15 consecutive days. Add token to your local app secrets Your local Streamlit app will read secrets from a file .streamlit/secrets.toml in your app's root directory. Create this file if it doesn't exist yet and add your token, the site name you created during setup, and the URL of your Tableau server like below: # .streamlit/secrets.toml [tableau] token_name = "xxx" token_secret = "xxx" server_url = "https://abc01.online.tableau.com/" site_id = "streamlitexample" # in your site's URL behind the server_url priority_highImportantAdd this file to .gitignore and don't commit it to your GitHub repo! Copy your app secrets to the cloud As the secrets.toml file above is not committed to GitHub, you need to pass its content to your deployed app (on Streamlit Community Cloud) separately. Go to the app dashboard and in the app's dropdown menu, click on Edit Secrets. Copy the content of secrets.toml into the text area. More information is available at Secrets management. Add tableauserverclient to your requirements file Add the tableauserverclient package to your requirements.txt file, preferably pinning its version (replace x.x.x with the version you want installed): # requirements.txt tableauserverclient==x.x.x Write your Streamlit app Copy the code below to your Streamlit app and run it. Note that this code just shows a few options of data you can get – explore the tableauserverclient library to find more! # streamlit_app.py import streamlit as st import tableauserverclient as TSC # Set up connection. tableau_auth = TSC.PersonalAccessTokenAuth( st.secrets["tableau"]["token_name"], st.secrets["tableau"]["personal_access_token"], st.secrets["tableau"]["site_id"], ) server = TSC.Server(st.secrets["tableau"]["server_url"], use_server_version=True) # Get various data. # Explore the tableauserverclient library for more options. # Uses st.cache_data to only rerun when the query changes or after 10 min. @st.cache_data(ttl=600) def run_query(): with server.auth.sign_in(tableau_auth): # Get all workbooks. workbooks, pagination_item = server.workbooks.get() workbooks_names = [w.name for w in workbooks] # Get views for first workbook. server.workbooks.populate_views(workbooks[0]) views_names = [v.name for v in workbooks[0].views] # Get image & CSV for first view of first workbook. view_item = workbooks[0].views[0] server.views.populate_image(view_item) server.views.populate_csv(view_item) view_name = view_item.name view_image = view_item.image # `view_item.csv` is a list of binary objects, convert to str. view_csv = b"".join(view_item.csv).decode("utf-8") return workbooks_names, views_names, view_name, view_image, view_csv workbooks_names, views_names, view_name, view_image, view_csv = run_query() # Print results. st.subheader("📓 Workbooks") st.write("Found the following workbooks:", ", ".join(workbooks_names)) st.subheader("👁️ Views") st.write( f"Workbook *{workbooks_names[0]}* has the following views:", ", ".join(views_names), ) st.subheader("🖼️ Image") st.write(f"Here's what view *{view_name}* looks like:") st.image(view_image, width=300) st.subheader("📊 Data") st.write(f"And here's the data for view *{view_name}*:") st.write(pd.read_csv(StringIO(view_csv))) See st.cache_data above? Without it, Streamlit would run the query every time the app reruns (e.g. on a widget interaction). With st.cache_data, it only runs when the query changes or after 10 minutes (that's what ttl is for). Watch out: If your database updates more frequently, you should adapt ttl or remove caching so viewers always see the latest data. Learn more in Caching. If everything worked out, your app should look like this (can differ based on your workbooks): Previous: SupabaseNext: TiDBforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy
https://docs.streamlit.io/develop/api-reference/caching-and-state/st.experimental_singleton#replay-static-st-elements-in-cache-decorated-functions
DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceremovePAGE ELEMENTSWrite and magicaddText elementsaddData elementsaddChart elementsaddInput widgetsaddMedia elementsaddLayouts and containersaddChat elementsaddStatus elementsaddThird-party componentsopen_in_newAPPLICATION LOGICNavigation and pagesaddExecution flowaddCaching and stateremovest.cache_datast.cache_resourcest.cachedeletest.session_statest.query_paramsst.experimental_get_query_paramsdeletest.experimental_set_query_paramsdeleteConnections and secretsaddCustom componentsaddUtilitiesaddConfigurationaddTOOLSApp testingaddCommand lineaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Develop/API reference/Caching and state/st.experimental_singletonpriority_highImportantThis is an experimental feature. Experimental features and their APIs may change or be removed at any time. To learn more, click here. st.experimental_singletonStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakedeleteDeprecation noticest.experimental_singleton was deprecated in version 1.18.0. Use st.cache_resource instead. Learn more in Caching.Decorator to cache functions that return global resources (e.g. database connections, ML models). Cached objects are shared across all users, sessions, and reruns. They must be thread-safe because they can be accessed from multiple threads concurrently. If thread safety is an issue, consider using st.session_state to store resources per session instead. You can clear a function's cache with func.clear() or clear the entire cache with st.cache_resource.clear(). To cache data, use st.cache_data instead. Learn more about caching at https://docs.streamlit.io/library/advanced-features/caching. Function signature[source] st.experimental_singleton(func, *, ttl, max_entries, show_spinner, validate, experimental_allow_widgets, hash_funcs=None) Parameters func (callable) The function that creates the cached resource. Streamlit hashes the function's source code. ttl (float, timedelta, str, or None) The maximum time to keep an entry in the cache. Can be one of: None if cache entries should never expire (default). A number specifying the time in seconds. A string specifying the time in a format supported by Pandas's Timedelta constructor, e.g. "1d", "1.5 days", or "1h23s". A timedelta object from Python's built-in datetime library, e.g. timedelta(days=1). max_entries (int or None) The maximum number of entries to keep in the cache, or None for an unbounded cache. When a new entry is added to a full cache, the oldest cached entry will be removed. Defaults to None. show_spinner (bool or str) Enable the spinner. Default is True to show a spinner when there is a "cache miss" and the cached resource is being created. If string, value of show_spinner param will be used for spinner text. validate (callable or None) An optional validation function for cached data. validate is called each time the cached value is accessed. It receives the cached value as its only parameter and it must return a boolean. If validate returns False, the current cached value is discarded, and the decorated function is called to compute a new value. This is useful e.g. to check the health of database connections. experimental_allow_widgets (bool) Allow widgets to be used in the cached function. Defaults to False. Support for widgets in cached functions is currently experimental. Setting this parameter to True may lead to excessive memory use since the widget value is treated as an additional input parameter to the cache. We may remove support for this option at any time without notice. hash_funcs (dict or None) Mapping of types or fully qualified names to hash functions. This is used to override the behavior of the hasher inside Streamlit's caching mechanism: when the hasher encounters an object, it will first check to see if its type matches a key in this dict and, if so, will use the provided function to generate a hash for it. See below for an example of how this can be used. Example import streamlit as st @st.cache_resource def get_database_session(url): # Create a database session object that points to the URL. return session s1 = get_database_session(SESSION_URL_1) # Actually executes the function, since this is the first time it was # encountered. s2 = get_database_session(SESSION_URL_1) # Does not execute the function. Instead, returns its previously computed # value. This means that now the connection object in s1 is the same as in s2. s3 = get_database_session(SESSION_URL_2) # This is a different URL, so the function executes. By default, all parameters to a cache_resource function must be hashable. Any parameter whose name begins with _ will not be hashed. You can use this as an "escape hatch" for parameters that are not hashable: import streamlit as st @st.cache_resource def get_database_session(_sessionmaker, url): # Create a database connection object that points to the URL. return connection s1 = get_database_session(create_sessionmaker(), DATA_URL_1) # Actually executes the function, since this is the first time it was # encountered. s2 = get_database_session(create_sessionmaker(), DATA_URL_1) # Does not execute the function. Instead, returns its previously computed # value - even though the _sessionmaker parameter was different # in both calls. A cache_resource function's cache can be procedurally cleared: import streamlit as st @st.cache_resource def get_database_session(_sessionmaker, url): # Create a database connection object that points to the URL. return connection fetch_and_clean_data.clear(_sessionmaker, "https://streamlit.io/") # Clear the cached entry for the arguments provided. get_database_session.clear() # Clear all cached entries for this function. To override the default hashing behavior, pass a custom hash function. You can do that by mapping a type (e.g. Person) to a hash function (str) like this: import streamlit as st from pydantic import BaseModel class Person(BaseModel): name: str @st.cache_resource(hash_funcs={Person: str}) def get_person_name(person: Person): return person.name Alternatively, you can map the type's fully-qualified name (e.g. "__main__.Person") to the hash function instead: import streamlit as st from pydantic import BaseModel class Person(BaseModel): name: str @st.cache_resource(hash_funcs={"__main__.Person": str}) def get_person_name(person: Person): return person.name st.experimental_singleton.clearStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakedeleteDeprecation noticest.experimental_singleton.clear was deprecated in version 1.18.0. Use st.cache_resource.clear instead. Learn more in Caching.Clear all cache_resource caches. Function signature[source] st.experimental_singleton.clear() Example In the example below, pressing the "Clear All" button will clear all singleton caches. i.e. Clears cached singleton objects from all functions decorated with @st.experimental_singleton. import streamlit as st from transformers import BertModel @st.experimental_singleton def get_database_session(url): # Create a database session object that points to the URL. return session @st.experimental_singleton def get_model(model_type): # Create a model of the specified type. return BertModel.from_pretrained(model_type) if st.button("Clear All"): # Clears all singleton caches: st.experimental_singleton.clear() Validating the cache The @st.experimental_singleton decorator is used to cache the output of a function, so that it only needs to be executed once. This can improve performance in certain situations, such as when a function takes a long time to execute or makes a network request. However, in some cases, the cached output may become invalid over time, such as when a database connection times out. To handle this, the @st.experimental_singleton decorator supports an optional validate parameter, which accepts a validation function that is called each time the cached output is accessed. If the validation function returns False, the cached output is discarded and the decorated function is executed again. Best Practices Use the validate parameter when the cached output may become invalid over time, such as when a database connection or an API key expires. Use the validate parameter judiciously, as it will add an additional overhead of calling the validation function each time the cached output is accessed. Make sure that the validation function is as fast as possible, as it will be called each time the cached output is accessed. Consider to validate cached data periodically, instead of each time it is accessed, to mitigate the performance impact. Handle errors that may occur during validation and provide a fallback mechanism if the validation fails. Replay static st elements in cache-decorated functions Functions decorated with @st.experimental_singleton can contain static st elements. When a cache-decorated function is executed, we record the element and block messages produced, so the elements will appear in the app even when execution of the function is skipped because the result was cached. In the example below, the @st.experimental_singleton decorator is used to cache the execution of the get_model function, that returns a 🤗 Hugging Face Transformers model. Notice the cached function also contains a st.bar_chart command, which will be replayed when the function is skipped because the result was cached. import numpy as np import pandas as pd import streamlit as st from transformers import AutoModel @st.experimental_singleton def get_model(model_type): # Contains a static element st.bar_chart st.bar_chart( np.random.rand(10, 1) ) # This will be recorded and displayed even when the function is skipped # Create a model of the specified type return AutoModel.from_pretrained(model_type) bert_model = get_model("distilbert-base-uncased") st.help(bert_model) # Display the model's docstring Supported static st elements in cache-decorated functions include: st.alert st.altair_chart st.area_chart st.audio st.bar_chart st.ballons st.bokeh_chart st.caption st.code st.components.v1.html st.components.v1.iframe st.container st.dataframe st.echo st.empty st.error st.exception st.expander st.experimental_get_query_params st.experimental_set_query_params st.form st.form_submit_button st.graphviz_chart st.help st.image st.info st.json st.latex st.line_chart st.markdown st.metric st.plotly_chart st.progress st.pydeck_chart st.snow st.spinner st.success st.table st.text st.vega_lite_chart st.video st.warning Replay input widgets in cache-decorated functions In addition to static elements, functions decorated with @st.experimental_singleton can also contain input widgets! Replaying input widgets is disabled by default. To enable it, you can set the experimental_allow_widgets parameter for @st.experimental_singleton to True. The example below enables widget replaying, and shows the use of a checkbox widget within a cache-decorated function. import streamlit as st # Enable widget replay @st.experimental_singleton(experimental_allow_widgets=True) def func(): # Contains an input widget st.checkbox("Works!") func() If the cache decorated function contains input widgets, but experimental_allow_widgets is set to False or unset, Streamlit will throw a CachedStFunctionWarning, like the one below: import streamlit as st # Widget replay is disabled by default @st.experimental_singleton def func(): # Streamlit will throw a CachedStFunctionWarning st.checkbox("Doesn't work") func() How widget replay works Let's demystify how widget replay in cache-decorated functions works and gain a conceptual understanding. Widget values are treated as additional inputs to the function, and are used to determine whether the function should be executed or not. Consider the following example: import streamlit as st @st.experimental_singleton(experimental_allow_widgets=True) def plus_one(x): y = x + 1 if st.checkbox("Nuke the value 💥"): st.write("Value was nuked, returning 0") y = 0 return y st.write(plus_one(2)) The plus_one function takes an integer x as input, and returns x + 1. The function also contains a checkbox widget, which is used to "nuke" the value of x. i.e. the return value of plus_one depends on the state of the checkbox: if it is checked, the function returns 0, otherwise it returns 3. In order to know which value the cache should return (in case of a cache hit), Streamlit treats the checkbox state (checked / unchecked) as an additional input to the function plus_one (just like x). If the user checks the checkbox (thereby changing its state), we look up the cache for the same value of x (2) and the same checkbox state (checked). If the cache contains a value for this combination of inputs, we return it. Otherwise, we execute the function and store the result in the cache. Let's now understand how enabling and disabling widget replay changes the behavior of the function. Widget replay disabled Widgets in cached functions throw a CachedStFunctionWarning and are ignored. Other static elements in cached functions replay as expected. Widget replay enabled Widgets in cached functions don't lead to a warning, and are replayed as expected. Interacting with a widget in a cached function will cause the function to be executed again, and the cache to be updated. Widgets in cached functions retain their state across reruns. Each unique combination of widget values is treated as a separate input to the function, and is used to determine whether the function should be executed or not. i.e. Each unique combination of widget values has its own cache entry; the cached function runs the first time and the saved value is used afterwards. Calling a cached function multiple times in one script run with the same arguments triggers a DuplicateWidgetID error. If the arguments to a cached function change, widgets from that function that render again retain their state. Changing the source code of a cached function invalidates the cache. Both st.experimental_singleton and st.experimental_memo support widget replay. Fundamentally, the behavior of a function with (supported) widgets in it doesn't change when it is decorated with @st.experimental_singleton or @st.experimental_memo. The only difference is that the function is only executed when we detect a cache "miss". Supported widgets All input widgets are supported in cache-decorated functions. The following is an exhaustive list of supported widgets: st.button st.camera_input st.checkbox st.color_picker st.date_input st.download_button st.file_uploader st.multiselect st.number_input st.radio st.selectbox st.select_slider st.slider st.text_area st.text_input st.time_input Previous: st.experimental_memoNext: st.session_stateforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy
https://docs.streamlit.io/develop/api-reference/connections/st.connections.experimentalbaseconnection#stconnectionsexperimentalbaseconnection
DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceremovePAGE ELEMENTSWrite and magicaddText elementsaddData elementsaddChart elementsaddInput widgetsaddMedia elementsaddLayouts and containersaddChat elementsaddStatus elementsaddThird-party componentsopen_in_newAPPLICATION LOGICNavigation and pagesaddExecution flowaddCaching and stateaddConnections and secretsremoveSECRETSst.secretssecrets.tomlCONNECTIONSst.connectionSnowflakeConnectionSQLConnectionBaseConnectionSnowparkConnectiondeleteCustom componentsaddUtilitiesaddConfigurationaddTOOLSApp testingaddCommand lineaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Develop/API reference/Connections and secrets/ExperimentalBaseConnectionpriority_highImportantThis is an experimental feature. Experimental features and their APIs may change or be removed at any time. To learn more, click here. starTipThis page only contains information on the st.connections.ExperimentalBaseConnection class. For a deeper dive into creating and managing data connections within Streamlit apps, read Connecting to data. st.connections.ExperimentalBaseConnectionStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakedeleteDeprecation noticest.connections.ExperimentalBaseConnection was deprecated in version 1.28.0. Use st.connections.BaseConnection instead.The abstract base class that all Streamlit Connections must inherit from. This base class provides connection authors with a standardized way to hook into the st.connection() factory function: connection authors are required to provide an implementation for the abstract method _connect in their subclasses. Additionally, it also provides a few methods/properties designed to make implementation of connections more convenient. See the docstrings for each of the methods of this class for more information Note While providing an implementation of _connect is technically all that's required to define a valid connection, connections should also provide the user with context-specific ways of interacting with the underlying connection object. For example, the first-party SQLConnection provides a query() method for reads and a session property for more complex operations. Class description[source] st.connections.ExperimentalBaseConnection(connection_name, **kwargs) Methods reset() Reset this connection so that it gets reinitialized the next time it's used. st.connections.ExperimentalBaseConnection.resetStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in Snowflakepriority_highWarningThis method did not exist in version 1.34.0 of Streamlit.Previous: SnowparkConnectionNext: Custom componentsforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy
https://docs.streamlit.io/knowledge-base/using-streamlit/how-to-get-row-selections#example
DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Knowledge base/FAQ/How do I get dataframe row selections from a user?How do I get dataframe row-selections from a user? At the moment, st.dataframe and st.data_editor do not natively support passing user-selected rows to the Python backend. We are working to support this in the future. For now, if you need to get row-selections from a user, you can accomplish this by adding an extra Checkbox column) to your dataframe and using st.data_editor. You can use this extra column to collect a user's selection(s). Example In the following example, we define a function which accepts a dataframe and returns the rows selected by a user. Within the function, the dataframe is copied to prevent mutating it. We insert a temporary "Select" column into the copied dataframe before passing the copied data into st.data_editor. We have disabled editing for all other columns, but you can make them editable if desired. After filtering the dataframe and dropping the temporary column, our function returns the selected rows. import streamlit as st import numpy as np import pandas as pd df = pd.DataFrame( { "Animal": ["Lion", "Elephant", "Giraffe", "Monkey", "Zebra"], "Habitat": ["Savanna", "Forest", "Savanna", "Forest", "Savanna"], "Lifespan (years)": [15, 60, 25, 20, 25], "Average weight (kg)": [190, 5000, 800, 10, 350], } ) def dataframe_with_selections(df): df_with_selections = df.copy() df_with_selections.insert(0, "Select", False) # Get dataframe row-selections from user with st.data_editor edited_df = st.data_editor( df_with_selections, hide_index=True, column_config={"Select": st.column_config.CheckboxColumn(required=True)}, disabled=df.columns, ) # Filter the dataframe using the temporary column, then drop the column selected_rows = edited_df[edited_df.Select] return selected_rows.drop('Select', axis=1) selection = dataframe_with_selections(df) st.write("Your selection:") st.write(selection) Previous: How to download a Pandas DataFrame as a CSV?Next: How do I upgrade to the latest version of Streamlit?forumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy
https://docs.streamlit.io/knowledge-base/dependencies/install-package-not-pypi-conda-available-github#overview
DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Knowledge base/Installing dependencies/How to install a package not on PyPI or Conda but available on GitHubHow to install a package not on PyPI/Conda but available on GitHub Overview Are you trying to deploy your app to Streamlit Community Cloud, but don't know how to specify a Python dependency in your requirements file that is available on a public GitHub repo but not any package index like PyPI or Conda? If so, continue reading to find out how! Let's suppose you want to install SomePackage and its Python dependencies from GitHub, a hosting service for the popular version control system (VCS) Git. And suppose SomePackage is found at the the following URL: https://github.com/SomePackage.git. pip (via requirements.txt) supports installing from GitHub. This support requires a working executable to be available (for Git). It is used through a URL prefix: git+. Specify the GitHub web URL To install SomePackage, innclude the following in your requirements.txt file: git+https://github.com/SomePackage#egg=SomePackage You can even specify a "git ref" such as branch name, a commit hash or a tag name, as shown in the examples below. Specify a Git branch name Install SomePackage by specifying a branch name such as main, master, develop, etc, in requirements.txt: git+https://github.com/SomePackage.git@main#egg=SomePackage Specify a commit hash Install SomePackage by specifying a commit hash in requirements.txt: git+https://github.com/SomePackage.git@eb40b4ff6f7c5c1e4366cgfg0671291bge918#egg=SomePackage Specify a tag Install SomePackage by specifying a tag in requirements.txt: git+https://github.com/SomePackage.git@v1.1.0#egg=SomePackage Limitations It is currently not possible to install private packages from private GitHub repos using the URI form: git+https://{token}@github.com/user/project.git@{version} where version is a tag, a branch, or a commit. And token is a personal access token with read only permissions. Streamlit Community Cloud only supports installing public packages from public GitHub repos.Previous: Installing dependenciesNext: ImportError libGL.so.1 cannot open shared object file No such file or directoryforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy
https://docs.streamlit.io/develop/tutorials/databases/tigergraph#copy-your-app-secrets-to-the-cloud
DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceaddTutorialsremoveExecution flowaddConnect to data sourcesremoveAWS S3BigQueryDeta BaseFirestoreopen_in_newGoogle Cloud StorageMicrosoft SQL ServerMongoDBMySQLNeonPostgreSQLPrivate Google SheetPublic Google SheetSnowflakeSupabaseTableauTiDBTigerGraphMultipage appsaddWork with LLMsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Develop/Tutorials/Connect to data sources/TigerGraphConnect Streamlit to TigerGraph Introduction This guide explains how to securely access a TigerGraph database from Streamlit Community Cloud. It uses the pyTigerGraph library and Streamlit's Secrets management. Create a TigerGraph Cloud Database First, follow the official tutorials to create a TigerGraph instance in TigerGraph Cloud, either as a blog or a video. Note your username, password, and subdomain. For this tutorial, we will be using the COVID-19 starter kit. When setting up your solution, select the “COVID-19 Analysis" option. Once it is started, ensure your data is downloaded and queries are installed. Add username and password to your local app secrets Your local Streamlit app will read secrets from a file .streamlit/secrets.toml in your app’s root directory. Create this file if it doesn’t exist yet and add your TigerGraph Cloud instance username, password, graph name, and subdomain as shown below: # .streamlit/secrets.toml [tigergraph] host = "https://xxx.i.tgcloud.io/" username = "xxx" password = "xxx" graphname = "xxx" priority_highImportantAdd this file to .gitignore and don't commit it to your GitHub repo! Copy your app secrets to the cloud As the secrets.toml file above is not committed to GitHub, you need to pass its content to your deployed app (on Streamlit Community Cloud) separately. Go to the app dashboard and in the app's dropdown menu, click on Edit Secrets. Copy the content of secrets.toml into the text area. More information is available at Secrets management. Add PyTigerGraph to your requirements file Add the pyTigerGraph package to your requirements.txt file, preferably pinning its version (replace x.x.x with the version you want installed): # requirements.txt pyTigerGraph==x.x.x Write your Streamlit app Copy the code below to your Streamlit app and run it. Make sure to adapt the name of your graph and query. # streamlit_app.py import streamlit as st import pyTigerGraph as tg # Initialize connection. conn = tg.TigerGraphConnection(**st.secrets["tigergraph"]) conn.apiToken = conn.getToken(conn.createSecret()) # Pull data from the graph by running the "mostDirectInfections" query. # Uses st.cache_data to only rerun when the query changes or after 10 min. @st.cache_data(ttl=600) def get_data(): most_infections = conn.runInstalledQuery("mostDirectInfections")[0]["Answer"][0] return most_infections["v_id"], most_infections["attributes"] items = get_data() # Print results. st.title(f"Patient {items[0]} has the most direct infections") for key, val in items[1].items(): st.write(f"Patient {items[0]}'s {key} is {val}.") See st.cache_data above? Without it, Streamlit would run the query every time the app reruns (e.g. on a widget interaction). With st.cache_data, it only runs when the query changes or after 10 minutes (that's what ttl is for). Watch out: If your database updates more frequently, you should adapt ttl or remove caching so viewers always see the latest data. Learn more in Caching. If everything worked out (and you used the example data we created above), your app should look like this: Previous: TiDBNext: Multipage appsforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy
https://docs.streamlit.io/deploy/streamlit-community-cloud/get-started/quickstart#stop-or-delete-your-codespace
DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudremoveGet startedremoveQuickstartCreate your accountConnect your GitHub accountExplore your workspaceFork and edit a public appTrust and securityDeploy your appaddManage your appaddShare your appaddManage your accountaddTroubleshootingStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Deploy/Streamlit Community Cloud/Get started/QuickstartQuickstart This is a concise set of steps to create your Streamlit Community Cloud account, deploy a sample app, and start editing it with GitHub Codespaces. For other options and complete explanations, start with Create your account. You will be signing in to your Google and GitHub accounts during this process. If you do not already have these accounts, you can create them before you begin. If you do not want to use a Google account, you can create your account with any email. Sign up for Streamlit Community Cloud Go to share.streamlit.io/signup. Click "Continue with Google". Enter your Google credentials and follow Google's authentication prompts. After authenticating with Google, click "Connect GitHub account". Enter your GitHub credentials and follow GitHub's authentication prompts. Click "Authorize streamlit". To finish, fill in your information and click "Continue" at the bottom of the screen. You will be taken to your Streamlit workspace. If you see a warning icon (warning) next to "Settings" in the upper-right corner, this will be addressed in the next steps. Create a new app with GitHub Codespaces Click the down arrow (expand_more) to expand the options under "New App". Click "Create new app with GitHub Codespaces". You will be prompted that "Streamlit is requesting additional permissions". Click "Authorize streamlit". The Streamlit Hello repository will be forked to your GitHub account. Fill in a repository name and click "Create!" Click "Create new codespace" to confirm the creation of a codespace on your GitHub account. Read more about GitHub Codespaces the learn about monthly limits for free use and paid plans. Wait for GitHub to set up your codespace. GitHub will automatically execute the commands to launch your Streamlit app within your codespace. Your app will be visible in a "Simple Browser" on the right. This may take a minute to complete from when your codespace first appears on screen. Edit your app in GitHub Codespaces Go to the app's main file (Hello.py) and add some text to the title in st.write(). Try typing ":balloon:" at the beginning. Files are automatically saved in your codespace with each edit. Click "Always rerun" in the upper-right corner of your app to automatically rerun with each edit. See your edits and keep going! Stop or delete your codespace When you are done, remember to stop your codespace on GitHub to avoid any undesired use of your capacity. Go to github.com/codespaces. At the bottom of the page, all your codespaces are listed. Click the overflow menu icon (more_horiz) for your codespace. Click "Stop codespace" if you'd like to return to your work later. Otherwise, click "Delete." Congratulations! You just deployed an app to Streamlit Community Cloud. 🎉 Head back to your workspace at share.streamlit.io/ and deploy another Streamlit app. Previous: Get startedNext: Create your accountforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy
https://docs.streamlit.io/develop/tutorials/llms#build-llm-apps
DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceaddTutorialsremoveExecution flowaddConnect to data sourcesaddMultipage appsaddWork with LLMsremoveBuild a basic LLM chat appBuild an LLM app using LangChainQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Develop/Tutorials/Work with LLMsBuild LLM apps Build a basic chat appBuild a simple OpenAI chat app to get started with Streamlit's chat elements.Build an LLM app using LangChainBuild a chat app using the LangChain framework with OpenAI.Previous: Multipage appsNext: Build a basic LLM chat appforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy
https://docs.streamlit.io/develop/tutorials/databases/aws-s3#copy-your-app-secrets-to-the-cloud
DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceaddTutorialsremoveExecution flowaddConnect to data sourcesremoveAWS S3BigQueryDeta BaseFirestoreopen_in_newGoogle Cloud StorageMicrosoft SQL ServerMongoDBMySQLNeonPostgreSQLPrivate Google SheetPublic Google SheetSnowflakeSupabaseTableauTiDBTigerGraphMultipage appsaddWork with LLMsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Develop/Tutorials/Connect to data sources/AWS S3Connect Streamlit to AWS S3 Introduction This guide explains how to securely access files on AWS S3 from Streamlit Community Cloud. It uses Streamlit FilesConnection, the s3fs library and optionally Streamlit's Secrets management. Create an S3 bucket and add a file push_pinNoteIf you already have a bucket that you want to use, feel free to skip to the next step. First, sign up for AWS or log in. Go to the S3 console and create a new bucket: Navigate to the upload section of your new bucket: And note down the "AWS Region" for later. In this example, it's us-east-1, but it may differ for you. Next, upload the following CSV file, which contains some example data: myfile.csv Create access keys Go to the AWS console, create access keys as shown below and copy the "Access Key ID" and "Secret Access Key": starTipAccess keys created as a root user have wide-ranging permissions. In order to make your AWS account more secure, you should consider creating an IAM account with restricted permissions and using its access keys. More information here. Set up your AWS credentials locally Streamlit FilesConnection and s3fs will read and use your existing AWS credentials and configuration if available - such as from an ~/.aws/credentials file or environment variables. If you don't already have this set up, or plan to host the app on Streamlit Community Cloud, you should specify the credentials from a file .streamlit/secrets.toml in your app's root directory or your home directory. Create this file if it doesn't exist yet and add to it the access key ID, access key secret, and the AWS default region you noted down earlier, as shown below: # .streamlit/secrets.toml AWS_ACCESS_KEY_ID = "xxx" AWS_SECRET_ACCESS_KEY = "xxx" AWS_DEFAULT_REGION = "xxx" priority_highImportantBe sure to replace xxx above with the values you noted down earlier, and add this file to .gitignore so you don't commit it to your GitHub repo! Copy your app secrets to the cloud To host your app on Streamlit Community Cloud, you will need to pass your credentials to your deployed app via secrets. Go to the app dashboard and in the app's dropdown menu, click on Edit Secrets. Copy the content of secrets.toml above into the text area. More information is available at Secrets management. Add FilesConnection and s3fs to your requirements file Add the FilesConnection and s3fs packages to your requirements.txt file, preferably pinning the versions (replace x.x.x with the version you want installed): # requirements.txt s3fs==x.x.x st-files-connection Write your Streamlit app Copy the code below to your Streamlit app and run it. Make sure to adapt the name of your bucket and file. Note that Streamlit automatically turns the access keys from your secrets file into environment variables, where s3fs searches for them by default. # streamlit_app.py import streamlit as st from st_files_connection import FilesConnection # Create connection object and retrieve file contents. # Specify input format is a csv and to cache the result for 600 seconds. conn = st.connection('s3', type=FilesConnection) df = conn.read("testbucket-jrieke/myfile.csv", input_format="csv", ttl=600) # Print results. for row in df.itertuples(): st.write(f"{row.Owner} has a :{row.Pet}:") See st.connection above? This handles secrets retrieval, setup, result caching and retries. By default, read() results are cached without expiring. In this case, we set ttl=600 to ensure the file contents is cached for no longer than 10 minutes. You can also set ttl=0 to disable caching. Learn more in Caching. If everything worked out (and you used the example file given above), your app should look like this: Previous: Connect to data sourcesNext: BigQueryforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy
https://docs.streamlit.io/develop/api-reference/data/st.dataframe#configuring-columns
DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceremovePAGE ELEMENTSWrite and magicaddText elementsaddData elementsremovest.dataframest.data_editorst.column_configaddst.tablest.metricst.jsonChart elementsaddInput widgetsaddMedia elementsaddLayouts and containersaddChat elementsaddStatus elementsaddThird-party componentsopen_in_newAPPLICATION LOGICNavigation and pagesaddExecution flowaddCaching and stateaddConnections and secretsaddCustom componentsaddUtilitiesaddConfigurationaddTOOLSApp testingaddCommand lineaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Develop/API reference/Data elements/st.dataframestarTipThis page only contains information on the st.dataframe API. For an overview of working with dataframes read Dataframes. If you want to let users interactively edit dataframes, check out st.data_editor. st.dataframeStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeDisplay a dataframe as an interactive table. This command works with dataframes from Pandas, PyArrow, Snowpark, and PySpark. It can also display several other types that can be converted to dataframes, e.g. numpy arrays, lists, sets and dictionaries. Function signature[source] st.dataframe(data=None, width=None, height=None, *, use_container_width=False, hide_index=None, column_order=None, column_config=None) Parameters data (pandas.DataFrame, pandas.Series, pandas.Styler, pandas.Index, pyarrow.Table, numpy.ndarray, pyspark.sql.DataFrame, snowflake.snowpark.dataframe.DataFrame, snowflake.snowpark.table.Table, Iterable, dict, or None) The data to display. If 'data' is a pandas.Styler, it will be used to style its underlying DataFrame. Streamlit supports custom cell values and colors. It does not support some of the more exotic pandas styling features, like bar charts, hovering, and captions. width (int or None) Desired width of the dataframe expressed in pixels. If None, the width will be automatically calculated based on the column content. height (int or None) Desired height of the dataframe expressed in pixels. If None, a default height is used. use_container_width (bool) If True, set the dataframe width to the width of the parent container. This takes precedence over the width argument. hide_index (bool or None) Whether to hide the index column(s). If None (default), the visibility of index columns is automatically determined based on the data. column_order (Iterable of str or None) Specifies the display order of columns. This also affects which columns are visible. For example, column_order=("col2", "col1") will display 'col2' first, followed by 'col1', and will hide all other non-index columns. If None (default), the order is inherited from the original data structure. column_config (dict or None) Configures how columns are displayed, e.g. their title, visibility, type, or format. This needs to be a dictionary where each key is a column name and the value is one of: None to hide the column. A string to set the display label of the column. One of the column types defined under st.column_config, e.g. st.column_config.NumberColumn("Dollar values”, format=”$ %d") to show a column as dollar amounts. See more info on the available column types and config options here. To configure the index column(s), use _index as the column name. Examples import streamlit as st import pandas as pd import numpy as np df = pd.DataFrame(np.random.randn(50, 20), columns=("col %d" % i for i in range(20))) st.dataframe(df) # Same as st.write(df) Built with Streamlit 🎈Fullscreen open_in_new You can also pass a Pandas Styler object to change the style of the rendered DataFrame: import streamlit as st import pandas as pd import numpy as np df = pd.DataFrame(np.random.randn(10, 20), columns=("col %d" % i for i in range(20))) st.dataframe(df.style.highlight_max(axis=0)) Built with Streamlit 🎈Fullscreen open_in_new Or you can customize the dataframe via column_config, hide_index, or column_order: import random import pandas as pd import streamlit as st df = pd.DataFrame( { "name": ["Roadmap", "Extras", "Issues"], "url": ["https://roadmap.streamlit.app", "https://extras.streamlit.app", "https://issues.streamlit.app"], "stars": [random.randint(0, 1000) for _ in range(3)], "views_history": [[random.randint(0, 5000) for _ in range(30)] for _ in range(3)], } ) st.dataframe( df, column_config={ "name": "App name", "stars": st.column_config.NumberColumn( "Github Stars", help="Number of stars on GitHub", format="%d ⭐", ), "url": st.column_config.LinkColumn("App URL"), "views_history": st.column_config.LineChartColumn( "Views (past 30 days)", y_min=0, y_max=5000 ), }, hide_index=True, ) Built with Streamlit 🎈Fullscreen open_in_new st.dataframe supports the use_container_width parameter to stretch across the full container width: import pandas as pd import streamlit as st # Cache the dataframe so it's only loaded once @st.cache_data def load_data(): return pd.DataFrame( { "first column": [1, 2, 3, 4], "second column": [10, 20, 30, 40], } ) # Boolean to resize the dataframe, stored as a session state variable st.checkbox("Use container width", value=False, key="use_container_width") df = load_data() # Display the dataframe and allow the user to stretch the dataframe # across the full width of the container, based on the checkbox value st.dataframe(df, use_container_width=st.session_state.use_container_width) Built with Streamlit 🎈Fullscreen open_in_new element.add_rowsStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeConcatenate a dataframe to the bottom of the current one. Function signature[source] element.add_rows(data=None, **kwargs) Parameters data (pandas.DataFrame, pandas.Styler, pyarrow.Table, numpy.ndarray, pyspark.sql.DataFrame, snowflake.snowpark.dataframe.DataFrame, Iterable, dict, or None) Table to concat. Optional. **kwargs (pandas.DataFrame, numpy.ndarray, Iterable, dict, or None) The named dataset to concat. Optional. You can only pass in 1 dataset (including the one in the data parameter). Example import streamlit as st import pandas as pd import numpy as np df1 = pd.DataFrame(np.random.randn(50, 20), columns=("col %d" % i for i in range(20))) my_table = st.table(df1) df2 = pd.DataFrame(np.random.randn(50, 20), columns=("col %d" % i for i in range(20))) my_table.add_rows(df2) # Now the table shown in the Streamlit app contains the data for # df1 followed by the data for df2. You can do the same thing with plots. For example, if you want to add more data to a line chart: # Assuming df1 and df2 from the example above still exist... my_chart = st.line_chart(df1) my_chart.add_rows(df2) # Now the chart shown in the Streamlit app contains the data for # df1 followed by the data for df2. And for plots whose datasets are named, you can pass the data with a keyword argument where the key is the name: my_chart = st.vega_lite_chart({ 'mark': 'line', 'encoding': {'x': 'a', 'y': 'b'}, 'datasets': { 'some_fancy_name': df1, # <-- named dataset }, 'data': {'name': 'some_fancy_name'}, }), my_chart.add_rows(some_fancy_name=df2) # <-- name used as keyword Interactivity Dataframes displayed with st.dataframe are interactive. End users can sort, resize, search, and copy data to their clipboard. For on overview of features, read our Dataframes guide. Configuring columns You can configure the display and editing behavior of columns in st.dataframe and st.data_editor via the Column configuration API. We have developed the API to let you add images, charts, and clickable URLs in dataframe and data editor columns. Additionally, you can make individual columns editable, set columns as categorical and specify which options they can take, hide the index of the dataframe, and much more. Built with Streamlit 🎈Fullscreen open_in_newPrevious: Data elementsNext: st.data_editorforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy
https://docs.streamlit.io/en/0.68.0/api.html#status-elements
DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceremovePAGE ELEMENTSWrite and magicaddText elementsaddData elementsaddChart elementsaddInput widgetsaddMedia elementsaddLayouts and containersaddChat elementsaddStatus elementsaddThird-party componentsopen_in_newAPPLICATION LOGICNavigation and pagesaddExecution flowaddCaching and stateaddConnections and secretsaddCustom componentsaddUtilitiesaddConfigurationaddTOOLSApp testingaddCommand lineaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Develop/API referenceAPI reference Streamlit makes it easy for you to visualize, mutate, and share data. The API reference is organized by activity type, like displaying data or optimizing performance. Each section includes methods associated with the activity type, including examples. Browse our API below and click to learn more about any of our available commands! 🎈 Display almost anything Write and magic st.writeWrite arguments to the app.st.write("Hello **world**!") st.write(my_data_frame) st.write(my_mpl_figure) st.write_streamWrite generators or streams to the app with a typewriter effect.st.write_stream(my_generator) st.write_stream(my_llm_stream) MagicAny time Streamlit sees either a variable or literal value on its own line, it automatically writes that to your app using st.write"Hello **world**!" my_data_frame my_mpl_figure Text elements MarkdownDisplay string formatted as Markdown.st.markdown("Hello **world**!") TitleDisplay text in title formatting.st.title("The app title") HeaderDisplay text in header formatting.st.header("This is a header") SubheaderDisplay text in subheader formatting.st.subheader("This is a subheader") CaptionDisplay text in small font.st.caption("This is written small caption text") Code blockDisplay a code block with optional syntax highlighting.st.code("a = 1234") EchoDisplay some code in the app, then execute it. Useful for tutorials.with st.echo(): st.write('This code will be printed') LaTeXDisplay mathematical expressions formatted as LaTeX.st.latex("\int a x^2 \,dx") Preformatted textWrite fixed-width and preformatted text.st.text("Hello world") DividerDisplay a horizontal rule.st.divider() Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration! PreviousTagsAdd tags to your Streamlit apps. Created by @gagan3012.st_tags(label='# Enter Keywords:', text='Press enter to add more', value=['Zero', 'One', 'Two'], suggestions=['five', 'six', 'seven', 'eight', 'nine', 'three', 'eleven', 'ten', 'four'], maxtags = 4, key='1') NLUApply text mining on a dataframe. Created by @JohnSnowLabs.nlu.load('sentiment').predict('I love NLU! <3') Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.mention(label="An awesome Streamlit App", icon="streamlit", url="https://extras.streamlit.app",) Annotated textDisplay annotated text in Streamlit apps. Created by @tvst.annotated_text("This ", ("is", "verb"), " some ", ("annotated", "adj"), ("text", "noun"), " for those of ", ("you", "pronoun"), " who ", ("like", "verb"), " this sort of ", ("thing", "noun"), ".") Drawable CanvasProvides a sketching canvas using Fabric.js. Created by @andfanilo.st_canvas(fill_color="rgba(255, 165, 0, 0.3)", stroke_width=stroke_width, stroke_color=stroke_color, background_color=bg_color, background_image=Image.open(bg_image) if bg_image else None, update_streamlit=realtime_update, height=150, drawing_mode=drawing_mode, point_display_radius=point_display_radius if drawing_mode == 'point' else 0, key="canvas",) TagsAdd tags to your Streamlit apps. Created by @gagan3012.st_tags(label='# Enter Keywords:', text='Press enter to add more', value=['Zero', 'One', 'Two'], suggestions=['five', 'six', 'seven', 'eight', 'nine', 'three', 'eleven', 'ten', 'four'], maxtags = 4, key='1') NLUApply text mining on a dataframe. Created by @JohnSnowLabs.nlu.load('sentiment').predict('I love NLU! <3') Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.mention(label="An awesome Streamlit App", icon="streamlit", url="https://extras.streamlit.app",) Annotated textDisplay annotated text in Streamlit apps. Created by @tvst.annotated_text("This ", ("is", "verb"), " some ", ("annotated", "adj"), ("text", "noun"), " for those of ", ("you", "pronoun"), " who ", ("like", "verb"), " this sort of ", ("thing", "noun"), ".") Drawable CanvasProvides a sketching canvas using Fabric.js. Created by @andfanilo.st_canvas(fill_color="rgba(255, 165, 0, 0.3)", stroke_width=stroke_width, stroke_color=stroke_color, background_color=bg_color, background_image=Image.open(bg_image) if bg_image else None, update_streamlit=realtime_update, height=150, drawing_mode=drawing_mode, point_display_radius=point_display_radius if drawing_mode == 'point' else 0, key="canvas",) TagsAdd tags to your Streamlit apps. Created by @gagan3012.st_tags(label='# Enter Keywords:', text='Press enter to add more', value=['Zero', 'One', 'Two'], suggestions=['five', 'six', 'seven', 'eight', 'nine', 'three', 'eleven', 'ten', 'four'], maxtags = 4, key='1') NLUApply text mining on a dataframe. Created by @JohnSnowLabs.nlu.load('sentiment').predict('I love NLU! <3') Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.mention(label="An awesome Streamlit App", icon="streamlit", url="https://extras.streamlit.app",) Next Data elements DataframesDisplay a dataframe as an interactive table.st.dataframe(my_data_frame) Data editorDisplay a data editor widget.edited = st.data_editor(df, num_rows="dynamic") Column configurationConfigure the display and editing behavior of dataframes and data editors.st.column_config.NumberColumn("Price (in USD)", min_value=0, format="$%d") Static tablesDisplay a static table.st.table(my_data_frame) MetricsDisplay a metric in big bold font, with an optional indicator of how the metric changed.st.metric("My metric", 42, 2) Dicts and JSONDisplay object or string as a pretty-printed JSON string.st.json(my_dict) Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration! PreviousImage CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates value = streamlit_image_coordinates("https://placekitten.com/200/300") st.write(value) Plotly EventsMake Plotly charts interactive!. Created by @null-jones.from streamlit_plotly_events import plotly_events fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.metric_cards import style_metric_cards col3.metric(label="No Change", value=5000, delta=0) style_metric_cards() Streamlit AggridImplementation of Ag-Grid component for Streamlit. Created by @PablocFonseca.df = pd.DataFrame({'col1': [1, 2, 3], 'col2': [4, 5, 6]}) grid_return = AgGrid(df, editable=True) new_df = grid_return['data'] Streamlit FoliumStreamlit Component for rendering Folium maps. Created by @randyzwitch.m = folium.Map(location=[39.949610, -75.150282], zoom_start=16) folium.Marker([39.949610, -75.150282], popup="Liberty Bell", tooltip="Liberty Bell").add_to(m) st_data = st_folium(m, width=725) Pandas ProfilingPandas profiling component for Streamlit. Created by @okld.df = pd.read_csv("https://storage.googleapis.com/tf-datasets/titanic/train.csv") pr = df.profile_report() st_profile_report(pr) Image CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates value = streamlit_image_coordinates("https://placekitten.com/200/300") st.write(value) Plotly EventsMake Plotly charts interactive!. Created by @null-jones.from streamlit_plotly_events import plotly_events fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.metric_cards import style_metric_cards col3.metric(label="No Change", value=5000, delta=0) style_metric_cards() Streamlit AggridImplementation of Ag-Grid component for Streamlit. Created by @PablocFonseca.df = pd.DataFrame({'col1': [1, 2, 3], 'col2': [4, 5, 6]}) grid_return = AgGrid(df, editable=True) new_df = grid_return['data'] Streamlit FoliumStreamlit Component for rendering Folium maps. Created by @randyzwitch.m = folium.Map(location=[39.949610, -75.150282], zoom_start=16) folium.Marker([39.949610, -75.150282], popup="Liberty Bell", tooltip="Liberty Bell").add_to(m) st_data = st_folium(m, width=725) Pandas ProfilingPandas profiling component for Streamlit. Created by @okld.df = pd.read_csv("https://storage.googleapis.com/tf-datasets/titanic/train.csv") pr = df.profile_report() st_profile_report(pr) Image CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates value = streamlit_image_coordinates("https://placekitten.com/200/300") st.write(value) Plotly EventsMake Plotly charts interactive!. Created by @null-jones.from streamlit_plotly_events import plotly_events fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.metric_cards import style_metric_cards col3.metric(label="No Change", value=5000, delta=0) style_metric_cards() Next Chart elements Simple area chartsDisplay an area chart.st.area_chart(my_data_frame) Simple bar chartsDisplay a bar chart.st.bar_chart(my_data_frame) Simple line chartsDisplay a line chart.st.line_chart(my_data_frame) Simple scatter chartsDisplay a line chart.st.scatter_chart(my_data_frame) Scatterplots on mapsDisplay a map with points on it.st.map(my_data_frame) MatplotlibDisplay a matplotlib.pyplot figure.st.pyplot(my_mpl_figure) AltairDisplay a chart using the Altair library.st.altair_chart(my_altair_chart) Vega-LiteDisplay a chart using the Vega-Lite library.st.vega_lite_chart(my_vega_lite_chart) PlotlyDisplay an interactive Plotly chart.st.plotly_chart(my_plotly_chart) BokehDisplay an interactive Bokeh chart.st.bokeh_chart(my_bokeh_chart) PyDeckDisplay a chart using the PyDeck library.st.pydeck_chart(my_pydeck_chart) GraphVizDisplay a graph using the dagre-d3 library.st.graphviz_chart(my_graphviz_spec) Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration! PreviousStreamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl("https://assets5.lottiefiles.com/packages/lf20_V9t630.json") st_lottie(lottie_hello, key="hello") Plotly EventsMake Plotly charts interactive!. Created by @null-jones.fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.chart += get_annotations_chart(annotations=[("Mar 01, 2008", "Pretty good day for GOOG"), ("Dec 01, 2007", "Something's going wrong for GOOG & AAPL"), ("Nov 01, 2008", "Market starts again thanks to..."), ("Dec 01, 2009", "Small crash for GOOG after..."),],) st.altair_chart(chart, use_container_width=True) PlostA deceptively simple plotting library for Streamlit. Created by @tvst.import plost plost.line_chart(my_dataframe, x='time', y='stock_value', color='stock_name',) HiPlotHigh dimensional Interactive Plotting. Created by @facebookresearch.data = [{'dropout':0.1, 'lr': 0.001, 'loss': 10.0, 'optimizer': 'SGD'}, {'dropout':0.15, 'lr': 0.01, 'loss': 3.5, 'optimizer': 'Adam'}, {'dropout':0.3, 'lr': 0.1, 'loss': 4.5, 'optimizer': 'Adam'}] hip.Experiment.from_iterable(data).display() EChartsHigh dimensional Interactive Plotting. Created by @andfanilo.from streamlit_echarts import st_echarts st_echarts(options=options) Streamlit FoliumStreamlit Component for rendering Folium maps. Created by @randyzwitch.m = folium.Map(location=[39.949610, -75.150282], zoom_start=16) st_data = st_folium(m, width=725) Spacy-StreamlitspaCy building blocks and visualizers for Streamlit apps. Created by @explosion.models = ["en_core_web_sm", "en_core_web_md"] spacy_streamlit.visualize(models, "Sundar Pichai is the CEO of Google.") Streamlit AgraphA Streamlit Graph Vis, based on react-grah-vis. Created by @ChrisDelClea.from streamlit_agraph import agraph, Node, Edge, Config agraph(nodes=nodes, edges=edges, config=config) Streamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl("https://assets5.lottiefiles.com/packages/lf20_V9t630.json") st_lottie(lottie_hello, key="hello") Plotly EventsMake Plotly charts interactive!. Created by @null-jones.fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.chart += get_annotations_chart(annotations=[("Mar 01, 2008", "Pretty good day for GOOG"), ("Dec 01, 2007", "Something's going wrong for GOOG & AAPL"), ("Nov 01, 2008", "Market starts again thanks to..."), ("Dec 01, 2009", "Small crash for GOOG after..."),],) st.altair_chart(chart, use_container_width=True) PlostA deceptively simple plotting library for Streamlit. Created by @tvst.import plost plost.line_chart(my_dataframe, x='time', y='stock_value', color='stock_name',) HiPlotHigh dimensional Interactive Plotting. Created by @facebookresearch.data = [{'dropout':0.1, 'lr': 0.001, 'loss': 10.0, 'optimizer': 'SGD'}, {'dropout':0.15, 'lr': 0.01, 'loss': 3.5, 'optimizer': 'Adam'}, {'dropout':0.3, 'lr': 0.1, 'loss': 4.5, 'optimizer': 'Adam'}] hip.Experiment.from_iterable(data).display() EChartsHigh dimensional Interactive Plotting. Created by @andfanilo.from streamlit_echarts import st_echarts st_echarts(options=options) Streamlit FoliumStreamlit Component for rendering Folium maps. Created by @randyzwitch.m = folium.Map(location=[39.949610, -75.150282], zoom_start=16) st_data = st_folium(m, width=725) Spacy-StreamlitspaCy building blocks and visualizers for Streamlit apps. Created by @explosion.models = ["en_core_web_sm", "en_core_web_md"] spacy_streamlit.visualize(models, "Sundar Pichai is the CEO of Google.") Streamlit AgraphA Streamlit Graph Vis, based on react-grah-vis. Created by @ChrisDelClea.from streamlit_agraph import agraph, Node, Edge, Config agraph(nodes=nodes, edges=edges, config=config) Streamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl("https://assets5.lottiefiles.com/packages/lf20_V9t630.json") st_lottie(lottie_hello, key="hello") Plotly EventsMake Plotly charts interactive!. Created by @null-jones.fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.chart += get_annotations_chart(annotations=[("Mar 01, 2008", "Pretty good day for GOOG"), ("Dec 01, 2007", "Something's going wrong for GOOG & AAPL"), ("Nov 01, 2008", "Market starts again thanks to..."), ("Dec 01, 2009", "Small crash for GOOG after..."),],) st.altair_chart(chart, use_container_width=True) Next Input widgets ButtonDisplay a button widget.clicked = st.button("Click me") Download buttonDisplay a download button widget.st.download_button("Download file", file) Form buttonDisplay a form submit button. For use with st.form.st.form_submit_button("Sign up") Link buttonDisplay a link button.st.link_button("Go to gallery", url) Page linkDisplay a link to another page in a multipage app.st.page_link("app.py", label="Home", icon="🏠") st.page_link("pages/profile.py", label="My profile") CheckboxDisplay a checkbox widget.selected = st.checkbox("I agree") Color pickerDisplay a color picker widget.color = st.color_picker("Pick a color") MultiselectDisplay a multiselect widget. The multiselect widget starts as empty.choices = st.multiselect("Buy", ["milk", "apples", "potatoes"]) RadioDisplay a radio button widget.choice = st.radio("Pick one", ["cats", "dogs"]) SelectboxDisplay a select widget.choice = st.selectbox("Pick one", ["cats", "dogs"]) Select-sliderDisplay a slider widget to select items from a list.size = st.select_slider("Pick a size", ["S", "M", "L"]) ToggleDisplay a toggle widget.activated = st.toggle("Activate") Number inputDisplay a numeric input widget.choice = st.number_input("Pick a number", 0, 10) SliderDisplay a slider widget.number = st.slider("Pick a number", 0, 100) Date inputDisplay a date input widget.date = st.date_input("Your birthday") Time inputDisplay a time input widget.time = st.time_input("Meeting time") Chat inputDisplay a chat input widget.prompt = st.chat_input("Say something") if prompt: st.write(f"The user has sent: {prompt}") Text-areaDisplay a multi-line text input widget.text = st.text_area("Text to translate") Text inputDisplay a single-line text input widget.name = st.text_input("First name") Data editorDisplay a data editor widget.edited = st.experimental_data_editor(df, num_rows="dynamic") File UploaderDisplay a file uploader widget.data = st.file_uploader("Upload a CSV") Camera inputDisplay a widget that allows users to upload images directly from a camera.image = st.camera_input("Take a picture") Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration! PreviousStreamlit ChatStreamlit Component for a Chatbot UI. Created by @AI-Yash.from streamlit_chat import message message("My message") message("Hello bot!", is_user=True) # align's the message to the right Streamlit Option MenuSelect a single item from a list of options in a menu. Created by @victoryhb.from streamlit_option_menu import option_menu option_menu("Main Menu", ["Home", 'Settings'], icons=['house', 'gear'], menu_icon="cast", default_index=1) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.stoggle import stoggle stoggle( "Click me!", """🥷 Surprise! Here's some additional content""",) Streamlit ElementsCreate a draggable and resizable dashboard in Streamlit. Created by @okls.from streamlit_elements import elements, mui, html with elements("new_element"): mui.Typography("Hello world") TagsAdd tags to your Streamlit apps. Created by @gagan3012.from streamlit_tags import st_tags st_tags(label='# Enter Keywords:', text='Press enter to add more', value=['Zero', 'One', 'Two'], suggestions=['five', 'six', 'seven', 'eight', 'nine', 'three', 'eleven', 'ten', 'four'], maxtags = 4, key='1') StqdmThe simplest way to handle a progress bar in streamlit app. Created by @Wirg.from stqdm import stqdm for _ in stqdm(range(50)): sleep(0.5) TimelineDisplay a Timeline in Streamlit apps using TimelineJS. Created by @innerdoc.from streamlit_timeline import timeline with open('example.json', "r") as f: timeline(f.read(), height=800) Camera input liveAlternative for st.camera_input which returns the webcam images live. Created by @blackary.from camera_input_live import camera_input_live image = camera_input_live() st.image(value) Streamlit AceAce editor component for Streamlit. Created by @okld.from streamlit_ace import st_ace content = st_ace() content Streamlit ChatStreamlit Component for a Chatbot UI. Created by @AI-Yash.from streamlit_chat import message message("My message") message("Hello bot!", is_user=True) # align's the message to the right Streamlit Option MenuSelect a single item from a list of options in a menu. Created by @victoryhb.from streamlit_option_menu import option_menu option_menu("Main Menu", ["Home", 'Settings'], icons=['house', 'gear'], menu_icon="cast", default_index=1) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.stoggle import stoggle stoggle( "Click me!", """🥷 Surprise! Here's some additional content""",) Streamlit ElementsCreate a draggable and resizable dashboard in Streamlit. Created by @okls.from streamlit_elements import elements, mui, html with elements("new_element"): mui.Typography("Hello world") TagsAdd tags to your Streamlit apps. Created by @gagan3012.from streamlit_tags import st_tags st_tags(label='# Enter Keywords:', text='Press enter to add more', value=['Zero', 'One', 'Two'], suggestions=['five', 'six', 'seven', 'eight', 'nine', 'three', 'eleven', 'ten', 'four'], maxtags = 4, key='1') StqdmThe simplest way to handle a progress bar in streamlit app. Created by @Wirg.from stqdm import stqdm for _ in stqdm(range(50)): sleep(0.5) TimelineDisplay a Timeline in Streamlit apps using TimelineJS. Created by @innerdoc.from streamlit_timeline import timeline with open('example.json', "r") as f: timeline(f.read(), height=800) Camera input liveAlternative for st.camera_input which returns the webcam images live. Created by @blackary.from camera_input_live import camera_input_live image = camera_input_live() st.image(value) Streamlit AceAce editor component for Streamlit. Created by @okld.from streamlit_ace import st_ace content = st_ace() content Streamlit ChatStreamlit Component for a Chatbot UI. Created by @AI-Yash.from streamlit_chat import message message("My message") message("Hello bot!", is_user=True) # align's the message to the right Streamlit Option MenuSelect a single item from a list of options in a menu. Created by @victoryhb.from streamlit_option_menu import option_menu option_menu("Main Menu", ["Home", 'Settings'], icons=['house', 'gear'], menu_icon="cast", default_index=1) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.stoggle import stoggle stoggle( "Click me!", """🥷 Surprise! Here's some additional content""",) Next Media elements ImageDisplay an image or list of images.st.image(numpy_array) st.image(image_bytes) st.image(file) st.image("https://example.com/myimage.jpg") AudioDisplay an audio player.st.audio(numpy_array) st.audio(audio_bytes) st.audio(file) st.audio("https://example.com/myaudio.mp3", format="audio/mp3") VideoDisplay a video player.st.video(numpy_array) st.video(video_bytes) st.video(file) st.video("https://example.com/myvideo.mp4", format="video/mp4") Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration! PreviousStreamlit CropperA simple image cropper for Streamlit. Created by @turner-anderson.from streamlit_cropper import st_cropper st_cropper(img, realtime_update=realtime_update, box_color=box_color, aspect_ratio=aspect_ratio) Image CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates streamlit_image_coordinates("https://placekitten.com/200/300") Streamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl("https://assets5.lottiefiles.com/packages/lf20_V9t630.json") st_lottie(lottie_hello, key="hello") Streamlit WebrtcHandling and transmitting real-time video/audio streams with Streamlit. Created by @whitphx.from streamlit_webrtc import webrtc_streamer webrtc_streamer(key="sample") Drawable CanvasProvides a sketching canvas using Fabric.js. Created by @andfanilo.from streamlit_drawable_canvas import st_canvas st_canvas(fill_color="rgba(255, 165, 0, 0.3)", stroke_width=stroke_width, stroke_color=stroke_color, background_color=bg_color, background_image=Image.open(bg_image) if bg_image else None, update_streamlit=realtime_update, height=150, drawing_mode=drawing_mode, point_display_radius=point_display_radius if drawing_mode == 'point' else 0, key="canvas",) Image ComparisonCompare images with a slider using JuxtaposeJS. Created by @fcakyon.from streamlit_image_comparison import image_comparison image_comparison(img1="image1.jpg", img2="image2.jpg",) Streamlit CropperA simple image cropper for Streamlit. Created by @turner-anderson.from streamlit_cropper import st_cropper st_cropper(img, realtime_update=realtime_update, box_color=box_color, aspect_ratio=aspect_ratio) Image CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates streamlit_image_coordinates("https://placekitten.com/200/300") Streamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl("https://assets5.lottiefiles.com/packages/lf20_V9t630.json") st_lottie(lottie_hello, key="hello") Streamlit WebrtcHandling and transmitting real-time video/audio streams with Streamlit. Created by @whitphx.from streamlit_webrtc import webrtc_streamer webrtc_streamer(key="sample") Drawable CanvasProvides a sketching canvas using Fabric.js. Created by @andfanilo.from streamlit_drawable_canvas import st_canvas st_canvas(fill_color="rgba(255, 165, 0, 0.3)", stroke_width=stroke_width, stroke_color=stroke_color, background_color=bg_color, background_image=Image.open(bg_image) if bg_image else None, update_streamlit=realtime_update, height=150, drawing_mode=drawing_mode, point_display_radius=point_display_radius if drawing_mode == 'point' else 0, key="canvas",) Image ComparisonCompare images with a slider using JuxtaposeJS. Created by @fcakyon.from streamlit_image_comparison import image_comparison image_comparison(img1="image1.jpg", img2="image2.jpg",) Streamlit CropperA simple image cropper for Streamlit. Created by @turner-anderson.from streamlit_cropper import st_cropper st_cropper(img, realtime_update=realtime_update, box_color=box_color, aspect_ratio=aspect_ratio) Image CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates streamlit_image_coordinates("https://placekitten.com/200/300") Streamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl("https://assets5.lottiefiles.com/packages/lf20_V9t630.json") st_lottie(lottie_hello, key="hello") Next Layouts and containers ColumnsInsert containers laid out as side-by-side columns.col1, col2 = st.columns(2) col1.write("this is column 1") col2.write("this is column 2") ContainerInsert a multi-element container.c = st.container() st.write("This will show last") c.write("This will show first") c.write("This will show second") Modal dialogsInsert a modal dialog that can rerun independently from the rest of the script.@st.experimental_dialog("Sign up") def email_form(): name = st.text_input("Name") email = st.text_input("Email") EmptyInsert a single-element container.c = st.empty() st.write("This will show last") c.write("This will be replaced") c.write("This will show first") ExpanderInsert a multi-element container that can be expanded/collapsed.with st.expander("Open to see more"): st.write("This is more content") PopoverInsert a multi-element popover container that can be opened/closed.with st.popover("Settings"): st.checkbox("Show completed") SidebarDisplay items in a sidebar.st.sidebar.write("This lives in the sidebar") st.sidebar.button("Click me!") TabsInsert containers separated into tabs.tab1, tab2 = st.tabs(["Tab 1", "Tab2"]) tab1.write("this is tab 1") tab2.write("this is tab 2") Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration!Streamlit ElementsCreate a draggable and resizable dashboard in Streamlit. Created by @okls.from streamlit_elements import elements, mui, html with elements("new_element"): mui.Typography("Hello world") PydanticAuto-generate Streamlit UI from Pydantic Models and Dataclasses. Created by @lukasmasuch.import streamlit_pydantic as sp sp.pydantic_form(key="my_form", model=ExampleModel) Streamlit PagesAn experimental version of Streamlit Multi-Page Apps. Created by @blackary.from st_pages import Page, show_pages, add_page_title show_pages([ Page("streamlit_app.py", "Home", "🏠"), Page("other_pages/page2.py", "Page 2", ":books:"), ]) Chat elements Streamlit provides a few commands to help you build conversational apps. These chat elements are designed to be used in conjunction with each other, but you can also use them separately. st.chat_message lets you insert a chat message container into the app so you can display messages from the user or the app. Chat containers can contain other Streamlit elements, including charts, tables, text, and more. st.chat_input lets you display a chat input widget so the user can type in a message. Chat inputDisplay a chat input widget.prompt = st.chat_input("Say something") if prompt: st.write(f"The user has sent: {prompt}") Chat messageInsert a chat message container.import numpy as np with st.chat_message("user"): st.write("Hello 👋") st.line_chart(np.random.randn(30, 3)) Status containerDisplay output of long-running tasks in a container.with st.status('Running'): do_something_slow() st.write_streamWrite generators or streams to the app with a typewriter effect.st.write_stream(my_generator) st.write_stream(my_llm_stream) Status elements Progress barDisplay a progress bar.for i in range(101): st.progress(i) do_something_slow() SpinnerTemporarily displays a message while executing a block of code.with st.spinner("Please wait..."): do_something_slow() Status containerDisplay output of long-running tasks in a container.with st.status('Running'): do_something_slow() ToastBriefly displays a toast message in the bottom-right corner.st.toast('Butter!', icon='🧈') BalloonsDisplay celebratory balloons!do_something() # Celebrate when all done! st.balloons() SnowflakesDisplay celebratory snowflakes!do_something() # Celebrate when all done! st.snow() Success boxDisplay a success message.st.success("Match found!") Info boxDisplay an informational message.st.info("Dataset is updated every day at midnight.") Warning boxDisplay warning message.st.warning("Unable to fetch image. Skipping...") Error boxDisplay error message.st.error("We encountered an error") Exception outputDisplay an exception.e = RuntimeError("This is an exception of type RuntimeError") st.exception(e) Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration!StqdmThe simplest way to handle a progress bar in streamlit app. Created by @Wirg.from stqdm import stqdm for _ in stqdm(range(50)): sleep(0.5) Custom notification boxA custom notification box with the ability to close it out. Created by @Socvest.from streamlit_custom_notification_box import custom_notification_box styles = {'material-icons':{'color': 'red'}, 'text-icon-link-close-container': {'box-shadow': '#3896de 0px 4px'}, 'notification-text': {'':''}, 'close-button':{'':''}, 'link':{'':''}} custom_notification_box(icon='info', textDisplay='We are almost done with your registration...', externalLink='more info', url='#', styles=styles, key="foo") Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.let_it_rain import rain rain(emoji="🎈", font_size=54, falling_speed=5, animation_length="infinite",) App logic and configuration Navigation and pages Switch pageProgrammatically navigates to a specified page.st.switch_page("pages/my_page.py") Page linkDisplay a link to another page in a multipage app.st.page_link("app.py", label="Home", icon="🏠") st.page_link("pages/profile.py", label="My profile") Execution flow Modal dialogsInsert a modal dialog that can rerun independently from the rest of the script.@st.experimental_dialog("Sign up") def email_form(): name = st.text_input("Name") email = st.text_input("Email") FormsCreate a form that batches elements together with a “Submit" button.with st.form(key='my_form'): name = st.text_input("Name") email = st.text_input("Email") st.form_submit_button("Sign up") Partial rerunsDefine a fragment to rerun independently from the rest of the script.@st.experimental_fragment(run_every="10s") def fragment(): df = get_data() st.line_chart(df) Rerun scriptRerun the script immediately.st.rerun() Stop executionStops execution immediately.st.stop() Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration!AutorefreshForce a refresh without tying up a script. Created by @kmcgrady.from streamlit_autorefresh import st_autorefresh st_autorefresh(interval=2000, limit=100, key="fizzbuzzcounter") PydanticAuto-generate Streamlit UI from Pydantic Models and Dataclasses. Created by @lukasmasuch.import streamlit_pydantic as sp sp.pydantic_form(key="my_form", model=ExampleModel) Streamlit PagesAn experimental version of Streamlit Multi-Page Apps. Created by @blackary.from st_pages import Page, show_pages, add_page_title show_pages([ Page("streamlit_app.py", "Home", "🏠"), Page("other_pages/page2.py", "Page 2", ":books:"), ]) Caching and state Cache dataFunction decorator to cache functions that return data (e.g. dataframe transforms, database queries, ML inference).@st.cache_data def long_function(param1, param2): # Perform expensive computation here or # fetch data from the web here return data Cache resourceFunction decorator to cache functions that return global resources (e.g. database connections, ML models).@st.cache_resource def init_model(): # Return a global resource here return pipeline( "sentiment-analysis", model="distilbert-base-uncased-finetuned-sst-2-english" ) Session stateSession state is a way to share variables between reruns, for each user session.st.session_state['key'] = value Query parametersGet, set, or clear the query parameters that are shown in the browser's URL bar.st.query_params[key] = value st.query_params.clear() Connections and databases Setup your connection Create a connectionConnect to a data source or APIconn = st.connection('pets_db', type='sql') pet_owners = conn.query('select * from pet_owners') st.dataframe(pet_owners) Built-in connections SnowflakeConnectionA connection to Snowflake.conn = st.connection('snowflake') SQLConnectionA connection to a SQL database using SQLAlchemy.conn = st.connection('sql') Build your own connections Connection base classBuild your own connection with BaseConnection.class MyConnection(BaseConnection[myconn.MyConnection]): def _connect(self, **kwargs) -> MyConnection: return myconn.connect(**self._secrets, **kwargs) def query(self, query): return self._instance.query(query) Secrets management Secrets singletonAccess secrets from a local TOML file.key = st.secrets["OpenAI_key"] Secrets fileSave your secrets in a per-project or per-profile TOML file.OpenAI_key = "<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/execution-flow#execution-flow
DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceremovePAGE ELEMENTSWrite and magicaddText elementsaddData elementsaddChart elementsaddInput widgetsaddMedia elementsaddLayouts and containersaddChat elementsaddStatus elementsaddThird-party componentsopen_in_newAPPLICATION LOGICNavigation and pagesaddExecution flowremovest.dialogst.formst.form_submit_buttonst.fragmentst.rerunst.stopCaching and stateaddConnections and secretsaddCustom componentsaddUtilitiesaddConfigurationaddTOOLSApp testingaddCommand lineaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Develop/API reference/Execution flowExecution flow Change execution By default, Streamlit apps execute the script entirely, but we allow some functionality to handle control flow in your applications. Modal dialogsInsert a modal dialog that can rerun independently from the rest of the script.@st.experimental_dialog("Sign up") def email_form(): name = st.text_input("Name") email = st.text_input("Email") Partial rerunsDefine a fragment to rerun independently from the rest of the script.@st.experimental_fragment(run_every="10s") def fragment(): df = get_data() st.line_chart(df) Rerun scriptRerun the script immediately.st.rerun() Stop executionStops execution immediately.st.stop() Group multiple widgets By default, Streamlit reruns your script everytime a user interacts with your app. However, sometimes it's a better user experience to wait until a group of related widgets is filled before actually rerunning the script. That's what st.form is for! FormsCreate a form that batches elements together with a “Submit" button.with st.form(key='my_form'): name = st.text_input("Name") email = st.text_input("Email") st.form_submit_button("Sign up") Form submit buttonDisplay a form submit button.with st.form(key='my_form'): name = st.text_input("Name") email = st.text_input("Email") st.form_submit_button("Sign up") Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration!AutorefreshForce a refresh without tying up a script. Created by @kmcgrady.from streamlit_autorefresh import st_autorefresh st_autorefresh(interval=2000, limit=100, key="fizzbuzzcounter") PydanticAuto-generate Streamlit UI from Pydantic Models and Dataclasses. Created by @lukasmasuch.import streamlit_pydantic as sp sp.pydantic_form(key="my_form", model=ExampleModel) Streamlit PagesAn experimental version of Streamlit Multi-Page Apps. Created by @blackary.from st_pages import Page, show_pages, add_page_title show_pages([ Page("streamlit_app.py", "Home", "🏠"), Page("other_pages/page2.py", "Page 2", ":books:"), ]) Previous: Navigation and pagesNext: st.dialogforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy
https://docs.streamlit.io/develop/concepts/architecture/fragments#fragments-vs-caching
DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsremoveCOREArchitecture & executionremoveRunning your appStreamlit's architectureThe app chromeCachingSession StateFormsFragmentsWidget behaviorMultipage appsaddApp designaddADDITIONALConnections and secretsaddCustom componentsaddConfiguration and themingaddApp testingaddAPI referenceaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Develop/Concepts/Architecture & execution/FragmentsWorking with fragments and partial reruns Reruns are a central part of every Streamlit app. When users interact with widgets, your script reruns from top to bottom, and your app's frontend is updated. Streamlit provides several features to help you develop your app within this execution model. Streamlit version 1.33.0 introduced fragments to allow rerunning a portion of your code instead of your full script. As your app grows larger and more complex, these partial reruns help your app be efficient and performant. Fragments give you finer, easy-to-understand control over your app's execution flow. Before you read about fragments, we recommend having a basic understanding of caching, Session State, and forms. Use cases for fragments Fragments are versatile and applicable to a wide variety of circumstances. Here are just a few, common scenarios where fragments are useful: Your app has multiple visualizations and each one takes time to load, but you have a filter input that only updates one of them. You have a dynamic form that doesn't need to update the rest of your app (until the form is complete). You want to automatically update a single component or group of components to stream data. Defining and calling a fragment Streamlit provides a decorator (st.experimental_fragment) to turn any function into a fragment function. When you call a fragment function that contains a widget function, a user triggers a partial rerun instead of a full rerun when they interact with that fragment's widget. During a partial rerun, your fragment function is re-executed. Anything within the main body of your fragment is updated on the frontend, while the rest of your app remains the same. We'll describe fragments written across multiple containers later on. Here is a basic example of defining and calling a fragment function. Just like with caching, remember to call your function after defining it. import streamlit as st @st.experimental_fragment def fragment_function(): if st.button("Hi!"): st.write("Hi back!") fragment_function() If you want the main body of your fragment to appear in the sidebar or another container, call your fragment function inside a context manager. with st.sidebar: fragment_function() Partial rerun execution flow Consider the following code with the explanation and diagram below. import streamlit as st st.title("My Awesome App") @st.experimental_fragment() def toggle_and_text(): cols = st.columns(2) cols[0].toggle("Toggle") cols[1].text_area("Enter text") @st.experimental_fragment() def filter_and_file(): cols = st.columns(2) cols[0].checkbox("Filter") cols[1].file_uploader("Upload image") toggle_and_text() cols = st.columns(2) cols[0].selectbox("Select", [1,2,3], None) cols[1].button("Update") filter_and_file() When a user interacts with an input widget inside a fragment, only the fragment reruns instead of the full script. When a user interacts with an input widget outside a fragment, the full script reruns as usual. If you run the code above, the full script will run top to bottom on your app's initial load. If you flip the toggle button in your running app, the first fragment (toggle_and_text()) will rerun, redrawing the toggle and text area while leaving everything else unchanged. If you click the checkbox, the second fragment (filter_and_file()) will rerun and consequently redraw the checkbox and file uploader. Everything else remains unchanged. Finally, if you click the update button, the full script will rerun, and Streamlit will redraw everything. Fragment return values and interacting with the rest of your app Streamlit ignores fragment return values during fragment reruns, so defining return values for your fragment functions is not recommended. Instead, if your fragment needs to share data with the rest of your app, use Session State. Fragments are just functions in your script, so they can access Session State, imported modules, and other Streamlit elements like containers. If your fragment writes to any container created outside of itself, note the following difference in behavior: Elements drawn in the main body of your fragment are cleared and redrawn in place during a fragment rerun. Repeated fragment reruns will not cause additional elements to appear. Elements drawn to containers outside the main body of fragment will not be cleared with each fragment rerun. Instead, Streamlit will draw them additively and these elements will accumulate until the next full-script rerun. To prevent elements from accumulating in outside containers, use st.empty containers. For a related tutorial, see Create a fragment across multiple containers. If you need to trigger a full-script rerun from inside a fragment, call st.rerun. For a related tutorial, see Trigger a full-script rerun from inside a fragment. Automate fragment reruns st.experimental_fragment includes a convenient run_every parameter that causes the fragment to rerun automatically at the specified time interval. These reruns are in addition to any reruns (fragment or full-script) triggered by your user. The automatic fragment reruns will continue even if your user is not interacting with your app. This is a great way to show a live data stream or status on a running background job, efficiently updating your rendered data and only your rendered data. @st.experimental_fragment(run_every="10s") def auto_function(): # This will update every 10 seconds! df = get_latest_updates() st.line_chart(df) auto_function() For a related tutorial, see Start and stop a streaming fragment. Compare fragments to other Streamlit features Fragments vs forms Here is a comparison between fragments and forms: Forms allow users to interact with widgets without rerunning your app. Streamlit does not send user actions within a form to your app's Python backend until the form is submitted. Widgets within a form can not dynamically update other widgets (in or out of the form) in real-time. Fragments run independently from the rest of your code. As your users interact with fragment widgets, their actions are immediately processed by your app's Python backend and your fragment code is rerun. Widgets within a fragment can dynamically update other widgets within the same fragment in real-time. A form batches user input without interaction between any widgets. A fragment immediately processes user input but limits the scope of the rerun. Fragments vs callbacks Here is a comparison between fragments and callbacks: Callbacks allow you to execute a function at the beginning of a script rerun. A callback is a single prefix to your script rerun. Fragments allow you to rerun a portion of your script. A fragment is a repeatable postfix to your script, running each time a user interacts with a fragment widget, or automatically in sequence when run_every is set. When callbacks render elements to your page, they are rendered before the rest of your page elements. When fragments render elements to your page, they are updated with each fragment rerun (unless they are written to containers outside of the fragment, in which case they accumulate there). Fragments vs custom components Here is a comparison between fragments and custom components: Components are custom frontend code that can interact with the Python code, native elements, and widgets in your Streamlit app. Custom components extend what’s possible with Streamlit. They follow the normal Streamlit execution flow. Fragments are parts of your app that can rerun independently of the full app. Fragments can be composed of multiple Streamlit elements, widgets, or any Python code. A fragment can include one or more custom components. A custom component could not easily include a fragment! Fragments vs caching Here is a comparison between fragments and caching: Caching: allows you to skip over a function and return a previously computed value. When you use caching, you execute everything except the cached function (if you've already run it before). Fragments: allow you to freeze most of your app and just execute the fragment. When you use fragments, you execute only the fragment (when triggering a fragment rerun). Caching saves you from unnecessarily running a piece of your app while the rest runs. Fragments save you from running your full app when you only want to run one piece. Limitations and unsupported behavior Fragments can't detect a change in input values. It is best to use Session State for dynamic input and output for fragment functions. Calling fragments within fragments is unsupported. Using caching and fragments on the same function is unsupported. Previous: FormsNext: Widget behaviorforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy
https://docs.streamlit.io/develop/concepts/configuration
DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsremoveCOREArchitecture & executionaddMultipage appsaddApp designaddADDITIONALConnections and secretsaddCustom componentsaddConfiguration and themingremoveConfiguration optionsHTTPS supportServing static filesCustomize your themeApp testingaddAPI referenceaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Develop/Concepts/Configuration and themingConfigure and customize your app Configuration optionsUnderstand they types of options available to you through Streamlit configuration.HTTPS supportUnderstand how to configure SSL and TLS for your Streamlit app.Static file servingUnderstand how to host files alongside your app to make them accessible by URL. Use this if you want to point to files with raw HTML.ThemingUnderstand how to use the theming configuration options to customize the color and appearance of your app.Previous: Custom componentsNext: Configuration optionsforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy
https://docs.streamlit.io/develop/api-reference/widgets#other-input-elements
DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceremovePAGE ELEMENTSWrite and magicaddText elementsaddData elementsaddChart elementsaddInput widgetsremoveBUTTONSst.buttonst.download_buttonst.form_submit_buttonlinkst.link_buttonst.page_linkSELECTIONSst.checkboxst.color_pickerst.multiselectst.radiost.selectboxst.select_sliderst.toggleNUMERICst.number_inputst.sliderDATE & TIMEst.date_inputst.time_inputTEXTst.chat_inputlinkst.text_areast.text_inputMEDIA & FILESst.camera_inputst.data_editorlinkst.file_uploaderMedia elementsaddLayouts and containersaddChat elementsaddStatus elementsaddThird-party componentsopen_in_newAPPLICATION LOGICNavigation and pagesaddExecution flowaddCaching and stateaddConnections and secretsaddCustom componentsaddUtilitiesaddConfigurationaddTOOLSApp testingaddCommand lineaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Develop/API reference/Input widgetsInput widgets With widgets, Streamlit allows you to bake interactivity directly into your apps with buttons, sliders, text inputs, and more. Button elements ButtonDisplay a button widget.clicked = st.button("Click me") Download buttonDisplay a download button widget.st.download_button("Download file", file) Form buttonDisplay a form submit button. For use with st.form.st.form_submit_button("Sign up") Link buttonDisplay a link button.st.link_button("Go to gallery", url) Page linkDisplay a link to another page in a multipage app.st.page_link("app.py", label="Home", icon="🏠") st.page_link("pages/profile.py", label="My profile") Selection elements CheckboxDisplay a checkbox widget.selected = st.checkbox("I agree") ToggleDisplay a toggle widget.activated = st.toggle("Activate") RadioDisplay a radio button widget.choice = st.radio("Pick one", ["cats", "dogs"]) SelectboxDisplay a select widget.choice = st.selectbox("Pick one", ["cats", "dogs"]) MultiselectDisplay a multiselect widget. The multiselect widget starts as empty.choices = st.multiselect("Buy", ["milk", "apples", "potatoes"]) Select sliderDisplay a slider widget to select items from a list.size = st.select_slider("Pick a size", ["S", "M", "L"]) Color pickerDisplay a color picker widget.color = st.color_picker("Pick a color") Numeric input elements Number inputDisplay a numeric input widget.choice = st.number_input("Pick a number", 0, 10) SliderDisplay a slider widget.number = st.slider("Pick a number", 0, 100) Date and time input elements Date inputDisplay a date input widget.date = st.date_input("Your birthday") Time inputDisplay a time input widget.time = st.time_input("Meeting time") Text input elements Text inputDisplay a single-line text input widget.name = st.text_input("First name") Text areaDisplay a multi-line text input widget.text = st.text_area("Text to translate") Chat inputDisplay a chat input widget.prompt = st.chat_input("Say something") if prompt: st.write(f"The user has sent: {prompt}") Other input elements Data editorDisplay a data editor widget.edited = st.experimental_data_editor(df, num_rows="dynamic") File uploaderDisplay a file uploader widget.data = st.file_uploader("Upload a CSV") Camera inputDisplay a widget that allows users to upload images directly from a camera.image = st.camera_input("Take a picture") Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration! PreviousStreamlit ChatStreamlit Component for a Chatbot UI. Created by @AI-Yash.from streamlit_chat import message message("My message") message("Hello bot!", is_user=True) # align's the message to the right Streamlit Option MenuSelect a single item from a list of options in a menu. Created by @victoryhb.from streamlit_option_menu import option_menu option_menu("Main Menu", ["Home", 'Settings'], icons=['house', 'gear'], menu_icon="cast", default_index=1) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.stoggle import stoggle stoggle( "Click me!", """🥷 Surprise! Here's some additional content""",) Streamlit ElementsCreate a draggable and resizable dashboard in Streamlit. Created by @okls.from streamlit_elements import elements, mui, html with elements("new_element"): mui.Typography("Hello world") TagsAdd tags to your Streamlit apps. Created by @gagan3012.from streamlit_tags import st_tags st_tags(label='# Enter Keywords:', text='Press enter to add more', value=['Zero', 'One', 'Two'], suggestions=['five', 'six', 'seven', 'eight', 'nine', 'three', 'eleven', 'ten', 'four'], maxtags = 4, key='1') StqdmThe simplest way to handle a progress bar in streamlit app. Created by @Wirg.from stqdm import stqdm for _ in stqdm(range(50)): sleep(0.5) TimelineDisplay a Timeline in Streamlit apps using TimelineJS. Created by @innerdoc.from streamlit_timeline import timeline with open('example.json', "r") as f: timeline(f.read(), height=800) Camera input liveAlternative for st.camera_input which returns the webcam images live. Created by @blackary.from camera_input_live import camera_input_live image = camera_input_live() st.image(value) Streamlit AceAce editor component for Streamlit. Created by @okld.from streamlit_ace import st_ace content = st_ace() content Streamlit ChatStreamlit Component for a Chatbot UI. Created by @AI-Yash.from streamlit_chat import message message("My message") message("Hello bot!", is_user=True) # align's the message to the right Streamlit Option MenuSelect a single item from a list of options in a menu. Created by @victoryhb.from streamlit_option_menu import option_menu option_menu("Main Menu", ["Home", 'Settings'], icons=['house', 'gear'], menu_icon="cast", default_index=1) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.stoggle import stoggle stoggle( "Click me!", """🥷 Surprise! Here's some additional content""",) Streamlit ElementsCreate a draggable and resizable dashboard in Streamlit. Created by @okls.from streamlit_elements import elements, mui, html with elements("new_element"): mui.Typography("Hello world") TagsAdd tags to your Streamlit apps. Created by @gagan3012.from streamlit_tags import st_tags st_tags(label='# Enter Keywords:', text='Press enter to add more', value=['Zero', 'One', 'Two'], suggestions=['five', 'six', 'seven', 'eight', 'nine', 'three', 'eleven', 'ten', 'four'], maxtags = 4, key='1') StqdmThe simplest way to handle a progress bar in streamlit app. Created by @Wirg.from stqdm import stqdm for _ in stqdm(range(50)): sleep(0.5) TimelineDisplay a Timeline in Streamlit apps using TimelineJS. Created by @innerdoc.from streamlit_timeline import timeline with open('example.json', "r") as f: timeline(f.read(), height=800) Camera input liveAlternative for st.camera_input which returns the webcam images live. Created by @blackary.from camera_input_live import camera_input_live image = camera_input_live() st.image(value) Streamlit AceAce editor component for Streamlit. Created by @okld.from streamlit_ace import st_ace content = st_ace() content Streamlit ChatStreamlit Component for a Chatbot UI. Created by @AI-Yash.from streamlit_chat import message message("My message") message("Hello bot!", is_user=True) # align's the message to the right Streamlit Option MenuSelect a single item from a list of options in a menu. Created by @victoryhb.from streamlit_option_menu import option_menu option_menu("Main Menu", ["Home", 'Settings'], icons=['house', 'gear'], menu_icon="cast", default_index=1) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.stoggle import stoggle stoggle( "Click me!", """🥷 Surprise! Here's some additional content""",) NextPrevious: Chart elementsNext: st.buttonforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy
https://docs.streamlit.io/develop/concepts/architecture/forms
DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsremoveCOREArchitecture & executionremoveRunning your appStreamlit's architectureThe app chromeCachingSession StateFormsFragmentsWidget behaviorMultipage appsaddApp designaddADDITIONALConnections and secretsaddCustom componentsaddConfiguration and themingaddApp testingaddAPI referenceaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Develop/Concepts/Architecture & execution/FormsUsing forms When you don't want to rerun your script with each input made by a user, st.form is here to help! Forms make it easy to batch user input into a single rerun. This guide to using forms provides examples and explains how users interact with forms. Example In the following example, a user can set multiple parameters to update the map. As the user changes the parameters, the script will not rerun and the map will not update. When the user submits the form with the button labeled "Update map", the script reruns and the map updates. If at any time the user clicks "Generate new points" which is outside of the form, the script will rerun. If the user has any unsubmitted changes within the form, these will not be sent with the rerun. All changes made to a form will only be sent to the Python backend when the form itself is submitted. View source codeexpand_moreimport streamlit as st import pandas as pd import numpy as np def get_data(): df = pd.DataFrame({ "lat": np.random.randn(200) / 50 + 37.76, "lon": np.random.randn(200) / 50 + -122.4, "team": ['A','B']*100 }) return df if st.button('Generate new points'): st.session_state.df = get_data() if 'df' not in st.session_state: st.session_state.df = get_data() df = st.session_state.df with st.form("my_form"): header = st.columns([1,2,2]) header[0].subheader('Color') header[1].subheader('Opacity') header[2].subheader('Size') row1 = st.columns([1,2,2]) colorA = row1[0].color_picker('Team A', '#0000FF') opacityA = row1[1].slider('A opacity', 20, 100, 50, label_visibility='hidden') sizeA = row1[2].slider('A size', 50, 200, 100, step=10, label_visibility='hidden') row2 = st.columns([1,2,2]) colorB = row2[0].color_picker('Team B', '#FF0000') opacityB = row2[1].slider('B opacity', 20, 100, 50, label_visibility='hidden') sizeB = row2[2].slider('B size', 50, 200, 100, step=10, label_visibility='hidden') st.form_submit_button('Update map') alphaA = int(opacityA*255/100) alphaB = int(opacityB*255/100) df['color'] = np.where(df.team=='A',colorA+f'{alphaA:02x}',colorB+f'{alphaB:02x}') df['size'] = np.where(df.team=='A',sizeA, sizeB) st.map(df, size='size', color='color') Built with Streamlit 🎈Fullscreen open_in_new User interaction If a widget is not in a form, that widget will trigger a script rerun whenever a user changes its value. For widgets with keyed input (st.number_input, st.text_input, st.text_area), a new value triggers a rerun when the user clicks or tabs out of the widget. A user can also submit a change by pressing Enter while thier cursor is active in the widget. On the other hand if a widget is inside of a form, the script will not rerun when a user clicks or tabs out of that widget. For widgets inside a form, the script will rerun when the form is submitted and all widgets within the form will send their updated values to the Python backend. A user can submit a form using Enter on their keyboard if their cursor active in a widget that accepts keyed input. Within st.number_input and st.text_input a user presses Enter to submit the form. Within st.text_area a user presses Ctrl+Enter/⌘+Enter to submit the form. Widget values Before a form is submitted, all widgets within that form will have default values, just like widgets outside of a form have default values. import streamlit as st with st.form("my_form"): st.write("Inside the form") my_number = st.slider('Pick a number', 1, 10) my_color = st.selectbox('Pick a color', ['red','orange','green','blue','violet']) st.form_submit_button('Submit my picks') # This is outside the form st.write(my_number) st.write(my_color) Built with Streamlit 🎈Fullscreen open_in_new Forms are containers When st.form is called, a container is created on the frontend. You can write to that container like you do with other container elements. That is, you can use Python's with statement as shown in the example above, or you can assign the form container to a variable and call methods on it directly. Additionally, you can place st.form_submit_button anywhere in the form container. import streamlit as st animal = st.form('my_animal') # This is writing directly to the main body. Since the form container is # defined above, this will appear below everything written in the form. sound = st.selectbox('Sounds like', ['meow','woof','squeak','tweet']) # These methods called on the form container, so they appear inside the form. submit = animal.form_submit_button(f'Say it with {sound}!') sentence = animal.text_input('Your sentence:', 'Where\'s the tuna?') say_it = sentence.rstrip('.,!?') + f', {sound}!' if submit: animal.subheader(say_it) else: animal.subheader('&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/tutorials/databases/bigquery#add-the-key-file-to-your-local-app-secrets
DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceaddTutorialsremoveExecution flowaddConnect to data sourcesremoveAWS S3BigQueryDeta BaseFirestoreopen_in_newGoogle Cloud StorageMicrosoft SQL ServerMongoDBMySQLNeonPostgreSQLPrivate Google SheetPublic Google SheetSnowflakeSupabaseTableauTiDBTigerGraphMultipage appsaddWork with LLMsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Develop/Tutorials/Connect to data sources/BigQueryConnect Streamlit to Google BigQuery Introduction This guide explains how to securely access a BigQuery database from Streamlit Community Cloud. It uses the google-cloud-bigquery library and Streamlit's Secrets management. Create a BigQuery database push_pinNoteIf you already have a database that you want to use, feel free to skip to the next step. For this example, we will use one of the sample datasets from BigQuery (namely the shakespeare table). If you want to create a new dataset instead, follow Google's quickstart guide. Enable the BigQuery API Programmatic access to BigQuery is controlled through Google Cloud Platform. Create an account or sign in and head over to the APIs & Services dashboard (select or create a project if asked). As shown below, search for the BigQuery API and enable it: Create a service account & key file To use the BigQuery API from Streamlit Community Cloud, you need a Google Cloud Platform service account (a special account type for programmatic data access). Go to the Service Accounts page and create an account with the Viewer permission (this will let the account access data but not change it): push_pinNoteIf the button CREATE SERVICE ACCOUNT is gray, you don't have the correct permissions. Ask the admin of your Google Cloud project for help. After clicking DONE, you should be back on the service accounts overview. Create a JSON key file for the new account and download it: Add the key file to your local app secrets Your local Streamlit app will read secrets from a file .streamlit/secrets.toml in your app's root directory. Create this file if it doesn't exist yet and add the content of the key file you just downloaded to it as shown below: # .streamlit/secrets.toml [gcp_service_account] type = "service_account" project_id = "xxx" private_key_id = "xxx" private_key = "xxx" client_email = "xxx" client_id = "xxx" auth_uri = "https://accounts.google.com/o/oauth2/auth" token_uri = "https://oauth2.googleapis.com/token" auth_provider_x509_cert_url = "https://www.googleapis.com/oauth2/v1/certs" client_x509_cert_url = "xxx" priority_highImportantAdd this file to .gitignore and don't commit it to your GitHub repo! Copy your app secrets to the cloud As the secrets.toml file above is not committed to GitHub, you need to pass its content to your deployed app (on Streamlit Community Cloud) separately. Go to the app dashboard and in the app's dropdown menu, click on Edit Secrets. Copy the content of secrets.toml into the text area. More information is available at Secrets management. Add google-cloud-bigquery to your requirements file Add the google-cloud-bigquery package to your requirements.txt file, preferably pinning its version (replace x.x.x with the version want installed): # requirements.txt google-cloud-bigquery==x.x.x Write your Streamlit app Copy the code below to your Streamlit app and run it. Make sure to adapt the query if you don't use the sample table. # streamlit_app.py import streamlit as st from google.oauth2 import service_account from google.cloud import bigquery # Create API client. credentials = service_account.Credentials.from_service_account_info( st.secrets["gcp_service_account"] ) client = bigquery.Client(credentials=credentials) # Perform query. # Uses st.cache_data to only rerun when the query changes or after 10 min. @st.cache_data(ttl=600) def run_query(query): query_job = client.query(query) rows_raw = query_job.result() # Convert to list of dicts. Required for st.cache_data to hash the return value. rows = [dict(row) for row in rows_raw] return rows rows = run_query("SELECT word FROM `bigquery-public-data.samples.shakespeare` LIMIT 10") # Print results. st.write("Some wise words from Shakespeare:") for row in rows: st.write("✍️ " + row['word']) See st.cache_data above? Without it, Streamlit would run the query every time the app reruns (e.g. on a widget interaction). With st.cache_data, it only runs when the query changes or after 10 minutes (that's what ttl is for). Watch out: If your database updates more frequently, you should adapt ttl or remove caching so viewers always see the latest data. Learn more in Caching. Alternatively, you can use pandas to read from BigQuery right into a dataframe! Follow all the above steps, install the pandas-gbq library (don't forget to add it to requirements.txt!), and call pandas.read_gbq(query, credentials=credentials). More info in the pandas docs. If everything worked out (and you used the sample table), your app should look like this: Previous: AWS S3Next: Deta BaseforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy
https://docs.streamlit.io/knowledge-base/deploy/authentication-without-sso#option-2-individual-password-for-each-user
DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Knowledge base/Deployment issues/Authentication without SSOAuthentication without SSO Introduction Want to secure your Streamlit app with passwords, but cannot implement single sign-on? We got you covered! This guide shows you two simple techniques for adding basic authentication to your Streamlit app, using Secrets management. priority_highWarningWhile this technique adds some level of security, it is NOT comparable to proper authentication with an SSO provider. Option 1: One global password for all users This is the easiest option! Your app will ask for a password that's shared between all users. It will be stored in the app secrets using Secrets management. If you want to change this password or revoke a user's access, you will need to change it for everyone. If you want to have one password per user instead, jump to Option 2 below. Step 1: Add the password to your local app secrets Your local Streamlit app will read secrets from a file .streamlit/secrets.toml in your app's root dir. Create this file if it doesn't exist yet and add your password to it as shown below: # .streamlit/secrets.toml password = "streamlit123" priority_highImportantBe sure to add this file to your .gitignore so you don't commit your secrets! Step 2: Copy your app secrets to the cloud As the secrets.toml file above is not committed to GitHub, you need to pass its content to your deployed app (on Streamlit Community Cloud) separately. Go to the app dashboard and in the app's dropdown menu, click on Edit Secrets. Copy the content of secrets.toml into the text area. More information is available at Secrets management. Step 3: Ask for the password in your Streamlit app Copy the code below to your Streamlit app, insert your normal app code below the check_password() function call at the bottom, and run it: # streamlit_app.py import hmac import streamlit as st def check_password(): """Returns `True` if the user had the correct password.""" def password_entered(): """Checks whether a password entered by the user is correct.""" if hmac.compare_digest(st.session_state["password"], st.secrets["password"]): st.session_state["password_correct"] = True del st.session_state["password"] # Don't store the password. else: st.session_state["password_correct"] = False # Return True if the password is validated. if st.session_state.get("password_correct", False): return True # Show input for password. st.text_input( "Password", type="password", on_change=password_entered, key="password" ) if "password_correct" in st.session_state: st.error("😕 Password incorrect") return False if not check_password(): st.stop() # Do not continue if check_password is not True. # Main Streamlit app starts here st.write("Here goes your normal Streamlit app...") st.button("Click me") If everything worked out, your app should look like this: Option 2: Individual password for each user This option allows you to set a username and password for each user of your app. Like in Option 1, both values will be stored in the app secrets using Secrets management. Step 1: Add usernames & passwords to your local app secrets Your local Streamlit app will read secrets from a file .streamlit/secrets.toml in your app's root dir. Create this file if it doesn't exist yet and add the usernames & password to it as shown below: # .streamlit/secrets.toml [passwords] # Follow the rule: username = "password" alice_foo = "streamlit123" bob_bar = "mycrazypw" priority_highImportantBe sure to add this file to your .gitignore so you don't commit your secrets! Alternatively, you could set up and manage usernames & passwords via a spreadsheet or database. To use secrets to securely connect to Google Sheets, AWS, and other data providers, read our tutorials on how to Connect Streamlit to data sources. Step 2: Copy your app secrets to the cloud As the secrets.toml file above is not committed to GitHub, you need to pass its content to your deployed app (on Streamlit Community Cloud) separately. Go to the app dashboard and in the app's dropdown menu, click on Edit Secrets. Copy the content of secrets.toml into the text area. More information is available at Secrets management. Step 3: Ask for username & password in your Streamlit app Copy the code below to your Streamlit app, insert your normal app code below the check_password() function call at the bottom, and run it: # streamlit_app.py import hmac import streamlit as st def check_password(): """Returns `True` if the user had a correct password.""" def login_form(): """Form with widgets to collect user information""" with st.form("Credentials"): st.text_input("Username", key="username") st.text_input("Password", type="password", key="password") st.form_submit_button("Log in", on_click=password_entered) def password_entered(): """Checks whether a password entered by the user is correct.""" if st.session_state["username"] in st.secrets[ "passwords" ] and hmac.compare_digest( st.session_state["password"], st.secrets.passwords[st.session_state["username"]], ): st.session_state["password_correct"] = True del st.session_state["password"] # Don't store the username or password. del st.session_state["username"] else: st.session_state["password_correct"] = False # Return True if the username + password is validated. if st.session_state.get("password_correct", False): return True # Show inputs for username + password. login_form() if "password_correct" in st.session_state: st.error("😕 User not known or password incorrect") return False if not check_password(): st.stop() # Main Streamlit app starts here st.write("Here goes your normal Streamlit app...") st.button("Click me") If everything worked out, your app should look like this: Previous: Deployment issuesNext: How can I deploy multiple Streamlit apps on different subdomains?forumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy
https://docs.streamlit.io/develop/api-reference/caching-and-state#manage-state
DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceremovePAGE ELEMENTSWrite and magicaddText elementsaddData elementsaddChart elementsaddInput widgetsaddMedia elementsaddLayouts and containersaddChat elementsaddStatus elementsaddThird-party componentsopen_in_newAPPLICATION LOGICNavigation and pagesaddExecution flowaddCaching and stateremovest.cache_datast.cache_resourcest.cachedeletest.session_statest.query_paramsst.experimental_get_query_paramsdeletest.experimental_set_query_paramsdeleteConnections and secretsaddCustom componentsaddUtilitiesaddConfigurationaddTOOLSApp testingaddCommand lineaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Develop/API reference/Caching and stateCaching and state Optimize performance and add statefulness to your app! Caching Streamlit provides powerful cache primitives for data and global resources. They allow your app to stay performant even when loading data from the web, manipulating large datasets, or performing expensive computations. Cache dataFunction decorator to cache functions that return data (e.g. dataframe transforms, database queries, ML inference).@st.cache_data def long_function(param1, param2): # Perform expensive computation here or # fetch data from the web here return data Cache resourceFunction decorator to cache functions that return global resources (e.g. database connections, ML models).@st.cache_resource def init_model(): # Return a global resource here return pipeline( "sentiment-analysis", model="distilbert-base-uncased-finetuned-sst-2-english" ) Manage state Streamlit re-executes your script with each user interaction. Widgets have built-in statefulness between reruns, but Session State lets you do more! Session StateSave data between reruns and across pages.st.session_state["foo"] = "bar" Query parametersGet, set, or clear the query parameters that are shown in the browser's URL bar.st.query_params[key] = value st.query_params.clear() Deprecated commands delete This command was deprecated in version 1.18.0. Use st.cache_data or st.cache_resource instead. CachingFunction decorator to memoize function executions.@st.cache(ttl=3600) def run_long_computation(arg1, arg2): # Do stuff here return computation_output delete This command was deprecated in version 1.18.0. Use st.cache_data instead. MemoExperimental function decorator to memoize function executions.@st.experimental_memo def fetch_and_clean_data(url): # Fetch data from URL here, and then clean it up. return data delete This command was deprecated in version 1.18.0. Use st.cache_resource instead. SingletonExperimental function decorator to store singleton objects.@st.experimental_singleton def get_database_session(url): # Create a database session object that points to the URL. return session deleteGet query parametersGet query parameters that are shown in the browser's URL bar.param_dict = st.experimental_get_query_params() deleteSet query parametersSet query parameters that are shown in the browser's URL bar.st.experimental_set_query_params( {"show_all"=True, "selected"=["asia", "america"]} ) Previous: Execution flowNext: st.cache_dataforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy
https://docs.streamlit.io/en/0.68.0/api.html#caching-and-state
DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceremovePAGE ELEMENTSWrite and magicaddText elementsaddData elementsaddChart elementsaddInput widgetsaddMedia elementsaddLayouts and containersaddChat elementsaddStatus elementsaddThird-party componentsopen_in_newAPPLICATION LOGICNavigation and pagesaddExecution flowaddCaching and stateaddConnections and secretsaddCustom componentsaddUtilitiesaddConfigurationaddTOOLSApp testingaddCommand lineaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Develop/API referenceAPI reference Streamlit makes it easy for you to visualize, mutate, and share data. The API reference is organized by activity type, like displaying data or optimizing performance. Each section includes methods associated with the activity type, including examples. Browse our API below and click to learn more about any of our available commands! 🎈 Display almost anything Write and magic st.writeWrite arguments to the app.st.write("Hello **world**!") st.write(my_data_frame) st.write(my_mpl_figure) st.write_streamWrite generators or streams to the app with a typewriter effect.st.write_stream(my_generator) st.write_stream(my_llm_stream) MagicAny time Streamlit sees either a variable or literal value on its own line, it automatically writes that to your app using st.write"Hello **world**!" my_data_frame my_mpl_figure Text elements MarkdownDisplay string formatted as Markdown.st.markdown("Hello **world**!") TitleDisplay text in title formatting.st.title("The app title") HeaderDisplay text in header formatting.st.header("This is a header") SubheaderDisplay text in subheader formatting.st.subheader("This is a subheader") CaptionDisplay text in small font.st.caption("This is written small caption text") Code blockDisplay a code block with optional syntax highlighting.st.code("a = 1234") EchoDisplay some code in the app, then execute it. Useful for tutorials.with st.echo(): st.write('This code will be printed') LaTeXDisplay mathematical expressions formatted as LaTeX.st.latex("\int a x^2 \,dx") Preformatted textWrite fixed-width and preformatted text.st.text("Hello world") DividerDisplay a horizontal rule.st.divider() Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration! PreviousTagsAdd tags to your Streamlit apps. Created by @gagan3012.st_tags(label='# Enter Keywords:', text='Press enter to add more', value=['Zero', 'One', 'Two'], suggestions=['five', 'six', 'seven', 'eight', 'nine', 'three', 'eleven', 'ten', 'four'], maxtags = 4, key='1') NLUApply text mining on a dataframe. Created by @JohnSnowLabs.nlu.load('sentiment').predict('I love NLU! <3') Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.mention(label="An awesome Streamlit App", icon="streamlit", url="https://extras.streamlit.app",) Annotated textDisplay annotated text in Streamlit apps. Created by @tvst.annotated_text("This ", ("is", "verb"), " some ", ("annotated", "adj"), ("text", "noun"), " for those of ", ("you", "pronoun"), " who ", ("like", "verb"), " this sort of ", ("thing", "noun"), ".") Drawable CanvasProvides a sketching canvas using Fabric.js. Created by @andfanilo.st_canvas(fill_color="rgba(255, 165, 0, 0.3)", stroke_width=stroke_width, stroke_color=stroke_color, background_color=bg_color, background_image=Image.open(bg_image) if bg_image else None, update_streamlit=realtime_update, height=150, drawing_mode=drawing_mode, point_display_radius=point_display_radius if drawing_mode == 'point' else 0, key="canvas",) TagsAdd tags to your Streamlit apps. Created by @gagan3012.st_tags(label='# Enter Keywords:', text='Press enter to add more', value=['Zero', 'One', 'Two'], suggestions=['five', 'six', 'seven', 'eight', 'nine', 'three', 'eleven', 'ten', 'four'], maxtags = 4, key='1') NLUApply text mining on a dataframe. Created by @JohnSnowLabs.nlu.load('sentiment').predict('I love NLU! <3') Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.mention(label="An awesome Streamlit App", icon="streamlit", url="https://extras.streamlit.app",) Annotated textDisplay annotated text in Streamlit apps. Created by @tvst.annotated_text("This ", ("is", "verb"), " some ", ("annotated", "adj"), ("text", "noun"), " for those of ", ("you", "pronoun"), " who ", ("like", "verb"), " this sort of ", ("thing", "noun"), ".") Drawable CanvasProvides a sketching canvas using Fabric.js. Created by @andfanilo.st_canvas(fill_color="rgba(255, 165, 0, 0.3)", stroke_width=stroke_width, stroke_color=stroke_color, background_color=bg_color, background_image=Image.open(bg_image) if bg_image else None, update_streamlit=realtime_update, height=150, drawing_mode=drawing_mode, point_display_radius=point_display_radius if drawing_mode == 'point' else 0, key="canvas",) TagsAdd tags to your Streamlit apps. Created by @gagan3012.st_tags(label='# Enter Keywords:', text='Press enter to add more', value=['Zero', 'One', 'Two'], suggestions=['five', 'six', 'seven', 'eight', 'nine', 'three', 'eleven', 'ten', 'four'], maxtags = 4, key='1') NLUApply text mining on a dataframe. Created by @JohnSnowLabs.nlu.load('sentiment').predict('I love NLU! <3') Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.mention(label="An awesome Streamlit App", icon="streamlit", url="https://extras.streamlit.app",) Next Data elements DataframesDisplay a dataframe as an interactive table.st.dataframe(my_data_frame) Data editorDisplay a data editor widget.edited = st.data_editor(df, num_rows="dynamic") Column configurationConfigure the display and editing behavior of dataframes and data editors.st.column_config.NumberColumn("Price (in USD)", min_value=0, format="$%d") Static tablesDisplay a static table.st.table(my_data_frame) MetricsDisplay a metric in big bold font, with an optional indicator of how the metric changed.st.metric("My metric", 42, 2) Dicts and JSONDisplay object or string as a pretty-printed JSON string.st.json(my_dict) Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration! PreviousImage CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates value = streamlit_image_coordinates("https://placekitten.com/200/300") st.write(value) Plotly EventsMake Plotly charts interactive!. Created by @null-jones.from streamlit_plotly_events import plotly_events fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.metric_cards import style_metric_cards col3.metric(label="No Change", value=5000, delta=0) style_metric_cards() Streamlit AggridImplementation of Ag-Grid component for Streamlit. Created by @PablocFonseca.df = pd.DataFrame({'col1': [1, 2, 3], 'col2': [4, 5, 6]}) grid_return = AgGrid(df, editable=True) new_df = grid_return['data'] Streamlit FoliumStreamlit Component for rendering Folium maps. Created by @randyzwitch.m = folium.Map(location=[39.949610, -75.150282], zoom_start=16) folium.Marker([39.949610, -75.150282], popup="Liberty Bell", tooltip="Liberty Bell").add_to(m) st_data = st_folium(m, width=725) Pandas ProfilingPandas profiling component for Streamlit. Created by @okld.df = pd.read_csv("https://storage.googleapis.com/tf-datasets/titanic/train.csv") pr = df.profile_report() st_profile_report(pr) Image CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates value = streamlit_image_coordinates("https://placekitten.com/200/300") st.write(value) Plotly EventsMake Plotly charts interactive!. Created by @null-jones.from streamlit_plotly_events import plotly_events fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.metric_cards import style_metric_cards col3.metric(label="No Change", value=5000, delta=0) style_metric_cards() Streamlit AggridImplementation of Ag-Grid component for Streamlit. Created by @PablocFonseca.df = pd.DataFrame({'col1': [1, 2, 3], 'col2': [4, 5, 6]}) grid_return = AgGrid(df, editable=True) new_df = grid_return['data'] Streamlit FoliumStreamlit Component for rendering Folium maps. Created by @randyzwitch.m = folium.Map(location=[39.949610, -75.150282], zoom_start=16) folium.Marker([39.949610, -75.150282], popup="Liberty Bell", tooltip="Liberty Bell").add_to(m) st_data = st_folium(m, width=725) Pandas ProfilingPandas profiling component for Streamlit. Created by @okld.df = pd.read_csv("https://storage.googleapis.com/tf-datasets/titanic/train.csv") pr = df.profile_report() st_profile_report(pr) Image CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates value = streamlit_image_coordinates("https://placekitten.com/200/300") st.write(value) Plotly EventsMake Plotly charts interactive!. Created by @null-jones.from streamlit_plotly_events import plotly_events fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.metric_cards import style_metric_cards col3.metric(label="No Change", value=5000, delta=0) style_metric_cards() Next Chart elements Simple area chartsDisplay an area chart.st.area_chart(my_data_frame) Simple bar chartsDisplay a bar chart.st.bar_chart(my_data_frame) Simple line chartsDisplay a line chart.st.line_chart(my_data_frame) Simple scatter chartsDisplay a line chart.st.scatter_chart(my_data_frame) Scatterplots on mapsDisplay a map with points on it.st.map(my_data_frame) MatplotlibDisplay a matplotlib.pyplot figure.st.pyplot(my_mpl_figure) AltairDisplay a chart using the Altair library.st.altair_chart(my_altair_chart) Vega-LiteDisplay a chart using the Vega-Lite library.st.vega_lite_chart(my_vega_lite_chart) PlotlyDisplay an interactive Plotly chart.st.plotly_chart(my_plotly_chart) BokehDisplay an interactive Bokeh chart.st.bokeh_chart(my_bokeh_chart) PyDeckDisplay a chart using the PyDeck library.st.pydeck_chart(my_pydeck_chart) GraphVizDisplay a graph using the dagre-d3 library.st.graphviz_chart(my_graphviz_spec) Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration! PreviousStreamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl("https://assets5.lottiefiles.com/packages/lf20_V9t630.json") st_lottie(lottie_hello, key="hello") Plotly EventsMake Plotly charts interactive!. Created by @null-jones.fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.chart += get_annotations_chart(annotations=[("Mar 01, 2008", "Pretty good day for GOOG"), ("Dec 01, 2007", "Something's going wrong for GOOG & AAPL"), ("Nov 01, 2008", "Market starts again thanks to..."), ("Dec 01, 2009", "Small crash for GOOG after..."),],) st.altair_chart(chart, use_container_width=True) PlostA deceptively simple plotting library for Streamlit. Created by @tvst.import plost plost.line_chart(my_dataframe, x='time', y='stock_value', color='stock_name',) HiPlotHigh dimensional Interactive Plotting. Created by @facebookresearch.data = [{'dropout':0.1, 'lr': 0.001, 'loss': 10.0, 'optimizer': 'SGD'}, {'dropout':0.15, 'lr': 0.01, 'loss': 3.5, 'optimizer': 'Adam'}, {'dropout':0.3, 'lr': 0.1, 'loss': 4.5, 'optimizer': 'Adam'}] hip.Experiment.from_iterable(data).display() EChartsHigh dimensional Interactive Plotting. Created by @andfanilo.from streamlit_echarts import st_echarts st_echarts(options=options) Streamlit FoliumStreamlit Component for rendering Folium maps. Created by @randyzwitch.m = folium.Map(location=[39.949610, -75.150282], zoom_start=16) st_data = st_folium(m, width=725) Spacy-StreamlitspaCy building blocks and visualizers for Streamlit apps. Created by @explosion.models = ["en_core_web_sm", "en_core_web_md"] spacy_streamlit.visualize(models, "Sundar Pichai is the CEO of Google.") Streamlit AgraphA Streamlit Graph Vis, based on react-grah-vis. Created by @ChrisDelClea.from streamlit_agraph import agraph, Node, Edge, Config agraph(nodes=nodes, edges=edges, config=config) Streamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl("https://assets5.lottiefiles.com/packages/lf20_V9t630.json") st_lottie(lottie_hello, key="hello") Plotly EventsMake Plotly charts interactive!. Created by @null-jones.fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.chart += get_annotations_chart(annotations=[("Mar 01, 2008", "Pretty good day for GOOG"), ("Dec 01, 2007", "Something's going wrong for GOOG & AAPL"), ("Nov 01, 2008", "Market starts again thanks to..."), ("Dec 01, 2009", "Small crash for GOOG after..."),],) st.altair_chart(chart, use_container_width=True) PlostA deceptively simple plotting library for Streamlit. Created by @tvst.import plost plost.line_chart(my_dataframe, x='time', y='stock_value', color='stock_name',) HiPlotHigh dimensional Interactive Plotting. Created by @facebookresearch.data = [{'dropout':0.1, 'lr': 0.001, 'loss': 10.0, 'optimizer': 'SGD'}, {'dropout':0.15, 'lr': 0.01, 'loss': 3.5, 'optimizer': 'Adam'}, {'dropout':0.3, 'lr': 0.1, 'loss': 4.5, 'optimizer': 'Adam'}] hip.Experiment.from_iterable(data).display() EChartsHigh dimensional Interactive Plotting. Created by @andfanilo.from streamlit_echarts import st_echarts st_echarts(options=options) Streamlit FoliumStreamlit Component for rendering Folium maps. Created by @randyzwitch.m = folium.Map(location=[39.949610, -75.150282], zoom_start=16) st_data = st_folium(m, width=725) Spacy-StreamlitspaCy building blocks and visualizers for Streamlit apps. Created by @explosion.models = ["en_core_web_sm", "en_core_web_md"] spacy_streamlit.visualize(models, "Sundar Pichai is the CEO of Google.") Streamlit AgraphA Streamlit Graph Vis, based on react-grah-vis. Created by @ChrisDelClea.from streamlit_agraph import agraph, Node, Edge, Config agraph(nodes=nodes, edges=edges, config=config) Streamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl("https://assets5.lottiefiles.com/packages/lf20_V9t630.json") st_lottie(lottie_hello, key="hello") Plotly EventsMake Plotly charts interactive!. Created by @null-jones.fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.chart += get_annotations_chart(annotations=[("Mar 01, 2008", "Pretty good day for GOOG"), ("Dec 01, 2007", "Something's going wrong for GOOG & AAPL"), ("Nov 01, 2008", "Market starts again thanks to..."), ("Dec 01, 2009", "Small crash for GOOG after..."),],) st.altair_chart(chart, use_container_width=True) Next Input widgets ButtonDisplay a button widget.clicked = st.button("Click me") Download buttonDisplay a download button widget.st.download_button("Download file", file) Form buttonDisplay a form submit button. For use with st.form.st.form_submit_button("Sign up") Link buttonDisplay a link button.st.link_button("Go to gallery", url) Page linkDisplay a link to another page in a multipage app.st.page_link("app.py", label="Home", icon="🏠") st.page_link("pages/profile.py", label="My profile") CheckboxDisplay a checkbox widget.selected = st.checkbox("I agree") Color pickerDisplay a color picker widget.color = st.color_picker("Pick a color") MultiselectDisplay a multiselect widget. The multiselect widget starts as empty.choices = st.multiselect("Buy", ["milk", "apples", "potatoes"]) RadioDisplay a radio button widget.choice = st.radio("Pick one", ["cats", "dogs"]) SelectboxDisplay a select widget.choice = st.selectbox("Pick one", ["cats", "dogs"]) Select-sliderDisplay a slider widget to select items from a list.size = st.select_slider("Pick a size", ["S", "M", "L"]) ToggleDisplay a toggle widget.activated = st.toggle("Activate") Number inputDisplay a numeric input widget.choice = st.number_input("Pick a number", 0, 10) SliderDisplay a slider widget.number = st.slider("Pick a number", 0, 100) Date inputDisplay a date input widget.date = st.date_input("Your birthday") Time inputDisplay a time input widget.time = st.time_input("Meeting time") Chat inputDisplay a chat input widget.prompt = st.chat_input("Say something") if prompt: st.write(f"The user has sent: {prompt}") Text-areaDisplay a multi-line text input widget.text = st.text_area("Text to translate") Text inputDisplay a single-line text input widget.name = st.text_input("First name") Data editorDisplay a data editor widget.edited = st.experimental_data_editor(df, num_rows="dynamic") File UploaderDisplay a file uploader widget.data = st.file_uploader("Upload a CSV") Camera inputDisplay a widget that allows users to upload images directly from a camera.image = st.camera_input("Take a picture") Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration! PreviousStreamlit ChatStreamlit Component for a Chatbot UI. Created by @AI-Yash.from streamlit_chat import message message("My message") message("Hello bot!", is_user=True) # align's the message to the right Streamlit Option MenuSelect a single item from a list of options in a menu. Created by @victoryhb.from streamlit_option_menu import option_menu option_menu("Main Menu", ["Home", 'Settings'], icons=['house', 'gear'], menu_icon="cast", default_index=1) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.stoggle import stoggle stoggle( "Click me!", """🥷 Surprise! Here's some additional content""",) Streamlit ElementsCreate a draggable and resizable dashboard in Streamlit. Created by @okls.from streamlit_elements import elements, mui, html with elements("new_element"): mui.Typography("Hello world") TagsAdd tags to your Streamlit apps. Created by @gagan3012.from streamlit_tags import st_tags st_tags(label='# Enter Keywords:', text='Press enter to add more', value=['Zero', 'One', 'Two'], suggestions=['five', 'six', 'seven', 'eight', 'nine', 'three', 'eleven', 'ten', 'four'], maxtags = 4, key='1') StqdmThe simplest way to handle a progress bar in streamlit app. Created by @Wirg.from stqdm import stqdm for _ in stqdm(range(50)): sleep(0.5) TimelineDisplay a Timeline in Streamlit apps using TimelineJS. Created by @innerdoc.from streamlit_timeline import timeline with open('example.json', "r") as f: timeline(f.read(), height=800) Camera input liveAlternative for st.camera_input which returns the webcam images live. Created by @blackary.from camera_input_live import camera_input_live image = camera_input_live() st.image(value) Streamlit AceAce editor component for Streamlit. Created by @okld.from streamlit_ace import st_ace content = st_ace() content Streamlit ChatStreamlit Component for a Chatbot UI. Created by @AI-Yash.from streamlit_chat import message message("My message") message("Hello bot!", is_user=True) # align's the message to the right Streamlit Option MenuSelect a single item from a list of options in a menu. Created by @victoryhb.from streamlit_option_menu import option_menu option_menu("Main Menu", ["Home", 'Settings'], icons=['house', 'gear'], menu_icon="cast", default_index=1) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.stoggle import stoggle stoggle( "Click me!", """🥷 Surprise! Here's some additional content""",) Streamlit ElementsCreate a draggable and resizable dashboard in Streamlit. Created by @okls.from streamlit_elements import elements, mui, html with elements("new_element"): mui.Typography("Hello world") TagsAdd tags to your Streamlit apps. Created by @gagan3012.from streamlit_tags import st_tags st_tags(label='# Enter Keywords:', text='Press enter to add more', value=['Zero', 'One', 'Two'], suggestions=['five', 'six', 'seven', 'eight', 'nine', 'three', 'eleven', 'ten', 'four'], maxtags = 4, key='1') StqdmThe simplest way to handle a progress bar in streamlit app. Created by @Wirg.from stqdm import stqdm for _ in stqdm(range(50)): sleep(0.5) TimelineDisplay a Timeline in Streamlit apps using TimelineJS. Created by @innerdoc.from streamlit_timeline import timeline with open('example.json', "r") as f: timeline(f.read(), height=800) Camera input liveAlternative for st.camera_input which returns the webcam images live. Created by @blackary.from camera_input_live import camera_input_live image = camera_input_live() st.image(value) Streamlit AceAce editor component for Streamlit. Created by @okld.from streamlit_ace import st_ace content = st_ace() content Streamlit ChatStreamlit Component for a Chatbot UI. Created by @AI-Yash.from streamlit_chat import message message("My message") message("Hello bot!", is_user=True) # align's the message to the right Streamlit Option MenuSelect a single item from a list of options in a menu. Created by @victoryhb.from streamlit_option_menu import option_menu option_menu("Main Menu", ["Home", 'Settings'], icons=['house', 'gear'], menu_icon="cast", default_index=1) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.stoggle import stoggle stoggle( "Click me!", """🥷 Surprise! Here's some additional content""",) Next Media elements ImageDisplay an image or list of images.st.image(numpy_array) st.image(image_bytes) st.image(file) st.image("https://example.com/myimage.jpg") AudioDisplay an audio player.st.audio(numpy_array) st.audio(audio_bytes) st.audio(file) st.audio("https://example.com/myaudio.mp3", format="audio/mp3") VideoDisplay a video player.st.video(numpy_array) st.video(video_bytes) st.video(file) st.video("https://example.com/myvideo.mp4", format="video/mp4") Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration! PreviousStreamlit CropperA simple image cropper for Streamlit. Created by @turner-anderson.from streamlit_cropper import st_cropper st_cropper(img, realtime_update=realtime_update, box_color=box_color, aspect_ratio=aspect_ratio) Image CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates streamlit_image_coordinates("https://placekitten.com/200/300") Streamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl("https://assets5.lottiefiles.com/packages/lf20_V9t630.json") st_lottie(lottie_hello, key="hello") Streamlit WebrtcHandling and transmitting real-time video/audio streams with Streamlit. Created by @whitphx.from streamlit_webrtc import webrtc_streamer webrtc_streamer(key="sample") Drawable CanvasProvides a sketching canvas using Fabric.js. Created by @andfanilo.from streamlit_drawable_canvas import st_canvas st_canvas(fill_color="rgba(255, 165, 0, 0.3)", stroke_width=stroke_width, stroke_color=stroke_color, background_color=bg_color, background_image=Image.open(bg_image) if bg_image else None, update_streamlit=realtime_update, height=150, drawing_mode=drawing_mode, point_display_radius=point_display_radius if drawing_mode == 'point' else 0, key="canvas",) Image ComparisonCompare images with a slider using JuxtaposeJS. Created by @fcakyon.from streamlit_image_comparison import image_comparison image_comparison(img1="image1.jpg", img2="image2.jpg",) Streamlit CropperA simple image cropper for Streamlit. Created by @turner-anderson.from streamlit_cropper import st_cropper st_cropper(img, realtime_update=realtime_update, box_color=box_color, aspect_ratio=aspect_ratio) Image CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates streamlit_image_coordinates("https://placekitten.com/200/300") Streamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl("https://assets5.lottiefiles.com/packages/lf20_V9t630.json") st_lottie(lottie_hello, key="hello") Streamlit WebrtcHandling and transmitting real-time video/audio streams with Streamlit. Created by @whitphx.from streamlit_webrtc import webrtc_streamer webrtc_streamer(key="sample") Drawable CanvasProvides a sketching canvas using Fabric.js. Created by @andfanilo.from streamlit_drawable_canvas import st_canvas st_canvas(fill_color="rgba(255, 165, 0, 0.3)", stroke_width=stroke_width, stroke_color=stroke_color, background_color=bg_color, background_image=Image.open(bg_image) if bg_image else None, update_streamlit=realtime_update, height=150, drawing_mode=drawing_mode, point_display_radius=point_display_radius if drawing_mode == 'point' else 0, key="canvas",) Image ComparisonCompare images with a slider using JuxtaposeJS. Created by @fcakyon.from streamlit_image_comparison import image_comparison image_comparison(img1="image1.jpg", img2="image2.jpg",) Streamlit CropperA simple image cropper for Streamlit. Created by @turner-anderson.from streamlit_cropper import st_cropper st_cropper(img, realtime_update=realtime_update, box_color=box_color, aspect_ratio=aspect_ratio) Image CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates streamlit_image_coordinates("https://placekitten.com/200/300") Streamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl("https://assets5.lottiefiles.com/packages/lf20_V9t630.json") st_lottie(lottie_hello, key="hello") Next Layouts and containers ColumnsInsert containers laid out as side-by-side columns.col1, col2 = st.columns(2) col1.write("this is column 1") col2.write("this is column 2") ContainerInsert a multi-element container.c = st.container() st.write("This will show last") c.write("This will show first") c.write("This will show second") Modal dialogsInsert a modal dialog that can rerun independently from the rest of the script.@st.experimental_dialog("Sign up") def email_form(): name = st.text_input("Name") email = st.text_input("Email") EmptyInsert a single-element container.c = st.empty() st.write("This will show last") c.write("This will be replaced") c.write("This will show first") ExpanderInsert a multi-element container that can be expanded/collapsed.with st.expander("Open to see more"): st.write("This is more content") PopoverInsert a multi-element popover container that can be opened/closed.with st.popover("Settings"): st.checkbox("Show completed") SidebarDisplay items in a sidebar.st.sidebar.write("This lives in the sidebar") st.sidebar.button("Click me!") TabsInsert containers separated into tabs.tab1, tab2 = st.tabs(["Tab 1", "Tab2"]) tab1.write("this is tab 1") tab2.write("this is tab 2") Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration!Streamlit ElementsCreate a draggable and resizable dashboard in Streamlit. Created by @okls.from streamlit_elements import elements, mui, html with elements("new_element"): mui.Typography("Hello world") PydanticAuto-generate Streamlit UI from Pydantic Models and Dataclasses. Created by @lukasmasuch.import streamlit_pydantic as sp sp.pydantic_form(key="my_form", model=ExampleModel) Streamlit PagesAn experimental version of Streamlit Multi-Page Apps. Created by @blackary.from st_pages import Page, show_pages, add_page_title show_pages([ Page("streamlit_app.py", "Home", "🏠"), Page("other_pages/page2.py", "Page 2", ":books:"), ]) Chat elements Streamlit provides a few commands to help you build conversational apps. These chat elements are designed to be used in conjunction with each other, but you can also use them separately. st.chat_message lets you insert a chat message container into the app so you can display messages from the user or the app. Chat containers can contain other Streamlit elements, including charts, tables, text, and more. st.chat_input lets you display a chat input widget so the user can type in a message. Chat inputDisplay a chat input widget.prompt = st.chat_input("Say something") if prompt: st.write(f"The user has sent: {prompt}") Chat messageInsert a chat message container.import numpy as np with st.chat_message("user"): st.write("Hello 👋") st.line_chart(np.random.randn(30, 3)) Status containerDisplay output of long-running tasks in a container.with st.status('Running'): do_something_slow() st.write_streamWrite generators or streams to the app with a typewriter effect.st.write_stream(my_generator) st.write_stream(my_llm_stream) Status elements Progress barDisplay a progress bar.for i in range(101): st.progress(i) do_something_slow() SpinnerTemporarily displays a message while executing a block of code.with st.spinner("Please wait..."): do_something_slow() Status containerDisplay output of long-running tasks in a container.with st.status('Running'): do_something_slow() ToastBriefly displays a toast message in the bottom-right corner.st.toast('Butter!', icon='🧈') BalloonsDisplay celebratory balloons!do_something() # Celebrate when all done! st.balloons() SnowflakesDisplay celebratory snowflakes!do_something() # Celebrate when all done! st.snow() Success boxDisplay a success message.st.success("Match found!") Info boxDisplay an informational message.st.info("Dataset is updated every day at midnight.") Warning boxDisplay warning message.st.warning("Unable to fetch image. Skipping...") Error boxDisplay error message.st.error("We encountered an error") Exception outputDisplay an exception.e = RuntimeError("This is an exception of type RuntimeError") st.exception(e) Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration!StqdmThe simplest way to handle a progress bar in streamlit app. Created by @Wirg.from stqdm import stqdm for _ in stqdm(range(50)): sleep(0.5) Custom notification boxA custom notification box with the ability to close it out. Created by @Socvest.from streamlit_custom_notification_box import custom_notification_box styles = {'material-icons':{'color': 'red'}, 'text-icon-link-close-container': {'box-shadow': '#3896de 0px 4px'}, 'notification-text': {'':''}, 'close-button':{'':''}, 'link':{'':''}} custom_notification_box(icon='info', textDisplay='We are almost done with your registration...', externalLink='more info', url='#', styles=styles, key="foo") Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.let_it_rain import rain rain(emoji="🎈", font_size=54, falling_speed=5, animation_length="infinite",) App logic and configuration Navigation and pages Switch pageProgrammatically navigates to a specified page.st.switch_page("pages/my_page.py") Page linkDisplay a link to another page in a multipage app.st.page_link("app.py", label="Home", icon="🏠") st.page_link("pages/profile.py", label="My profile") Execution flow Modal dialogsInsert a modal dialog that can rerun independently from the rest of the script.@st.experimental_dialog("Sign up") def email_form(): name = st.text_input("Name") email = st.text_input("Email") FormsCreate a form that batches elements together with a “Submit" button.with st.form(key='my_form'): name = st.text_input("Name") email = st.text_input("Email") st.form_submit_button("Sign up") Partial rerunsDefine a fragment to rerun independently from the rest of the script.@st.experimental_fragment(run_every="10s") def fragment(): df = get_data() st.line_chart(df) Rerun scriptRerun the script immediately.st.rerun() Stop executionStops execution immediately.st.stop() Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration!AutorefreshForce a refresh without tying up a script. Created by @kmcgrady.from streamlit_autorefresh import st_autorefresh st_autorefresh(interval=2000, limit=100, key="fizzbuzzcounter") PydanticAuto-generate Streamlit UI from Pydantic Models and Dataclasses. Created by @lukasmasuch.import streamlit_pydantic as sp sp.pydantic_form(key="my_form", model=ExampleModel) Streamlit PagesAn experimental version of Streamlit Multi-Page Apps. Created by @blackary.from st_pages import Page, show_pages, add_page_title show_pages([ Page("streamlit_app.py", "Home", "🏠"), Page("other_pages/page2.py", "Page 2", ":books:"), ]) Caching and state Cache dataFunction decorator to cache functions that return data (e.g. dataframe transforms, database queries, ML inference).@st.cache_data def long_function(param1, param2): # Perform expensive computation here or # fetch data from the web here return data Cache resourceFunction decorator to cache functions that return global resources (e.g. database connections, ML models).@st.cache_resource def init_model(): # Return a global resource here return pipeline( "sentiment-analysis", model="distilbert-base-uncased-finetuned-sst-2-english" ) Session stateSession state is a way to share variables between reruns, for each user session.st.session_state['key'] = value Query parametersGet, set, or clear the query parameters that are shown in the browser's URL bar.st.query_params[key] = value st.query_params.clear() Connections and databases Setup your connection Create a connectionConnect to a data source or APIconn = st.connection('pets_db', type='sql') pet_owners = conn.query('select * from pet_owners') st.dataframe(pet_owners) Built-in connections SnowflakeConnectionA connection to Snowflake.conn = st.connection('snowflake') SQLConnectionA connection to a SQL database using SQLAlchemy.conn = st.connection('sql') Build your own connections Connection base classBuild your own connection with BaseConnection.class MyConnection(BaseConnection[myconn.MyConnection]): def _connect(self, **kwargs) -> MyConnection: return myconn.connect(**self._secrets, **kwargs) def query(self, query): return self._instance.query(query) Secrets management Secrets singletonAccess secrets from a local TOML file.key = st.secrets["OpenAI_key"] Secrets fileSave your secrets in a per-project or per-profile TOML file.OpenAI_key = "<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/deploy/streamlit-community-cloud/deploy-your-app/app-dependencies#apt-get-dependencies
DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudremoveGet startedaddDeploy your appremoveApp dependenciesSecrets managementManage your appaddShare your appaddManage your accountaddTroubleshootingStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Deploy/Streamlit Community Cloud/Deploy your app/App dependenciesApp dependencies The main reason that apps fail to build properly is because Streamlit Community Cloud can't find your dependencies! There are two kinds of dependencies your app might have: Python dependencies and external dependencies. Python dependencies are other Python packages (just like Streamlit!) that you import into you script. External dependencies are less common, but they include any other software your script needs to function properly. Since Streamlit Community Cloud runs on Linux, these will be Linux dependencies installed with apt-get outside the Python environment. For your dependencies to be installed correctly, make sure you: Add a requirements file for Python dependencies. (optional) Add a packages.txt file to manage any external dependencies. push_pinNotePython requirements files should be placed either in the root of your repository or in the same directory as your Streamlit app. Add Python dependencies With each import statement in your script, you are bringing in a Python dependency. You need to tell Streamlit Community Cloud how to install those dependencies through a Python package manager. We recommend using a requirements.txt which is based on pip. You should not include built-in Python libraries like math or random in your requirements.txt file. These are a part of Python and aren't installed separately. Also, Streamlit Community Cloud has streamlit installed by default. You don't strictly need to include streamlit unless you want to pin or restrict the version. If you deploy an app without a requirements.txt file, your app will run in an environment with just streamlit (and its dependencies) installed. If you have a script like the following, no extra dependencies would be needed since pandas and numpy are installed as direct dependencies of streamlit. Similarly, math and random are built into Python. import streamlit as st import pandas as pd import numpy as np import math import random st.write('Hi!') However, a valid requirements.txt file would be: streamlit pandas numpy Alternatively, if you needed to specify certain versions, another valid example would be: streamlit==1.24.1 pandas>2.0 numpy<=1.25.1 In the above example, streamlit is pinned to version 1.24.1, pandas must be strictly greater than version 2.0, and numpy must be at-or-below version 1.25.1. Each line in your requirements.txt file is effectively what you would like to pip install into your cloud environment. push_pinNoteWe recommend that you use the latest version of Streamlit to ensure full Streamlit Community Cloud functionality. Be sure to take note of Streamlit's current requirements for package compatibility when planning your environment, especially protobuf>=3.20,<5. If you pin streamlit below 1.20.0, you may experience unexpected results if you've pinned any dependencies of altair. If streamlit is installed below version 1.20.0, altair<5 will be reinstalled on top of your environment for compatibility reasons. When this happens all of altair's dependencies will be updated. Other Python package managers There are other Python package managers besides pip. If you want to consider alternatives to using a requirements.txt file, Streamlit Community Cloud will look for other Python dependency managers to use in the order below. Streamlit will stop and install the first dependency file found. Recognized FilenamePython Package ManagerPipfilepipenvenvironment.ymlcondarequirements.txtpippyproject.tomlpoetry priority_highWarningYou should only use one requirements file for your app. If you include more than one (e.g. requirements.txt and Pipfile), only the first file encountered will be used as described above. Additionally, Streamlit will first look in the directory of your Streamlit app; however, if no requirements file is found, Streamlit will then look at the root of the repo. apt-get dependencies For many apps, a packages.txt file is not required. However, if your script requires any software to be installed that is not a Python package, then you will need a packages.txt file. Streamlit Community Cloud is built on Debian Linux. Anything you would like to apt-get install needs to go in your packages.txt file. If packages.txt exists in the root directory of your repository we automatically detect it, parse it, and install the listed packages. You can read more about apt-get in Linux documentation. Add apt-get dependencies to packages.txt — one package name per line. For example, mysqlclient is a Python package which requires additional software be installed to function. A valid packages.txt file to enable mysqlclient would be: build-essential pkg-config default-libmysqlclient-dev Previous: Deploy your appNext: Secrets managementforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy
https://docs.streamlit.io/deploy/streamlit-community-cloud/manage-your-app/edit-your-app
DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudremoveGet startedaddDeploy your appaddManage your appremoveApp analyticsApp settingsDelete your appEdit your appFavorite your appReboot your appShare your appaddManage your accountaddTroubleshootingStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Deploy/Streamlit Community Cloud/Manage your app/Edit your appEdit your app You can edit your app from any development environment of your choice. Community Cloud will monitor your repository and automatically copy any file changes you commit. You will immediately see commits reflected in your deployed app for most changes (such as edits to your app's Python files). Community Cloud also makes it easy to skip the work of setting up a development environment. With a few simple clicks, you can configure a development environment using GitHub Codespaces. Edit your app with GitHub Codespaces Spin up a cloud-based development environment for your deployed app in minutes. You can run your app within your codespace to enjoy experimenting in a safe, sandboxed environment. When you are done editing your code, you can commit your changes to your repo or just leave them in your codespace to return to later. Create a codespace for your deployed app From your workspace at share.streamlit.io, click the overflow icon (more_vert) next to your app. Click "Edit." A .devcontainer/devcontainer.json file will be added to your repository. If you already have a file of the same name in your repository, it will not be changed. You may delete or rename your existing devcontainer configuration if you would like your repository to receive the instance created by Streamlit Community Cloud. Click "Create codespace" to confirm the creation of a codespace on your account. Read more about GitHub Codespaces to learn about monthly limits for free use and paid plans. Wait for GitHub to set up your codespace. GitHub will automatically execute the commands to launch your Streamlit app within your codespace. Your app will be visible in a "Simple Browser" on the right. This may take a minute to complete from when your codespace first appears on screen. When you make changes to your app, the file is automatically saved within your codespace. Your edits do not affect your repository unless you choose to commit those changes. We will describe committing your changes in a later step. In order to see updates automatically reflected on the right, click "Always rerun" when prompted after an edit. See your edits appear within the "Simple Browser" tab and keep going with more! Commit your changes to your repository (optional) After making edits to your app, you can choose to commit your edits to your repository to update your deployed app instantly. If you just want to keep your edits in your codespace to return to later, skip to Stop or delete your codespace. In the left navigation bar, click the source control icon. Fill out your desired commit message and click "Commit." Click "Yes" to stage and commit all your changes. To learn more about source control in GitHub Codespaces, check out Source control in GitHub Docs. Stop or delete your codespace When you are done, remember to stop your codespace on GitHub to avoid any undesired use of your capacity. Go to github.com/codespaces. At the bottom of the page, all your codespaces are listed. Click the overflow menu icon (more_horiz) for your codespace. Click "Stop codespace" if you'd like to return to your work later. Otherwise, click "Delete." Previous: Delete your appNext: Favorite your appforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy
https://docs.streamlit.io/develop/api-reference/app-testing/testing-element-classes#elementvalue
DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceremovePAGE ELEMENTSWrite and magicaddText elementsaddData elementsaddChart elementsaddInput widgetsaddMedia elementsaddLayouts and containersaddChat elementsaddStatus elementsaddThird-party componentsopen_in_newAPPLICATION LOGICNavigation and pagesaddExecution flowaddCaching and stateaddConnections and secretsaddCustom componentsaddUtilitiesaddConfigurationaddTOOLSApp testingremovest.testing.v1.AppTestTesting element classesCommand lineaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Develop/API reference/App testing/Testing element classesTesting element classes st.testing.v1.element_tree.Block The Block class has the same methods and attributes as AppTest. A Block instance represents a container of elements just as AppTest represents the entire app. For example, Block.button will produce a WidgetList of Button in the same manner as AppTest.button. ChatMessage, Column, and Tab all inherit from Block. For all container classes, parameters of the original element can be obtained as properties. For example, ChatMessage.avatar and Tab.label. st.testing.v1.element_tree.ElementStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeElement base class for testing. This class's methods and attributes are universal for all elements implemented in testing. For example, Caption, Code, Text, and Title inherit from Element. All widget classes also inherit from Element, but have additional methods specific to each widget type. See the AppTest class for the full list of supported elements. For all element classes, parameters of the original element can be obtained as properties. For example, Button.label, Caption.help, and Toast.icon. Class description[source] st.testing.v1.element_tree.Element(proto, root) Methods run(*, timeout=None) Run the AppTest script which contains the element. Attributes value The value or contents of the element. st.testing.v1.element_tree.ButtonStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.button and st.form_submit_button. Class description[source] st.testing.v1.element_tree.Button(proto, root) Methods click() Set the value of the button to True. run(*, timeout=None) Run the AppTest script which contains the element. set_value(v) Set the value of the button. Attributes value The value of the button. (bool) st.testing.v1.element_tree.ChatInputStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.chat_input. Class description[source] st.testing.v1.element_tree.ChatInput(proto, root) Methods run(*, timeout=None) Run the AppTest script which contains the element. set_value(v) Set the value of the widget. Attributes value The value of the widget. (str) st.testing.v1.element_tree.CheckboxStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.checkbox. Class description[source] st.testing.v1.element_tree.Checkbox(proto, root) Methods check() Set the value of the widget to True. run(*, timeout=None) Run the AppTest script which contains the element. set_value(v) Set the value of the widget. uncheck() Set the value of the widget to False. Attributes value The value of the widget. (bool) st.testing.v1.element_tree.ColorPickerStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.color_picker. Class description[source] st.testing.v1.element_tree.ColorPicker(proto, root) Methods pick(v) Set the value of the widget as a hex string. May omit the "#" prefix. run(*, timeout=None) Run the AppTest script which contains the element. set_value(v) Set the value of the widget as a hex string. Attributes value The currently selected value as a hex string. (str) st.testing.v1.element_tree.DateInputStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.date_input. Class description[source] st.testing.v1.element_tree.DateInput(proto, root) Methods run(*, timeout=None) Run the AppTest script which contains the element. set_value(v) Set the value of the widget. Attributes value The value of the widget. (date or Tuple of date) st.testing.v1.element_tree.MultiselectStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.multiselect. Class description[source] st.testing.v1.element_tree.Multiselect(proto, root) Methods run(*, timeout=None) Run the AppTest script which contains the element. select(v) Add a selection to the widget. Do nothing if the value is already selected. If testing a multiselect widget with repeated options, use set_value instead. set_value(v) Set the value of the multiselect widget. (list) unselect(v) Remove a selection from the widget. Do nothing if the value is not already selected. If a value is selected multiple times, the first instance is removed. Attributes format_func The widget's formatting function for displaying options. (callable) indices The indices of the currently selected values from the options. (list) value The currently selected values from the options. (list) st.testing.v1.element_tree.NumberInputStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.number_input. Class description[source] st.testing.v1.element_tree.NumberInput(proto, root) Methods decrement() Decrement the st.number_input widget as if the user clicked "-". increment() Increment the st.number_input widget as if the user clicked "+". run(*, timeout=None) Run the AppTest script which contains the element. set_value(v) Set the value of the st.number_input widget. Attributes value Get the current value of the st.number_input widget. st.testing.v1.element_tree.RadioStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.radio. Class description[source] st.testing.v1.element_tree.Radio(proto, root) Methods run(*, timeout=None) Run the AppTest script which contains the element. set_value(v) Set the selection by value. Attributes format_func The widget's formatting function for displaying options. (callable) index The index of the current selection. (int) value The currently selected value from the options. (Any) st.testing.v1.element_tree.SelectSliderStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.select_slider. Class description[source] st.testing.v1.element_tree.SelectSlider(proto, root) Methods run(*, timeout=None) Run the AppTest script which contains the element. set_range(lower, upper) Set the ranged selection by values. set_value(v) Set the (single) selection by value. Attributes format_func The widget's formatting function for displaying options. (callable) value The currently selected value or range. (Any or Sequence of Any) st.testing.v1.element_tree.SelectboxStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.selectbox. Class description[source] st.testing.v1.element_tree.Selectbox(proto, root) Methods run(*, timeout=None) Run the AppTest script which contains the element. select(v) Set the selection by value. select_index(index) Set the selection by index. set_value(v) Set the selection by value. Attributes format_func The widget's formatting function for displaying options. (callable) index The index of the current selection. (int) value The currently selected value from the options. (Any) st.testing.v1.element_tree.SliderStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.slider. Class description[source] st.testing.v1.element_tree.Slider(proto, root) Methods run(*, timeout=None) Run the AppTest script which contains the element. set_range(lower, upper) Set the ranged value of the slider. set_value(v) Set the (single) value of the slider. Attributes value The currently selected value or range. (Any or Sequence of Any) st.testing.v1.element_tree.TextAreaStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.text_area. Class description[source] st.testing.v1.element_tree.TextArea(proto, root) Methods input(v) Set the value of the widget only if the value does not exceed the maximum allowed characters. run(*, timeout=None) Run the AppTest script which contains the element. set_value(v) Set the value of the widget. Attributes value The current value of the widget. (str) st.testing.v1.element_tree.TextInputStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.text_input. Class description[source] st.testing.v1.element_tree.TextInput(proto, root) Methods input(v) Set the value of the widget only if the value does not exceed the maximum allowed characters. run(*, timeout=None) Run the AppTest script which contains the element. set_value(v) Set the value of the widget. Attributes value The current value of the widget. (str) st.testing.v1.element_tree.TimeInputStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.time_input. Class description[source] st.testing.v1.element_tree.TimeInput(proto, root) Methods decrement() Select the previous available time. increment() Select the next available time. run(*, timeout=None) Run the AppTest script which contains the element. set_value(v) Set the value of the widget. Attributes value The current value of the widget. (time) st.testing.v1.element_tree.ToggleStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.toggle. Class description[source] st.testing.v1.element_tree.Toggle(proto, root) Methods run(*, timeout=None) Run the AppTest script which contains the element. set_value(v) Set the value of the widget. Attributes value The current value of the widget. (bool) Previous: st.testing.v1.AppTestNext: Command lineforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy
https://docs.streamlit.io/en/0.69.0/api.html#media-elements
DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceremovePAGE ELEMENTSWrite and magicaddText elementsaddData elementsaddChart elementsaddInput widgetsaddMedia elementsaddLayouts and containersaddChat elementsaddStatus elementsaddThird-party componentsopen_in_newAPPLICATION LOGICNavigation and pagesaddExecution flowaddCaching and stateaddConnections and secretsaddCustom componentsaddUtilitiesaddConfigurationaddTOOLSApp testingaddCommand lineaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Develop/API referenceAPI reference Streamlit makes it easy for you to visualize, mutate, and share data. The API reference is organized by activity type, like displaying data or optimizing performance. Each section includes methods associated with the activity type, including examples. Browse our API below and click to learn more about any of our available commands! 🎈 Display almost anything Write and magic st.writeWrite arguments to the app.st.write("Hello **world**!") st.write(my_data_frame) st.write(my_mpl_figure) st.write_streamWrite generators or streams to the app with a typewriter effect.st.write_stream(my_generator) st.write_stream(my_llm_stream) MagicAny time Streamlit sees either a variable or literal value on its own line, it automatically writes that to your app using st.write"Hello **world**!" my_data_frame my_mpl_figure Text elements MarkdownDisplay string formatted as Markdown.st.markdown("Hello **world**!") TitleDisplay text in title formatting.st.title("The app title") HeaderDisplay text in header formatting.st.header("This is a header") SubheaderDisplay text in subheader formatting.st.subheader("This is a subheader") CaptionDisplay text in small font.st.caption("This is written small caption text") Code blockDisplay a code block with optional syntax highlighting.st.code("a = 1234") EchoDisplay some code in the app, then execute it. Useful for tutorials.with st.echo(): st.write('This code will be printed') LaTeXDisplay mathematical expressions formatted as LaTeX.st.latex("\int a x^2 \,dx") Preformatted textWrite fixed-width and preformatted text.st.text("Hello world") DividerDisplay a horizontal rule.st.divider() Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration! PreviousTagsAdd tags to your Streamlit apps. Created by @gagan3012.st_tags(label='# Enter Keywords:', text='Press enter to add more', value=['Zero', 'One', 'Two'], suggestions=['five', 'six', 'seven', 'eight', 'nine', 'three', 'eleven', 'ten', 'four'], maxtags = 4, key='1') NLUApply text mining on a dataframe. Created by @JohnSnowLabs.nlu.load('sentiment').predict('I love NLU! <3') Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.mention(label="An awesome Streamlit App", icon="streamlit", url="https://extras.streamlit.app",) Annotated textDisplay annotated text in Streamlit apps. Created by @tvst.annotated_text("This ", ("is", "verb"), " some ", ("annotated", "adj"), ("text", "noun"), " for those of ", ("you", "pronoun"), " who ", ("like", "verb"), " this sort of ", ("thing", "noun"), ".") Drawable CanvasProvides a sketching canvas using Fabric.js. Created by @andfanilo.st_canvas(fill_color="rgba(255, 165, 0, 0.3)", stroke_width=stroke_width, stroke_color=stroke_color, background_color=bg_color, background_image=Image.open(bg_image) if bg_image else None, update_streamlit=realtime_update, height=150, drawing_mode=drawing_mode, point_display_radius=point_display_radius if drawing_mode == 'point' else 0, key="canvas",) TagsAdd tags to your Streamlit apps. Created by @gagan3012.st_tags(label='# Enter Keywords:', text='Press enter to add more', value=['Zero', 'One', 'Two'], suggestions=['five', 'six', 'seven', 'eight', 'nine', 'three', 'eleven', 'ten', 'four'], maxtags = 4, key='1') NLUApply text mining on a dataframe. Created by @JohnSnowLabs.nlu.load('sentiment').predict('I love NLU! <3') Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.mention(label="An awesome Streamlit App", icon="streamlit", url="https://extras.streamlit.app",) Annotated textDisplay annotated text in Streamlit apps. Created by @tvst.annotated_text("This ", ("is", "verb"), " some ", ("annotated", "adj"), ("text", "noun"), " for those of ", ("you", "pronoun"), " who ", ("like", "verb"), " this sort of ", ("thing", "noun"), ".") Drawable CanvasProvides a sketching canvas using Fabric.js. Created by @andfanilo.st_canvas(fill_color="rgba(255, 165, 0, 0.3)", stroke_width=stroke_width, stroke_color=stroke_color, background_color=bg_color, background_image=Image.open(bg_image) if bg_image else None, update_streamlit=realtime_update, height=150, drawing_mode=drawing_mode, point_display_radius=point_display_radius if drawing_mode == 'point' else 0, key="canvas",) TagsAdd tags to your Streamlit apps. Created by @gagan3012.st_tags(label='# Enter Keywords:', text='Press enter to add more', value=['Zero', 'One', 'Two'], suggestions=['five', 'six', 'seven', 'eight', 'nine', 'three', 'eleven', 'ten', 'four'], maxtags = 4, key='1') NLUApply text mining on a dataframe. Created by @JohnSnowLabs.nlu.load('sentiment').predict('I love NLU! <3') Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.mention(label="An awesome Streamlit App", icon="streamlit", url="https://extras.streamlit.app",) Next Data elements DataframesDisplay a dataframe as an interactive table.st.dataframe(my_data_frame) Data editorDisplay a data editor widget.edited = st.data_editor(df, num_rows="dynamic") Column configurationConfigure the display and editing behavior of dataframes and data editors.st.column_config.NumberColumn("Price (in USD)", min_value=0, format="$%d") Static tablesDisplay a static table.st.table(my_data_frame) MetricsDisplay a metric in big bold font, with an optional indicator of how the metric changed.st.metric("My metric", 42, 2) Dicts and JSONDisplay object or string as a pretty-printed JSON string.st.json(my_dict) Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration! PreviousImage CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates value = streamlit_image_coordinates("https://placekitten.com/200/300") st.write(value) Plotly EventsMake Plotly charts interactive!. Created by @null-jones.from streamlit_plotly_events import plotly_events fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.metric_cards import style_metric_cards col3.metric(label="No Change", value=5000, delta=0) style_metric_cards() Streamlit AggridImplementation of Ag-Grid component for Streamlit. Created by @PablocFonseca.df = pd.DataFrame({'col1': [1, 2, 3], 'col2': [4, 5, 6]}) grid_return = AgGrid(df, editable=True) new_df = grid_return['data'] Streamlit FoliumStreamlit Component for rendering Folium maps. Created by @randyzwitch.m = folium.Map(location=[39.949610, -75.150282], zoom_start=16) folium.Marker([39.949610, -75.150282], popup="Liberty Bell", tooltip="Liberty Bell").add_to(m) st_data = st_folium(m, width=725) Pandas ProfilingPandas profiling component for Streamlit. Created by @okld.df = pd.read_csv("https://storage.googleapis.com/tf-datasets/titanic/train.csv") pr = df.profile_report() st_profile_report(pr) Image CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates value = streamlit_image_coordinates("https://placekitten.com/200/300") st.write(value) Plotly EventsMake Plotly charts interactive!. Created by @null-jones.from streamlit_plotly_events import plotly_events fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.metric_cards import style_metric_cards col3.metric(label="No Change", value=5000, delta=0) style_metric_cards() Streamlit AggridImplementation of Ag-Grid component for Streamlit. Created by @PablocFonseca.df = pd.DataFrame({'col1': [1, 2, 3], 'col2': [4, 5, 6]}) grid_return = AgGrid(df, editable=True) new_df = grid_return['data'] Streamlit FoliumStreamlit Component for rendering Folium maps. Created by @randyzwitch.m = folium.Map(location=[39.949610, -75.150282], zoom_start=16) folium.Marker([39.949610, -75.150282], popup="Liberty Bell", tooltip="Liberty Bell").add_to(m) st_data = st_folium(m, width=725) Pandas ProfilingPandas profiling component for Streamlit. Created by @okld.df = pd.read_csv("https://storage.googleapis.com/tf-datasets/titanic/train.csv") pr = df.profile_report() st_profile_report(pr) Image CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates value = streamlit_image_coordinates("https://placekitten.com/200/300") st.write(value) Plotly EventsMake Plotly charts interactive!. Created by @null-jones.from streamlit_plotly_events import plotly_events fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.metric_cards import style_metric_cards col3.metric(label="No Change", value=5000, delta=0) style_metric_cards() Next Chart elements Simple area chartsDisplay an area chart.st.area_chart(my_data_frame) Simple bar chartsDisplay a bar chart.st.bar_chart(my_data_frame) Simple line chartsDisplay a line chart.st.line_chart(my_data_frame) Simple scatter chartsDisplay a line chart.st.scatter_chart(my_data_frame) Scatterplots on mapsDisplay a map with points on it.st.map(my_data_frame) MatplotlibDisplay a matplotlib.pyplot figure.st.pyplot(my_mpl_figure) AltairDisplay a chart using the Altair library.st.altair_chart(my_altair_chart) Vega-LiteDisplay a chart using the Vega-Lite library.st.vega_lite_chart(my_vega_lite_chart) PlotlyDisplay an interactive Plotly chart.st.plotly_chart(my_plotly_chart) BokehDisplay an interactive Bokeh chart.st.bokeh_chart(my_bokeh_chart) PyDeckDisplay a chart using the PyDeck library.st.pydeck_chart(my_pydeck_chart) GraphVizDisplay a graph using the dagre-d3 library.st.graphviz_chart(my_graphviz_spec) Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration! PreviousStreamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl("https://assets5.lottiefiles.com/packages/lf20_V9t630.json") st_lottie(lottie_hello, key="hello") Plotly EventsMake Plotly charts interactive!. Created by @null-jones.fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.chart += get_annotations_chart(annotations=[("Mar 01, 2008", "Pretty good day for GOOG"), ("Dec 01, 2007", "Something's going wrong for GOOG & AAPL"), ("Nov 01, 2008", "Market starts again thanks to..."), ("Dec 01, 2009", "Small crash for GOOG after..."),],) st.altair_chart(chart, use_container_width=True) PlostA deceptively simple plotting library for Streamlit. Created by @tvst.import plost plost.line_chart(my_dataframe, x='time', y='stock_value', color='stock_name',) HiPlotHigh dimensional Interactive Plotting. Created by @facebookresearch.data = [{'dropout':0.1, 'lr': 0.001, 'loss': 10.0, 'optimizer': 'SGD'}, {'dropout':0.15, 'lr': 0.01, 'loss': 3.5, 'optimizer': 'Adam'}, {'dropout':0.3, 'lr': 0.1, 'loss': 4.5, 'optimizer': 'Adam'}] hip.Experiment.from_iterable(data).display() EChartsHigh dimensional Interactive Plotting. Created by @andfanilo.from streamlit_echarts import st_echarts st_echarts(options=options) Streamlit FoliumStreamlit Component for rendering Folium maps. Created by @randyzwitch.m = folium.Map(location=[39.949610, -75.150282], zoom_start=16) st_data = st_folium(m, width=725) Spacy-StreamlitspaCy building blocks and visualizers for Streamlit apps. Created by @explosion.models = ["en_core_web_sm", "en_core_web_md"] spacy_streamlit.visualize(models, "Sundar Pichai is the CEO of Google.") Streamlit AgraphA Streamlit Graph Vis, based on react-grah-vis. Created by @ChrisDelClea.from streamlit_agraph import agraph, Node, Edge, Config agraph(nodes=nodes, edges=edges, config=config) Streamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl("https://assets5.lottiefiles.com/packages/lf20_V9t630.json") st_lottie(lottie_hello, key="hello") Plotly EventsMake Plotly charts interactive!. Created by @null-jones.fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.chart += get_annotations_chart(annotations=[("Mar 01, 2008", "Pretty good day for GOOG"), ("Dec 01, 2007", "Something's going wrong for GOOG & AAPL"), ("Nov 01, 2008", "Market starts again thanks to..."), ("Dec 01, 2009", "Small crash for GOOG after..."),],) st.altair_chart(chart, use_container_width=True) PlostA deceptively simple plotting library for Streamlit. Created by @tvst.import plost plost.line_chart(my_dataframe, x='time', y='stock_value', color='stock_name',) HiPlotHigh dimensional Interactive Plotting. Created by @facebookresearch.data = [{'dropout':0.1, 'lr': 0.001, 'loss': 10.0, 'optimizer': 'SGD'}, {'dropout':0.15, 'lr': 0.01, 'loss': 3.5, 'optimizer': 'Adam'}, {'dropout':0.3, 'lr': 0.1, 'loss': 4.5, 'optimizer': 'Adam'}] hip.Experiment.from_iterable(data).display() EChartsHigh dimensional Interactive Plotting. Created by @andfanilo.from streamlit_echarts import st_echarts st_echarts(options=options) Streamlit FoliumStreamlit Component for rendering Folium maps. Created by @randyzwitch.m = folium.Map(location=[39.949610, -75.150282], zoom_start=16) st_data = st_folium(m, width=725) Spacy-StreamlitspaCy building blocks and visualizers for Streamlit apps. Created by @explosion.models = ["en_core_web_sm", "en_core_web_md"] spacy_streamlit.visualize(models, "Sundar Pichai is the CEO of Google.") Streamlit AgraphA Streamlit Graph Vis, based on react-grah-vis. Created by @ChrisDelClea.from streamlit_agraph import agraph, Node, Edge, Config agraph(nodes=nodes, edges=edges, config=config) Streamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl("https://assets5.lottiefiles.com/packages/lf20_V9t630.json") st_lottie(lottie_hello, key="hello") Plotly EventsMake Plotly charts interactive!. Created by @null-jones.fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.chart += get_annotations_chart(annotations=[("Mar 01, 2008", "Pretty good day for GOOG"), ("Dec 01, 2007", "Something's going wrong for GOOG & AAPL"), ("Nov 01, 2008", "Market starts again thanks to..."), ("Dec 01, 2009", "Small crash for GOOG after..."),],) st.altair_chart(chart, use_container_width=True) Next Input widgets ButtonDisplay a button widget.clicked = st.button("Click me") Download buttonDisplay a download button widget.st.download_button("Download file", file) Form buttonDisplay a form submit button. For use with st.form.st.form_submit_button("Sign up") Link buttonDisplay a link button.st.link_button("Go to gallery", url) Page linkDisplay a link to another page in a multipage app.st.page_link("app.py", label="Home", icon="🏠") st.page_link("pages/profile.py", label="My profile") CheckboxDisplay a checkbox widget.selected = st.checkbox("I agree") Color pickerDisplay a color picker widget.color = st.color_picker("Pick a color") MultiselectDisplay a multiselect widget. The multiselect widget starts as empty.choices = st.multiselect("Buy", ["milk", "apples", "potatoes"]) RadioDisplay a radio button widget.choice = st.radio("Pick one", ["cats", "dogs"]) SelectboxDisplay a select widget.choice = st.selectbox("Pick one", ["cats", "dogs"]) Select-sliderDisplay a slider widget to select items from a list.size = st.select_slider("Pick a size", ["S", "M", "L"]) ToggleDisplay a toggle widget.activated = st.toggle("Activate") Number inputDisplay a numeric input widget.choice = st.number_input("Pick a number", 0, 10) SliderDisplay a slider widget.number = st.slider("Pick a number", 0, 100) Date inputDisplay a date input widget.date = st.date_input("Your birthday") Time inputDisplay a time input widget.time = st.time_input("Meeting time") Chat inputDisplay a chat input widget.prompt = st.chat_input("Say something") if prompt: st.write(f"The user has sent: {prompt}") Text-areaDisplay a multi-line text input widget.text = st.text_area("Text to translate") Text inputDisplay a single-line text input widget.name = st.text_input("First name") Data editorDisplay a data editor widget.edited = st.experimental_data_editor(df, num_rows="dynamic") File UploaderDisplay a file uploader widget.data = st.file_uploader("Upload a CSV") Camera inputDisplay a widget that allows users to upload images directly from a camera.image = st.camera_input("Take a picture") Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration! PreviousStreamlit ChatStreamlit Component for a Chatbot UI. Created by @AI-Yash.from streamlit_chat import message message("My message") message("Hello bot!", is_user=True) # align's the message to the right Streamlit Option MenuSelect a single item from a list of options in a menu. Created by @victoryhb.from streamlit_option_menu import option_menu option_menu("Main Menu", ["Home", 'Settings'], icons=['house', 'gear'], menu_icon="cast", default_index=1) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.stoggle import stoggle stoggle( "Click me!", """🥷 Surprise! Here's some additional content""",) Streamlit ElementsCreate a draggable and resizable dashboard in Streamlit. Created by @okls.from streamlit_elements import elements, mui, html with elements("new_element"): mui.Typography("Hello world") TagsAdd tags to your Streamlit apps. Created by @gagan3012.from streamlit_tags import st_tags st_tags(label='# Enter Keywords:', text='Press enter to add more', value=['Zero', 'One', 'Two'], suggestions=['five', 'six', 'seven', 'eight', 'nine', 'three', 'eleven', 'ten', 'four'], maxtags = 4, key='1') StqdmThe simplest way to handle a progress bar in streamlit app. Created by @Wirg.from stqdm import stqdm for _ in stqdm(range(50)): sleep(0.5) TimelineDisplay a Timeline in Streamlit apps using TimelineJS. Created by @innerdoc.from streamlit_timeline import timeline with open('example.json', "r") as f: timeline(f.read(), height=800) Camera input liveAlternative for st.camera_input which returns the webcam images live. Created by @blackary.from camera_input_live import camera_input_live image = camera_input_live() st.image(value) Streamlit AceAce editor component for Streamlit. Created by @okld.from streamlit_ace import st_ace content = st_ace() content Streamlit ChatStreamlit Component for a Chatbot UI. Created by @AI-Yash.from streamlit_chat import message message("My message") message("Hello bot!", is_user=True) # align's the message to the right Streamlit Option MenuSelect a single item from a list of options in a menu. Created by @victoryhb.from streamlit_option_menu import option_menu option_menu("Main Menu", ["Home", 'Settings'], icons=['house', 'gear'], menu_icon="cast", default_index=1) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.stoggle import stoggle stoggle( "Click me!", """🥷 Surprise! Here's some additional content""",) Streamlit ElementsCreate a draggable and resizable dashboard in Streamlit. Created by @okls.from streamlit_elements import elements, mui, html with elements("new_element"): mui.Typography("Hello world") TagsAdd tags to your Streamlit apps. Created by @gagan3012.from streamlit_tags import st_tags st_tags(label='# Enter Keywords:', text='Press enter to add more', value=['Zero', 'One', 'Two'], suggestions=['five', 'six', 'seven', 'eight', 'nine', 'three', 'eleven', 'ten', 'four'], maxtags = 4, key='1') StqdmThe simplest way to handle a progress bar in streamlit app. Created by @Wirg.from stqdm import stqdm for _ in stqdm(range(50)): sleep(0.5) TimelineDisplay a Timeline in Streamlit apps using TimelineJS. Created by @innerdoc.from streamlit_timeline import timeline with open('example.json', "r") as f: timeline(f.read(), height=800) Camera input liveAlternative for st.camera_input which returns the webcam images live. Created by @blackary.from camera_input_live import camera_input_live image = camera_input_live() st.image(value) Streamlit AceAce editor component for Streamlit. Created by @okld.from streamlit_ace import st_ace content = st_ace() content Streamlit ChatStreamlit Component for a Chatbot UI. Created by @AI-Yash.from streamlit_chat import message message("My message") message("Hello bot!", is_user=True) # align's the message to the right Streamlit Option MenuSelect a single item from a list of options in a menu. Created by @victoryhb.from streamlit_option_menu import option_menu option_menu("Main Menu", ["Home", 'Settings'], icons=['house', 'gear'], menu_icon="cast", default_index=1) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.stoggle import stoggle stoggle( "Click me!", """🥷 Surprise! Here's some additional content""",) Next Media elements ImageDisplay an image or list of images.st.image(numpy_array) st.image(image_bytes) st.image(file) st.image("https://example.com/myimage.jpg") AudioDisplay an audio player.st.audio(numpy_array) st.audio(audio_bytes) st.audio(file) st.audio("https://example.com/myaudio.mp3", format="audio/mp3") VideoDisplay a video player.st.video(numpy_array) st.video(video_bytes) st.video(file) st.video("https://example.com/myvideo.mp4", format="video/mp4") Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration! PreviousStreamlit CropperA simple image cropper for Streamlit. Created by @turner-anderson.from streamlit_cropper import st_cropper st_cropper(img, realtime_update=realtime_update, box_color=box_color, aspect_ratio=aspect_ratio) Image CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates streamlit_image_coordinates("https://placekitten.com/200/300") Streamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl("https://assets5.lottiefiles.com/packages/lf20_V9t630.json") st_lottie(lottie_hello, key="hello") Streamlit WebrtcHandling and transmitting real-time video/audio streams with Streamlit. Created by @whitphx.from streamlit_webrtc import webrtc_streamer webrtc_streamer(key="sample") Drawable CanvasProvides a sketching canvas using Fabric.js. Created by @andfanilo.from streamlit_drawable_canvas import st_canvas st_canvas(fill_color="rgba(255, 165, 0, 0.3)", stroke_width=stroke_width, stroke_color=stroke_color, background_color=bg_color, background_image=Image.open(bg_image) if bg_image else None, update_streamlit=realtime_update, height=150, drawing_mode=drawing_mode, point_display_radius=point_display_radius if drawing_mode == 'point' else 0, key="canvas",) Image ComparisonCompare images with a slider using JuxtaposeJS. Created by @fcakyon.from streamlit_image_comparison import image_comparison image_comparison(img1="image1.jpg", img2="image2.jpg",) Streamlit CropperA simple image cropper for Streamlit. Created by @turner-anderson.from streamlit_cropper import st_cropper st_cropper(img, realtime_update=realtime_update, box_color=box_color, aspect_ratio=aspect_ratio) Image CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates streamlit_image_coordinates("https://placekitten.com/200/300") Streamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl("https://assets5.lottiefiles.com/packages/lf20_V9t630.json") st_lottie(lottie_hello, key="hello") Streamlit WebrtcHandling and transmitting real-time video/audio streams with Streamlit. Created by @whitphx.from streamlit_webrtc import webrtc_streamer webrtc_streamer(key="sample") Drawable CanvasProvides a sketching canvas using Fabric.js. Created by @andfanilo.from streamlit_drawable_canvas import st_canvas st_canvas(fill_color="rgba(255, 165, 0, 0.3)", stroke_width=stroke_width, stroke_color=stroke_color, background_color=bg_color, background_image=Image.open(bg_image) if bg_image else None, update_streamlit=realtime_update, height=150, drawing_mode=drawing_mode, point_display_radius=point_display_radius if drawing_mode == 'point' else 0, key="canvas",) Image ComparisonCompare images with a slider using JuxtaposeJS. Created by @fcakyon.from streamlit_image_comparison import image_comparison image_comparison(img1="image1.jpg", img2="image2.jpg",) Streamlit CropperA simple image cropper for Streamlit. Created by @turner-anderson.from streamlit_cropper import st_cropper st_cropper(img, realtime_update=realtime_update, box_color=box_color, aspect_ratio=aspect_ratio) Image CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates streamlit_image_coordinates("https://placekitten.com/200/300") Streamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl("https://assets5.lottiefiles.com/packages/lf20_V9t630.json") st_lottie(lottie_hello, key="hello") Next Layouts and containers ColumnsInsert containers laid out as side-by-side columns.col1, col2 = st.columns(2) col1.write("this is column 1") col2.write("this is column 2") ContainerInsert a multi-element container.c = st.container() st.write("This will show last") c.write("This will show first") c.write("This will show second") Modal dialogsInsert a modal dialog that can rerun independently from the rest of the script.@st.experimental_dialog("Sign up") def email_form(): name = st.text_input("Name") email = st.text_input("Email") EmptyInsert a single-element container.c = st.empty() st.write("This will show last") c.write("This will be replaced") c.write("This will show first") ExpanderInsert a multi-element container that can be expanded/collapsed.with st.expander("Open to see more"): st.write("This is more content") PopoverInsert a multi-element popover container that can be opened/closed.with st.popover("Settings"): st.checkbox("Show completed") SidebarDisplay items in a sidebar.st.sidebar.write("This lives in the sidebar") st.sidebar.button("Click me!") TabsInsert containers separated into tabs.tab1, tab2 = st.tabs(["Tab 1", "Tab2"]) tab1.write("this is tab 1") tab2.write("this is tab 2") Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration!Streamlit ElementsCreate a draggable and resizable dashboard in Streamlit. Created by @okls.from streamlit_elements import elements, mui, html with elements("new_element"): mui.Typography("Hello world") PydanticAuto-generate Streamlit UI from Pydantic Models and Dataclasses. Created by @lukasmasuch.import streamlit_pydantic as sp sp.pydantic_form(key="my_form", model=ExampleModel) Streamlit PagesAn experimental version of Streamlit Multi-Page Apps. Created by @blackary.from st_pages import Page, show_pages, add_page_title show_pages([ Page("streamlit_app.py", "Home", "🏠"), Page("other_pages/page2.py", "Page 2", ":books:"), ]) Chat elements Streamlit provides a few commands to help you build conversational apps. These chat elements are designed to be used in conjunction with each other, but you can also use them separately. st.chat_message lets you insert a chat message container into the app so you can display messages from the user or the app. Chat containers can contain other Streamlit elements, including charts, tables, text, and more. st.chat_input lets you display a chat input widget so the user can type in a message. Chat inputDisplay a chat input widget.prompt = st.chat_input("Say something") if prompt: st.write(f"The user has sent: {prompt}") Chat messageInsert a chat message container.import numpy as np with st.chat_message("user"): st.write("Hello 👋") st.line_chart(np.random.randn(30, 3)) Status containerDisplay output of long-running tasks in a container.with st.status('Running'): do_something_slow() st.write_streamWrite generators or streams to the app with a typewriter effect.st.write_stream(my_generator) st.write_stream(my_llm_stream) Status elements Progress barDisplay a progress bar.for i in range(101): st.progress(i) do_something_slow() SpinnerTemporarily displays a message while executing a block of code.with st.spinner("Please wait..."): do_something_slow() Status containerDisplay output of long-running tasks in a container.with st.status('Running'): do_something_slow() ToastBriefly displays a toast message in the bottom-right corner.st.toast('Butter!', icon='🧈') BalloonsDisplay celebratory balloons!do_something() # Celebrate when all done! st.balloons() SnowflakesDisplay celebratory snowflakes!do_something() # Celebrate when all done! st.snow() Success boxDisplay a success message.st.success("Match found!") Info boxDisplay an informational message.st.info("Dataset is updated every day at midnight.") Warning boxDisplay warning message.st.warning("Unable to fetch image. Skipping...") Error boxDisplay error message.st.error("We encountered an error") Exception outputDisplay an exception.e = RuntimeError("This is an exception of type RuntimeError") st.exception(e) Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration!StqdmThe simplest way to handle a progress bar in streamlit app. Created by @Wirg.from stqdm import stqdm for _ in stqdm(range(50)): sleep(0.5) Custom notification boxA custom notification box with the ability to close it out. Created by @Socvest.from streamlit_custom_notification_box import custom_notification_box styles = {'material-icons':{'color': 'red'}, 'text-icon-link-close-container': {'box-shadow': '#3896de 0px 4px'}, 'notification-text': {'':''}, 'close-button':{'':''}, 'link':{'':''}} custom_notification_box(icon='info', textDisplay='We are almost done with your registration...', externalLink='more info', url='#', styles=styles, key="foo") Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.let_it_rain import rain rain(emoji="🎈", font_size=54, falling_speed=5, animation_length="infinite",) App logic and configuration Navigation and pages Switch pageProgrammatically navigates to a specified page.st.switch_page("pages/my_page.py") Page linkDisplay a link to another page in a multipage app.st.page_link("app.py", label="Home", icon="🏠") st.page_link("pages/profile.py", label="My profile") Execution flow Modal dialogsInsert a modal dialog that can rerun independently from the rest of the script.@st.experimental_dialog("Sign up") def email_form(): name = st.text_input("Name") email = st.text_input("Email") FormsCreate a form that batches elements together with a “Submit" button.with st.form(key='my_form'): name = st.text_input("Name") email = st.text_input("Email") st.form_submit_button("Sign up") Partial rerunsDefine a fragment to rerun independently from the rest of the script.@st.experimental_fragment(run_every="10s") def fragment(): df = get_data() st.line_chart(df) Rerun scriptRerun the script immediately.st.rerun() Stop executionStops execution immediately.st.stop() Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration!AutorefreshForce a refresh without tying up a script. Created by @kmcgrady.from streamlit_autorefresh import st_autorefresh st_autorefresh(interval=2000, limit=100, key="fizzbuzzcounter") PydanticAuto-generate Streamlit UI from Pydantic Models and Dataclasses. Created by @lukasmasuch.import streamlit_pydantic as sp sp.pydantic_form(key="my_form", model=ExampleModel) Streamlit PagesAn experimental version of Streamlit Multi-Page Apps. Created by @blackary.from st_pages import Page, show_pages, add_page_title show_pages([ Page("streamlit_app.py", "Home", "🏠"), Page("other_pages/page2.py", "Page 2", ":books:"), ]) Caching and state Cache dataFunction decorator to cache functions that return data (e.g. dataframe transforms, database queries, ML inference).@st.cache_data def long_function(param1, param2): # Perform expensive computation here or # fetch data from the web here return data Cache resourceFunction decorator to cache functions that return global resources (e.g. database connections, ML models).@st.cache_resource def init_model(): # Return a global resource here return pipeline( "sentiment-analysis", model="distilbert-base-uncased-finetuned-sst-2-english" ) Session stateSession state is a way to share variables between reruns, for each user session.st.session_state['key'] = value Query parametersGet, set, or clear the query parameters that are shown in the browser's URL bar.st.query_params[key] = value st.query_params.clear() Connections and databases Setup your connection Create a connectionConnect to a data source or APIconn = st.connection('pets_db', type='sql') pet_owners = conn.query('select * from pet_owners') st.dataframe(pet_owners) Built-in connections SnowflakeConnectionA connection to Snowflake.conn = st.connection('snowflake') SQLConnectionA connection to a SQL database using SQLAlchemy.conn = st.connection('sql') Build your own connections Connection base classBuild your own connection with BaseConnection.class MyConnection(BaseConnection[myconn.MyConnection]): def _connect(self, **kwargs) -> MyConnection: return myconn.connect(**self._secrets, **kwargs) def query(self, query): return self._instance.query(query) Secrets management Secrets singletonAccess secrets from a local TOML file.key = st.secrets["OpenAI_key"] Secrets fileSave your secrets in a per-project or per-profile TOML file.OpenAI_key = "<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/app-chrome#clear-cache
DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsremoveCOREArchitecture & executionremoveRunning your appStreamlit's architectureThe app chromeCachingSession StateFormsFragmentsWidget behaviorMultipage appsaddApp designaddADDITIONALConnections and secretsaddCustom componentsaddConfiguration and themingaddApp testingaddAPI referenceaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Develop/Concepts/Architecture & execution/The app chromeThe app chrome Your Streamlit app has a few widgets in the top right to help you as you develop. These widgets also help your viewers as they use your app. We call this things “the app chrome”. The chrome includes a status area, toolbar, and app menu. Your app menu is configurable. By default, you can access developer options from the app menu when viewing an app locally or on Streamlit Community Cloud while logged into an account with administrative access. While viewing an app, click the icon in the upper-right corner to access the menu. Menu options The menu is split into two sections. The upper section contains options available to all viewers and the lower section contains options for developers. Read more about customizing this menu at the end of this page. Rerun You can manually trigger a rerun of your app by clicking "Rerun" from the app menu. This rerun will not reset your session. Your widget states and values stored in st.session_state will be preserved. As a shortcut, without opening the app menu, you can rerun your app by pressing "R" on your keyboard (if you aren't currently focused on an input element). Settings With the "Settings" option, you can control the appearance of your app while it is running. If viewing the app locally, you can set how your app responds to changes in your source code. See more about development flow in Basic concepts. You can also force your app to appear in wide mode, even if not set within the script using st.set_page_config. Theme settings After clicking "Settings" from the app menu, you can choose between "Light", "Dark", or "Use system setting" for the app's base theme. Click on "Edit active theme" to modify the theme, color-by-color. Print Click "Print" or use keyboard shortcuts (⌘+P or Ctrl+P) to open a print dialog. This option uses your browser's built-in print-to-pdf function. To modify the appearance of your print, you can do the following: Expand or collapse the sidebar before printing to respectively include or exclude it from the print. Resize the sidebar in your app by clicking and dragging its right border to achieve your desired width. You may need to enable "Background graphics" in your print dialog if you are printing in dark mode. You may need to disable wide mode in Settings or adjust the print scale to prevent elements from clipping off the page. Record a screencast You can easily make screen recordings right from your app! Screen recording is supported in the latest versions of Chrome, Edge, and Firefox. Ensure your browser is up-to-date for compatibility. Depending on your current settings, you may need to grant permission to your browser to record your screen or to use your microphone if recording a voiceover. While viewing your app, open the app menu from the upper-right corner. Click "Record a screencast." If you want to record audio through your microphone, check "Also record audio." Click "Start recording." (You may be prompted by your OS to permit your browser to record your screen or use your microphone.) Select which tab, window, or monitor you want to record from the listed options. The interface will vary depending on your browser. Click "Share." While recording, you will see a red circle on your app's tab and on the app menu icon. If you want to cancel the recording, click "Stop sharing" at the bottom of your app. When you are done recording, press "Esc" on your keyboard or click "Stop recording" from your app's menu. Follow your browser's instructions to save your recording. Your saved recording will be available where your browser saves downloads. The whole process looks like this: About You can conveniently check what version of Streamlit is running from the "About" option. Developers also have the option to customize the message shown here using st.set_page_config. Developer options By default, developer options only show when viewing an app locally or when viewing a Community Cloud app while logged in with administrative permission. You can customize the menu if you want to make these options available for all users. Clear cache Reset your app's cache by clicking "Clear cache" from the app's menu or by pressing "C" on your keyboard while not focused on an input element. This will remove all cached entries for @st.cache_data and @st.cache_resource. Deploy this app If you are running an app locally from within a git repo, you can deploy your app to Streamlit Community Cloud in a few easy clicks! Make sure your work has been pushed to your online GitHub repository before beginning. For the greatest convenience, make sure you have already created your Community Cloud account and are signed in. Click "Deploy" next to the app menu icon (more_vert). Click "Deploy now". You will be taken to Community Cloud's "Deploy an app" page. Your app's repository, branch, and file name will be prefilled to match your current app! Learn more about deploying an app on Streamlit Community Cloud. The whole process looks like this: Customize the menu Using client.toolbarMode in your app's configuration, you can make the app menu appear in the following ways: "developer" — Show the developer options to all viewers. "viewer" — Hide the developer options from all viewers. "minimal" — Show only those options set externally. These options can be declared through st.set_page_config or populated through Streamlit Community Cloud. "auto" — This is the default and will show the developer options when accessed through localhost or through Streamlit Community Cloud when logged into an administrative account for the app. Otherwise, the developer options will not show. Previous: Streamlit's architectureNext: CachingforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy
https://docs.streamlit.io/develop/api-reference/app-testing/testing-element-classes#testing-element-classes
DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceremovePAGE ELEMENTSWrite and magicaddText elementsaddData elementsaddChart elementsaddInput widgetsaddMedia elementsaddLayouts and containersaddChat elementsaddStatus elementsaddThird-party componentsopen_in_newAPPLICATION LOGICNavigation and pagesaddExecution flowaddCaching and stateaddConnections and secretsaddCustom componentsaddUtilitiesaddConfigurationaddTOOLSApp testingremovest.testing.v1.AppTestTesting element classesCommand lineaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Develop/API reference/App testing/Testing element classesTesting element classes st.testing.v1.element_tree.Block The Block class has the same methods and attributes as AppTest. A Block instance represents a container of elements just as AppTest represents the entire app. For example, Block.button will produce a WidgetList of Button in the same manner as AppTest.button. ChatMessage, Column, and Tab all inherit from Block. For all container classes, parameters of the original element can be obtained as properties. For example, ChatMessage.avatar and Tab.label. st.testing.v1.element_tree.ElementStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeElement base class for testing. This class's methods and attributes are universal for all elements implemented in testing. For example, Caption, Code, Text, and Title inherit from Element. All widget classes also inherit from Element, but have additional methods specific to each widget type. See the AppTest class for the full list of supported elements. For all element classes, parameters of the original element can be obtained as properties. For example, Button.label, Caption.help, and Toast.icon. Class description[source] st.testing.v1.element_tree.Element(proto, root) Methods run(*, timeout=None) Run the AppTest script which contains the element. Attributes value The value or contents of the element. st.testing.v1.element_tree.ButtonStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.button and st.form_submit_button. Class description[source] st.testing.v1.element_tree.Button(proto, root) Methods click() Set the value of the button to True. run(*, timeout=None) Run the AppTest script which contains the element. set_value(v) Set the value of the button. Attributes value The value of the button. (bool) st.testing.v1.element_tree.ChatInputStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.chat_input. Class description[source] st.testing.v1.element_tree.ChatInput(proto, root) Methods run(*, timeout=None) Run the AppTest script which contains the element. set_value(v) Set the value of the widget. Attributes value The value of the widget. (str) st.testing.v1.element_tree.CheckboxStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.checkbox. Class description[source] st.testing.v1.element_tree.Checkbox(proto, root) Methods check() Set the value of the widget to True. run(*, timeout=None) Run the AppTest script which contains the element. set_value(v) Set the value of the widget. uncheck() Set the value of the widget to False. Attributes value The value of the widget. (bool) st.testing.v1.element_tree.ColorPickerStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.color_picker. Class description[source] st.testing.v1.element_tree.ColorPicker(proto, root) Methods pick(v) Set the value of the widget as a hex string. May omit the "#" prefix. run(*, timeout=None) Run the AppTest script which contains the element. set_value(v) Set the value of the widget as a hex string. Attributes value The currently selected value as a hex string. (str) st.testing.v1.element_tree.DateInputStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.date_input. Class description[source] st.testing.v1.element_tree.DateInput(proto, root) Methods run(*, timeout=None) Run the AppTest script which contains the element. set_value(v) Set the value of the widget. Attributes value The value of the widget. (date or Tuple of date) st.testing.v1.element_tree.MultiselectStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.multiselect. Class description[source] st.testing.v1.element_tree.Multiselect(proto, root) Methods run(*, timeout=None) Run the AppTest script which contains the element. select(v) Add a selection to the widget. Do nothing if the value is already selected. If testing a multiselect widget with repeated options, use set_value instead. set_value(v) Set the value of the multiselect widget. (list) unselect(v) Remove a selection from the widget. Do nothing if the value is not already selected. If a value is selected multiple times, the first instance is removed. Attributes format_func The widget's formatting function for displaying options. (callable) indices The indices of the currently selected values from the options. (list) value The currently selected values from the options. (list) st.testing.v1.element_tree.NumberInputStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.number_input. Class description[source] st.testing.v1.element_tree.NumberInput(proto, root) Methods decrement() Decrement the st.number_input widget as if the user clicked "-". increment() Increment the st.number_input widget as if the user clicked "+". run(*, timeout=None) Run the AppTest script which contains the element. set_value(v) Set the value of the st.number_input widget. Attributes value Get the current value of the st.number_input widget. st.testing.v1.element_tree.RadioStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.radio. Class description[source] st.testing.v1.element_tree.Radio(proto, root) Methods run(*, timeout=None) Run the AppTest script which contains the element. set_value(v) Set the selection by value. Attributes format_func The widget's formatting function for displaying options. (callable) index The index of the current selection. (int) value The currently selected value from the options. (Any) st.testing.v1.element_tree.SelectSliderStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.select_slider. Class description[source] st.testing.v1.element_tree.SelectSlider(proto, root) Methods run(*, timeout=None) Run the AppTest script which contains the element. set_range(lower, upper) Set the ranged selection by values. set_value(v) Set the (single) selection by value. Attributes format_func The widget's formatting function for displaying options. (callable) value The currently selected value or range. (Any or Sequence of Any) st.testing.v1.element_tree.SelectboxStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.selectbox. Class description[source] st.testing.v1.element_tree.Selectbox(proto, root) Methods run(*, timeout=None) Run the AppTest script which contains the element. select(v) Set the selection by value. select_index(index) Set the selection by index. set_value(v) Set the selection by value. Attributes format_func The widget's formatting function for displaying options. (callable) index The index of the current selection. (int) value The currently selected value from the options. (Any) st.testing.v1.element_tree.SliderStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.slider. Class description[source] st.testing.v1.element_tree.Slider(proto, root) Methods run(*, timeout=None) Run the AppTest script which contains the element. set_range(lower, upper) Set the ranged value of the slider. set_value(v) Set the (single) value of the slider. Attributes value The currently selected value or range. (Any or Sequence of Any) st.testing.v1.element_tree.TextAreaStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.text_area. Class description[source] st.testing.v1.element_tree.TextArea(proto, root) Methods input(v) Set the value of the widget only if the value does not exceed the maximum allowed characters. run(*, timeout=None) Run the AppTest script which contains the element. set_value(v) Set the value of the widget. Attributes value The current value of the widget. (str) st.testing.v1.element_tree.TextInputStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.text_input. Class description[source] st.testing.v1.element_tree.TextInput(proto, root) Methods input(v) Set the value of the widget only if the value does not exceed the maximum allowed characters. run(*, timeout=None) Run the AppTest script which contains the element. set_value(v) Set the value of the widget. Attributes value The current value of the widget. (str) st.testing.v1.element_tree.TimeInputStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.time_input. Class description[source] st.testing.v1.element_tree.TimeInput(proto, root) Methods decrement() Select the previous available time. increment() Select the next available time. run(*, timeout=None) Run the AppTest script which contains the element. set_value(v) Set the value of the widget. Attributes value The current value of the widget. (time) st.testing.v1.element_tree.ToggleStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.toggle. Class description[source] st.testing.v1.element_tree.Toggle(proto, root) Methods run(*, timeout=None) Run the AppTest script which contains the element. set_value(v) Set the value of the widget. Attributes value The current value of the widget. (bool) Previous: st.testing.v1.AppTestNext: Command lineforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy
https://docs.streamlit.io/en/0.75.0/api.html#layouts-and-containers
DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceremovePAGE ELEMENTSWrite and magicaddText elementsaddData elementsaddChart elementsaddInput widgetsaddMedia elementsaddLayouts and containersaddChat elementsaddStatus elementsaddThird-party componentsopen_in_newAPPLICATION LOGICNavigation and pagesaddExecution flowaddCaching and stateaddConnections and secretsaddCustom componentsaddUtilitiesaddConfigurationaddTOOLSApp testingaddCommand lineaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Develop/API referenceAPI reference Streamlit makes it easy for you to visualize, mutate, and share data. The API reference is organized by activity type, like displaying data or optimizing performance. Each section includes methods associated with the activity type, including examples. Browse our API below and click to learn more about any of our available commands! 🎈 Display almost anything Write and magic st.writeWrite arguments to the app.st.write("Hello **world**!") st.write(my_data_frame) st.write(my_mpl_figure) st.write_streamWrite generators or streams to the app with a typewriter effect.st.write_stream(my_generator) st.write_stream(my_llm_stream) MagicAny time Streamlit sees either a variable or literal value on its own line, it automatically writes that to your app using st.write"Hello **world**!" my_data_frame my_mpl_figure Text elements MarkdownDisplay string formatted as Markdown.st.markdown("Hello **world**!") TitleDisplay text in title formatting.st.title("The app title") HeaderDisplay text in header formatting.st.header("This is a header") SubheaderDisplay text in subheader formatting.st.subheader("This is a subheader") CaptionDisplay text in small font.st.caption("This is written small caption text") Code blockDisplay a code block with optional syntax highlighting.st.code("a = 1234") EchoDisplay some code in the app, then execute it. Useful for tutorials.with st.echo(): st.write('This code will be printed') LaTeXDisplay mathematical expressions formatted as LaTeX.st.latex("\int a x^2 \,dx") Preformatted textWrite fixed-width and preformatted text.st.text("Hello world") DividerDisplay a horizontal rule.st.divider() Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration! PreviousTagsAdd tags to your Streamlit apps. Created by @gagan3012.st_tags(label='# Enter Keywords:', text='Press enter to add more', value=['Zero', 'One', 'Two'], suggestions=['five', 'six', 'seven', 'eight', 'nine', 'three', 'eleven', 'ten', 'four'], maxtags = 4, key='1') NLUApply text mining on a dataframe. Created by @JohnSnowLabs.nlu.load('sentiment').predict('I love NLU! <3') Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.mention(label="An awesome Streamlit App", icon="streamlit", url="https://extras.streamlit.app",) Annotated textDisplay annotated text in Streamlit apps. Created by @tvst.annotated_text("This ", ("is", "verb"), " some ", ("annotated", "adj"), ("text", "noun"), " for those of ", ("you", "pronoun"), " who ", ("like", "verb"), " this sort of ", ("thing", "noun"), ".") Drawable CanvasProvides a sketching canvas using Fabric.js. Created by @andfanilo.st_canvas(fill_color="rgba(255, 165, 0, 0.3)", stroke_width=stroke_width, stroke_color=stroke_color, background_color=bg_color, background_image=Image.open(bg_image) if bg_image else None, update_streamlit=realtime_update, height=150, drawing_mode=drawing_mode, point_display_radius=point_display_radius if drawing_mode == 'point' else 0, key="canvas",) TagsAdd tags to your Streamlit apps. Created by @gagan3012.st_tags(label='# Enter Keywords:', text='Press enter to add more', value=['Zero', 'One', 'Two'], suggestions=['five', 'six', 'seven', 'eight', 'nine', 'three', 'eleven', 'ten', 'four'], maxtags = 4, key='1') NLUApply text mining on a dataframe. Created by @JohnSnowLabs.nlu.load('sentiment').predict('I love NLU! <3') Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.mention(label="An awesome Streamlit App", icon="streamlit", url="https://extras.streamlit.app",) Annotated textDisplay annotated text in Streamlit apps. Created by @tvst.annotated_text("This ", ("is", "verb"), " some ", ("annotated", "adj"), ("text", "noun"), " for those of ", ("you", "pronoun"), " who ", ("like", "verb"), " this sort of ", ("thing", "noun"), ".") Drawable CanvasProvides a sketching canvas using Fabric.js. Created by @andfanilo.st_canvas(fill_color="rgba(255, 165, 0, 0.3)", stroke_width=stroke_width, stroke_color=stroke_color, background_color=bg_color, background_image=Image.open(bg_image) if bg_image else None, update_streamlit=realtime_update, height=150, drawing_mode=drawing_mode, point_display_radius=point_display_radius if drawing_mode == 'point' else 0, key="canvas",) TagsAdd tags to your Streamlit apps. Created by @gagan3012.st_tags(label='# Enter Keywords:', text='Press enter to add more', value=['Zero', 'One', 'Two'], suggestions=['five', 'six', 'seven', 'eight', 'nine', 'three', 'eleven', 'ten', 'four'], maxtags = 4, key='1') NLUApply text mining on a dataframe. Created by @JohnSnowLabs.nlu.load('sentiment').predict('I love NLU! <3') Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.mention(label="An awesome Streamlit App", icon="streamlit", url="https://extras.streamlit.app",) Next Data elements DataframesDisplay a dataframe as an interactive table.st.dataframe(my_data_frame) Data editorDisplay a data editor widget.edited = st.data_editor(df, num_rows="dynamic") Column configurationConfigure the display and editing behavior of dataframes and data editors.st.column_config.NumberColumn("Price (in USD)", min_value=0, format="$%d") Static tablesDisplay a static table.st.table(my_data_frame) MetricsDisplay a metric in big bold font, with an optional indicator of how the metric changed.st.metric("My metric", 42, 2) Dicts and JSONDisplay object or string as a pretty-printed JSON string.st.json(my_dict) Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration! PreviousImage CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates value = streamlit_image_coordinates("https://placekitten.com/200/300") st.write(value) Plotly EventsMake Plotly charts interactive!. Created by @null-jones.from streamlit_plotly_events import plotly_events fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.metric_cards import style_metric_cards col3.metric(label="No Change", value=5000, delta=0) style_metric_cards() Streamlit AggridImplementation of Ag-Grid component for Streamlit. Created by @PablocFonseca.df = pd.DataFrame({'col1': [1, 2, 3], 'col2': [4, 5, 6]}) grid_return = AgGrid(df, editable=True) new_df = grid_return['data'] Streamlit FoliumStreamlit Component for rendering Folium maps. Created by @randyzwitch.m = folium.Map(location=[39.949610, -75.150282], zoom_start=16) folium.Marker([39.949610, -75.150282], popup="Liberty Bell", tooltip="Liberty Bell").add_to(m) st_data = st_folium(m, width=725) Pandas ProfilingPandas profiling component for Streamlit. Created by @okld.df = pd.read_csv("https://storage.googleapis.com/tf-datasets/titanic/train.csv") pr = df.profile_report() st_profile_report(pr) Image CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates value = streamlit_image_coordinates("https://placekitten.com/200/300") st.write(value) Plotly EventsMake Plotly charts interactive!. Created by @null-jones.from streamlit_plotly_events import plotly_events fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.metric_cards import style_metric_cards col3.metric(label="No Change", value=5000, delta=0) style_metric_cards() Streamlit AggridImplementation of Ag-Grid component for Streamlit. Created by @PablocFonseca.df = pd.DataFrame({'col1': [1, 2, 3], 'col2': [4, 5, 6]}) grid_return = AgGrid(df, editable=True) new_df = grid_return['data'] Streamlit FoliumStreamlit Component for rendering Folium maps. Created by @randyzwitch.m = folium.Map(location=[39.949610, -75.150282], zoom_start=16) folium.Marker([39.949610, -75.150282], popup="Liberty Bell", tooltip="Liberty Bell").add_to(m) st_data = st_folium(m, width=725) Pandas ProfilingPandas profiling component for Streamlit. Created by @okld.df = pd.read_csv("https://storage.googleapis.com/tf-datasets/titanic/train.csv") pr = df.profile_report() st_profile_report(pr) Image CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates value = streamlit_image_coordinates("https://placekitten.com/200/300") st.write(value) Plotly EventsMake Plotly charts interactive!. Created by @null-jones.from streamlit_plotly_events import plotly_events fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.metric_cards import style_metric_cards col3.metric(label="No Change", value=5000, delta=0) style_metric_cards() Next Chart elements Simple area chartsDisplay an area chart.st.area_chart(my_data_frame) Simple bar chartsDisplay a bar chart.st.bar_chart(my_data_frame) Simple line chartsDisplay a line chart.st.line_chart(my_data_frame) Simple scatter chartsDisplay a line chart.st.scatter_chart(my_data_frame) Scatterplots on mapsDisplay a map with points on it.st.map(my_data_frame) MatplotlibDisplay a matplotlib.pyplot figure.st.pyplot(my_mpl_figure) AltairDisplay a chart using the Altair library.st.altair_chart(my_altair_chart) Vega-LiteDisplay a chart using the Vega-Lite library.st.vega_lite_chart(my_vega_lite_chart) PlotlyDisplay an interactive Plotly chart.st.plotly_chart(my_plotly_chart) BokehDisplay an interactive Bokeh chart.st.bokeh_chart(my_bokeh_chart) PyDeckDisplay a chart using the PyDeck library.st.pydeck_chart(my_pydeck_chart) GraphVizDisplay a graph using the dagre-d3 library.st.graphviz_chart(my_graphviz_spec) Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration! PreviousStreamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl("https://assets5.lottiefiles.com/packages/lf20_V9t630.json") st_lottie(lottie_hello, key="hello") Plotly EventsMake Plotly charts interactive!. Created by @null-jones.fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.chart += get_annotations_chart(annotations=[("Mar 01, 2008", "Pretty good day for GOOG"), ("Dec 01, 2007", "Something's going wrong for GOOG & AAPL"), ("Nov 01, 2008", "Market starts again thanks to..."), ("Dec 01, 2009", "Small crash for GOOG after..."),],) st.altair_chart(chart, use_container_width=True) PlostA deceptively simple plotting library for Streamlit. Created by @tvst.import plost plost.line_chart(my_dataframe, x='time', y='stock_value', color='stock_name',) HiPlotHigh dimensional Interactive Plotting. Created by @facebookresearch.data = [{'dropout':0.1, 'lr': 0.001, 'loss': 10.0, 'optimizer': 'SGD'}, {'dropout':0.15, 'lr': 0.01, 'loss': 3.5, 'optimizer': 'Adam'}, {'dropout':0.3, 'lr': 0.1, 'loss': 4.5, 'optimizer': 'Adam'}] hip.Experiment.from_iterable(data).display() EChartsHigh dimensional Interactive Plotting. Created by @andfanilo.from streamlit_echarts import st_echarts st_echarts(options=options) Streamlit FoliumStreamlit Component for rendering Folium maps. Created by @randyzwitch.m = folium.Map(location=[39.949610, -75.150282], zoom_start=16) st_data = st_folium(m, width=725) Spacy-StreamlitspaCy building blocks and visualizers for Streamlit apps. Created by @explosion.models = ["en_core_web_sm", "en_core_web_md"] spacy_streamlit.visualize(models, "Sundar Pichai is the CEO of Google.") Streamlit AgraphA Streamlit Graph Vis, based on react-grah-vis. Created by @ChrisDelClea.from streamlit_agraph import agraph, Node, Edge, Config agraph(nodes=nodes, edges=edges, config=config) Streamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl("https://assets5.lottiefiles.com/packages/lf20_V9t630.json") st_lottie(lottie_hello, key="hello") Plotly EventsMake Plotly charts interactive!. Created by @null-jones.fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.chart += get_annotations_chart(annotations=[("Mar 01, 2008", "Pretty good day for GOOG"), ("Dec 01, 2007", "Something's going wrong for GOOG & AAPL"), ("Nov 01, 2008", "Market starts again thanks to..."), ("Dec 01, 2009", "Small crash for GOOG after..."),],) st.altair_chart(chart, use_container_width=True) PlostA deceptively simple plotting library for Streamlit. Created by @tvst.import plost plost.line_chart(my_dataframe, x='time', y='stock_value', color='stock_name',) HiPlotHigh dimensional Interactive Plotting. Created by @facebookresearch.data = [{'dropout':0.1, 'lr': 0.001, 'loss': 10.0, 'optimizer': 'SGD'}, {'dropout':0.15, 'lr': 0.01, 'loss': 3.5, 'optimizer': 'Adam'}, {'dropout':0.3, 'lr': 0.1, 'loss': 4.5, 'optimizer': 'Adam'}] hip.Experiment.from_iterable(data).display() EChartsHigh dimensional Interactive Plotting. Created by @andfanilo.from streamlit_echarts import st_echarts st_echarts(options=options) Streamlit FoliumStreamlit Component for rendering Folium maps. Created by @randyzwitch.m = folium.Map(location=[39.949610, -75.150282], zoom_start=16) st_data = st_folium(m, width=725) Spacy-StreamlitspaCy building blocks and visualizers for Streamlit apps. Created by @explosion.models = ["en_core_web_sm", "en_core_web_md"] spacy_streamlit.visualize(models, "Sundar Pichai is the CEO of Google.") Streamlit AgraphA Streamlit Graph Vis, based on react-grah-vis. Created by @ChrisDelClea.from streamlit_agraph import agraph, Node, Edge, Config agraph(nodes=nodes, edges=edges, config=config) Streamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl("https://assets5.lottiefiles.com/packages/lf20_V9t630.json") st_lottie(lottie_hello, key="hello") Plotly EventsMake Plotly charts interactive!. Created by @null-jones.fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.chart += get_annotations_chart(annotations=[("Mar 01, 2008", "Pretty good day for GOOG"), ("Dec 01, 2007", "Something's going wrong for GOOG & AAPL"), ("Nov 01, 2008", "Market starts again thanks to..."), ("Dec 01, 2009", "Small crash for GOOG after..."),],) st.altair_chart(chart, use_container_width=True) Next Input widgets ButtonDisplay a button widget.clicked = st.button("Click me") Download buttonDisplay a download button widget.st.download_button("Download file", file) Form buttonDisplay a form submit button. For use with st.form.st.form_submit_button("Sign up") Link buttonDisplay a link button.st.link_button("Go to gallery", url) Page linkDisplay a link to another page in a multipage app.st.page_link("app.py", label="Home", icon="🏠") st.page_link("pages/profile.py", label="My profile") CheckboxDisplay a checkbox widget.selected = st.checkbox("I agree") Color pickerDisplay a color picker widget.color = st.color_picker("Pick a color") MultiselectDisplay a multiselect widget. The multiselect widget starts as empty.choices = st.multiselect("Buy", ["milk", "apples", "potatoes"]) RadioDisplay a radio button widget.choice = st.radio("Pick one", ["cats", "dogs"]) SelectboxDisplay a select widget.choice = st.selectbox("Pick one", ["cats", "dogs"]) Select-sliderDisplay a slider widget to select items from a list.size = st.select_slider("Pick a size", ["S", "M", "L"]) ToggleDisplay a toggle widget.activated = st.toggle("Activate") Number inputDisplay a numeric input widget.choice = st.number_input("Pick a number", 0, 10) SliderDisplay a slider widget.number = st.slider("Pick a number", 0, 100) Date inputDisplay a date input widget.date = st.date_input("Your birthday") Time inputDisplay a time input widget.time = st.time_input("Meeting time") Chat inputDisplay a chat input widget.prompt = st.chat_input("Say something") if prompt: st.write(f"The user has sent: {prompt}") Text-areaDisplay a multi-line text input widget.text = st.text_area("Text to translate") Text inputDisplay a single-line text input widget.name = st.text_input("First name") Data editorDisplay a data editor widget.edited = st.experimental_data_editor(df, num_rows="dynamic") File UploaderDisplay a file uploader widget.data = st.file_uploader("Upload a CSV") Camera inputDisplay a widget that allows users to upload images directly from a camera.image = st.camera_input("Take a picture") Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration! PreviousStreamlit ChatStreamlit Component for a Chatbot UI. Created by @AI-Yash.from streamlit_chat import message message("My message") message("Hello bot!", is_user=True) # align's the message to the right Streamlit Option MenuSelect a single item from a list of options in a menu. Created by @victoryhb.from streamlit_option_menu import option_menu option_menu("Main Menu", ["Home", 'Settings'], icons=['house', 'gear'], menu_icon="cast", default_index=1) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.stoggle import stoggle stoggle( "Click me!", """🥷 Surprise! Here's some additional content""",) Streamlit ElementsCreate a draggable and resizable dashboard in Streamlit. Created by @okls.from streamlit_elements import elements, mui, html with elements("new_element"): mui.Typography("Hello world") TagsAdd tags to your Streamlit apps. Created by @gagan3012.from streamlit_tags import st_tags st_tags(label='# Enter Keywords:', text='Press enter to add more', value=['Zero', 'One', 'Two'], suggestions=['five', 'six', 'seven', 'eight', 'nine', 'three', 'eleven', 'ten', 'four'], maxtags = 4, key='1') StqdmThe simplest way to handle a progress bar in streamlit app. Created by @Wirg.from stqdm import stqdm for _ in stqdm(range(50)): sleep(0.5) TimelineDisplay a Timeline in Streamlit apps using TimelineJS. Created by @innerdoc.from streamlit_timeline import timeline with open('example.json', "r") as f: timeline(f.read(), height=800) Camera input liveAlternative for st.camera_input which returns the webcam images live. Created by @blackary.from camera_input_live import camera_input_live image = camera_input_live() st.image(value) Streamlit AceAce editor component for Streamlit. Created by @okld.from streamlit_ace import st_ace content = st_ace() content Streamlit ChatStreamlit Component for a Chatbot UI. Created by @AI-Yash.from streamlit_chat import message message("My message") message("Hello bot!", is_user=True) # align's the message to the right Streamlit Option MenuSelect a single item from a list of options in a menu. Created by @victoryhb.from streamlit_option_menu import option_menu option_menu("Main Menu", ["Home", 'Settings'], icons=['house', 'gear'], menu_icon="cast", default_index=1) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.stoggle import stoggle stoggle( "Click me!", """🥷 Surprise! Here's some additional content""",) Streamlit ElementsCreate a draggable and resizable dashboard in Streamlit. Created by @okls.from streamlit_elements import elements, mui, html with elements("new_element"): mui.Typography("Hello world") TagsAdd tags to your Streamlit apps. Created by @gagan3012.from streamlit_tags import st_tags st_tags(label='# Enter Keywords:', text='Press enter to add more', value=['Zero', 'One', 'Two'], suggestions=['five', 'six', 'seven', 'eight', 'nine', 'three', 'eleven', 'ten', 'four'], maxtags = 4, key='1') StqdmThe simplest way to handle a progress bar in streamlit app. Created by @Wirg.from stqdm import stqdm for _ in stqdm(range(50)): sleep(0.5) TimelineDisplay a Timeline in Streamlit apps using TimelineJS. Created by @innerdoc.from streamlit_timeline import timeline with open('example.json', "r") as f: timeline(f.read(), height=800) Camera input liveAlternative for st.camera_input which returns the webcam images live. Created by @blackary.from camera_input_live import camera_input_live image = camera_input_live() st.image(value) Streamlit AceAce editor component for Streamlit. Created by @okld.from streamlit_ace import st_ace content = st_ace() content Streamlit ChatStreamlit Component for a Chatbot UI. Created by @AI-Yash.from streamlit_chat import message message("My message") message("Hello bot!", is_user=True) # align's the message to the right Streamlit Option MenuSelect a single item from a list of options in a menu. Created by @victoryhb.from streamlit_option_menu import option_menu option_menu("Main Menu", ["Home", 'Settings'], icons=['house', 'gear'], menu_icon="cast", default_index=1) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.stoggle import stoggle stoggle( "Click me!", """🥷 Surprise! Here's some additional content""",) Next Media elements ImageDisplay an image or list of images.st.image(numpy_array) st.image(image_bytes) st.image(file) st.image("https://example.com/myimage.jpg") AudioDisplay an audio player.st.audio(numpy_array) st.audio(audio_bytes) st.audio(file) st.audio("https://example.com/myaudio.mp3", format="audio/mp3") VideoDisplay a video player.st.video(numpy_array) st.video(video_bytes) st.video(file) st.video("https://example.com/myvideo.mp4", format="video/mp4") Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration! PreviousStreamlit CropperA simple image cropper for Streamlit. Created by @turner-anderson.from streamlit_cropper import st_cropper st_cropper(img, realtime_update=realtime_update, box_color=box_color, aspect_ratio=aspect_ratio) Image CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates streamlit_image_coordinates("https://placekitten.com/200/300") Streamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl("https://assets5.lottiefiles.com/packages/lf20_V9t630.json") st_lottie(lottie_hello, key="hello") Streamlit WebrtcHandling and transmitting real-time video/audio streams with Streamlit. Created by @whitphx.from streamlit_webrtc import webrtc_streamer webrtc_streamer(key="sample") Drawable CanvasProvides a sketching canvas using Fabric.js. Created by @andfanilo.from streamlit_drawable_canvas import st_canvas st_canvas(fill_color="rgba(255, 165, 0, 0.3)", stroke_width=stroke_width, stroke_color=stroke_color, background_color=bg_color, background_image=Image.open(bg_image) if bg_image else None, update_streamlit=realtime_update, height=150, drawing_mode=drawing_mode, point_display_radius=point_display_radius if drawing_mode == 'point' else 0, key="canvas",) Image ComparisonCompare images with a slider using JuxtaposeJS. Created by @fcakyon.from streamlit_image_comparison import image_comparison image_comparison(img1="image1.jpg", img2="image2.jpg",) Streamlit CropperA simple image cropper for Streamlit. Created by @turner-anderson.from streamlit_cropper import st_cropper st_cropper(img, realtime_update=realtime_update, box_color=box_color, aspect_ratio=aspect_ratio) Image CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates streamlit_image_coordinates("https://placekitten.com/200/300") Streamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl("https://assets5.lottiefiles.com/packages/lf20_V9t630.json") st_lottie(lottie_hello, key="hello") Streamlit WebrtcHandling and transmitting real-time video/audio streams with Streamlit. Created by @whitphx.from streamlit_webrtc import webrtc_streamer webrtc_streamer(key="sample") Drawable CanvasProvides a sketching canvas using Fabric.js. Created by @andfanilo.from streamlit_drawable_canvas import st_canvas st_canvas(fill_color="rgba(255, 165, 0, 0.3)", stroke_width=stroke_width, stroke_color=stroke_color, background_color=bg_color, background_image=Image.open(bg_image) if bg_image else None, update_streamlit=realtime_update, height=150, drawing_mode=drawing_mode, point_display_radius=point_display_radius if drawing_mode == 'point' else 0, key="canvas",) Image ComparisonCompare images with a slider using JuxtaposeJS. Created by @fcakyon.from streamlit_image_comparison import image_comparison image_comparison(img1="image1.jpg", img2="image2.jpg",) Streamlit CropperA simple image cropper for Streamlit. Created by @turner-anderson.from streamlit_cropper import st_cropper st_cropper(img, realtime_update=realtime_update, box_color=box_color, aspect_ratio=aspect_ratio) Image CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates streamlit_image_coordinates("https://placekitten.com/200/300") Streamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl("https://assets5.lottiefiles.com/packages/lf20_V9t630.json") st_lottie(lottie_hello, key="hello") Next Layouts and containers ColumnsInsert containers laid out as side-by-side columns.col1, col2 = st.columns(2) col1.write("this is column 1") col2.write("this is column 2") ContainerInsert a multi-element container.c = st.container() st.write("This will show last") c.write("This will show first") c.write("This will show second") Modal dialogsInsert a modal dialog that can rerun independently from the rest of the script.@st.experimental_dialog("Sign up") def email_form(): name = st.text_input("Name") email = st.text_input("Email") EmptyInsert a single-element container.c = st.empty() st.write("This will show last") c.write("This will be replaced") c.write("This will show first") ExpanderInsert a multi-element container that can be expanded/collapsed.with st.expander("Open to see more"): st.write("This is more content") PopoverInsert a multi-element popover container that can be opened/closed.with st.popover("Settings"): st.checkbox("Show completed") SidebarDisplay items in a sidebar.st.sidebar.write("This lives in the sidebar") st.sidebar.button("Click me!") TabsInsert containers separated into tabs.tab1, tab2 = st.tabs(["Tab 1", "Tab2"]) tab1.write("this is tab 1") tab2.write("this is tab 2") Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration!Streamlit ElementsCreate a draggable and resizable dashboard in Streamlit. Created by @okls.from streamlit_elements import elements, mui, html with elements("new_element"): mui.Typography("Hello world") PydanticAuto-generate Streamlit UI from Pydantic Models and Dataclasses. Created by @lukasmasuch.import streamlit_pydantic as sp sp.pydantic_form(key="my_form", model=ExampleModel) Streamlit PagesAn experimental version of Streamlit Multi-Page Apps. Created by @blackary.from st_pages import Page, show_pages, add_page_title show_pages([ Page("streamlit_app.py", "Home", "🏠"), Page("other_pages/page2.py", "Page 2", ":books:"), ]) Chat elements Streamlit provides a few commands to help you build conversational apps. These chat elements are designed to be used in conjunction with each other, but you can also use them separately. st.chat_message lets you insert a chat message container into the app so you can display messages from the user or the app. Chat containers can contain other Streamlit elements, including charts, tables, text, and more. st.chat_input lets you display a chat input widget so the user can type in a message. Chat inputDisplay a chat input widget.prompt = st.chat_input("Say something") if prompt: st.write(f"The user has sent: {prompt}") Chat messageInsert a chat message container.import numpy as np with st.chat_message("user"): st.write("Hello 👋") st.line_chart(np.random.randn(30, 3)) Status containerDisplay output of long-running tasks in a container.with st.status('Running'): do_something_slow() st.write_streamWrite generators or streams to the app with a typewriter effect.st.write_stream(my_generator) st.write_stream(my_llm_stream) Status elements Progress barDisplay a progress bar.for i in range(101): st.progress(i) do_something_slow() SpinnerTemporarily displays a message while executing a block of code.with st.spinner("Please wait..."): do_something_slow() Status containerDisplay output of long-running tasks in a container.with st.status('Running'): do_something_slow() ToastBriefly displays a toast message in the bottom-right corner.st.toast('Butter!', icon='🧈') BalloonsDisplay celebratory balloons!do_something() # Celebrate when all done! st.balloons() SnowflakesDisplay celebratory snowflakes!do_something() # Celebrate when all done! st.snow() Success boxDisplay a success message.st.success("Match found!") Info boxDisplay an informational message.st.info("Dataset is updated every day at midnight.") Warning boxDisplay warning message.st.warning("Unable to fetch image. Skipping...") Error boxDisplay error message.st.error("We encountered an error") Exception outputDisplay an exception.e = RuntimeError("This is an exception of type RuntimeError") st.exception(e) Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration!StqdmThe simplest way to handle a progress bar in streamlit app. Created by @Wirg.from stqdm import stqdm for _ in stqdm(range(50)): sleep(0.5) Custom notification boxA custom notification box with the ability to close it out. Created by @Socvest.from streamlit_custom_notification_box import custom_notification_box styles = {'material-icons':{'color': 'red'}, 'text-icon-link-close-container': {'box-shadow': '#3896de 0px 4px'}, 'notification-text': {'':''}, 'close-button':{'':''}, 'link':{'':''}} custom_notification_box(icon='info', textDisplay='We are almost done with your registration...', externalLink='more info', url='#', styles=styles, key="foo") Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.let_it_rain import rain rain(emoji="🎈", font_size=54, falling_speed=5, animation_length="infinite",) App logic and configuration Navigation and pages Switch pageProgrammatically navigates to a specified page.st.switch_page("pages/my_page.py") Page linkDisplay a link to another page in a multipage app.st.page_link("app.py", label="Home", icon="🏠") st.page_link("pages/profile.py", label="My profile") Execution flow Modal dialogsInsert a modal dialog that can rerun independently from the rest of the script.@st.experimental_dialog("Sign up") def email_form(): name = st.text_input("Name") email = st.text_input("Email") FormsCreate a form that batches elements together with a “Submit" button.with st.form(key='my_form'): name = st.text_input("Name") email = st.text_input("Email") st.form_submit_button("Sign up") Partial rerunsDefine a fragment to rerun independently from the rest of the script.@st.experimental_fragment(run_every="10s") def fragment(): df = get_data() st.line_chart(df) Rerun scriptRerun the script immediately.st.rerun() Stop executionStops execution immediately.st.stop() Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration!AutorefreshForce a refresh without tying up a script. Created by @kmcgrady.from streamlit_autorefresh import st_autorefresh st_autorefresh(interval=2000, limit=100, key="fizzbuzzcounter") PydanticAuto-generate Streamlit UI from Pydantic Models and Dataclasses. Created by @lukasmasuch.import streamlit_pydantic as sp sp.pydantic_form(key="my_form", model=ExampleModel) Streamlit PagesAn experimental version of Streamlit Multi-Page Apps. Created by @blackary.from st_pages import Page, show_pages, add_page_title show_pages([ Page("streamlit_app.py", "Home", "🏠"), Page("other_pages/page2.py", "Page 2", ":books:"), ]) Caching and state Cache dataFunction decorator to cache functions that return data (e.g. dataframe transforms, database queries, ML inference).@st.cache_data def long_function(param1, param2): # Perform expensive computation here or # fetch data from the web here return data Cache resourceFunction decorator to cache functions that return global resources (e.g. database connections, ML models).@st.cache_resource def init_model(): # Return a global resource here return pipeline( "sentiment-analysis", model="distilbert-base-uncased-finetuned-sst-2-english" ) Session stateSession state is a way to share variables between reruns, for each user session.st.session_state['key'] = value Query parametersGet, set, or clear the query parameters that are shown in the browser's URL bar.st.query_params[key] = value st.query_params.clear() Connections and databases Setup your connection Create a connectionConnect to a data source or APIconn = st.connection('pets_db', type='sql') pet_owners = conn.query('select * from pet_owners') st.dataframe(pet_owners) Built-in connections SnowflakeConnectionA connection to Snowflake.conn = st.connection('snowflake') SQLConnectionA connection to a SQL database using SQLAlchemy.conn = st.connection('sql') Build your own connections Connection base classBuild your own connection with BaseConnection.class MyConnection(BaseConnection[myconn.MyConnection]): def _connect(self, **kwargs) -> MyConnection: return myconn.connect(**self._secrets, **kwargs) def query(self, query): return self._instance.query(query) Secrets management Secrets singletonAccess secrets from a local TOML file.key = st.secrets["OpenAI_key"] Secrets fileSave your secrets in a per-project or per-profile TOML file.OpenAI_key = "<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/get-started/installation/anaconda-distribution#whats-next
DocumentationsearchSearchrocket_launchGet startedInstallationremoveUse command lineUse Anaconda DistributionUse GitHub CodespacesUse SnowflakeFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Get started/Installation/Use Anaconda DistributionInstall Streamlit using Anaconda Distribution This page walks you through installing Streamlit locally using Anaconda Distribution. At the end, you'll build a simple "Hello world" app and run it. You can read more about Getting started with Anaconda Distribution in Anaconda's docs. If you prefer to manage your Python environments via command line, check out how to Install Streamlit using command line. Prerequisites A code editor Anaconda Distribution includes Python and basically everything you need to get started. The only thing left for you to choose is a code editor. Our favorite editor is VS Code, which is also what we use in all our tutorials. Knowledge about environment managers Environment managers create virtual environments to isolate Python package installations between projects. For a detailed introduction to Python environments, check out Python Virtual Environments: A Primer. But don't worry! In this guide we'll teach you how to install and use an environment manager (Anaconda). Install Anaconda Distribution Go to anaconda.com/download. Install Anaconda Distribution for your OS. Create an environment using Anaconda Navigator Open Anaconda Navigator (the graphical interface included with Anaconda Distribution). You can decline signing in to Anaconda if prompted. In the left menu, click "Environments". At the bottom of your environments list, click "Create". Enter "streamlitenv" for the name of your environment. Click "Create." Activate your environment Click the green play icon (play_circle) next to your environment. Click "Open Terminal." A terminal will open with your environment activated. Your environment's name will appear in parentheses at the beginning of your terminal's prompt to show that it's activated. Install Streamlit in your environment In your terminal, type: pip install streamlit To validate your installation, enter: streamlit hello If this doesn't work, use the long-form command: python -m streamlit hello The Streamlit Hello example app will automatically open in your browser. If it doesn't, open your browser and go to the localhost address indicated in your terminal, typically http://localhost:8501. Play around with the app! Close your terminal. Create a Hello World app and run it Open VS Code with a new project. Create a Python file named app.py in your project folder. Copy the following code into app.py and save it. import streamlit as st st.write("Hello World") Click your Python interpreter in the lower-right corner, then choose your streamlitenv environment from the drop-down. Right-click app.py in your file navigation and click "Open in integrated terminal". A terminal will open with your environment activated. Confirm this by looking for "(streamlitenv)" at the beginning of your next prompt. If it is not there, manually activate your environment with the command: conda activate streamlitenv In your terminal, type: streamlit run app.py If this doesn't work, use the long-form command: python -m streamlit run app.py Your app will automatically open in your browser. If it doesn't for any reason, open your browser and go to the localhost address indicated in your terminal, typically http://localhost:8501. Change st.write to st.title and save your file: import streamlit as st st.title("Hello World") In your browser, click "Always rerun" to instantly rerun your app whenever you save a change to your file. Your app will update! Keep making changes and you will see your changes as soon as you save your file. When you're done, you can stop your app with Ctrl+C in your terminal or just by closing your terminal. What's next? Read about our Basic concepts and try out more commands in your app.Previous: Use command lineNext: Use GitHub CodespacesforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy
https://docs.streamlit.io/en/0.75.0/api.html#chat-elements
DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceremovePAGE ELEMENTSWrite and magicaddText elementsaddData elementsaddChart elementsaddInput widgetsaddMedia elementsaddLayouts and containersaddChat elementsaddStatus elementsaddThird-party componentsopen_in_newAPPLICATION LOGICNavigation and pagesaddExecution flowaddCaching and stateaddConnections and secretsaddCustom componentsaddUtilitiesaddConfigurationaddTOOLSApp testingaddCommand lineaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Develop/API referenceAPI reference Streamlit makes it easy for you to visualize, mutate, and share data. The API reference is organized by activity type, like displaying data or optimizing performance. Each section includes methods associated with the activity type, including examples. Browse our API below and click to learn more about any of our available commands! 🎈 Display almost anything Write and magic st.writeWrite arguments to the app.st.write("Hello **world**!") st.write(my_data_frame) st.write(my_mpl_figure) st.write_streamWrite generators or streams to the app with a typewriter effect.st.write_stream(my_generator) st.write_stream(my_llm_stream) MagicAny time Streamlit sees either a variable or literal value on its own line, it automatically writes that to your app using st.write"Hello **world**!" my_data_frame my_mpl_figure Text elements MarkdownDisplay string formatted as Markdown.st.markdown("Hello **world**!") TitleDisplay text in title formatting.st.title("The app title") HeaderDisplay text in header formatting.st.header("This is a header") SubheaderDisplay text in subheader formatting.st.subheader("This is a subheader") CaptionDisplay text in small font.st.caption("This is written small caption text") Code blockDisplay a code block with optional syntax highlighting.st.code("a = 1234") EchoDisplay some code in the app, then execute it. Useful for tutorials.with st.echo(): st.write('This code will be printed') LaTeXDisplay mathematical expressions formatted as LaTeX.st.latex("\int a x^2 \,dx") Preformatted textWrite fixed-width and preformatted text.st.text("Hello world") DividerDisplay a horizontal rule.st.divider() Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration! PreviousTagsAdd tags to your Streamlit apps. Created by @gagan3012.st_tags(label='# Enter Keywords:', text='Press enter to add more', value=['Zero', 'One', 'Two'], suggestions=['five', 'six', 'seven', 'eight', 'nine', 'three', 'eleven', 'ten', 'four'], maxtags = 4, key='1') NLUApply text mining on a dataframe. Created by @JohnSnowLabs.nlu.load('sentiment').predict('I love NLU! <3') Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.mention(label="An awesome Streamlit App", icon="streamlit", url="https://extras.streamlit.app",) Annotated textDisplay annotated text in Streamlit apps. Created by @tvst.annotated_text("This ", ("is", "verb"), " some ", ("annotated", "adj"), ("text", "noun"), " for those of ", ("you", "pronoun"), " who ", ("like", "verb"), " this sort of ", ("thing", "noun"), ".") Drawable CanvasProvides a sketching canvas using Fabric.js. Created by @andfanilo.st_canvas(fill_color="rgba(255, 165, 0, 0.3)", stroke_width=stroke_width, stroke_color=stroke_color, background_color=bg_color, background_image=Image.open(bg_image) if bg_image else None, update_streamlit=realtime_update, height=150, drawing_mode=drawing_mode, point_display_radius=point_display_radius if drawing_mode == 'point' else 0, key="canvas",) TagsAdd tags to your Streamlit apps. Created by @gagan3012.st_tags(label='# Enter Keywords:', text='Press enter to add more', value=['Zero', 'One', 'Two'], suggestions=['five', 'six', 'seven', 'eight', 'nine', 'three', 'eleven', 'ten', 'four'], maxtags = 4, key='1') NLUApply text mining on a dataframe. Created by @JohnSnowLabs.nlu.load('sentiment').predict('I love NLU! <3') Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.mention(label="An awesome Streamlit App", icon="streamlit", url="https://extras.streamlit.app",) Annotated textDisplay annotated text in Streamlit apps. Created by @tvst.annotated_text("This ", ("is", "verb"), " some ", ("annotated", "adj"), ("text", "noun"), " for those of ", ("you", "pronoun"), " who ", ("like", "verb"), " this sort of ", ("thing", "noun"), ".") Drawable CanvasProvides a sketching canvas using Fabric.js. Created by @andfanilo.st_canvas(fill_color="rgba(255, 165, 0, 0.3)", stroke_width=stroke_width, stroke_color=stroke_color, background_color=bg_color, background_image=Image.open(bg_image) if bg_image else None, update_streamlit=realtime_update, height=150, drawing_mode=drawing_mode, point_display_radius=point_display_radius if drawing_mode == 'point' else 0, key="canvas",) TagsAdd tags to your Streamlit apps. Created by @gagan3012.st_tags(label='# Enter Keywords:', text='Press enter to add more', value=['Zero', 'One', 'Two'], suggestions=['five', 'six', 'seven', 'eight', 'nine', 'three', 'eleven', 'ten', 'four'], maxtags = 4, key='1') NLUApply text mining on a dataframe. Created by @JohnSnowLabs.nlu.load('sentiment').predict('I love NLU! <3') Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.mention(label="An awesome Streamlit App", icon="streamlit", url="https://extras.streamlit.app",) Next Data elements DataframesDisplay a dataframe as an interactive table.st.dataframe(my_data_frame) Data editorDisplay a data editor widget.edited = st.data_editor(df, num_rows="dynamic") Column configurationConfigure the display and editing behavior of dataframes and data editors.st.column_config.NumberColumn("Price (in USD)", min_value=0, format="$%d") Static tablesDisplay a static table.st.table(my_data_frame) MetricsDisplay a metric in big bold font, with an optional indicator of how the metric changed.st.metric("My metric", 42, 2) Dicts and JSONDisplay object or string as a pretty-printed JSON string.st.json(my_dict) Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration! PreviousImage CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates value = streamlit_image_coordinates("https://placekitten.com/200/300") st.write(value) Plotly EventsMake Plotly charts interactive!. Created by @null-jones.from streamlit_plotly_events import plotly_events fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.metric_cards import style_metric_cards col3.metric(label="No Change", value=5000, delta=0) style_metric_cards() Streamlit AggridImplementation of Ag-Grid component for Streamlit. Created by @PablocFonseca.df = pd.DataFrame({'col1': [1, 2, 3], 'col2': [4, 5, 6]}) grid_return = AgGrid(df, editable=True) new_df = grid_return['data'] Streamlit FoliumStreamlit Component for rendering Folium maps. Created by @randyzwitch.m = folium.Map(location=[39.949610, -75.150282], zoom_start=16) folium.Marker([39.949610, -75.150282], popup="Liberty Bell", tooltip="Liberty Bell").add_to(m) st_data = st_folium(m, width=725) Pandas ProfilingPandas profiling component for Streamlit. Created by @okld.df = pd.read_csv("https://storage.googleapis.com/tf-datasets/titanic/train.csv") pr = df.profile_report() st_profile_report(pr) Image CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates value = streamlit_image_coordinates("https://placekitten.com/200/300") st.write(value) Plotly EventsMake Plotly charts interactive!. Created by @null-jones.from streamlit_plotly_events import plotly_events fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.metric_cards import style_metric_cards col3.metric(label="No Change", value=5000, delta=0) style_metric_cards() Streamlit AggridImplementation of Ag-Grid component for Streamlit. Created by @PablocFonseca.df = pd.DataFrame({'col1': [1, 2, 3], 'col2': [4, 5, 6]}) grid_return = AgGrid(df, editable=True) new_df = grid_return['data'] Streamlit FoliumStreamlit Component for rendering Folium maps. Created by @randyzwitch.m = folium.Map(location=[39.949610, -75.150282], zoom_start=16) folium.Marker([39.949610, -75.150282], popup="Liberty Bell", tooltip="Liberty Bell").add_to(m) st_data = st_folium(m, width=725) Pandas ProfilingPandas profiling component for Streamlit. Created by @okld.df = pd.read_csv("https://storage.googleapis.com/tf-datasets/titanic/train.csv") pr = df.profile_report() st_profile_report(pr) Image CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates value = streamlit_image_coordinates("https://placekitten.com/200/300") st.write(value) Plotly EventsMake Plotly charts interactive!. Created by @null-jones.from streamlit_plotly_events import plotly_events fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.metric_cards import style_metric_cards col3.metric(label="No Change", value=5000, delta=0) style_metric_cards() Next Chart elements Simple area chartsDisplay an area chart.st.area_chart(my_data_frame) Simple bar chartsDisplay a bar chart.st.bar_chart(my_data_frame) Simple line chartsDisplay a line chart.st.line_chart(my_data_frame) Simple scatter chartsDisplay a line chart.st.scatter_chart(my_data_frame) Scatterplots on mapsDisplay a map with points on it.st.map(my_data_frame) MatplotlibDisplay a matplotlib.pyplot figure.st.pyplot(my_mpl_figure) AltairDisplay a chart using the Altair library.st.altair_chart(my_altair_chart) Vega-LiteDisplay a chart using the Vega-Lite library.st.vega_lite_chart(my_vega_lite_chart) PlotlyDisplay an interactive Plotly chart.st.plotly_chart(my_plotly_chart) BokehDisplay an interactive Bokeh chart.st.bokeh_chart(my_bokeh_chart) PyDeckDisplay a chart using the PyDeck library.st.pydeck_chart(my_pydeck_chart) GraphVizDisplay a graph using the dagre-d3 library.st.graphviz_chart(my_graphviz_spec) Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration! PreviousStreamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl("https://assets5.lottiefiles.com/packages/lf20_V9t630.json") st_lottie(lottie_hello, key="hello") Plotly EventsMake Plotly charts interactive!. Created by @null-jones.fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.chart += get_annotations_chart(annotations=[("Mar 01, 2008", "Pretty good day for GOOG"), ("Dec 01, 2007", "Something's going wrong for GOOG & AAPL"), ("Nov 01, 2008", "Market starts again thanks to..."), ("Dec 01, 2009", "Small crash for GOOG after..."),],) st.altair_chart(chart, use_container_width=True) PlostA deceptively simple plotting library for Streamlit. Created by @tvst.import plost plost.line_chart(my_dataframe, x='time', y='stock_value', color='stock_name',) HiPlotHigh dimensional Interactive Plotting. Created by @facebookresearch.data = [{'dropout':0.1, 'lr': 0.001, 'loss': 10.0, 'optimizer': 'SGD'}, {'dropout':0.15, 'lr': 0.01, 'loss': 3.5, 'optimizer': 'Adam'}, {'dropout':0.3, 'lr': 0.1, 'loss': 4.5, 'optimizer': 'Adam'}] hip.Experiment.from_iterable(data).display() EChartsHigh dimensional Interactive Plotting. Created by @andfanilo.from streamlit_echarts import st_echarts st_echarts(options=options) Streamlit FoliumStreamlit Component for rendering Folium maps. Created by @randyzwitch.m = folium.Map(location=[39.949610, -75.150282], zoom_start=16) st_data = st_folium(m, width=725) Spacy-StreamlitspaCy building blocks and visualizers for Streamlit apps. Created by @explosion.models = ["en_core_web_sm", "en_core_web_md"] spacy_streamlit.visualize(models, "Sundar Pichai is the CEO of Google.") Streamlit AgraphA Streamlit Graph Vis, based on react-grah-vis. Created by @ChrisDelClea.from streamlit_agraph import agraph, Node, Edge, Config agraph(nodes=nodes, edges=edges, config=config) Streamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl("https://assets5.lottiefiles.com/packages/lf20_V9t630.json") st_lottie(lottie_hello, key="hello") Plotly EventsMake Plotly charts interactive!. Created by @null-jones.fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.chart += get_annotations_chart(annotations=[("Mar 01, 2008", "Pretty good day for GOOG"), ("Dec 01, 2007", "Something's going wrong for GOOG & AAPL"), ("Nov 01, 2008", "Market starts again thanks to..."), ("Dec 01, 2009", "Small crash for GOOG after..."),],) st.altair_chart(chart, use_container_width=True) PlostA deceptively simple plotting library for Streamlit. Created by @tvst.import plost plost.line_chart(my_dataframe, x='time', y='stock_value', color='stock_name',) HiPlotHigh dimensional Interactive Plotting. Created by @facebookresearch.data = [{'dropout':0.1, 'lr': 0.001, 'loss': 10.0, 'optimizer': 'SGD'}, {'dropout':0.15, 'lr': 0.01, 'loss': 3.5, 'optimizer': 'Adam'}, {'dropout':0.3, 'lr': 0.1, 'loss': 4.5, 'optimizer': 'Adam'}] hip.Experiment.from_iterable(data).display() EChartsHigh dimensional Interactive Plotting. Created by @andfanilo.from streamlit_echarts import st_echarts st_echarts(options=options) Streamlit FoliumStreamlit Component for rendering Folium maps. Created by @randyzwitch.m = folium.Map(location=[39.949610, -75.150282], zoom_start=16) st_data = st_folium(m, width=725) Spacy-StreamlitspaCy building blocks and visualizers for Streamlit apps. Created by @explosion.models = ["en_core_web_sm", "en_core_web_md"] spacy_streamlit.visualize(models, "Sundar Pichai is the CEO of Google.") Streamlit AgraphA Streamlit Graph Vis, based on react-grah-vis. Created by @ChrisDelClea.from streamlit_agraph import agraph, Node, Edge, Config agraph(nodes=nodes, edges=edges, config=config) Streamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl("https://assets5.lottiefiles.com/packages/lf20_V9t630.json") st_lottie(lottie_hello, key="hello") Plotly EventsMake Plotly charts interactive!. Created by @null-jones.fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.chart += get_annotations_chart(annotations=[("Mar 01, 2008", "Pretty good day for GOOG"), ("Dec 01, 2007", "Something's going wrong for GOOG & AAPL"), ("Nov 01, 2008", "Market starts again thanks to..."), ("Dec 01, 2009", "Small crash for GOOG after..."),],) st.altair_chart(chart, use_container_width=True) Next Input widgets ButtonDisplay a button widget.clicked = st.button("Click me") Download buttonDisplay a download button widget.st.download_button("Download file", file) Form buttonDisplay a form submit button. For use with st.form.st.form_submit_button("Sign up") Link buttonDisplay a link button.st.link_button("Go to gallery", url) Page linkDisplay a link to another page in a multipage app.st.page_link("app.py", label="Home", icon="🏠") st.page_link("pages/profile.py", label="My profile") CheckboxDisplay a checkbox widget.selected = st.checkbox("I agree") Color pickerDisplay a color picker widget.color = st.color_picker("Pick a color") MultiselectDisplay a multiselect widget. The multiselect widget starts as empty.choices = st.multiselect("Buy", ["milk", "apples", "potatoes"]) RadioDisplay a radio button widget.choice = st.radio("Pick one", ["cats", "dogs"]) SelectboxDisplay a select widget.choice = st.selectbox("Pick one", ["cats", "dogs"]) Select-sliderDisplay a slider widget to select items from a list.size = st.select_slider("Pick a size", ["S", "M", "L"]) ToggleDisplay a toggle widget.activated = st.toggle("Activate") Number inputDisplay a numeric input widget.choice = st.number_input("Pick a number", 0, 10) SliderDisplay a slider widget.number = st.slider("Pick a number", 0, 100) Date inputDisplay a date input widget.date = st.date_input("Your birthday") Time inputDisplay a time input widget.time = st.time_input("Meeting time") Chat inputDisplay a chat input widget.prompt = st.chat_input("Say something") if prompt: st.write(f"The user has sent: {prompt}") Text-areaDisplay a multi-line text input widget.text = st.text_area("Text to translate") Text inputDisplay a single-line text input widget.name = st.text_input("First name") Data editorDisplay a data editor widget.edited = st.experimental_data_editor(df, num_rows="dynamic") File UploaderDisplay a file uploader widget.data = st.file_uploader("Upload a CSV") Camera inputDisplay a widget that allows users to upload images directly from a camera.image = st.camera_input("Take a picture") Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration! PreviousStreamlit ChatStreamlit Component for a Chatbot UI. Created by @AI-Yash.from streamlit_chat import message message("My message") message("Hello bot!", is_user=True) # align's the message to the right Streamlit Option MenuSelect a single item from a list of options in a menu. Created by @victoryhb.from streamlit_option_menu import option_menu option_menu("Main Menu", ["Home", 'Settings'], icons=['house', 'gear'], menu_icon="cast", default_index=1) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.stoggle import stoggle stoggle( "Click me!", """🥷 Surprise! Here's some additional content""",) Streamlit ElementsCreate a draggable and resizable dashboard in Streamlit. Created by @okls.from streamlit_elements import elements, mui, html with elements("new_element"): mui.Typography("Hello world") TagsAdd tags to your Streamlit apps. Created by @gagan3012.from streamlit_tags import st_tags st_tags(label='# Enter Keywords:', text='Press enter to add more', value=['Zero', 'One', 'Two'], suggestions=['five', 'six', 'seven', 'eight', 'nine', 'three', 'eleven', 'ten', 'four'], maxtags = 4, key='1') StqdmThe simplest way to handle a progress bar in streamlit app. Created by @Wirg.from stqdm import stqdm for _ in stqdm(range(50)): sleep(0.5) TimelineDisplay a Timeline in Streamlit apps using TimelineJS. Created by @innerdoc.from streamlit_timeline import timeline with open('example.json', "r") as f: timeline(f.read(), height=800) Camera input liveAlternative for st.camera_input which returns the webcam images live. Created by @blackary.from camera_input_live import camera_input_live image = camera_input_live() st.image(value) Streamlit AceAce editor component for Streamlit. Created by @okld.from streamlit_ace import st_ace content = st_ace() content Streamlit ChatStreamlit Component for a Chatbot UI. Created by @AI-Yash.from streamlit_chat import message message("My message") message("Hello bot!", is_user=True) # align's the message to the right Streamlit Option MenuSelect a single item from a list of options in a menu. Created by @victoryhb.from streamlit_option_menu import option_menu option_menu("Main Menu", ["Home", 'Settings'], icons=['house', 'gear'], menu_icon="cast", default_index=1) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.stoggle import stoggle stoggle( "Click me!", """🥷 Surprise! Here's some additional content""",) Streamlit ElementsCreate a draggable and resizable dashboard in Streamlit. Created by @okls.from streamlit_elements import elements, mui, html with elements("new_element"): mui.Typography("Hello world") TagsAdd tags to your Streamlit apps. Created by @gagan3012.from streamlit_tags import st_tags st_tags(label='# Enter Keywords:', text='Press enter to add more', value=['Zero', 'One', 'Two'], suggestions=['five', 'six', 'seven', 'eight', 'nine', 'three', 'eleven', 'ten', 'four'], maxtags = 4, key='1') StqdmThe simplest way to handle a progress bar in streamlit app. Created by @Wirg.from stqdm import stqdm for _ in stqdm(range(50)): sleep(0.5) TimelineDisplay a Timeline in Streamlit apps using TimelineJS. Created by @innerdoc.from streamlit_timeline import timeline with open('example.json', "r") as f: timeline(f.read(), height=800) Camera input liveAlternative for st.camera_input which returns the webcam images live. Created by @blackary.from camera_input_live import camera_input_live image = camera_input_live() st.image(value) Streamlit AceAce editor component for Streamlit. Created by @okld.from streamlit_ace import st_ace content = st_ace() content Streamlit ChatStreamlit Component for a Chatbot UI. Created by @AI-Yash.from streamlit_chat import message message("My message") message("Hello bot!", is_user=True) # align's the message to the right Streamlit Option MenuSelect a single item from a list of options in a menu. Created by @victoryhb.from streamlit_option_menu import option_menu option_menu("Main Menu", ["Home", 'Settings'], icons=['house', 'gear'], menu_icon="cast", default_index=1) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.stoggle import stoggle stoggle( "Click me!", """🥷 Surprise! Here's some additional content""",) Next Media elements ImageDisplay an image or list of images.st.image(numpy_array) st.image(image_bytes) st.image(file) st.image("https://example.com/myimage.jpg") AudioDisplay an audio player.st.audio(numpy_array) st.audio(audio_bytes) st.audio(file) st.audio("https://example.com/myaudio.mp3", format="audio/mp3") VideoDisplay a video player.st.video(numpy_array) st.video(video_bytes) st.video(file) st.video("https://example.com/myvideo.mp4", format="video/mp4") Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration! PreviousStreamlit CropperA simple image cropper for Streamlit. Created by @turner-anderson.from streamlit_cropper import st_cropper st_cropper(img, realtime_update=realtime_update, box_color=box_color, aspect_ratio=aspect_ratio) Image CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates streamlit_image_coordinates("https://placekitten.com/200/300") Streamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl("https://assets5.lottiefiles.com/packages/lf20_V9t630.json") st_lottie(lottie_hello, key="hello") Streamlit WebrtcHandling and transmitting real-time video/audio streams with Streamlit. Created by @whitphx.from streamlit_webrtc import webrtc_streamer webrtc_streamer(key="sample") Drawable CanvasProvides a sketching canvas using Fabric.js. Created by @andfanilo.from streamlit_drawable_canvas import st_canvas st_canvas(fill_color="rgba(255, 165, 0, 0.3)", stroke_width=stroke_width, stroke_color=stroke_color, background_color=bg_color, background_image=Image.open(bg_image) if bg_image else None, update_streamlit=realtime_update, height=150, drawing_mode=drawing_mode, point_display_radius=point_display_radius if drawing_mode == 'point' else 0, key="canvas",) Image ComparisonCompare images with a slider using JuxtaposeJS. Created by @fcakyon.from streamlit_image_comparison import image_comparison image_comparison(img1="image1.jpg", img2="image2.jpg",) Streamlit CropperA simple image cropper for Streamlit. Created by @turner-anderson.from streamlit_cropper import st_cropper st_cropper(img, realtime_update=realtime_update, box_color=box_color, aspect_ratio=aspect_ratio) Image CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates streamlit_image_coordinates("https://placekitten.com/200/300") Streamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl("https://assets5.lottiefiles.com/packages/lf20_V9t630.json") st_lottie(lottie_hello, key="hello") Streamlit WebrtcHandling and transmitting real-time video/audio streams with Streamlit. Created by @whitphx.from streamlit_webrtc import webrtc_streamer webrtc_streamer(key="sample") Drawable CanvasProvides a sketching canvas using Fabric.js. Created by @andfanilo.from streamlit_drawable_canvas import st_canvas st_canvas(fill_color="rgba(255, 165, 0, 0.3)", stroke_width=stroke_width, stroke_color=stroke_color, background_color=bg_color, background_image=Image.open(bg_image) if bg_image else None, update_streamlit=realtime_update, height=150, drawing_mode=drawing_mode, point_display_radius=point_display_radius if drawing_mode == 'point' else 0, key="canvas",) Image ComparisonCompare images with a slider using JuxtaposeJS. Created by @fcakyon.from streamlit_image_comparison import image_comparison image_comparison(img1="image1.jpg", img2="image2.jpg",) Streamlit CropperA simple image cropper for Streamlit. Created by @turner-anderson.from streamlit_cropper import st_cropper st_cropper(img, realtime_update=realtime_update, box_color=box_color, aspect_ratio=aspect_ratio) Image CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates streamlit_image_coordinates("https://placekitten.com/200/300") Streamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl("https://assets5.lottiefiles.com/packages/lf20_V9t630.json") st_lottie(lottie_hello, key="hello") Next Layouts and containers ColumnsInsert containers laid out as side-by-side columns.col1, col2 = st.columns(2) col1.write("this is column 1") col2.write("this is column 2") ContainerInsert a multi-element container.c = st.container() st.write("This will show last") c.write("This will show first") c.write("This will show second") Modal dialogsInsert a modal dialog that can rerun independently from the rest of the script.@st.experimental_dialog("Sign up") def email_form(): name = st.text_input("Name") email = st.text_input("Email") EmptyInsert a single-element container.c = st.empty() st.write("This will show last") c.write("This will be replaced") c.write("This will show first") ExpanderInsert a multi-element container that can be expanded/collapsed.with st.expander("Open to see more"): st.write("This is more content") PopoverInsert a multi-element popover container that can be opened/closed.with st.popover("Settings"): st.checkbox("Show completed") SidebarDisplay items in a sidebar.st.sidebar.write("This lives in the sidebar") st.sidebar.button("Click me!") TabsInsert containers separated into tabs.tab1, tab2 = st.tabs(["Tab 1", "Tab2"]) tab1.write("this is tab 1") tab2.write("this is tab 2") Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration!Streamlit ElementsCreate a draggable and resizable dashboard in Streamlit. Created by @okls.from streamlit_elements import elements, mui, html with elements("new_element"): mui.Typography("Hello world") PydanticAuto-generate Streamlit UI from Pydantic Models and Dataclasses. Created by @lukasmasuch.import streamlit_pydantic as sp sp.pydantic_form(key="my_form", model=ExampleModel) Streamlit PagesAn experimental version of Streamlit Multi-Page Apps. Created by @blackary.from st_pages import Page, show_pages, add_page_title show_pages([ Page("streamlit_app.py", "Home", "🏠"), Page("other_pages/page2.py", "Page 2", ":books:"), ]) Chat elements Streamlit provides a few commands to help you build conversational apps. These chat elements are designed to be used in conjunction with each other, but you can also use them separately. st.chat_message lets you insert a chat message container into the app so you can display messages from the user or the app. Chat containers can contain other Streamlit elements, including charts, tables, text, and more. st.chat_input lets you display a chat input widget so the user can type in a message. Chat inputDisplay a chat input widget.prompt = st.chat_input("Say something") if prompt: st.write(f"The user has sent: {prompt}") Chat messageInsert a chat message container.import numpy as np with st.chat_message("user"): st.write("Hello 👋") st.line_chart(np.random.randn(30, 3)) Status containerDisplay output of long-running tasks in a container.with st.status('Running'): do_something_slow() st.write_streamWrite generators or streams to the app with a typewriter effect.st.write_stream(my_generator) st.write_stream(my_llm_stream) Status elements Progress barDisplay a progress bar.for i in range(101): st.progress(i) do_something_slow() SpinnerTemporarily displays a message while executing a block of code.with st.spinner("Please wait..."): do_something_slow() Status containerDisplay output of long-running tasks in a container.with st.status('Running'): do_something_slow() ToastBriefly displays a toast message in the bottom-right corner.st.toast('Butter!', icon='🧈') BalloonsDisplay celebratory balloons!do_something() # Celebrate when all done! st.balloons() SnowflakesDisplay celebratory snowflakes!do_something() # Celebrate when all done! st.snow() Success boxDisplay a success message.st.success("Match found!") Info boxDisplay an informational message.st.info("Dataset is updated every day at midnight.") Warning boxDisplay warning message.st.warning("Unable to fetch image. Skipping...") Error boxDisplay error message.st.error("We encountered an error") Exception outputDisplay an exception.e = RuntimeError("This is an exception of type RuntimeError") st.exception(e) Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration!StqdmThe simplest way to handle a progress bar in streamlit app. Created by @Wirg.from stqdm import stqdm for _ in stqdm(range(50)): sleep(0.5) Custom notification boxA custom notification box with the ability to close it out. Created by @Socvest.from streamlit_custom_notification_box import custom_notification_box styles = {'material-icons':{'color': 'red'}, 'text-icon-link-close-container': {'box-shadow': '#3896de 0px 4px'}, 'notification-text': {'':''}, 'close-button':{'':''}, 'link':{'':''}} custom_notification_box(icon='info', textDisplay='We are almost done with your registration...', externalLink='more info', url='#', styles=styles, key="foo") Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.let_it_rain import rain rain(emoji="🎈", font_size=54, falling_speed=5, animation_length="infinite",) App logic and configuration Navigation and pages Switch pageProgrammatically navigates to a specified page.st.switch_page("pages/my_page.py") Page linkDisplay a link to another page in a multipage app.st.page_link("app.py", label="Home", icon="🏠") st.page_link("pages/profile.py", label="My profile") Execution flow Modal dialogsInsert a modal dialog that can rerun independently from the rest of the script.@st.experimental_dialog("Sign up") def email_form(): name = st.text_input("Name") email = st.text_input("Email") FormsCreate a form that batches elements together with a “Submit" button.with st.form(key='my_form'): name = st.text_input("Name") email = st.text_input("Email") st.form_submit_button("Sign up") Partial rerunsDefine a fragment to rerun independently from the rest of the script.@st.experimental_fragment(run_every="10s") def fragment(): df = get_data() st.line_chart(df) Rerun scriptRerun the script immediately.st.rerun() Stop executionStops execution immediately.st.stop() Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration!AutorefreshForce a refresh without tying up a script. Created by @kmcgrady.from streamlit_autorefresh import st_autorefresh st_autorefresh(interval=2000, limit=100, key="fizzbuzzcounter") PydanticAuto-generate Streamlit UI from Pydantic Models and Dataclasses. Created by @lukasmasuch.import streamlit_pydantic as sp sp.pydantic_form(key="my_form", model=ExampleModel) Streamlit PagesAn experimental version of Streamlit Multi-Page Apps. Created by @blackary.from st_pages import Page, show_pages, add_page_title show_pages([ Page("streamlit_app.py", "Home", "🏠"), Page("other_pages/page2.py", "Page 2", ":books:"), ]) Caching and state Cache dataFunction decorator to cache functions that return data (e.g. dataframe transforms, database queries, ML inference).@st.cache_data def long_function(param1, param2): # Perform expensive computation here or # fetch data from the web here return data Cache resourceFunction decorator to cache functions that return global resources (e.g. database connections, ML models).@st.cache_resource def init_model(): # Return a global resource here return pipeline( "sentiment-analysis", model="distilbert-base-uncased-finetuned-sst-2-english" ) Session stateSession state is a way to share variables between reruns, for each user session.st.session_state['key'] = value Query parametersGet, set, or clear the query parameters that are shown in the browser's URL bar.st.query_params[key] = value st.query_params.clear() Connections and databases Setup your connection Create a connectionConnect to a data source or APIconn = st.connection('pets_db', type='sql') pet_owners = conn.query('select * from pet_owners') st.dataframe(pet_owners) Built-in connections SnowflakeConnectionA connection to Snowflake.conn = st.connection('snowflake') SQLConnectionA connection to a SQL database using SQLAlchemy.conn = st.connection('sql') Build your own connections Connection base classBuild your own connection with BaseConnection.class MyConnection(BaseConnection[myconn.MyConnection]): def _connect(self, **kwargs) -> MyConnection: return myconn.connect(**self._secrets, **kwargs) def query(self, query): return self._instance.query(query) Secrets management Secrets singletonAccess secrets from a local TOML file.key = st.secrets["OpenAI_key"] Secrets fileSave your secrets in a per-project or per-profile TOML file.OpenAI_key = "<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#numberinputrun
DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceremovePAGE ELEMENTSWrite and magicaddText elementsaddData elementsaddChart elementsaddInput widgetsaddMedia elementsaddLayouts and containersaddChat elementsaddStatus elementsaddThird-party componentsopen_in_newAPPLICATION LOGICNavigation and pagesaddExecution flowaddCaching and stateaddConnections and secretsaddCustom componentsaddUtilitiesaddConfigurationaddTOOLSApp testingremovest.testing.v1.AppTestTesting element classesCommand lineaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Develop/API reference/App testing/Testing element classesTesting element classes st.testing.v1.element_tree.Block The Block class has the same methods and attributes as AppTest. A Block instance represents a container of elements just as AppTest represents the entire app. For example, Block.button will produce a WidgetList of Button in the same manner as AppTest.button. ChatMessage, Column, and Tab all inherit from Block. For all container classes, parameters of the original element can be obtained as properties. For example, ChatMessage.avatar and Tab.label. st.testing.v1.element_tree.ElementStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeElement base class for testing. This class's methods and attributes are universal for all elements implemented in testing. For example, Caption, Code, Text, and Title inherit from Element. All widget classes also inherit from Element, but have additional methods specific to each widget type. See the AppTest class for the full list of supported elements. For all element classes, parameters of the original element can be obtained as properties. For example, Button.label, Caption.help, and Toast.icon. Class description[source] st.testing.v1.element_tree.Element(proto, root) Methods run(*, timeout=None) Run the AppTest script which contains the element. Attributes value The value or contents of the element. st.testing.v1.element_tree.ButtonStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.button and st.form_submit_button. Class description[source] st.testing.v1.element_tree.Button(proto, root) Methods click() Set the value of the button to True. run(*, timeout=None) Run the AppTest script which contains the element. set_value(v) Set the value of the button. Attributes value The value of the button. (bool) st.testing.v1.element_tree.ChatInputStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.chat_input. Class description[source] st.testing.v1.element_tree.ChatInput(proto, root) Methods run(*, timeout=None) Run the AppTest script which contains the element. set_value(v) Set the value of the widget. Attributes value The value of the widget. (str) st.testing.v1.element_tree.CheckboxStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.checkbox. Class description[source] st.testing.v1.element_tree.Checkbox(proto, root) Methods check() Set the value of the widget to True. run(*, timeout=None) Run the AppTest script which contains the element. set_value(v) Set the value of the widget. uncheck() Set the value of the widget to False. Attributes value The value of the widget. (bool) st.testing.v1.element_tree.ColorPickerStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.color_picker. Class description[source] st.testing.v1.element_tree.ColorPicker(proto, root) Methods pick(v) Set the value of the widget as a hex string. May omit the "#" prefix. run(*, timeout=None) Run the AppTest script which contains the element. set_value(v) Set the value of the widget as a hex string. Attributes value The currently selected value as a hex string. (str) st.testing.v1.element_tree.DateInputStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.date_input. Class description[source] st.testing.v1.element_tree.DateInput(proto, root) Methods run(*, timeout=None) Run the AppTest script which contains the element. set_value(v) Set the value of the widget. Attributes value The value of the widget. (date or Tuple of date) st.testing.v1.element_tree.MultiselectStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.multiselect. Class description[source] st.testing.v1.element_tree.Multiselect(proto, root) Methods run(*, timeout=None) Run the AppTest script which contains the element. select(v) Add a selection to the widget. Do nothing if the value is already selected. If testing a multiselect widget with repeated options, use set_value instead. set_value(v) Set the value of the multiselect widget. (list) unselect(v) Remove a selection from the widget. Do nothing if the value is not already selected. If a value is selected multiple times, the first instance is removed. Attributes format_func The widget's formatting function for displaying options. (callable) indices The indices of the currently selected values from the options. (list) value The currently selected values from the options. (list) st.testing.v1.element_tree.NumberInputStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.number_input. Class description[source] st.testing.v1.element_tree.NumberInput(proto, root) Methods decrement() Decrement the st.number_input widget as if the user clicked "-". increment() Increment the st.number_input widget as if the user clicked "+". run(*, timeout=None) Run the AppTest script which contains the element. set_value(v) Set the value of the st.number_input widget. Attributes value Get the current value of the st.number_input widget. st.testing.v1.element_tree.RadioStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.radio. Class description[source] st.testing.v1.element_tree.Radio(proto, root) Methods run(*, timeout=None) Run the AppTest script which contains the element. set_value(v) Set the selection by value. Attributes format_func The widget's formatting function for displaying options. (callable) index The index of the current selection. (int) value The currently selected value from the options. (Any) st.testing.v1.element_tree.SelectSliderStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.select_slider. Class description[source] st.testing.v1.element_tree.SelectSlider(proto, root) Methods run(*, timeout=None) Run the AppTest script which contains the element. set_range(lower, upper) Set the ranged selection by values. set_value(v) Set the (single) selection by value. Attributes format_func The widget's formatting function for displaying options. (callable) value The currently selected value or range. (Any or Sequence of Any) st.testing.v1.element_tree.SelectboxStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.selectbox. Class description[source] st.testing.v1.element_tree.Selectbox(proto, root) Methods run(*, timeout=None) Run the AppTest script which contains the element. select(v) Set the selection by value. select_index(index) Set the selection by index. set_value(v) Set the selection by value. Attributes format_func The widget's formatting function for displaying options. (callable) index The index of the current selection. (int) value The currently selected value from the options. (Any) st.testing.v1.element_tree.SliderStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.slider. Class description[source] st.testing.v1.element_tree.Slider(proto, root) Methods run(*, timeout=None) Run the AppTest script which contains the element. set_range(lower, upper) Set the ranged value of the slider. set_value(v) Set the (single) value of the slider. Attributes value The currently selected value or range. (Any or Sequence of Any) st.testing.v1.element_tree.TextAreaStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.text_area. Class description[source] st.testing.v1.element_tree.TextArea(proto, root) Methods input(v) Set the value of the widget only if the value does not exceed the maximum allowed characters. run(*, timeout=None) Run the AppTest script which contains the element. set_value(v) Set the value of the widget. Attributes value The current value of the widget. (str) st.testing.v1.element_tree.TextInputStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.text_input. Class description[source] st.testing.v1.element_tree.TextInput(proto, root) Methods input(v) Set the value of the widget only if the value does not exceed the maximum allowed characters. run(*, timeout=None) Run the AppTest script which contains the element. set_value(v) Set the value of the widget. Attributes value The current value of the widget. (str) st.testing.v1.element_tree.TimeInputStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.time_input. Class description[source] st.testing.v1.element_tree.TimeInput(proto, root) Methods decrement() Select the previous available time. increment() Select the next available time. run(*, timeout=None) Run the AppTest script which contains the element. set_value(v) Set the value of the widget. Attributes value The current value of the widget. (time) st.testing.v1.element_tree.ToggleStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.toggle. Class description[source] st.testing.v1.element_tree.Toggle(proto, root) Methods run(*, timeout=None) Run the AppTest script which contains the element. set_value(v) Set the value of the widget. Attributes value The current value of the widget. (bool) Previous: st.testing.v1.AppTestNext: Command lineforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy
https://docs.streamlit.io/en/0.72.0/api.html#streamlit.file_uploader
DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceremovePAGE ELEMENTSWrite and magicaddText elementsaddData elementsaddChart elementsaddInput widgetsaddMedia elementsaddLayouts and containersaddChat elementsaddStatus elementsaddThird-party componentsopen_in_newAPPLICATION LOGICNavigation and pagesaddExecution flowaddCaching and stateaddConnections and secretsaddCustom componentsaddUtilitiesaddConfigurationaddTOOLSApp testingaddCommand lineaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Develop/API referenceAPI reference Streamlit makes it easy for you to visualize, mutate, and share data. The API reference is organized by activity type, like displaying data or optimizing performance. Each section includes methods associated with the activity type, including examples. Browse our API below and click to learn more about any of our available commands! 🎈 Display almost anything Write and magic st.writeWrite arguments to the app.st.write("Hello **world**!") st.write(my_data_frame) st.write(my_mpl_figure) st.write_streamWrite generators or streams to the app with a typewriter effect.st.write_stream(my_generator) st.write_stream(my_llm_stream) MagicAny time Streamlit sees either a variable or literal value on its own line, it automatically writes that to your app using st.write"Hello **world**!" my_data_frame my_mpl_figure Text elements MarkdownDisplay string formatted as Markdown.st.markdown("Hello **world**!") TitleDisplay text in title formatting.st.title("The app title") HeaderDisplay text in header formatting.st.header("This is a header") SubheaderDisplay text in subheader formatting.st.subheader("This is a subheader") CaptionDisplay text in small font.st.caption("This is written small caption text") Code blockDisplay a code block with optional syntax highlighting.st.code("a = 1234") EchoDisplay some code in the app, then execute it. Useful for tutorials.with st.echo(): st.write('This code will be printed') LaTeXDisplay mathematical expressions formatted as LaTeX.st.latex("\int a x^2 \,dx") Preformatted textWrite fixed-width and preformatted text.st.text("Hello world") DividerDisplay a horizontal rule.st.divider() Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration! PreviousTagsAdd tags to your Streamlit apps. Created by @gagan3012.st_tags(label='# Enter Keywords:', text='Press enter to add more', value=['Zero', 'One', 'Two'], suggestions=['five', 'six', 'seven', 'eight', 'nine', 'three', 'eleven', 'ten', 'four'], maxtags = 4, key='1') NLUApply text mining on a dataframe. Created by @JohnSnowLabs.nlu.load('sentiment').predict('I love NLU! <3') Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.mention(label="An awesome Streamlit App", icon="streamlit", url="https://extras.streamlit.app",) Annotated textDisplay annotated text in Streamlit apps. Created by @tvst.annotated_text("This ", ("is", "verb"), " some ", ("annotated", "adj"), ("text", "noun"), " for those of ", ("you", "pronoun"), " who ", ("like", "verb"), " this sort of ", ("thing", "noun"), ".") Drawable CanvasProvides a sketching canvas using Fabric.js. Created by @andfanilo.st_canvas(fill_color="rgba(255, 165, 0, 0.3)", stroke_width=stroke_width, stroke_color=stroke_color, background_color=bg_color, background_image=Image.open(bg_image) if bg_image else None, update_streamlit=realtime_update, height=150, drawing_mode=drawing_mode, point_display_radius=point_display_radius if drawing_mode == 'point' else 0, key="canvas",) TagsAdd tags to your Streamlit apps. Created by @gagan3012.st_tags(label='# Enter Keywords:', text='Press enter to add more', value=['Zero', 'One', 'Two'], suggestions=['five', 'six', 'seven', 'eight', 'nine', 'three', 'eleven', 'ten', 'four'], maxtags = 4, key='1') NLUApply text mining on a dataframe. Created by @JohnSnowLabs.nlu.load('sentiment').predict('I love NLU! <3') Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.mention(label="An awesome Streamlit App", icon="streamlit", url="https://extras.streamlit.app",) Annotated textDisplay annotated text in Streamlit apps. Created by @tvst.annotated_text("This ", ("is", "verb"), " some ", ("annotated", "adj"), ("text", "noun"), " for those of ", ("you", "pronoun"), " who ", ("like", "verb"), " this sort of ", ("thing", "noun"), ".") Drawable CanvasProvides a sketching canvas using Fabric.js. Created by @andfanilo.st_canvas(fill_color="rgba(255, 165, 0, 0.3)", stroke_width=stroke_width, stroke_color=stroke_color, background_color=bg_color, background_image=Image.open(bg_image) if bg_image else None, update_streamlit=realtime_update, height=150, drawing_mode=drawing_mode, point_display_radius=point_display_radius if drawing_mode == 'point' else 0, key="canvas",) TagsAdd tags to your Streamlit apps. Created by @gagan3012.st_tags(label='# Enter Keywords:', text='Press enter to add more', value=['Zero', 'One', 'Two'], suggestions=['five', 'six', 'seven', 'eight', 'nine', 'three', 'eleven', 'ten', 'four'], maxtags = 4, key='1') NLUApply text mining on a dataframe. Created by @JohnSnowLabs.nlu.load('sentiment').predict('I love NLU! <3') Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.mention(label="An awesome Streamlit App", icon="streamlit", url="https://extras.streamlit.app",) Next Data elements DataframesDisplay a dataframe as an interactive table.st.dataframe(my_data_frame) Data editorDisplay a data editor widget.edited = st.data_editor(df, num_rows="dynamic") Column configurationConfigure the display and editing behavior of dataframes and data editors.st.column_config.NumberColumn("Price (in USD)", min_value=0, format="$%d") Static tablesDisplay a static table.st.table(my_data_frame) MetricsDisplay a metric in big bold font, with an optional indicator of how the metric changed.st.metric("My metric", 42, 2) Dicts and JSONDisplay object or string as a pretty-printed JSON string.st.json(my_dict) Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration! PreviousImage CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates value = streamlit_image_coordinates("https://placekitten.com/200/300") st.write(value) Plotly EventsMake Plotly charts interactive!. Created by @null-jones.from streamlit_plotly_events import plotly_events fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.metric_cards import style_metric_cards col3.metric(label="No Change", value=5000, delta=0) style_metric_cards() Streamlit AggridImplementation of Ag-Grid component for Streamlit. Created by @PablocFonseca.df = pd.DataFrame({'col1': [1, 2, 3], 'col2': [4, 5, 6]}) grid_return = AgGrid(df, editable=True) new_df = grid_return['data'] Streamlit FoliumStreamlit Component for rendering Folium maps. Created by @randyzwitch.m = folium.Map(location=[39.949610, -75.150282], zoom_start=16) folium.Marker([39.949610, -75.150282], popup="Liberty Bell", tooltip="Liberty Bell").add_to(m) st_data = st_folium(m, width=725) Pandas ProfilingPandas profiling component for Streamlit. Created by @okld.df = pd.read_csv("https://storage.googleapis.com/tf-datasets/titanic/train.csv") pr = df.profile_report() st_profile_report(pr) Image CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates value = streamlit_image_coordinates("https://placekitten.com/200/300") st.write(value) Plotly EventsMake Plotly charts interactive!. Created by @null-jones.from streamlit_plotly_events import plotly_events fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.metric_cards import style_metric_cards col3.metric(label="No Change", value=5000, delta=0) style_metric_cards() Streamlit AggridImplementation of Ag-Grid component for Streamlit. Created by @PablocFonseca.df = pd.DataFrame({'col1': [1, 2, 3], 'col2': [4, 5, 6]}) grid_return = AgGrid(df, editable=True) new_df = grid_return['data'] Streamlit FoliumStreamlit Component for rendering Folium maps. Created by @randyzwitch.m = folium.Map(location=[39.949610, -75.150282], zoom_start=16) folium.Marker([39.949610, -75.150282], popup="Liberty Bell", tooltip="Liberty Bell").add_to(m) st_data = st_folium(m, width=725) Pandas ProfilingPandas profiling component for Streamlit. Created by @okld.df = pd.read_csv("https://storage.googleapis.com/tf-datasets/titanic/train.csv") pr = df.profile_report() st_profile_report(pr) Image CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates value = streamlit_image_coordinates("https://placekitten.com/200/300") st.write(value) Plotly EventsMake Plotly charts interactive!. Created by @null-jones.from streamlit_plotly_events import plotly_events fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.metric_cards import style_metric_cards col3.metric(label="No Change", value=5000, delta=0) style_metric_cards() Next Chart elements Simple area chartsDisplay an area chart.st.area_chart(my_data_frame) Simple bar chartsDisplay a bar chart.st.bar_chart(my_data_frame) Simple line chartsDisplay a line chart.st.line_chart(my_data_frame) Simple scatter chartsDisplay a line chart.st.scatter_chart(my_data_frame) Scatterplots on mapsDisplay a map with points on it.st.map(my_data_frame) MatplotlibDisplay a matplotlib.pyplot figure.st.pyplot(my_mpl_figure) AltairDisplay a chart using the Altair library.st.altair_chart(my_altair_chart) Vega-LiteDisplay a chart using the Vega-Lite library.st.vega_lite_chart(my_vega_lite_chart) PlotlyDisplay an interactive Plotly chart.st.plotly_chart(my_plotly_chart) BokehDisplay an interactive Bokeh chart.st.bokeh_chart(my_bokeh_chart) PyDeckDisplay a chart using the PyDeck library.st.pydeck_chart(my_pydeck_chart) GraphVizDisplay a graph using the dagre-d3 library.st.graphviz_chart(my_graphviz_spec) Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration! PreviousStreamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl("https://assets5.lottiefiles.com/packages/lf20_V9t630.json") st_lottie(lottie_hello, key="hello") Plotly EventsMake Plotly charts interactive!. Created by @null-jones.fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.chart += get_annotations_chart(annotations=[("Mar 01, 2008", "Pretty good day for GOOG"), ("Dec 01, 2007", "Something's going wrong for GOOG & AAPL"), ("Nov 01, 2008", "Market starts again thanks to..."), ("Dec 01, 2009", "Small crash for GOOG after..."),],) st.altair_chart(chart, use_container_width=True) PlostA deceptively simple plotting library for Streamlit. Created by @tvst.import plost plost.line_chart(my_dataframe, x='time', y='stock_value', color='stock_name',) HiPlotHigh dimensional Interactive Plotting. Created by @facebookresearch.data = [{'dropout':0.1, 'lr': 0.001, 'loss': 10.0, 'optimizer': 'SGD'}, {'dropout':0.15, 'lr': 0.01, 'loss': 3.5, 'optimizer': 'Adam'}, {'dropout':0.3, 'lr': 0.1, 'loss': 4.5, 'optimizer': 'Adam'}] hip.Experiment.from_iterable(data).display() EChartsHigh dimensional Interactive Plotting. Created by @andfanilo.from streamlit_echarts import st_echarts st_echarts(options=options) Streamlit FoliumStreamlit Component for rendering Folium maps. Created by @randyzwitch.m = folium.Map(location=[39.949610, -75.150282], zoom_start=16) st_data = st_folium(m, width=725) Spacy-StreamlitspaCy building blocks and visualizers for Streamlit apps. Created by @explosion.models = ["en_core_web_sm", "en_core_web_md"] spacy_streamlit.visualize(models, "Sundar Pichai is the CEO of Google.") Streamlit AgraphA Streamlit Graph Vis, based on react-grah-vis. Created by @ChrisDelClea.from streamlit_agraph import agraph, Node, Edge, Config agraph(nodes=nodes, edges=edges, config=config) Streamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl("https://assets5.lottiefiles.com/packages/lf20_V9t630.json") st_lottie(lottie_hello, key="hello") Plotly EventsMake Plotly charts interactive!. Created by @null-jones.fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.chart += get_annotations_chart(annotations=[("Mar 01, 2008", "Pretty good day for GOOG"), ("Dec 01, 2007", "Something's going wrong for GOOG & AAPL"), ("Nov 01, 2008", "Market starts again thanks to..."), ("Dec 01, 2009", "Small crash for GOOG after..."),],) st.altair_chart(chart, use_container_width=True) PlostA deceptively simple plotting library for Streamlit. Created by @tvst.import plost plost.line_chart(my_dataframe, x='time', y='stock_value', color='stock_name',) HiPlotHigh dimensional Interactive Plotting. Created by @facebookresearch.data = [{'dropout':0.1, 'lr': 0.001, 'loss': 10.0, 'optimizer': 'SGD'}, {'dropout':0.15, 'lr': 0.01, 'loss': 3.5, 'optimizer': 'Adam'}, {'dropout':0.3, 'lr': 0.1, 'loss': 4.5, 'optimizer': 'Adam'}] hip.Experiment.from_iterable(data).display() EChartsHigh dimensional Interactive Plotting. Created by @andfanilo.from streamlit_echarts import st_echarts st_echarts(options=options) Streamlit FoliumStreamlit Component for rendering Folium maps. Created by @randyzwitch.m = folium.Map(location=[39.949610, -75.150282], zoom_start=16) st_data = st_folium(m, width=725) Spacy-StreamlitspaCy building blocks and visualizers for Streamlit apps. Created by @explosion.models = ["en_core_web_sm", "en_core_web_md"] spacy_streamlit.visualize(models, "Sundar Pichai is the CEO of Google.") Streamlit AgraphA Streamlit Graph Vis, based on react-grah-vis. Created by @ChrisDelClea.from streamlit_agraph import agraph, Node, Edge, Config agraph(nodes=nodes, edges=edges, config=config) Streamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl("https://assets5.lottiefiles.com/packages/lf20_V9t630.json") st_lottie(lottie_hello, key="hello") Plotly EventsMake Plotly charts interactive!. Created by @null-jones.fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.chart += get_annotations_chart(annotations=[("Mar 01, 2008", "Pretty good day for GOOG"), ("Dec 01, 2007", "Something's going wrong for GOOG & AAPL"), ("Nov 01, 2008", "Market starts again thanks to..."), ("Dec 01, 2009", "Small crash for GOOG after..."),],) st.altair_chart(chart, use_container_width=True) Next Input widgets ButtonDisplay a button widget.clicked = st.button("Click me") Download buttonDisplay a download button widget.st.download_button("Download file", file) Form buttonDisplay a form submit button. For use with st.form.st.form_submit_button("Sign up") Link buttonDisplay a link button.st.link_button("Go to gallery", url) Page linkDisplay a link to another page in a multipage app.st.page_link("app.py", label="Home", icon="🏠") st.page_link("pages/profile.py", label="My profile") CheckboxDisplay a checkbox widget.selected = st.checkbox("I agree") Color pickerDisplay a color picker widget.color = st.color_picker("Pick a color") MultiselectDisplay a multiselect widget. The multiselect widget starts as empty.choices = st.multiselect("Buy", ["milk", "apples", "potatoes"]) RadioDisplay a radio button widget.choice = st.radio("Pick one", ["cats", "dogs"]) SelectboxDisplay a select widget.choice = st.selectbox("Pick one", ["cats", "dogs"]) Select-sliderDisplay a slider widget to select items from a list.size = st.select_slider("Pick a size", ["S", "M", "L"]) ToggleDisplay a toggle widget.activated = st.toggle("Activate") Number inputDisplay a numeric input widget.choice = st.number_input("Pick a number", 0, 10) SliderDisplay a slider widget.number = st.slider("Pick a number", 0, 100) Date inputDisplay a date input widget.date = st.date_input("Your birthday") Time inputDisplay a time input widget.time = st.time_input("Meeting time") Chat inputDisplay a chat input widget.prompt = st.chat_input("Say something") if prompt: st.write(f"The user has sent: {prompt}") Text-areaDisplay a multi-line text input widget.text = st.text_area("Text to translate") Text inputDisplay a single-line text input widget.name = st.text_input("First name") Data editorDisplay a data editor widget.edited = st.experimental_data_editor(df, num_rows="dynamic") File UploaderDisplay a file uploader widget.data = st.file_uploader("Upload a CSV") Camera inputDisplay a widget that allows users to upload images directly from a camera.image = st.camera_input("Take a picture") Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration! PreviousStreamlit ChatStreamlit Component for a Chatbot UI. Created by @AI-Yash.from streamlit_chat import message message("My message") message("Hello bot!", is_user=True) # align's the message to the right Streamlit Option MenuSelect a single item from a list of options in a menu. Created by @victoryhb.from streamlit_option_menu import option_menu option_menu("Main Menu", ["Home", 'Settings'], icons=['house', 'gear'], menu_icon="cast", default_index=1) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.stoggle import stoggle stoggle( "Click me!", """🥷 Surprise! Here's some additional content""",) Streamlit ElementsCreate a draggable and resizable dashboard in Streamlit. Created by @okls.from streamlit_elements import elements, mui, html with elements("new_element"): mui.Typography("Hello world") TagsAdd tags to your Streamlit apps. Created by @gagan3012.from streamlit_tags import st_tags st_tags(label='# Enter Keywords:', text='Press enter to add more', value=['Zero', 'One', 'Two'], suggestions=['five', 'six', 'seven', 'eight', 'nine', 'three', 'eleven', 'ten', 'four'], maxtags = 4, key='1') StqdmThe simplest way to handle a progress bar in streamlit app. Created by @Wirg.from stqdm import stqdm for _ in stqdm(range(50)): sleep(0.5) TimelineDisplay a Timeline in Streamlit apps using TimelineJS. Created by @innerdoc.from streamlit_timeline import timeline with open('example.json', "r") as f: timeline(f.read(), height=800) Camera input liveAlternative for st.camera_input which returns the webcam images live. Created by @blackary.from camera_input_live import camera_input_live image = camera_input_live() st.image(value) Streamlit AceAce editor component for Streamlit. Created by @okld.from streamlit_ace import st_ace content = st_ace() content Streamlit ChatStreamlit Component for a Chatbot UI. Created by @AI-Yash.from streamlit_chat import message message("My message") message("Hello bot!", is_user=True) # align's the message to the right Streamlit Option MenuSelect a single item from a list of options in a menu. Created by @victoryhb.from streamlit_option_menu import option_menu option_menu("Main Menu", ["Home", 'Settings'], icons=['house', 'gear'], menu_icon="cast", default_index=1) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.stoggle import stoggle stoggle( "Click me!", """🥷 Surprise! Here's some additional content""",) Streamlit ElementsCreate a draggable and resizable dashboard in Streamlit. Created by @okls.from streamlit_elements import elements, mui, html with elements("new_element"): mui.Typography("Hello world") TagsAdd tags to your Streamlit apps. Created by @gagan3012.from streamlit_tags import st_tags st_tags(label='# Enter Keywords:', text='Press enter to add more', value=['Zero', 'One', 'Two'], suggestions=['five', 'six', 'seven', 'eight', 'nine', 'three', 'eleven', 'ten', 'four'], maxtags = 4, key='1') StqdmThe simplest way to handle a progress bar in streamlit app. Created by @Wirg.from stqdm import stqdm for _ in stqdm(range(50)): sleep(0.5) TimelineDisplay a Timeline in Streamlit apps using TimelineJS. Created by @innerdoc.from streamlit_timeline import timeline with open('example.json', "r") as f: timeline(f.read(), height=800) Camera input liveAlternative for st.camera_input which returns the webcam images live. Created by @blackary.from camera_input_live import camera_input_live image = camera_input_live() st.image(value) Streamlit AceAce editor component for Streamlit. Created by @okld.from streamlit_ace import st_ace content = st_ace() content Streamlit ChatStreamlit Component for a Chatbot UI. Created by @AI-Yash.from streamlit_chat import message message("My message") message("Hello bot!", is_user=True) # align's the message to the right Streamlit Option MenuSelect a single item from a list of options in a menu. Created by @victoryhb.from streamlit_option_menu import option_menu option_menu("Main Menu", ["Home", 'Settings'], icons=['house', 'gear'], menu_icon="cast", default_index=1) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.stoggle import stoggle stoggle( "Click me!", """🥷 Surprise! Here's some additional content""",) Next Media elements ImageDisplay an image or list of images.st.image(numpy_array) st.image(image_bytes) st.image(file) st.image("https://example.com/myimage.jpg") AudioDisplay an audio player.st.audio(numpy_array) st.audio(audio_bytes) st.audio(file) st.audio("https://example.com/myaudio.mp3", format="audio/mp3") VideoDisplay a video player.st.video(numpy_array) st.video(video_bytes) st.video(file) st.video("https://example.com/myvideo.mp4", format="video/mp4") Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration! PreviousStreamlit CropperA simple image cropper for Streamlit. Created by @turner-anderson.from streamlit_cropper import st_cropper st_cropper(img, realtime_update=realtime_update, box_color=box_color, aspect_ratio=aspect_ratio) Image CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates streamlit_image_coordinates("https://placekitten.com/200/300") Streamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl("https://assets5.lottiefiles.com/packages/lf20_V9t630.json") st_lottie(lottie_hello, key="hello") Streamlit WebrtcHandling and transmitting real-time video/audio streams with Streamlit. Created by @whitphx.from streamlit_webrtc import webrtc_streamer webrtc_streamer(key="sample") Drawable CanvasProvides a sketching canvas using Fabric.js. Created by @andfanilo.from streamlit_drawable_canvas import st_canvas st_canvas(fill_color="rgba(255, 165, 0, 0.3)", stroke_width=stroke_width, stroke_color=stroke_color, background_color=bg_color, background_image=Image.open(bg_image) if bg_image else None, update_streamlit=realtime_update, height=150, drawing_mode=drawing_mode, point_display_radius=point_display_radius if drawing_mode == 'point' else 0, key="canvas",) Image ComparisonCompare images with a slider using JuxtaposeJS. Created by @fcakyon.from streamlit_image_comparison import image_comparison image_comparison(img1="image1.jpg", img2="image2.jpg",) Streamlit CropperA simple image cropper for Streamlit. Created by @turner-anderson.from streamlit_cropper import st_cropper st_cropper(img, realtime_update=realtime_update, box_color=box_color, aspect_ratio=aspect_ratio) Image CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates streamlit_image_coordinates("https://placekitten.com/200/300") Streamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl("https://assets5.lottiefiles.com/packages/lf20_V9t630.json") st_lottie(lottie_hello, key="hello") Streamlit WebrtcHandling and transmitting real-time video/audio streams with Streamlit. Created by @whitphx.from streamlit_webrtc import webrtc_streamer webrtc_streamer(key="sample") Drawable CanvasProvides a sketching canvas using Fabric.js. Created by @andfanilo.from streamlit_drawable_canvas import st_canvas st_canvas(fill_color="rgba(255, 165, 0, 0.3)", stroke_width=stroke_width, stroke_color=stroke_color, background_color=bg_color, background_image=Image.open(bg_image) if bg_image else None, update_streamlit=realtime_update, height=150, drawing_mode=drawing_mode, point_display_radius=point_display_radius if drawing_mode == 'point' else 0, key="canvas",) Image ComparisonCompare images with a slider using JuxtaposeJS. Created by @fcakyon.from streamlit_image_comparison import image_comparison image_comparison(img1="image1.jpg", img2="image2.jpg",) Streamlit CropperA simple image cropper for Streamlit. Created by @turner-anderson.from streamlit_cropper import st_cropper st_cropper(img, realtime_update=realtime_update, box_color=box_color, aspect_ratio=aspect_ratio) Image CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates streamlit_image_coordinates("https://placekitten.com/200/300") Streamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl("https://assets5.lottiefiles.com/packages/lf20_V9t630.json") st_lottie(lottie_hello, key="hello") Next Layouts and containers ColumnsInsert containers laid out as side-by-side columns.col1, col2 = st.columns(2) col1.write("this is column 1") col2.write("this is column 2") ContainerInsert a multi-element container.c = st.container() st.write("This will show last") c.write("This will show first") c.write("This will show second") Modal dialogsInsert a modal dialog that can rerun independently from the rest of the script.@st.experimental_dialog("Sign up") def email_form(): name = st.text_input("Name") email = st.text_input("Email") EmptyInsert a single-element container.c = st.empty() st.write("This will show last") c.write("This will be replaced") c.write("This will show first") ExpanderInsert a multi-element container that can be expanded/collapsed.with st.expander("Open to see more"): st.write("This is more content") PopoverInsert a multi-element popover container that can be opened/closed.with st.popover("Settings"): st.checkbox("Show completed") SidebarDisplay items in a sidebar.st.sidebar.write("This lives in the sidebar") st.sidebar.button("Click me!") TabsInsert containers separated into tabs.tab1, tab2 = st.tabs(["Tab 1", "Tab2"]) tab1.write("this is tab 1") tab2.write("this is tab 2") Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration!Streamlit ElementsCreate a draggable and resizable dashboard in Streamlit. Created by @okls.from streamlit_elements import elements, mui, html with elements("new_element"): mui.Typography("Hello world") PydanticAuto-generate Streamlit UI from Pydantic Models and Dataclasses. Created by @lukasmasuch.import streamlit_pydantic as sp sp.pydantic_form(key="my_form", model=ExampleModel) Streamlit PagesAn experimental version of Streamlit Multi-Page Apps. Created by @blackary.from st_pages import Page, show_pages, add_page_title show_pages([ Page("streamlit_app.py", "Home", "🏠"), Page("other_pages/page2.py", "Page 2", ":books:"), ]) Chat elements Streamlit provides a few commands to help you build conversational apps. These chat elements are designed to be used in conjunction with each other, but you can also use them separately. st.chat_message lets you insert a chat message container into the app so you can display messages from the user or the app. Chat containers can contain other Streamlit elements, including charts, tables, text, and more. st.chat_input lets you display a chat input widget so the user can type in a message. Chat inputDisplay a chat input widget.prompt = st.chat_input("Say something") if prompt: st.write(f"The user has sent: {prompt}") Chat messageInsert a chat message container.import numpy as np with st.chat_message("user"): st.write("Hello 👋") st.line_chart(np.random.randn(30, 3)) Status containerDisplay output of long-running tasks in a container.with st.status('Running'): do_something_slow() st.write_streamWrite generators or streams to the app with a typewriter effect.st.write_stream(my_generator) st.write_stream(my_llm_stream) Status elements Progress barDisplay a progress bar.for i in range(101): st.progress(i) do_something_slow() SpinnerTemporarily displays a message while executing a block of code.with st.spinner("Please wait..."): do_something_slow() Status containerDisplay output of long-running tasks in a container.with st.status('Running'): do_something_slow() ToastBriefly displays a toast message in the bottom-right corner.st.toast('Butter!', icon='🧈') BalloonsDisplay celebratory balloons!do_something() # Celebrate when all done! st.balloons() SnowflakesDisplay celebratory snowflakes!do_something() # Celebrate when all done! st.snow() Success boxDisplay a success message.st.success("Match found!") Info boxDisplay an informational message.st.info("Dataset is updated every day at midnight.") Warning boxDisplay warning message.st.warning("Unable to fetch image. Skipping...") Error boxDisplay error message.st.error("We encountered an error") Exception outputDisplay an exception.e = RuntimeError("This is an exception of type RuntimeError") st.exception(e) Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration!StqdmThe simplest way to handle a progress bar in streamlit app. Created by @Wirg.from stqdm import stqdm for _ in stqdm(range(50)): sleep(0.5) Custom notification boxA custom notification box with the ability to close it out. Created by @Socvest.from streamlit_custom_notification_box import custom_notification_box styles = {'material-icons':{'color': 'red'}, 'text-icon-link-close-container': {'box-shadow': '#3896de 0px 4px'}, 'notification-text': {'':''}, 'close-button':{'':''}, 'link':{'':''}} custom_notification_box(icon='info', textDisplay='We are almost done with your registration...', externalLink='more info', url='#', styles=styles, key="foo") Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.let_it_rain import rain rain(emoji="🎈", font_size=54, falling_speed=5, animation_length="infinite",) App logic and configuration Navigation and pages Switch pageProgrammatically navigates to a specified page.st.switch_page("pages/my_page.py") Page linkDisplay a link to another page in a multipage app.st.page_link("app.py", label="Home", icon="🏠") st.page_link("pages/profile.py", label="My profile") Execution flow Modal dialogsInsert a modal dialog that can rerun independently from the rest of the script.@st.experimental_dialog("Sign up") def email_form(): name = st.text_input("Name") email = st.text_input("Email") FormsCreate a form that batches elements together with a “Submit" button.with st.form(key='my_form'): name = st.text_input("Name") email = st.text_input("Email") st.form_submit_button("Sign up") Partial rerunsDefine a fragment to rerun independently from the rest of the script.@st.experimental_fragment(run_every="10s") def fragment(): df = get_data() st.line_chart(df) Rerun scriptRerun the script immediately.st.rerun() Stop executionStops execution immediately.st.stop() Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration!AutorefreshForce a refresh without tying up a script. Created by @kmcgrady.from streamlit_autorefresh import st_autorefresh st_autorefresh(interval=2000, limit=100, key="fizzbuzzcounter") PydanticAuto-generate Streamlit UI from Pydantic Models and Dataclasses. Created by @lukasmasuch.import streamlit_pydantic as sp sp.pydantic_form(key="my_form", model=ExampleModel) Streamlit PagesAn experimental version of Streamlit Multi-Page Apps. Created by @blackary.from st_pages import Page, show_pages, add_page_title show_pages([ Page("streamlit_app.py", "Home", "🏠"), Page("other_pages/page2.py", "Page 2", ":books:"), ]) Caching and state Cache dataFunction decorator to cache functions that return data (e.g. dataframe transforms, database queries, ML inference).@st.cache_data def long_function(param1, param2): # Perform expensive computation here or # fetch data from the web here return data Cache resourceFunction decorator to cache functions that return global resources (e.g. database connections, ML models).@st.cache_resource def init_model(): # Return a global resource here return pipeline( "sentiment-analysis", model="distilbert-base-uncased-finetuned-sst-2-english" ) Session stateSession state is a way to share variables between reruns, for each user session.st.session_state['key'] = value Query parametersGet, set, or clear the query parameters that are shown in the browser's URL bar.st.query_params[key] = value st.query_params.clear() Connections and databases Setup your connection Create a connectionConnect to a data source or APIconn = st.connection('pets_db', type='sql') pet_owners = conn.query('select * from pet_owners') st.dataframe(pet_owners) Built-in connections SnowflakeConnectionA connection to Snowflake.conn = st.connection('snowflake') SQLConnectionA connection to a SQL database using SQLAlchemy.conn = st.connection('sql') Build your own connections Connection base classBuild your own connection with BaseConnection.class MyConnection(BaseConnection[myconn.MyConnection]): def _connect(self, **kwargs) -> MyConnection: return myconn.connect(**self._secrets, **kwargs) def query(self, query): return self._instance.query(query) Secrets management Secrets singletonAccess secrets from a local TOML file.key = st.secrets["OpenAI_key"] Secrets fileSave your secrets in a per-project or per-profile TOML file.OpenAI_key = "<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/en/0.76.0/api.html#developer-tools
DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceremovePAGE ELEMENTSWrite and magicaddText elementsaddData elementsaddChart elementsaddInput widgetsaddMedia elementsaddLayouts and containersaddChat elementsaddStatus elementsaddThird-party componentsopen_in_newAPPLICATION LOGICNavigation and pagesaddExecution flowaddCaching and stateaddConnections and secretsaddCustom componentsaddUtilitiesaddConfigurationaddTOOLSApp testingaddCommand lineaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Develop/API referenceAPI reference Streamlit makes it easy for you to visualize, mutate, and share data. The API reference is organized by activity type, like displaying data or optimizing performance. Each section includes methods associated with the activity type, including examples. Browse our API below and click to learn more about any of our available commands! 🎈 Display almost anything Write and magic st.writeWrite arguments to the app.st.write("Hello **world**!") st.write(my_data_frame) st.write(my_mpl_figure) st.write_streamWrite generators or streams to the app with a typewriter effect.st.write_stream(my_generator) st.write_stream(my_llm_stream) MagicAny time Streamlit sees either a variable or literal value on its own line, it automatically writes that to your app using st.write"Hello **world**!" my_data_frame my_mpl_figure Text elements MarkdownDisplay string formatted as Markdown.st.markdown("Hello **world**!") TitleDisplay text in title formatting.st.title("The app title") HeaderDisplay text in header formatting.st.header("This is a header") SubheaderDisplay text in subheader formatting.st.subheader("This is a subheader") CaptionDisplay text in small font.st.caption("This is written small caption text") Code blockDisplay a code block with optional syntax highlighting.st.code("a = 1234") EchoDisplay some code in the app, then execute it. Useful for tutorials.with st.echo(): st.write('This code will be printed') LaTeXDisplay mathematical expressions formatted as LaTeX.st.latex("\int a x^2 \,dx") Preformatted textWrite fixed-width and preformatted text.st.text("Hello world") DividerDisplay a horizontal rule.st.divider() Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration! PreviousTagsAdd tags to your Streamlit apps. Created by @gagan3012.st_tags(label='# Enter Keywords:', text='Press enter to add more', value=['Zero', 'One', 'Two'], suggestions=['five', 'six', 'seven', 'eight', 'nine', 'three', 'eleven', 'ten', 'four'], maxtags = 4, key='1') NLUApply text mining on a dataframe. Created by @JohnSnowLabs.nlu.load('sentiment').predict('I love NLU! <3') Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.mention(label="An awesome Streamlit App", icon="streamlit", url="https://extras.streamlit.app",) Annotated textDisplay annotated text in Streamlit apps. Created by @tvst.annotated_text("This ", ("is", "verb"), " some ", ("annotated", "adj"), ("text", "noun"), " for those of ", ("you", "pronoun"), " who ", ("like", "verb"), " this sort of ", ("thing", "noun"), ".") Drawable CanvasProvides a sketching canvas using Fabric.js. Created by @andfanilo.st_canvas(fill_color="rgba(255, 165, 0, 0.3)", stroke_width=stroke_width, stroke_color=stroke_color, background_color=bg_color, background_image=Image.open(bg_image) if bg_image else None, update_streamlit=realtime_update, height=150, drawing_mode=drawing_mode, point_display_radius=point_display_radius if drawing_mode == 'point' else 0, key="canvas",) TagsAdd tags to your Streamlit apps. Created by @gagan3012.st_tags(label='# Enter Keywords:', text='Press enter to add more', value=['Zero', 'One', 'Two'], suggestions=['five', 'six', 'seven', 'eight', 'nine', 'three', 'eleven', 'ten', 'four'], maxtags = 4, key='1') NLUApply text mining on a dataframe. Created by @JohnSnowLabs.nlu.load('sentiment').predict('I love NLU! <3') Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.mention(label="An awesome Streamlit App", icon="streamlit", url="https://extras.streamlit.app",) Annotated textDisplay annotated text in Streamlit apps. Created by @tvst.annotated_text("This ", ("is", "verb"), " some ", ("annotated", "adj"), ("text", "noun"), " for those of ", ("you", "pronoun"), " who ", ("like", "verb"), " this sort of ", ("thing", "noun"), ".") Drawable CanvasProvides a sketching canvas using Fabric.js. Created by @andfanilo.st_canvas(fill_color="rgba(255, 165, 0, 0.3)", stroke_width=stroke_width, stroke_color=stroke_color, background_color=bg_color, background_image=Image.open(bg_image) if bg_image else None, update_streamlit=realtime_update, height=150, drawing_mode=drawing_mode, point_display_radius=point_display_radius if drawing_mode == 'point' else 0, key="canvas",) TagsAdd tags to your Streamlit apps. Created by @gagan3012.st_tags(label='# Enter Keywords:', text='Press enter to add more', value=['Zero', 'One', 'Two'], suggestions=['five', 'six', 'seven', 'eight', 'nine', 'three', 'eleven', 'ten', 'four'], maxtags = 4, key='1') NLUApply text mining on a dataframe. Created by @JohnSnowLabs.nlu.load('sentiment').predict('I love NLU! <3') Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.mention(label="An awesome Streamlit App", icon="streamlit", url="https://extras.streamlit.app",) Next Data elements DataframesDisplay a dataframe as an interactive table.st.dataframe(my_data_frame) Data editorDisplay a data editor widget.edited = st.data_editor(df, num_rows="dynamic") Column configurationConfigure the display and editing behavior of dataframes and data editors.st.column_config.NumberColumn("Price (in USD)", min_value=0, format="$%d") Static tablesDisplay a static table.st.table(my_data_frame) MetricsDisplay a metric in big bold font, with an optional indicator of how the metric changed.st.metric("My metric", 42, 2) Dicts and JSONDisplay object or string as a pretty-printed JSON string.st.json(my_dict) Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration! PreviousImage CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates value = streamlit_image_coordinates("https://placekitten.com/200/300") st.write(value) Plotly EventsMake Plotly charts interactive!. Created by @null-jones.from streamlit_plotly_events import plotly_events fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.metric_cards import style_metric_cards col3.metric(label="No Change", value=5000, delta=0) style_metric_cards() Streamlit AggridImplementation of Ag-Grid component for Streamlit. Created by @PablocFonseca.df = pd.DataFrame({'col1': [1, 2, 3], 'col2': [4, 5, 6]}) grid_return = AgGrid(df, editable=True) new_df = grid_return['data'] Streamlit FoliumStreamlit Component for rendering Folium maps. Created by @randyzwitch.m = folium.Map(location=[39.949610, -75.150282], zoom_start=16) folium.Marker([39.949610, -75.150282], popup="Liberty Bell", tooltip="Liberty Bell").add_to(m) st_data = st_folium(m, width=725) Pandas ProfilingPandas profiling component for Streamlit. Created by @okld.df = pd.read_csv("https://storage.googleapis.com/tf-datasets/titanic/train.csv") pr = df.profile_report() st_profile_report(pr) Image CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates value = streamlit_image_coordinates("https://placekitten.com/200/300") st.write(value) Plotly EventsMake Plotly charts interactive!. Created by @null-jones.from streamlit_plotly_events import plotly_events fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.metric_cards import style_metric_cards col3.metric(label="No Change", value=5000, delta=0) style_metric_cards() Streamlit AggridImplementation of Ag-Grid component for Streamlit. Created by @PablocFonseca.df = pd.DataFrame({'col1': [1, 2, 3], 'col2': [4, 5, 6]}) grid_return = AgGrid(df, editable=True) new_df = grid_return['data'] Streamlit FoliumStreamlit Component for rendering Folium maps. Created by @randyzwitch.m = folium.Map(location=[39.949610, -75.150282], zoom_start=16) folium.Marker([39.949610, -75.150282], popup="Liberty Bell", tooltip="Liberty Bell").add_to(m) st_data = st_folium(m, width=725) Pandas ProfilingPandas profiling component for Streamlit. Created by @okld.df = pd.read_csv("https://storage.googleapis.com/tf-datasets/titanic/train.csv") pr = df.profile_report() st_profile_report(pr) Image CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates value = streamlit_image_coordinates("https://placekitten.com/200/300") st.write(value) Plotly EventsMake Plotly charts interactive!. Created by @null-jones.from streamlit_plotly_events import plotly_events fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.metric_cards import style_metric_cards col3.metric(label="No Change", value=5000, delta=0) style_metric_cards() Next Chart elements Simple area chartsDisplay an area chart.st.area_chart(my_data_frame) Simple bar chartsDisplay a bar chart.st.bar_chart(my_data_frame) Simple line chartsDisplay a line chart.st.line_chart(my_data_frame) Simple scatter chartsDisplay a line chart.st.scatter_chart(my_data_frame) Scatterplots on mapsDisplay a map with points on it.st.map(my_data_frame) MatplotlibDisplay a matplotlib.pyplot figure.st.pyplot(my_mpl_figure) AltairDisplay a chart using the Altair library.st.altair_chart(my_altair_chart) Vega-LiteDisplay a chart using the Vega-Lite library.st.vega_lite_chart(my_vega_lite_chart) PlotlyDisplay an interactive Plotly chart.st.plotly_chart(my_plotly_chart) BokehDisplay an interactive Bokeh chart.st.bokeh_chart(my_bokeh_chart) PyDeckDisplay a chart using the PyDeck library.st.pydeck_chart(my_pydeck_chart) GraphVizDisplay a graph using the dagre-d3 library.st.graphviz_chart(my_graphviz_spec) Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration! PreviousStreamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl("https://assets5.lottiefiles.com/packages/lf20_V9t630.json") st_lottie(lottie_hello, key="hello") Plotly EventsMake Plotly charts interactive!. Created by @null-jones.fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.chart += get_annotations_chart(annotations=[("Mar 01, 2008", "Pretty good day for GOOG"), ("Dec 01, 2007", "Something's going wrong for GOOG & AAPL"), ("Nov 01, 2008", "Market starts again thanks to..."), ("Dec 01, 2009", "Small crash for GOOG after..."),],) st.altair_chart(chart, use_container_width=True) PlostA deceptively simple plotting library for Streamlit. Created by @tvst.import plost plost.line_chart(my_dataframe, x='time', y='stock_value', color='stock_name',) HiPlotHigh dimensional Interactive Plotting. Created by @facebookresearch.data = [{'dropout':0.1, 'lr': 0.001, 'loss': 10.0, 'optimizer': 'SGD'}, {'dropout':0.15, 'lr': 0.01, 'loss': 3.5, 'optimizer': 'Adam'}, {'dropout':0.3, 'lr': 0.1, 'loss': 4.5, 'optimizer': 'Adam'}] hip.Experiment.from_iterable(data).display() EChartsHigh dimensional Interactive Plotting. Created by @andfanilo.from streamlit_echarts import st_echarts st_echarts(options=options) Streamlit FoliumStreamlit Component for rendering Folium maps. Created by @randyzwitch.m = folium.Map(location=[39.949610, -75.150282], zoom_start=16) st_data = st_folium(m, width=725) Spacy-StreamlitspaCy building blocks and visualizers for Streamlit apps. Created by @explosion.models = ["en_core_web_sm", "en_core_web_md"] spacy_streamlit.visualize(models, "Sundar Pichai is the CEO of Google.") Streamlit AgraphA Streamlit Graph Vis, based on react-grah-vis. Created by @ChrisDelClea.from streamlit_agraph import agraph, Node, Edge, Config agraph(nodes=nodes, edges=edges, config=config) Streamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl("https://assets5.lottiefiles.com/packages/lf20_V9t630.json") st_lottie(lottie_hello, key="hello") Plotly EventsMake Plotly charts interactive!. Created by @null-jones.fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.chart += get_annotations_chart(annotations=[("Mar 01, 2008", "Pretty good day for GOOG"), ("Dec 01, 2007", "Something's going wrong for GOOG & AAPL"), ("Nov 01, 2008", "Market starts again thanks to..."), ("Dec 01, 2009", "Small crash for GOOG after..."),],) st.altair_chart(chart, use_container_width=True) PlostA deceptively simple plotting library for Streamlit. Created by @tvst.import plost plost.line_chart(my_dataframe, x='time', y='stock_value', color='stock_name',) HiPlotHigh dimensional Interactive Plotting. Created by @facebookresearch.data = [{'dropout':0.1, 'lr': 0.001, 'loss': 10.0, 'optimizer': 'SGD'}, {'dropout':0.15, 'lr': 0.01, 'loss': 3.5, 'optimizer': 'Adam'}, {'dropout':0.3, 'lr': 0.1, 'loss': 4.5, 'optimizer': 'Adam'}] hip.Experiment.from_iterable(data).display() EChartsHigh dimensional Interactive Plotting. Created by @andfanilo.from streamlit_echarts import st_echarts st_echarts(options=options) Streamlit FoliumStreamlit Component for rendering Folium maps. Created by @randyzwitch.m = folium.Map(location=[39.949610, -75.150282], zoom_start=16) st_data = st_folium(m, width=725) Spacy-StreamlitspaCy building blocks and visualizers for Streamlit apps. Created by @explosion.models = ["en_core_web_sm", "en_core_web_md"] spacy_streamlit.visualize(models, "Sundar Pichai is the CEO of Google.") Streamlit AgraphA Streamlit Graph Vis, based on react-grah-vis. Created by @ChrisDelClea.from streamlit_agraph import agraph, Node, Edge, Config agraph(nodes=nodes, edges=edges, config=config) Streamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl("https://assets5.lottiefiles.com/packages/lf20_V9t630.json") st_lottie(lottie_hello, key="hello") Plotly EventsMake Plotly charts interactive!. Created by @null-jones.fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.chart += get_annotations_chart(annotations=[("Mar 01, 2008", "Pretty good day for GOOG"), ("Dec 01, 2007", "Something's going wrong for GOOG & AAPL"), ("Nov 01, 2008", "Market starts again thanks to..."), ("Dec 01, 2009", "Small crash for GOOG after..."),],) st.altair_chart(chart, use_container_width=True) Next Input widgets ButtonDisplay a button widget.clicked = st.button("Click me") Download buttonDisplay a download button widget.st.download_button("Download file", file) Form buttonDisplay a form submit button. For use with st.form.st.form_submit_button("Sign up") Link buttonDisplay a link button.st.link_button("Go to gallery", url) Page linkDisplay a link to another page in a multipage app.st.page_link("app.py", label="Home", icon="🏠") st.page_link("pages/profile.py", label="My profile") CheckboxDisplay a checkbox widget.selected = st.checkbox("I agree") Color pickerDisplay a color picker widget.color = st.color_picker("Pick a color") MultiselectDisplay a multiselect widget. The multiselect widget starts as empty.choices = st.multiselect("Buy", ["milk", "apples", "potatoes"]) RadioDisplay a radio button widget.choice = st.radio("Pick one", ["cats", "dogs"]) SelectboxDisplay a select widget.choice = st.selectbox("Pick one", ["cats", "dogs"]) Select-sliderDisplay a slider widget to select items from a list.size = st.select_slider("Pick a size", ["S", "M", "L"]) ToggleDisplay a toggle widget.activated = st.toggle("Activate") Number inputDisplay a numeric input widget.choice = st.number_input("Pick a number", 0, 10) SliderDisplay a slider widget.number = st.slider("Pick a number", 0, 100) Date inputDisplay a date input widget.date = st.date_input("Your birthday") Time inputDisplay a time input widget.time = st.time_input("Meeting time") Chat inputDisplay a chat input widget.prompt = st.chat_input("Say something") if prompt: st.write(f"The user has sent: {prompt}") Text-areaDisplay a multi-line text input widget.text = st.text_area("Text to translate") Text inputDisplay a single-line text input widget.name = st.text_input("First name") Data editorDisplay a data editor widget.edited = st.experimental_data_editor(df, num_rows="dynamic") File UploaderDisplay a file uploader widget.data = st.file_uploader("Upload a CSV") Camera inputDisplay a widget that allows users to upload images directly from a camera.image = st.camera_input("Take a picture") Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration! PreviousStreamlit ChatStreamlit Component for a Chatbot UI. Created by @AI-Yash.from streamlit_chat import message message("My message") message("Hello bot!", is_user=True) # align's the message to the right Streamlit Option MenuSelect a single item from a list of options in a menu. Created by @victoryhb.from streamlit_option_menu import option_menu option_menu("Main Menu", ["Home", 'Settings'], icons=['house', 'gear'], menu_icon="cast", default_index=1) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.stoggle import stoggle stoggle( "Click me!", """🥷 Surprise! Here's some additional content""",) Streamlit ElementsCreate a draggable and resizable dashboard in Streamlit. Created by @okls.from streamlit_elements import elements, mui, html with elements("new_element"): mui.Typography("Hello world") TagsAdd tags to your Streamlit apps. Created by @gagan3012.from streamlit_tags import st_tags st_tags(label='# Enter Keywords:', text='Press enter to add more', value=['Zero', 'One', 'Two'], suggestions=['five', 'six', 'seven', 'eight', 'nine', 'three', 'eleven', 'ten', 'four'], maxtags = 4, key='1') StqdmThe simplest way to handle a progress bar in streamlit app. Created by @Wirg.from stqdm import stqdm for _ in stqdm(range(50)): sleep(0.5) TimelineDisplay a Timeline in Streamlit apps using TimelineJS. Created by @innerdoc.from streamlit_timeline import timeline with open('example.json', "r") as f: timeline(f.read(), height=800) Camera input liveAlternative for st.camera_input which returns the webcam images live. Created by @blackary.from camera_input_live import camera_input_live image = camera_input_live() st.image(value) Streamlit AceAce editor component for Streamlit. Created by @okld.from streamlit_ace import st_ace content = st_ace() content Streamlit ChatStreamlit Component for a Chatbot UI. Created by @AI-Yash.from streamlit_chat import message message("My message") message("Hello bot!", is_user=True) # align's the message to the right Streamlit Option MenuSelect a single item from a list of options in a menu. Created by @victoryhb.from streamlit_option_menu import option_menu option_menu("Main Menu", ["Home", 'Settings'], icons=['house', 'gear'], menu_icon="cast", default_index=1) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.stoggle import stoggle stoggle( "Click me!", """🥷 Surprise! Here's some additional content""",) Streamlit ElementsCreate a draggable and resizable dashboard in Streamlit. Created by @okls.from streamlit_elements import elements, mui, html with elements("new_element"): mui.Typography("Hello world") TagsAdd tags to your Streamlit apps. Created by @gagan3012.from streamlit_tags import st_tags st_tags(label='# Enter Keywords:', text='Press enter to add more', value=['Zero', 'One', 'Two'], suggestions=['five', 'six', 'seven', 'eight', 'nine', 'three', 'eleven', 'ten', 'four'], maxtags = 4, key='1') StqdmThe simplest way to handle a progress bar in streamlit app. Created by @Wirg.from stqdm import stqdm for _ in stqdm(range(50)): sleep(0.5) TimelineDisplay a Timeline in Streamlit apps using TimelineJS. Created by @innerdoc.from streamlit_timeline import timeline with open('example.json', "r") as f: timeline(f.read(), height=800) Camera input liveAlternative for st.camera_input which returns the webcam images live. Created by @blackary.from camera_input_live import camera_input_live image = camera_input_live() st.image(value) Streamlit AceAce editor component for Streamlit. Created by @okld.from streamlit_ace import st_ace content = st_ace() content Streamlit ChatStreamlit Component for a Chatbot UI. Created by @AI-Yash.from streamlit_chat import message message("My message") message("Hello bot!", is_user=True) # align's the message to the right Streamlit Option MenuSelect a single item from a list of options in a menu. Created by @victoryhb.from streamlit_option_menu import option_menu option_menu("Main Menu", ["Home", 'Settings'], icons=['house', 'gear'], menu_icon="cast", default_index=1) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.stoggle import stoggle stoggle( "Click me!", """🥷 Surprise! Here's some additional content""",) Next Media elements ImageDisplay an image or list of images.st.image(numpy_array) st.image(image_bytes) st.image(file) st.image("https://example.com/myimage.jpg") AudioDisplay an audio player.st.audio(numpy_array) st.audio(audio_bytes) st.audio(file) st.audio("https://example.com/myaudio.mp3", format="audio/mp3") VideoDisplay a video player.st.video(numpy_array) st.video(video_bytes) st.video(file) st.video("https://example.com/myvideo.mp4", format="video/mp4") Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration! PreviousStreamlit CropperA simple image cropper for Streamlit. Created by @turner-anderson.from streamlit_cropper import st_cropper st_cropper(img, realtime_update=realtime_update, box_color=box_color, aspect_ratio=aspect_ratio) Image CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates streamlit_image_coordinates("https://placekitten.com/200/300") Streamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl("https://assets5.lottiefiles.com/packages/lf20_V9t630.json") st_lottie(lottie_hello, key="hello") Streamlit WebrtcHandling and transmitting real-time video/audio streams with Streamlit. Created by @whitphx.from streamlit_webrtc import webrtc_streamer webrtc_streamer(key="sample") Drawable CanvasProvides a sketching canvas using Fabric.js. Created by @andfanilo.from streamlit_drawable_canvas import st_canvas st_canvas(fill_color="rgba(255, 165, 0, 0.3)", stroke_width=stroke_width, stroke_color=stroke_color, background_color=bg_color, background_image=Image.open(bg_image) if bg_image else None, update_streamlit=realtime_update, height=150, drawing_mode=drawing_mode, point_display_radius=point_display_radius if drawing_mode == 'point' else 0, key="canvas",) Image ComparisonCompare images with a slider using JuxtaposeJS. Created by @fcakyon.from streamlit_image_comparison import image_comparison image_comparison(img1="image1.jpg", img2="image2.jpg",) Streamlit CropperA simple image cropper for Streamlit. Created by @turner-anderson.from streamlit_cropper import st_cropper st_cropper(img, realtime_update=realtime_update, box_color=box_color, aspect_ratio=aspect_ratio) Image CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates streamlit_image_coordinates("https://placekitten.com/200/300") Streamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl("https://assets5.lottiefiles.com/packages/lf20_V9t630.json") st_lottie(lottie_hello, key="hello") Streamlit WebrtcHandling and transmitting real-time video/audio streams with Streamlit. Created by @whitphx.from streamlit_webrtc import webrtc_streamer webrtc_streamer(key="sample") Drawable CanvasProvides a sketching canvas using Fabric.js. Created by @andfanilo.from streamlit_drawable_canvas import st_canvas st_canvas(fill_color="rgba(255, 165, 0, 0.3)", stroke_width=stroke_width, stroke_color=stroke_color, background_color=bg_color, background_image=Image.open(bg_image) if bg_image else None, update_streamlit=realtime_update, height=150, drawing_mode=drawing_mode, point_display_radius=point_display_radius if drawing_mode == 'point' else 0, key="canvas",) Image ComparisonCompare images with a slider using JuxtaposeJS. Created by @fcakyon.from streamlit_image_comparison import image_comparison image_comparison(img1="image1.jpg", img2="image2.jpg",) Streamlit CropperA simple image cropper for Streamlit. Created by @turner-anderson.from streamlit_cropper import st_cropper st_cropper(img, realtime_update=realtime_update, box_color=box_color, aspect_ratio=aspect_ratio) Image CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates streamlit_image_coordinates("https://placekitten.com/200/300") Streamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl("https://assets5.lottiefiles.com/packages/lf20_V9t630.json") st_lottie(lottie_hello, key="hello") Next Layouts and containers ColumnsInsert containers laid out as side-by-side columns.col1, col2 = st.columns(2) col1.write("this is column 1") col2.write("this is column 2") ContainerInsert a multi-element container.c = st.container() st.write("This will show last") c.write("This will show first") c.write("This will show second") Modal dialogsInsert a modal dialog that can rerun independently from the rest of the script.@st.experimental_dialog("Sign up") def email_form(): name = st.text_input("Name") email = st.text_input("Email") EmptyInsert a single-element container.c = st.empty() st.write("This will show last") c.write("This will be replaced") c.write("This will show first") ExpanderInsert a multi-element container that can be expanded/collapsed.with st.expander("Open to see more"): st.write("This is more content") PopoverInsert a multi-element popover container that can be opened/closed.with st.popover("Settings"): st.checkbox("Show completed") SidebarDisplay items in a sidebar.st.sidebar.write("This lives in the sidebar") st.sidebar.button("Click me!") TabsInsert containers separated into tabs.tab1, tab2 = st.tabs(["Tab 1", "Tab2"]) tab1.write("this is tab 1") tab2.write("this is tab 2") Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration!Streamlit ElementsCreate a draggable and resizable dashboard in Streamlit. Created by @okls.from streamlit_elements import elements, mui, html with elements("new_element"): mui.Typography("Hello world") PydanticAuto-generate Streamlit UI from Pydantic Models and Dataclasses. Created by @lukasmasuch.import streamlit_pydantic as sp sp.pydantic_form(key="my_form", model=ExampleModel) Streamlit PagesAn experimental version of Streamlit Multi-Page Apps. Created by @blackary.from st_pages import Page, show_pages, add_page_title show_pages([ Page("streamlit_app.py", "Home", "🏠"), Page("other_pages/page2.py", "Page 2", ":books:"), ]) Chat elements Streamlit provides a few commands to help you build conversational apps. These chat elements are designed to be used in conjunction with each other, but you can also use them separately. st.chat_message lets you insert a chat message container into the app so you can display messages from the user or the app. Chat containers can contain other Streamlit elements, including charts, tables, text, and more. st.chat_input lets you display a chat input widget so the user can type in a message. Chat inputDisplay a chat input widget.prompt = st.chat_input("Say something") if prompt: st.write(f"The user has sent: {prompt}") Chat messageInsert a chat message container.import numpy as np with st.chat_message("user"): st.write("Hello 👋") st.line_chart(np.random.randn(30, 3)) Status containerDisplay output of long-running tasks in a container.with st.status('Running'): do_something_slow() st.write_streamWrite generators or streams to the app with a typewriter effect.st.write_stream(my_generator) st.write_stream(my_llm_stream) Status elements Progress barDisplay a progress bar.for i in range(101): st.progress(i) do_something_slow() SpinnerTemporarily displays a message while executing a block of code.with st.spinner("Please wait..."): do_something_slow() Status containerDisplay output of long-running tasks in a container.with st.status('Running'): do_something_slow() ToastBriefly displays a toast message in the bottom-right corner.st.toast('Butter!', icon='🧈') BalloonsDisplay celebratory balloons!do_something() # Celebrate when all done! st.balloons() SnowflakesDisplay celebratory snowflakes!do_something() # Celebrate when all done! st.snow() Success boxDisplay a success message.st.success("Match found!") Info boxDisplay an informational message.st.info("Dataset is updated every day at midnight.") Warning boxDisplay warning message.st.warning("Unable to fetch image. Skipping...") Error boxDisplay error message.st.error("We encountered an error") Exception outputDisplay an exception.e = RuntimeError("This is an exception of type RuntimeError") st.exception(e) Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration!StqdmThe simplest way to handle a progress bar in streamlit app. Created by @Wirg.from stqdm import stqdm for _ in stqdm(range(50)): sleep(0.5) Custom notification boxA custom notification box with the ability to close it out. Created by @Socvest.from streamlit_custom_notification_box import custom_notification_box styles = {'material-icons':{'color': 'red'}, 'text-icon-link-close-container': {'box-shadow': '#3896de 0px 4px'}, 'notification-text': {'':''}, 'close-button':{'':''}, 'link':{'':''}} custom_notification_box(icon='info', textDisplay='We are almost done with your registration...', externalLink='more info', url='#', styles=styles, key="foo") Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.let_it_rain import rain rain(emoji="🎈", font_size=54, falling_speed=5, animation_length="infinite",) App logic and configuration Navigation and pages Switch pageProgrammatically navigates to a specified page.st.switch_page("pages/my_page.py") Page linkDisplay a link to another page in a multipage app.st.page_link("app.py", label="Home", icon="🏠") st.page_link("pages/profile.py", label="My profile") Execution flow Modal dialogsInsert a modal dialog that can rerun independently from the rest of the script.@st.experimental_dialog("Sign up") def email_form(): name = st.text_input("Name") email = st.text_input("Email") FormsCreate a form that batches elements together with a “Submit" button.with st.form(key='my_form'): name = st.text_input("Name") email = st.text_input("Email") st.form_submit_button("Sign up") Partial rerunsDefine a fragment to rerun independently from the rest of the script.@st.experimental_fragment(run_every="10s") def fragment(): df = get_data() st.line_chart(df) Rerun scriptRerun the script immediately.st.rerun() Stop executionStops execution immediately.st.stop() Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration!AutorefreshForce a refresh without tying up a script. Created by @kmcgrady.from streamlit_autorefresh import st_autorefresh st_autorefresh(interval=2000, limit=100, key="fizzbuzzcounter") PydanticAuto-generate Streamlit UI from Pydantic Models and Dataclasses. Created by @lukasmasuch.import streamlit_pydantic as sp sp.pydantic_form(key="my_form", model=ExampleModel) Streamlit PagesAn experimental version of Streamlit Multi-Page Apps. Created by @blackary.from st_pages import Page, show_pages, add_page_title show_pages([ Page("streamlit_app.py", "Home", "🏠"), Page("other_pages/page2.py", "Page 2", ":books:"), ]) Caching and state Cache dataFunction decorator to cache functions that return data (e.g. dataframe transforms, database queries, ML inference).@st.cache_data def long_function(param1, param2): # Perform expensive computation here or # fetch data from the web here return data Cache resourceFunction decorator to cache functions that return global resources (e.g. database connections, ML models).@st.cache_resource def init_model(): # Return a global resource here return pipeline( "sentiment-analysis", model="distilbert-base-uncased-finetuned-sst-2-english" ) Session stateSession state is a way to share variables between reruns, for each user session.st.session_state['key'] = value Query parametersGet, set, or clear the query parameters that are shown in the browser's URL bar.st.query_params[key] = value st.query_params.clear() Connections and databases Setup your connection Create a connectionConnect to a data source or APIconn = st.connection('pets_db', type='sql') pet_owners = conn.query('select * from pet_owners') st.dataframe(pet_owners) Built-in connections SnowflakeConnectionA connection to Snowflake.conn = st.connection('snowflake') SQLConnectionA connection to a SQL database using SQLAlchemy.conn = st.connection('sql') Build your own connections Connection base classBuild your own connection with BaseConnection.class MyConnection(BaseConnection[myconn.MyConnection]): def _connect(self, **kwargs) -> MyConnection: return myconn.connect(**self._secrets, **kwargs) def query(self, query): return self._instance.query(query) Secrets management Secrets singletonAccess secrets from a local TOML file.key = st.secrets["OpenAI_key"] Secrets fileSave your secrets in a per-project or per-profile TOML file.OpenAI_key = "<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/app-chrome#settings
DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsremoveCOREArchitecture & executionremoveRunning your appStreamlit's architectureThe app chromeCachingSession StateFormsFragmentsWidget behaviorMultipage appsaddApp designaddADDITIONALConnections and secretsaddCustom componentsaddConfiguration and themingaddApp testingaddAPI referenceaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Develop/Concepts/Architecture & execution/The app chromeThe app chrome Your Streamlit app has a few widgets in the top right to help you as you develop. These widgets also help your viewers as they use your app. We call this things “the app chrome”. The chrome includes a status area, toolbar, and app menu. Your app menu is configurable. By default, you can access developer options from the app menu when viewing an app locally or on Streamlit Community Cloud while logged into an account with administrative access. While viewing an app, click the icon in the upper-right corner to access the menu. Menu options The menu is split into two sections. The upper section contains options available to all viewers and the lower section contains options for developers. Read more about customizing this menu at the end of this page. Rerun You can manually trigger a rerun of your app by clicking "Rerun" from the app menu. This rerun will not reset your session. Your widget states and values stored in st.session_state will be preserved. As a shortcut, without opening the app menu, you can rerun your app by pressing "R" on your keyboard (if you aren't currently focused on an input element). Settings With the "Settings" option, you can control the appearance of your app while it is running. If viewing the app locally, you can set how your app responds to changes in your source code. See more about development flow in Basic concepts. You can also force your app to appear in wide mode, even if not set within the script using st.set_page_config. Theme settings After clicking "Settings" from the app menu, you can choose between "Light", "Dark", or "Use system setting" for the app's base theme. Click on "Edit active theme" to modify the theme, color-by-color. Print Click "Print" or use keyboard shortcuts (⌘+P or Ctrl+P) to open a print dialog. This option uses your browser's built-in print-to-pdf function. To modify the appearance of your print, you can do the following: Expand or collapse the sidebar before printing to respectively include or exclude it from the print. Resize the sidebar in your app by clicking and dragging its right border to achieve your desired width. You may need to enable "Background graphics" in your print dialog if you are printing in dark mode. You may need to disable wide mode in Settings or adjust the print scale to prevent elements from clipping off the page. Record a screencast You can easily make screen recordings right from your app! Screen recording is supported in the latest versions of Chrome, Edge, and Firefox. Ensure your browser is up-to-date for compatibility. Depending on your current settings, you may need to grant permission to your browser to record your screen or to use your microphone if recording a voiceover. While viewing your app, open the app menu from the upper-right corner. Click "Record a screencast." If you want to record audio through your microphone, check "Also record audio." Click "Start recording." (You may be prompted by your OS to permit your browser to record your screen or use your microphone.) Select which tab, window, or monitor you want to record from the listed options. The interface will vary depending on your browser. Click "Share." While recording, you will see a red circle on your app's tab and on the app menu icon. If you want to cancel the recording, click "Stop sharing" at the bottom of your app. When you are done recording, press "Esc" on your keyboard or click "Stop recording" from your app's menu. Follow your browser's instructions to save your recording. Your saved recording will be available where your browser saves downloads. The whole process looks like this: About You can conveniently check what version of Streamlit is running from the "About" option. Developers also have the option to customize the message shown here using st.set_page_config. Developer options By default, developer options only show when viewing an app locally or when viewing a Community Cloud app while logged in with administrative permission. You can customize the menu if you want to make these options available for all users. Clear cache Reset your app's cache by clicking "Clear cache" from the app's menu or by pressing "C" on your keyboard while not focused on an input element. This will remove all cached entries for @st.cache_data and @st.cache_resource. Deploy this app If you are running an app locally from within a git repo, you can deploy your app to Streamlit Community Cloud in a few easy clicks! Make sure your work has been pushed to your online GitHub repository before beginning. For the greatest convenience, make sure you have already created your Community Cloud account and are signed in. Click "Deploy" next to the app menu icon (more_vert). Click "Deploy now". You will be taken to Community Cloud's "Deploy an app" page. Your app's repository, branch, and file name will be prefilled to match your current app! Learn more about deploying an app on Streamlit Community Cloud. The whole process looks like this: Customize the menu Using client.toolbarMode in your app's configuration, you can make the app menu appear in the following ways: "developer" — Show the developer options to all viewers. "viewer" — Hide the developer options from all viewers. "minimal" — Show only those options set externally. These options can be declared through st.set_page_config or populated through Streamlit Community Cloud. "auto" — This is the default and will show the developer options when accessed through localhost or through Streamlit Community Cloud when logged into an administrative account for the app. Otherwise, the developer options will not show. Previous: Streamlit's architectureNext: CachingforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy
https://docs.streamlit.io/deploy/tutorials
DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsremoveDockerKubernetesschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Deploy/Other platformsDeployment tutorials This sections contains step-by-step guides on how to deploy Streamlit apps to various cloud platforms and services. We have deployment guides for: Streamlit Community CloudDockerKubernetes While we work on official Streamlit deployment guides for other hosting providers, here are some user-submitted tutorials for different cloud services: How to Deploy Streamlit to a Free Amazon EC2 instance, by Rahul Agarwal. Host Streamlit on Azure, by Richard Peterson. How to deploy Streamlit apps to Google App Engine, by Yuichiro Tachibana (Tsuchiya). Host Streamlit on Heroku, by Maarten Grootendorst. Deploy Streamlit on Ploomber Cloud, by Ido Michael. Host Streamlit on 21YunBox, by Toby Lei. Community-supported deployment wiki. Previous: Streamlit in SnowflakeNext: DockerforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy
https://docs.streamlit.io/knowledge-base/deploy/organizing-apps-workspaces-streamlit-cloud#organization-workspace
DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Knowledge base/Deployment issues/Organizing your apps with workspaces on Streamlit Community CloudOrganizing your apps with workspaces on Streamlit Community Cloud Streamlit Community Cloud is organized into workspaces, which automatically group your apps according to the corresponding GitHub repository's owner. If you are part of multiple repositories, then you will have multiple workspaces. Personal workspace If an app's GitHub repository is owned by you, the app will appear in your personal workspace, named "<YourGitHubHandle>". Organization workspace If an app's GitHub repository is owned by an organization (such as your company), the app will appear in a separate workspace, named "<GitHubOrganizationHandle>". Workspaces with view access You will also have access to any workspaces containing app(s) for which you only have view access. These apps will have a "view-only" tooltip when you click on their respective overflow menu icons (⋮). Switching between workspaces To switch between workspaces, click on the workspace listed in the top right corner, then select the desired workspace name. push_pinNoteIf you have further questions about workspaces on Streamlit Community Cloud, please emails us at success@streamlit.io.Previous: Invoking a Python subprocess in a deployed Streamlit appNext: App is not loading when running remotelyforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy
https://docs.streamlit.io/develop/concepts/multipage-apps/pages-directory#naming-and-ordering-your-pages
DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsremoveCOREArchitecture & executionaddMultipage appsremovePages directory (v1)App designaddADDITIONALConnections and secretsaddCustom componentsaddConfiguration and themingaddApp testingaddAPI referenceaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Develop/Concepts/Multipage apps/Pages directory (v1)Creating multipage apps using the pages/ directory As your app grows large, it becomes useful to organize your script into multiple pages. This makes your app easier to manage as a developer and easier to navigate as a user. Streamlit provides a frictionless way to create multipage apps. Pages are automatically shown in a navigation widget inside your app's sidebar. If a user clicks on a page in the sidebar, Streamlit navigates to that page without reloading the frontend — making app browsing incredibly fast! In this guide, let’s learn how to create multipage apps. Structuring your multipage app Streamlit identifies pages in a multipage app by directory structure and filenames. The file you pass to streamlit run is called your entrypoint file. This is your app's homepage. When you have a pages/ directory next to your entrypoint file, Streamlit will identify each Python file within it as a page. The following example has three pages. your_homepage.py is the entrypoint file and homepage. your_working_directory/ ├── pages/ │ ├── a_page.py │ └── another_page.py └── your_homepage.py Run your multipage app just like you would for a single-page app. Pass your entrypoint file to streamlit run. streamlit run your_homepage.py Only .py files in the pages/ directory will be identified as pages. Streamlit ignores all other files in the pages/ directory and its subdirectories. Streamlit also ignores Python files in subdirectories of pages/. Keep reading to learn how filenames are displayed and ordered in your app's navigation. Naming and ordering your pages The entrypoint file is your app's homepage and the first page users will see when visiting your app. Once you've added pages to your app, the entrypoint file appears as the topmost page in the sidebar. Streamlit determines the page label and ordering of each page from your filenames. Labels may differ from the page title set in st.set_page_config. Filenames for pages Filenames are composed of four different parts as follows: number. A non-negative integer. separator. Any combination of underscore ("_"), dash ("-"), and space (" "). label. Everything up to, but not including, ".py". ".py" How Streamlit converts filenames into page labels Streamlit displays page labels as follows: If your filename contains a label, Streamlit displays the label in the left navigation. Any underscores within the page's label are treated as spaces. If your filename contains a number but does not contain a label, Streamlit displays the number instead. If your filename contains only a separator with no number and no label, Streamlit will not display the page in the sidebar navigation. The following filenames would all display as "Awesome homepage" in the sidebar navigation. "Awesome homepage.py" "Awesome_homepage.py" "02Awesome_homepage.py" "--Awesome_homepage.py" "1_Awesome_homepage.py" "33 - Awesome homepage.py" How pages are sorted in the sidebar The entrypoint file is always displayed first. The remaining pages are sorted as follows: Files that have a number appear before files without a number. Files are sorted based on the number (if any), followed by the label (if any). When files are sorted, Streamlit treats the number as an actual number rather than a string. So 03 is the same as 3. This table shows examples of filenames and their corresponding labels, sorted by the order in which they appear in the sidebar. Examples: FilenameRendered label1 - first page.pyfirst page12 monkeys.pymonkeys123.py123123_hello_dear_world.pyhello dear world_12 monkeys.py12 monkeys starTipEmojis can be used to make your page names more fun! For example, a file named 🏠_Home.py will create a page titled "🏠 Home" in the sidebar. When adding emojis to filenames, it’s best practice to include a numbered prefix to make autocompletion in your terminal easier. Terminal-autocomplete can get confused by unicode (which is how emojis are represented). Navigating between pages Pages are automatically shown in a sidebar navigation UI. When a user clicks on a page in the sidebar UI, Streamlit navigates to that page without reloading the entire frontend — making app browsing incredibly fast! Optionally, you can hide the default navigation UI and build your own with st.page_link. For more information, see Build a custom navigation menu with st.page_link. If you need to programmatically switch pages, use st.switch_page. Users can also navigate between pages using URLs. Pages have their own URLs, defined by the file's label. When multiple files have the same label, Streamlit picks the first one (based on the ordering described above). Users can view a specific page by visiting the page's URL. priority_highImportantNavigating between pages by URL creates a new browser session and clears st.session_state. In particular, clicking markdown links to other pages resets st.session_state. In order to retain values in st.session_state, a user must use the sidebar navigation or other Streamlit widgets to switch pages. If a user tries to access a URL for a page that does not exist, they will see a modal like the one below, saying the user has requested a page that was not found in the app’s pages/ directory. Notes and limitations Pages support run-on-save. When you update a page while your app is running, this causes a rerun for users currently viewing that exact page. When you update a page while your app is running, the app will not automatically rerun for users currently viewing a different page. While your app is running, adding or deleting a page updates the sidebar navigation immediately. st.set_page_config works at the page level. When you set title or favicon using st.set_page_config, this applies to the current page only. When you set layout using st.set_page_config, the setting will remain for the session until changed by another call to st.set_page_config. If you use st.set_page_config to set layout, it's recommended to call it on all pages. Pages share the same Python modules globally: # page1.py import foo foo.hello = 123 # page2.py import foo st.write(foo.hello) # If page1 already executed, this writes 123 Pages share the same st.session_state: # page1.py import streamlit as st if "shared" not in st.session_state: st.session_state["shared"] = True # page2.py import streamlit as st st.write(st.session_state["shared"]) # If page1 already executed, this writes True You now have a solid understanding of multipage apps. You've learned how to structure apps, define pages, and navigate between pages in the user interface. It's time to create your first multipage app! 🥳Previous: Multipage appsNext: App designforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy
https://docs.streamlit.io/en/0.72.0/api.html#build-your-own-connections
DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceremovePAGE ELEMENTSWrite and magicaddText elementsaddData elementsaddChart elementsaddInput widgetsaddMedia elementsaddLayouts and containersaddChat elementsaddStatus elementsaddThird-party componentsopen_in_newAPPLICATION LOGICNavigation and pagesaddExecution flowaddCaching and stateaddConnections and secretsaddCustom componentsaddUtilitiesaddConfigurationaddTOOLSApp testingaddCommand lineaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Develop/API referenceAPI reference Streamlit makes it easy for you to visualize, mutate, and share data. The API reference is organized by activity type, like displaying data or optimizing performance. Each section includes methods associated with the activity type, including examples. Browse our API below and click to learn more about any of our available commands! 🎈 Display almost anything Write and magic st.writeWrite arguments to the app.st.write("Hello **world**!") st.write(my_data_frame) st.write(my_mpl_figure) st.write_streamWrite generators or streams to the app with a typewriter effect.st.write_stream(my_generator) st.write_stream(my_llm_stream) MagicAny time Streamlit sees either a variable or literal value on its own line, it automatically writes that to your app using st.write"Hello **world**!" my_data_frame my_mpl_figure Text elements MarkdownDisplay string formatted as Markdown.st.markdown("Hello **world**!") TitleDisplay text in title formatting.st.title("The app title") HeaderDisplay text in header formatting.st.header("This is a header") SubheaderDisplay text in subheader formatting.st.subheader("This is a subheader") CaptionDisplay text in small font.st.caption("This is written small caption text") Code blockDisplay a code block with optional syntax highlighting.st.code("a = 1234") EchoDisplay some code in the app, then execute it. Useful for tutorials.with st.echo(): st.write('This code will be printed') LaTeXDisplay mathematical expressions formatted as LaTeX.st.latex("\int a x^2 \,dx") Preformatted textWrite fixed-width and preformatted text.st.text("Hello world") DividerDisplay a horizontal rule.st.divider() Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration! PreviousTagsAdd tags to your Streamlit apps. Created by @gagan3012.st_tags(label='# Enter Keywords:', text='Press enter to add more', value=['Zero', 'One', 'Two'], suggestions=['five', 'six', 'seven', 'eight', 'nine', 'three', 'eleven', 'ten', 'four'], maxtags = 4, key='1') NLUApply text mining on a dataframe. Created by @JohnSnowLabs.nlu.load('sentiment').predict('I love NLU! <3') Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.mention(label="An awesome Streamlit App", icon="streamlit", url="https://extras.streamlit.app",) Annotated textDisplay annotated text in Streamlit apps. Created by @tvst.annotated_text("This ", ("is", "verb"), " some ", ("annotated", "adj"), ("text", "noun"), " for those of ", ("you", "pronoun"), " who ", ("like", "verb"), " this sort of ", ("thing", "noun"), ".") Drawable CanvasProvides a sketching canvas using Fabric.js. Created by @andfanilo.st_canvas(fill_color="rgba(255, 165, 0, 0.3)", stroke_width=stroke_width, stroke_color=stroke_color, background_color=bg_color, background_image=Image.open(bg_image) if bg_image else None, update_streamlit=realtime_update, height=150, drawing_mode=drawing_mode, point_display_radius=point_display_radius if drawing_mode == 'point' else 0, key="canvas",) TagsAdd tags to your Streamlit apps. Created by @gagan3012.st_tags(label='# Enter Keywords:', text='Press enter to add more', value=['Zero', 'One', 'Two'], suggestions=['five', 'six', 'seven', 'eight', 'nine', 'three', 'eleven', 'ten', 'four'], maxtags = 4, key='1') NLUApply text mining on a dataframe. Created by @JohnSnowLabs.nlu.load('sentiment').predict('I love NLU! <3') Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.mention(label="An awesome Streamlit App", icon="streamlit", url="https://extras.streamlit.app",) Annotated textDisplay annotated text in Streamlit apps. Created by @tvst.annotated_text("This ", ("is", "verb"), " some ", ("annotated", "adj"), ("text", "noun"), " for those of ", ("you", "pronoun"), " who ", ("like", "verb"), " this sort of ", ("thing", "noun"), ".") Drawable CanvasProvides a sketching canvas using Fabric.js. Created by @andfanilo.st_canvas(fill_color="rgba(255, 165, 0, 0.3)", stroke_width=stroke_width, stroke_color=stroke_color, background_color=bg_color, background_image=Image.open(bg_image) if bg_image else None, update_streamlit=realtime_update, height=150, drawing_mode=drawing_mode, point_display_radius=point_display_radius if drawing_mode == 'point' else 0, key="canvas",) TagsAdd tags to your Streamlit apps. Created by @gagan3012.st_tags(label='# Enter Keywords:', text='Press enter to add more', value=['Zero', 'One', 'Two'], suggestions=['five', 'six', 'seven', 'eight', 'nine', 'three', 'eleven', 'ten', 'four'], maxtags = 4, key='1') NLUApply text mining on a dataframe. Created by @JohnSnowLabs.nlu.load('sentiment').predict('I love NLU! <3') Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.mention(label="An awesome Streamlit App", icon="streamlit", url="https://extras.streamlit.app",) Next Data elements DataframesDisplay a dataframe as an interactive table.st.dataframe(my_data_frame) Data editorDisplay a data editor widget.edited = st.data_editor(df, num_rows="dynamic") Column configurationConfigure the display and editing behavior of dataframes and data editors.st.column_config.NumberColumn("Price (in USD)", min_value=0, format="$%d") Static tablesDisplay a static table.st.table(my_data_frame) MetricsDisplay a metric in big bold font, with an optional indicator of how the metric changed.st.metric("My metric", 42, 2) Dicts and JSONDisplay object or string as a pretty-printed JSON string.st.json(my_dict) Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration! PreviousImage CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates value = streamlit_image_coordinates("https://placekitten.com/200/300") st.write(value) Plotly EventsMake Plotly charts interactive!. Created by @null-jones.from streamlit_plotly_events import plotly_events fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.metric_cards import style_metric_cards col3.metric(label="No Change", value=5000, delta=0) style_metric_cards() Streamlit AggridImplementation of Ag-Grid component for Streamlit. Created by @PablocFonseca.df = pd.DataFrame({'col1': [1, 2, 3], 'col2': [4, 5, 6]}) grid_return = AgGrid(df, editable=True) new_df = grid_return['data'] Streamlit FoliumStreamlit Component for rendering Folium maps. Created by @randyzwitch.m = folium.Map(location=[39.949610, -75.150282], zoom_start=16) folium.Marker([39.949610, -75.150282], popup="Liberty Bell", tooltip="Liberty Bell").add_to(m) st_data = st_folium(m, width=725) Pandas ProfilingPandas profiling component for Streamlit. Created by @okld.df = pd.read_csv("https://storage.googleapis.com/tf-datasets/titanic/train.csv") pr = df.profile_report() st_profile_report(pr) Image CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates value = streamlit_image_coordinates("https://placekitten.com/200/300") st.write(value) Plotly EventsMake Plotly charts interactive!. Created by @null-jones.from streamlit_plotly_events import plotly_events fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.metric_cards import style_metric_cards col3.metric(label="No Change", value=5000, delta=0) style_metric_cards() Streamlit AggridImplementation of Ag-Grid component for Streamlit. Created by @PablocFonseca.df = pd.DataFrame({'col1': [1, 2, 3], 'col2': [4, 5, 6]}) grid_return = AgGrid(df, editable=True) new_df = grid_return['data'] Streamlit FoliumStreamlit Component for rendering Folium maps. Created by @randyzwitch.m = folium.Map(location=[39.949610, -75.150282], zoom_start=16) folium.Marker([39.949610, -75.150282], popup="Liberty Bell", tooltip="Liberty Bell").add_to(m) st_data = st_folium(m, width=725) Pandas ProfilingPandas profiling component for Streamlit. Created by @okld.df = pd.read_csv("https://storage.googleapis.com/tf-datasets/titanic/train.csv") pr = df.profile_report() st_profile_report(pr) Image CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates value = streamlit_image_coordinates("https://placekitten.com/200/300") st.write(value) Plotly EventsMake Plotly charts interactive!. Created by @null-jones.from streamlit_plotly_events import plotly_events fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.metric_cards import style_metric_cards col3.metric(label="No Change", value=5000, delta=0) style_metric_cards() Next Chart elements Simple area chartsDisplay an area chart.st.area_chart(my_data_frame) Simple bar chartsDisplay a bar chart.st.bar_chart(my_data_frame) Simple line chartsDisplay a line chart.st.line_chart(my_data_frame) Simple scatter chartsDisplay a line chart.st.scatter_chart(my_data_frame) Scatterplots on mapsDisplay a map with points on it.st.map(my_data_frame) MatplotlibDisplay a matplotlib.pyplot figure.st.pyplot(my_mpl_figure) AltairDisplay a chart using the Altair library.st.altair_chart(my_altair_chart) Vega-LiteDisplay a chart using the Vega-Lite library.st.vega_lite_chart(my_vega_lite_chart) PlotlyDisplay an interactive Plotly chart.st.plotly_chart(my_plotly_chart) BokehDisplay an interactive Bokeh chart.st.bokeh_chart(my_bokeh_chart) PyDeckDisplay a chart using the PyDeck library.st.pydeck_chart(my_pydeck_chart) GraphVizDisplay a graph using the dagre-d3 library.st.graphviz_chart(my_graphviz_spec) Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration! PreviousStreamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl("https://assets5.lottiefiles.com/packages/lf20_V9t630.json") st_lottie(lottie_hello, key="hello") Plotly EventsMake Plotly charts interactive!. Created by @null-jones.fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.chart += get_annotations_chart(annotations=[("Mar 01, 2008", "Pretty good day for GOOG"), ("Dec 01, 2007", "Something's going wrong for GOOG & AAPL"), ("Nov 01, 2008", "Market starts again thanks to..."), ("Dec 01, 2009", "Small crash for GOOG after..."),],) st.altair_chart(chart, use_container_width=True) PlostA deceptively simple plotting library for Streamlit. Created by @tvst.import plost plost.line_chart(my_dataframe, x='time', y='stock_value', color='stock_name',) HiPlotHigh dimensional Interactive Plotting. Created by @facebookresearch.data = [{'dropout':0.1, 'lr': 0.001, 'loss': 10.0, 'optimizer': 'SGD'}, {'dropout':0.15, 'lr': 0.01, 'loss': 3.5, 'optimizer': 'Adam'}, {'dropout':0.3, 'lr': 0.1, 'loss': 4.5, 'optimizer': 'Adam'}] hip.Experiment.from_iterable(data).display() EChartsHigh dimensional Interactive Plotting. Created by @andfanilo.from streamlit_echarts import st_echarts st_echarts(options=options) Streamlit FoliumStreamlit Component for rendering Folium maps. Created by @randyzwitch.m = folium.Map(location=[39.949610, -75.150282], zoom_start=16) st_data = st_folium(m, width=725) Spacy-StreamlitspaCy building blocks and visualizers for Streamlit apps. Created by @explosion.models = ["en_core_web_sm", "en_core_web_md"] spacy_streamlit.visualize(models, "Sundar Pichai is the CEO of Google.") Streamlit AgraphA Streamlit Graph Vis, based on react-grah-vis. Created by @ChrisDelClea.from streamlit_agraph import agraph, Node, Edge, Config agraph(nodes=nodes, edges=edges, config=config) Streamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl("https://assets5.lottiefiles.com/packages/lf20_V9t630.json") st_lottie(lottie_hello, key="hello") Plotly EventsMake Plotly charts interactive!. Created by @null-jones.fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.chart += get_annotations_chart(annotations=[("Mar 01, 2008", "Pretty good day for GOOG"), ("Dec 01, 2007", "Something's going wrong for GOOG & AAPL"), ("Nov 01, 2008", "Market starts again thanks to..."), ("Dec 01, 2009", "Small crash for GOOG after..."),],) st.altair_chart(chart, use_container_width=True) PlostA deceptively simple plotting library for Streamlit. Created by @tvst.import plost plost.line_chart(my_dataframe, x='time', y='stock_value', color='stock_name',) HiPlotHigh dimensional Interactive Plotting. Created by @facebookresearch.data = [{'dropout':0.1, 'lr': 0.001, 'loss': 10.0, 'optimizer': 'SGD'}, {'dropout':0.15, 'lr': 0.01, 'loss': 3.5, 'optimizer': 'Adam'}, {'dropout':0.3, 'lr': 0.1, 'loss': 4.5, 'optimizer': 'Adam'}] hip.Experiment.from_iterable(data).display() EChartsHigh dimensional Interactive Plotting. Created by @andfanilo.from streamlit_echarts import st_echarts st_echarts(options=options) Streamlit FoliumStreamlit Component for rendering Folium maps. Created by @randyzwitch.m = folium.Map(location=[39.949610, -75.150282], zoom_start=16) st_data = st_folium(m, width=725) Spacy-StreamlitspaCy building blocks and visualizers for Streamlit apps. Created by @explosion.models = ["en_core_web_sm", "en_core_web_md"] spacy_streamlit.visualize(models, "Sundar Pichai is the CEO of Google.") Streamlit AgraphA Streamlit Graph Vis, based on react-grah-vis. Created by @ChrisDelClea.from streamlit_agraph import agraph, Node, Edge, Config agraph(nodes=nodes, edges=edges, config=config) Streamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl("https://assets5.lottiefiles.com/packages/lf20_V9t630.json") st_lottie(lottie_hello, key="hello") Plotly EventsMake Plotly charts interactive!. Created by @null-jones.fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.chart += get_annotations_chart(annotations=[("Mar 01, 2008", "Pretty good day for GOOG"), ("Dec 01, 2007", "Something's going wrong for GOOG & AAPL"), ("Nov 01, 2008", "Market starts again thanks to..."), ("Dec 01, 2009", "Small crash for GOOG after..."),],) st.altair_chart(chart, use_container_width=True) Next Input widgets ButtonDisplay a button widget.clicked = st.button("Click me") Download buttonDisplay a download button widget.st.download_button("Download file", file) Form buttonDisplay a form submit button. For use with st.form.st.form_submit_button("Sign up") Link buttonDisplay a link button.st.link_button("Go to gallery", url) Page linkDisplay a link to another page in a multipage app.st.page_link("app.py", label="Home", icon="🏠") st.page_link("pages/profile.py", label="My profile") CheckboxDisplay a checkbox widget.selected = st.checkbox("I agree") Color pickerDisplay a color picker widget.color = st.color_picker("Pick a color") MultiselectDisplay a multiselect widget. The multiselect widget starts as empty.choices = st.multiselect("Buy", ["milk", "apples", "potatoes"]) RadioDisplay a radio button widget.choice = st.radio("Pick one", ["cats", "dogs"]) SelectboxDisplay a select widget.choice = st.selectbox("Pick one", ["cats", "dogs"]) Select-sliderDisplay a slider widget to select items from a list.size = st.select_slider("Pick a size", ["S", "M", "L"]) ToggleDisplay a toggle widget.activated = st.toggle("Activate") Number inputDisplay a numeric input widget.choice = st.number_input("Pick a number", 0, 10) SliderDisplay a slider widget.number = st.slider("Pick a number", 0, 100) Date inputDisplay a date input widget.date = st.date_input("Your birthday") Time inputDisplay a time input widget.time = st.time_input("Meeting time") Chat inputDisplay a chat input widget.prompt = st.chat_input("Say something") if prompt: st.write(f"The user has sent: {prompt}") Text-areaDisplay a multi-line text input widget.text = st.text_area("Text to translate") Text inputDisplay a single-line text input widget.name = st.text_input("First name") Data editorDisplay a data editor widget.edited = st.experimental_data_editor(df, num_rows="dynamic") File UploaderDisplay a file uploader widget.data = st.file_uploader("Upload a CSV") Camera inputDisplay a widget that allows users to upload images directly from a camera.image = st.camera_input("Take a picture") Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration! PreviousStreamlit ChatStreamlit Component for a Chatbot UI. Created by @AI-Yash.from streamlit_chat import message message("My message") message("Hello bot!", is_user=True) # align's the message to the right Streamlit Option MenuSelect a single item from a list of options in a menu. Created by @victoryhb.from streamlit_option_menu import option_menu option_menu("Main Menu", ["Home", 'Settings'], icons=['house', 'gear'], menu_icon="cast", default_index=1) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.stoggle import stoggle stoggle( "Click me!", """🥷 Surprise! Here's some additional content""",) Streamlit ElementsCreate a draggable and resizable dashboard in Streamlit. Created by @okls.from streamlit_elements import elements, mui, html with elements("new_element"): mui.Typography("Hello world") TagsAdd tags to your Streamlit apps. Created by @gagan3012.from streamlit_tags import st_tags st_tags(label='# Enter Keywords:', text='Press enter to add more', value=['Zero', 'One', 'Two'], suggestions=['five', 'six', 'seven', 'eight', 'nine', 'three', 'eleven', 'ten', 'four'], maxtags = 4, key='1') StqdmThe simplest way to handle a progress bar in streamlit app. Created by @Wirg.from stqdm import stqdm for _ in stqdm(range(50)): sleep(0.5) TimelineDisplay a Timeline in Streamlit apps using TimelineJS. Created by @innerdoc.from streamlit_timeline import timeline with open('example.json', "r") as f: timeline(f.read(), height=800) Camera input liveAlternative for st.camera_input which returns the webcam images live. Created by @blackary.from camera_input_live import camera_input_live image = camera_input_live() st.image(value) Streamlit AceAce editor component for Streamlit. Created by @okld.from streamlit_ace import st_ace content = st_ace() content Streamlit ChatStreamlit Component for a Chatbot UI. Created by @AI-Yash.from streamlit_chat import message message("My message") message("Hello bot!", is_user=True) # align's the message to the right Streamlit Option MenuSelect a single item from a list of options in a menu. Created by @victoryhb.from streamlit_option_menu import option_menu option_menu("Main Menu", ["Home", 'Settings'], icons=['house', 'gear'], menu_icon="cast", default_index=1) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.stoggle import stoggle stoggle( "Click me!", """🥷 Surprise! Here's some additional content""",) Streamlit ElementsCreate a draggable and resizable dashboard in Streamlit. Created by @okls.from streamlit_elements import elements, mui, html with elements("new_element"): mui.Typography("Hello world") TagsAdd tags to your Streamlit apps. Created by @gagan3012.from streamlit_tags import st_tags st_tags(label='# Enter Keywords:', text='Press enter to add more', value=['Zero', 'One', 'Two'], suggestions=['five', 'six', 'seven', 'eight', 'nine', 'three', 'eleven', 'ten', 'four'], maxtags = 4, key='1') StqdmThe simplest way to handle a progress bar in streamlit app. Created by @Wirg.from stqdm import stqdm for _ in stqdm(range(50)): sleep(0.5) TimelineDisplay a Timeline in Streamlit apps using TimelineJS. Created by @innerdoc.from streamlit_timeline import timeline with open('example.json', "r") as f: timeline(f.read(), height=800) Camera input liveAlternative for st.camera_input which returns the webcam images live. Created by @blackary.from camera_input_live import camera_input_live image = camera_input_live() st.image(value) Streamlit AceAce editor component for Streamlit. Created by @okld.from streamlit_ace import st_ace content = st_ace() content Streamlit ChatStreamlit Component for a Chatbot UI. Created by @AI-Yash.from streamlit_chat import message message("My message") message("Hello bot!", is_user=True) # align's the message to the right Streamlit Option MenuSelect a single item from a list of options in a menu. Created by @victoryhb.from streamlit_option_menu import option_menu option_menu("Main Menu", ["Home", 'Settings'], icons=['house', 'gear'], menu_icon="cast", default_index=1) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.stoggle import stoggle stoggle( "Click me!", """🥷 Surprise! Here's some additional content""",) Next Media elements ImageDisplay an image or list of images.st.image(numpy_array) st.image(image_bytes) st.image(file) st.image("https://example.com/myimage.jpg") AudioDisplay an audio player.st.audio(numpy_array) st.audio(audio_bytes) st.audio(file) st.audio("https://example.com/myaudio.mp3", format="audio/mp3") VideoDisplay a video player.st.video(numpy_array) st.video(video_bytes) st.video(file) st.video("https://example.com/myvideo.mp4", format="video/mp4") Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration! PreviousStreamlit CropperA simple image cropper for Streamlit. Created by @turner-anderson.from streamlit_cropper import st_cropper st_cropper(img, realtime_update=realtime_update, box_color=box_color, aspect_ratio=aspect_ratio) Image CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates streamlit_image_coordinates("https://placekitten.com/200/300") Streamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl("https://assets5.lottiefiles.com/packages/lf20_V9t630.json") st_lottie(lottie_hello, key="hello") Streamlit WebrtcHandling and transmitting real-time video/audio streams with Streamlit. Created by @whitphx.from streamlit_webrtc import webrtc_streamer webrtc_streamer(key="sample") Drawable CanvasProvides a sketching canvas using Fabric.js. Created by @andfanilo.from streamlit_drawable_canvas import st_canvas st_canvas(fill_color="rgba(255, 165, 0, 0.3)", stroke_width=stroke_width, stroke_color=stroke_color, background_color=bg_color, background_image=Image.open(bg_image) if bg_image else None, update_streamlit=realtime_update, height=150, drawing_mode=drawing_mode, point_display_radius=point_display_radius if drawing_mode == 'point' else 0, key="canvas",) Image ComparisonCompare images with a slider using JuxtaposeJS. Created by @fcakyon.from streamlit_image_comparison import image_comparison image_comparison(img1="image1.jpg", img2="image2.jpg",) Streamlit CropperA simple image cropper for Streamlit. Created by @turner-anderson.from streamlit_cropper import st_cropper st_cropper(img, realtime_update=realtime_update, box_color=box_color, aspect_ratio=aspect_ratio) Image CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates streamlit_image_coordinates("https://placekitten.com/200/300") Streamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl("https://assets5.lottiefiles.com/packages/lf20_V9t630.json") st_lottie(lottie_hello, key="hello") Streamlit WebrtcHandling and transmitting real-time video/audio streams with Streamlit. Created by @whitphx.from streamlit_webrtc import webrtc_streamer webrtc_streamer(key="sample") Drawable CanvasProvides a sketching canvas using Fabric.js. Created by @andfanilo.from streamlit_drawable_canvas import st_canvas st_canvas(fill_color="rgba(255, 165, 0, 0.3)", stroke_width=stroke_width, stroke_color=stroke_color, background_color=bg_color, background_image=Image.open(bg_image) if bg_image else None, update_streamlit=realtime_update, height=150, drawing_mode=drawing_mode, point_display_radius=point_display_radius if drawing_mode == 'point' else 0, key="canvas",) Image ComparisonCompare images with a slider using JuxtaposeJS. Created by @fcakyon.from streamlit_image_comparison import image_comparison image_comparison(img1="image1.jpg", img2="image2.jpg",) Streamlit CropperA simple image cropper for Streamlit. Created by @turner-anderson.from streamlit_cropper import st_cropper st_cropper(img, realtime_update=realtime_update, box_color=box_color, aspect_ratio=aspect_ratio) Image CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates streamlit_image_coordinates("https://placekitten.com/200/300") Streamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl("https://assets5.lottiefiles.com/packages/lf20_V9t630.json") st_lottie(lottie_hello, key="hello") Next Layouts and containers ColumnsInsert containers laid out as side-by-side columns.col1, col2 = st.columns(2) col1.write("this is column 1") col2.write("this is column 2") ContainerInsert a multi-element container.c = st.container() st.write("This will show last") c.write("This will show first") c.write("This will show second") Modal dialogsInsert a modal dialog that can rerun independently from the rest of the script.@st.experimental_dialog("Sign up") def email_form(): name = st.text_input("Name") email = st.text_input("Email") EmptyInsert a single-element container.c = st.empty() st.write("This will show last") c.write("This will be replaced") c.write("This will show first") ExpanderInsert a multi-element container that can be expanded/collapsed.with st.expander("Open to see more"): st.write("This is more content") PopoverInsert a multi-element popover container that can be opened/closed.with st.popover("Settings"): st.checkbox("Show completed") SidebarDisplay items in a sidebar.st.sidebar.write("This lives in the sidebar") st.sidebar.button("Click me!") TabsInsert containers separated into tabs.tab1, tab2 = st.tabs(["Tab 1", "Tab2"]) tab1.write("this is tab 1") tab2.write("this is tab 2") Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration!Streamlit ElementsCreate a draggable and resizable dashboard in Streamlit. Created by @okls.from streamlit_elements import elements, mui, html with elements("new_element"): mui.Typography("Hello world") PydanticAuto-generate Streamlit UI from Pydantic Models and Dataclasses. Created by @lukasmasuch.import streamlit_pydantic as sp sp.pydantic_form(key="my_form", model=ExampleModel) Streamlit PagesAn experimental version of Streamlit Multi-Page Apps. Created by @blackary.from st_pages import Page, show_pages, add_page_title show_pages([ Page("streamlit_app.py", "Home", "🏠"), Page("other_pages/page2.py", "Page 2", ":books:"), ]) Chat elements Streamlit provides a few commands to help you build conversational apps. These chat elements are designed to be used in conjunction with each other, but you can also use them separately. st.chat_message lets you insert a chat message container into the app so you can display messages from the user or the app. Chat containers can contain other Streamlit elements, including charts, tables, text, and more. st.chat_input lets you display a chat input widget so the user can type in a message. Chat inputDisplay a chat input widget.prompt = st.chat_input("Say something") if prompt: st.write(f"The user has sent: {prompt}") Chat messageInsert a chat message container.import numpy as np with st.chat_message("user"): st.write("Hello 👋") st.line_chart(np.random.randn(30, 3)) Status containerDisplay output of long-running tasks in a container.with st.status('Running'): do_something_slow() st.write_streamWrite generators or streams to the app with a typewriter effect.st.write_stream(my_generator) st.write_stream(my_llm_stream) Status elements Progress barDisplay a progress bar.for i in range(101): st.progress(i) do_something_slow() SpinnerTemporarily displays a message while executing a block of code.with st.spinner("Please wait..."): do_something_slow() Status containerDisplay output of long-running tasks in a container.with st.status('Running'): do_something_slow() ToastBriefly displays a toast message in the bottom-right corner.st.toast('Butter!', icon='🧈') BalloonsDisplay celebratory balloons!do_something() # Celebrate when all done! st.balloons() SnowflakesDisplay celebratory snowflakes!do_something() # Celebrate when all done! st.snow() Success boxDisplay a success message.st.success("Match found!") Info boxDisplay an informational message.st.info("Dataset is updated every day at midnight.") Warning boxDisplay warning message.st.warning("Unable to fetch image. Skipping...") Error boxDisplay error message.st.error("We encountered an error") Exception outputDisplay an exception.e = RuntimeError("This is an exception of type RuntimeError") st.exception(e) Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration!StqdmThe simplest way to handle a progress bar in streamlit app. Created by @Wirg.from stqdm import stqdm for _ in stqdm(range(50)): sleep(0.5) Custom notification boxA custom notification box with the ability to close it out. Created by @Socvest.from streamlit_custom_notification_box import custom_notification_box styles = {'material-icons':{'color': 'red'}, 'text-icon-link-close-container': {'box-shadow': '#3896de 0px 4px'}, 'notification-text': {'':''}, 'close-button':{'':''}, 'link':{'':''}} custom_notification_box(icon='info', textDisplay='We are almost done with your registration...', externalLink='more info', url='#', styles=styles, key="foo") Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.let_it_rain import rain rain(emoji="🎈", font_size=54, falling_speed=5, animation_length="infinite",) App logic and configuration Navigation and pages Switch pageProgrammatically navigates to a specified page.st.switch_page("pages/my_page.py") Page linkDisplay a link to another page in a multipage app.st.page_link("app.py", label="Home", icon="🏠") st.page_link("pages/profile.py", label="My profile") Execution flow Modal dialogsInsert a modal dialog that can rerun independently from the rest of the script.@st.experimental_dialog("Sign up") def email_form(): name = st.text_input("Name") email = st.text_input("Email") FormsCreate a form that batches elements together with a “Submit" button.with st.form(key='my_form'): name = st.text_input("Name") email = st.text_input("Email") st.form_submit_button("Sign up") Partial rerunsDefine a fragment to rerun independently from the rest of the script.@st.experimental_fragment(run_every="10s") def fragment(): df = get_data() st.line_chart(df) Rerun scriptRerun the script immediately.st.rerun() Stop executionStops execution immediately.st.stop() Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration!AutorefreshForce a refresh without tying up a script. Created by @kmcgrady.from streamlit_autorefresh import st_autorefresh st_autorefresh(interval=2000, limit=100, key="fizzbuzzcounter") PydanticAuto-generate Streamlit UI from Pydantic Models and Dataclasses. Created by @lukasmasuch.import streamlit_pydantic as sp sp.pydantic_form(key="my_form", model=ExampleModel) Streamlit PagesAn experimental version of Streamlit Multi-Page Apps. Created by @blackary.from st_pages import Page, show_pages, add_page_title show_pages([ Page("streamlit_app.py", "Home", "🏠"), Page("other_pages/page2.py", "Page 2", ":books:"), ]) Caching and state Cache dataFunction decorator to cache functions that return data (e.g. dataframe transforms, database queries, ML inference).@st.cache_data def long_function(param1, param2): # Perform expensive computation here or # fetch data from the web here return data Cache resourceFunction decorator to cache functions that return global resources (e.g. database connections, ML models).@st.cache_resource def init_model(): # Return a global resource here return pipeline( "sentiment-analysis", model="distilbert-base-uncased-finetuned-sst-2-english" ) Session stateSession state is a way to share variables between reruns, for each user session.st.session_state['key'] = value Query parametersGet, set, or clear the query parameters that are shown in the browser's URL bar.st.query_params[key] = value st.query_params.clear() Connections and databases Setup your connection Create a connectionConnect to a data source or APIconn = st.connection('pets_db', type='sql') pet_owners = conn.query('select * from pet_owners') st.dataframe(pet_owners) Built-in connections SnowflakeConnectionA connection to Snowflake.conn = st.connection('snowflake') SQLConnectionA connection to a SQL database using SQLAlchemy.conn = st.connection('sql') Build your own connections Connection base classBuild your own connection with BaseConnection.class MyConnection(BaseConnection[myconn.MyConnection]): def _connect(self, **kwargs) -> MyConnection: return myconn.connect(**self._secrets, **kwargs) def query(self, query): return self._instance.query(query) Secrets management Secrets singletonAccess secrets from a local TOML file.key = st.secrets["OpenAI_key"] Secrets fileSave your secrets in a per-project or per-profile TOML file.OpenAI_key = "<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/en/0.71.0/api.html#utilities-and-user-info
DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceremovePAGE ELEMENTSWrite and magicaddText elementsaddData elementsaddChart elementsaddInput widgetsaddMedia elementsaddLayouts and containersaddChat elementsaddStatus elementsaddThird-party componentsopen_in_newAPPLICATION LOGICNavigation and pagesaddExecution flowaddCaching and stateaddConnections and secretsaddCustom componentsaddUtilitiesaddConfigurationaddTOOLSApp testingaddCommand lineaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Develop/API referenceAPI reference Streamlit makes it easy for you to visualize, mutate, and share data. The API reference is organized by activity type, like displaying data or optimizing performance. Each section includes methods associated with the activity type, including examples. Browse our API below and click to learn more about any of our available commands! 🎈 Display almost anything Write and magic st.writeWrite arguments to the app.st.write("Hello **world**!") st.write(my_data_frame) st.write(my_mpl_figure) st.write_streamWrite generators or streams to the app with a typewriter effect.st.write_stream(my_generator) st.write_stream(my_llm_stream) MagicAny time Streamlit sees either a variable or literal value on its own line, it automatically writes that to your app using st.write"Hello **world**!" my_data_frame my_mpl_figure Text elements MarkdownDisplay string formatted as Markdown.st.markdown("Hello **world**!") TitleDisplay text in title formatting.st.title("The app title") HeaderDisplay text in header formatting.st.header("This is a header") SubheaderDisplay text in subheader formatting.st.subheader("This is a subheader") CaptionDisplay text in small font.st.caption("This is written small caption text") Code blockDisplay a code block with optional syntax highlighting.st.code("a = 1234") EchoDisplay some code in the app, then execute it. Useful for tutorials.with st.echo(): st.write('This code will be printed') LaTeXDisplay mathematical expressions formatted as LaTeX.st.latex("\int a x^2 \,dx") Preformatted textWrite fixed-width and preformatted text.st.text("Hello world") DividerDisplay a horizontal rule.st.divider() Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration! PreviousTagsAdd tags to your Streamlit apps. Created by @gagan3012.st_tags(label='# Enter Keywords:', text='Press enter to add more', value=['Zero', 'One', 'Two'], suggestions=['five', 'six', 'seven', 'eight', 'nine', 'three', 'eleven', 'ten', 'four'], maxtags = 4, key='1') NLUApply text mining on a dataframe. Created by @JohnSnowLabs.nlu.load('sentiment').predict('I love NLU! <3') Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.mention(label="An awesome Streamlit App", icon="streamlit", url="https://extras.streamlit.app",) Annotated textDisplay annotated text in Streamlit apps. Created by @tvst.annotated_text("This ", ("is", "verb"), " some ", ("annotated", "adj"), ("text", "noun"), " for those of ", ("you", "pronoun"), " who ", ("like", "verb"), " this sort of ", ("thing", "noun"), ".") Drawable CanvasProvides a sketching canvas using Fabric.js. Created by @andfanilo.st_canvas(fill_color="rgba(255, 165, 0, 0.3)", stroke_width=stroke_width, stroke_color=stroke_color, background_color=bg_color, background_image=Image.open(bg_image) if bg_image else None, update_streamlit=realtime_update, height=150, drawing_mode=drawing_mode, point_display_radius=point_display_radius if drawing_mode == 'point' else 0, key="canvas",) TagsAdd tags to your Streamlit apps. Created by @gagan3012.st_tags(label='# Enter Keywords:', text='Press enter to add more', value=['Zero', 'One', 'Two'], suggestions=['five', 'six', 'seven', 'eight', 'nine', 'three', 'eleven', 'ten', 'four'], maxtags = 4, key='1') NLUApply text mining on a dataframe. Created by @JohnSnowLabs.nlu.load('sentiment').predict('I love NLU! <3') Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.mention(label="An awesome Streamlit App", icon="streamlit", url="https://extras.streamlit.app",) Annotated textDisplay annotated text in Streamlit apps. Created by @tvst.annotated_text("This ", ("is", "verb"), " some ", ("annotated", "adj"), ("text", "noun"), " for those of ", ("you", "pronoun"), " who ", ("like", "verb"), " this sort of ", ("thing", "noun"), ".") Drawable CanvasProvides a sketching canvas using Fabric.js. Created by @andfanilo.st_canvas(fill_color="rgba(255, 165, 0, 0.3)", stroke_width=stroke_width, stroke_color=stroke_color, background_color=bg_color, background_image=Image.open(bg_image) if bg_image else None, update_streamlit=realtime_update, height=150, drawing_mode=drawing_mode, point_display_radius=point_display_radius if drawing_mode == 'point' else 0, key="canvas",) TagsAdd tags to your Streamlit apps. Created by @gagan3012.st_tags(label='# Enter Keywords:', text='Press enter to add more', value=['Zero', 'One', 'Two'], suggestions=['five', 'six', 'seven', 'eight', 'nine', 'three', 'eleven', 'ten', 'four'], maxtags = 4, key='1') NLUApply text mining on a dataframe. Created by @JohnSnowLabs.nlu.load('sentiment').predict('I love NLU! <3') Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.mention(label="An awesome Streamlit App", icon="streamlit", url="https://extras.streamlit.app",) Next Data elements DataframesDisplay a dataframe as an interactive table.st.dataframe(my_data_frame) Data editorDisplay a data editor widget.edited = st.data_editor(df, num_rows="dynamic") Column configurationConfigure the display and editing behavior of dataframes and data editors.st.column_config.NumberColumn("Price (in USD)", min_value=0, format="$%d") Static tablesDisplay a static table.st.table(my_data_frame) MetricsDisplay a metric in big bold font, with an optional indicator of how the metric changed.st.metric("My metric", 42, 2) Dicts and JSONDisplay object or string as a pretty-printed JSON string.st.json(my_dict) Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration! PreviousImage CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates value = streamlit_image_coordinates("https://placekitten.com/200/300") st.write(value) Plotly EventsMake Plotly charts interactive!. Created by @null-jones.from streamlit_plotly_events import plotly_events fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.metric_cards import style_metric_cards col3.metric(label="No Change", value=5000, delta=0) style_metric_cards() Streamlit AggridImplementation of Ag-Grid component for Streamlit. Created by @PablocFonseca.df = pd.DataFrame({'col1': [1, 2, 3], 'col2': [4, 5, 6]}) grid_return = AgGrid(df, editable=True) new_df = grid_return['data'] Streamlit FoliumStreamlit Component for rendering Folium maps. Created by @randyzwitch.m = folium.Map(location=[39.949610, -75.150282], zoom_start=16) folium.Marker([39.949610, -75.150282], popup="Liberty Bell", tooltip="Liberty Bell").add_to(m) st_data = st_folium(m, width=725) Pandas ProfilingPandas profiling component for Streamlit. Created by @okld.df = pd.read_csv("https://storage.googleapis.com/tf-datasets/titanic/train.csv") pr = df.profile_report() st_profile_report(pr) Image CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates value = streamlit_image_coordinates("https://placekitten.com/200/300") st.write(value) Plotly EventsMake Plotly charts interactive!. Created by @null-jones.from streamlit_plotly_events import plotly_events fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.metric_cards import style_metric_cards col3.metric(label="No Change", value=5000, delta=0) style_metric_cards() Streamlit AggridImplementation of Ag-Grid component for Streamlit. Created by @PablocFonseca.df = pd.DataFrame({'col1': [1, 2, 3], 'col2': [4, 5, 6]}) grid_return = AgGrid(df, editable=True) new_df = grid_return['data'] Streamlit FoliumStreamlit Component for rendering Folium maps. Created by @randyzwitch.m = folium.Map(location=[39.949610, -75.150282], zoom_start=16) folium.Marker([39.949610, -75.150282], popup="Liberty Bell", tooltip="Liberty Bell").add_to(m) st_data = st_folium(m, width=725) Pandas ProfilingPandas profiling component for Streamlit. Created by @okld.df = pd.read_csv("https://storage.googleapis.com/tf-datasets/titanic/train.csv") pr = df.profile_report() st_profile_report(pr) Image CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates value = streamlit_image_coordinates("https://placekitten.com/200/300") st.write(value) Plotly EventsMake Plotly charts interactive!. Created by @null-jones.from streamlit_plotly_events import plotly_events fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.metric_cards import style_metric_cards col3.metric(label="No Change", value=5000, delta=0) style_metric_cards() Next Chart elements Simple area chartsDisplay an area chart.st.area_chart(my_data_frame) Simple bar chartsDisplay a bar chart.st.bar_chart(my_data_frame) Simple line chartsDisplay a line chart.st.line_chart(my_data_frame) Simple scatter chartsDisplay a line chart.st.scatter_chart(my_data_frame) Scatterplots on mapsDisplay a map with points on it.st.map(my_data_frame) MatplotlibDisplay a matplotlib.pyplot figure.st.pyplot(my_mpl_figure) AltairDisplay a chart using the Altair library.st.altair_chart(my_altair_chart) Vega-LiteDisplay a chart using the Vega-Lite library.st.vega_lite_chart(my_vega_lite_chart) PlotlyDisplay an interactive Plotly chart.st.plotly_chart(my_plotly_chart) BokehDisplay an interactive Bokeh chart.st.bokeh_chart(my_bokeh_chart) PyDeckDisplay a chart using the PyDeck library.st.pydeck_chart(my_pydeck_chart) GraphVizDisplay a graph using the dagre-d3 library.st.graphviz_chart(my_graphviz_spec) Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration! PreviousStreamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl("https://assets5.lottiefiles.com/packages/lf20_V9t630.json") st_lottie(lottie_hello, key="hello") Plotly EventsMake Plotly charts interactive!. Created by @null-jones.fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.chart += get_annotations_chart(annotations=[("Mar 01, 2008", "Pretty good day for GOOG"), ("Dec 01, 2007", "Something's going wrong for GOOG & AAPL"), ("Nov 01, 2008", "Market starts again thanks to..."), ("Dec 01, 2009", "Small crash for GOOG after..."),],) st.altair_chart(chart, use_container_width=True) PlostA deceptively simple plotting library for Streamlit. Created by @tvst.import plost plost.line_chart(my_dataframe, x='time', y='stock_value', color='stock_name',) HiPlotHigh dimensional Interactive Plotting. Created by @facebookresearch.data = [{'dropout':0.1, 'lr': 0.001, 'loss': 10.0, 'optimizer': 'SGD'}, {'dropout':0.15, 'lr': 0.01, 'loss': 3.5, 'optimizer': 'Adam'}, {'dropout':0.3, 'lr': 0.1, 'loss': 4.5, 'optimizer': 'Adam'}] hip.Experiment.from_iterable(data).display() EChartsHigh dimensional Interactive Plotting. Created by @andfanilo.from streamlit_echarts import st_echarts st_echarts(options=options) Streamlit FoliumStreamlit Component for rendering Folium maps. Created by @randyzwitch.m = folium.Map(location=[39.949610, -75.150282], zoom_start=16) st_data = st_folium(m, width=725) Spacy-StreamlitspaCy building blocks and visualizers for Streamlit apps. Created by @explosion.models = ["en_core_web_sm", "en_core_web_md"] spacy_streamlit.visualize(models, "Sundar Pichai is the CEO of Google.") Streamlit AgraphA Streamlit Graph Vis, based on react-grah-vis. Created by @ChrisDelClea.from streamlit_agraph import agraph, Node, Edge, Config agraph(nodes=nodes, edges=edges, config=config) Streamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl("https://assets5.lottiefiles.com/packages/lf20_V9t630.json") st_lottie(lottie_hello, key="hello") Plotly EventsMake Plotly charts interactive!. Created by @null-jones.fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.chart += get_annotations_chart(annotations=[("Mar 01, 2008", "Pretty good day for GOOG"), ("Dec 01, 2007", "Something's going wrong for GOOG & AAPL"), ("Nov 01, 2008", "Market starts again thanks to..."), ("Dec 01, 2009", "Small crash for GOOG after..."),],) st.altair_chart(chart, use_container_width=True) PlostA deceptively simple plotting library for Streamlit. Created by @tvst.import plost plost.line_chart(my_dataframe, x='time', y='stock_value', color='stock_name',) HiPlotHigh dimensional Interactive Plotting. Created by @facebookresearch.data = [{'dropout':0.1, 'lr': 0.001, 'loss': 10.0, 'optimizer': 'SGD'}, {'dropout':0.15, 'lr': 0.01, 'loss': 3.5, 'optimizer': 'Adam'}, {'dropout':0.3, 'lr': 0.1, 'loss': 4.5, 'optimizer': 'Adam'}] hip.Experiment.from_iterable(data).display() EChartsHigh dimensional Interactive Plotting. Created by @andfanilo.from streamlit_echarts import st_echarts st_echarts(options=options) Streamlit FoliumStreamlit Component for rendering Folium maps. Created by @randyzwitch.m = folium.Map(location=[39.949610, -75.150282], zoom_start=16) st_data = st_folium(m, width=725) Spacy-StreamlitspaCy building blocks and visualizers for Streamlit apps. Created by @explosion.models = ["en_core_web_sm", "en_core_web_md"] spacy_streamlit.visualize(models, "Sundar Pichai is the CEO of Google.") Streamlit AgraphA Streamlit Graph Vis, based on react-grah-vis. Created by @ChrisDelClea.from streamlit_agraph import agraph, Node, Edge, Config agraph(nodes=nodes, edges=edges, config=config) Streamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl("https://assets5.lottiefiles.com/packages/lf20_V9t630.json") st_lottie(lottie_hello, key="hello") Plotly EventsMake Plotly charts interactive!. Created by @null-jones.fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.chart += get_annotations_chart(annotations=[("Mar 01, 2008", "Pretty good day for GOOG"), ("Dec 01, 2007", "Something's going wrong for GOOG & AAPL"), ("Nov 01, 2008", "Market starts again thanks to..."), ("Dec 01, 2009", "Small crash for GOOG after..."),],) st.altair_chart(chart, use_container_width=True) Next Input widgets ButtonDisplay a button widget.clicked = st.button("Click me") Download buttonDisplay a download button widget.st.download_button("Download file", file) Form buttonDisplay a form submit button. For use with st.form.st.form_submit_button("Sign up") Link buttonDisplay a link button.st.link_button("Go to gallery", url) Page linkDisplay a link to another page in a multipage app.st.page_link("app.py", label="Home", icon="🏠") st.page_link("pages/profile.py", label="My profile") CheckboxDisplay a checkbox widget.selected = st.checkbox("I agree") Color pickerDisplay a color picker widget.color = st.color_picker("Pick a color") MultiselectDisplay a multiselect widget. The multiselect widget starts as empty.choices = st.multiselect("Buy", ["milk", "apples", "potatoes"]) RadioDisplay a radio button widget.choice = st.radio("Pick one", ["cats", "dogs"]) SelectboxDisplay a select widget.choice = st.selectbox("Pick one", ["cats", "dogs"]) Select-sliderDisplay a slider widget to select items from a list.size = st.select_slider("Pick a size", ["S", "M", "L"]) ToggleDisplay a toggle widget.activated = st.toggle("Activate") Number inputDisplay a numeric input widget.choice = st.number_input("Pick a number", 0, 10) SliderDisplay a slider widget.number = st.slider("Pick a number", 0, 100) Date inputDisplay a date input widget.date = st.date_input("Your birthday") Time inputDisplay a time input widget.time = st.time_input("Meeting time") Chat inputDisplay a chat input widget.prompt = st.chat_input("Say something") if prompt: st.write(f"The user has sent: {prompt}") Text-areaDisplay a multi-line text input widget.text = st.text_area("Text to translate") Text inputDisplay a single-line text input widget.name = st.text_input("First name") Data editorDisplay a data editor widget.edited = st.experimental_data_editor(df, num_rows="dynamic") File UploaderDisplay a file uploader widget.data = st.file_uploader("Upload a CSV") Camera inputDisplay a widget that allows users to upload images directly from a camera.image = st.camera_input("Take a picture") Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration! PreviousStreamlit ChatStreamlit Component for a Chatbot UI. Created by @AI-Yash.from streamlit_chat import message message("My message") message("Hello bot!", is_user=True) # align's the message to the right Streamlit Option MenuSelect a single item from a list of options in a menu. Created by @victoryhb.from streamlit_option_menu import option_menu option_menu("Main Menu", ["Home", 'Settings'], icons=['house', 'gear'], menu_icon="cast", default_index=1) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.stoggle import stoggle stoggle( "Click me!", """🥷 Surprise! Here's some additional content""",) Streamlit ElementsCreate a draggable and resizable dashboard in Streamlit. Created by @okls.from streamlit_elements import elements, mui, html with elements("new_element"): mui.Typography("Hello world") TagsAdd tags to your Streamlit apps. Created by @gagan3012.from streamlit_tags import st_tags st_tags(label='# Enter Keywords:', text='Press enter to add more', value=['Zero', 'One', 'Two'], suggestions=['five', 'six', 'seven', 'eight', 'nine', 'three', 'eleven', 'ten', 'four'], maxtags = 4, key='1') StqdmThe simplest way to handle a progress bar in streamlit app. Created by @Wirg.from stqdm import stqdm for _ in stqdm(range(50)): sleep(0.5) TimelineDisplay a Timeline in Streamlit apps using TimelineJS. Created by @innerdoc.from streamlit_timeline import timeline with open('example.json', "r") as f: timeline(f.read(), height=800) Camera input liveAlternative for st.camera_input which returns the webcam images live. Created by @blackary.from camera_input_live import camera_input_live image = camera_input_live() st.image(value) Streamlit AceAce editor component for Streamlit. Created by @okld.from streamlit_ace import st_ace content = st_ace() content Streamlit ChatStreamlit Component for a Chatbot UI. Created by @AI-Yash.from streamlit_chat import message message("My message") message("Hello bot!", is_user=True) # align's the message to the right Streamlit Option MenuSelect a single item from a list of options in a menu. Created by @victoryhb.from streamlit_option_menu import option_menu option_menu("Main Menu", ["Home", 'Settings'], icons=['house', 'gear'], menu_icon="cast", default_index=1) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.stoggle import stoggle stoggle( "Click me!", """🥷 Surprise! Here's some additional content""",) Streamlit ElementsCreate a draggable and resizable dashboard in Streamlit. Created by @okls.from streamlit_elements import elements, mui, html with elements("new_element"): mui.Typography("Hello world") TagsAdd tags to your Streamlit apps. Created by @gagan3012.from streamlit_tags import st_tags st_tags(label='# Enter Keywords:', text='Press enter to add more', value=['Zero', 'One', 'Two'], suggestions=['five', 'six', 'seven', 'eight', 'nine', 'three', 'eleven', 'ten', 'four'], maxtags = 4, key='1') StqdmThe simplest way to handle a progress bar in streamlit app. Created by @Wirg.from stqdm import stqdm for _ in stqdm(range(50)): sleep(0.5) TimelineDisplay a Timeline in Streamlit apps using TimelineJS. Created by @innerdoc.from streamlit_timeline import timeline with open('example.json', "r") as f: timeline(f.read(), height=800) Camera input liveAlternative for st.camera_input which returns the webcam images live. Created by @blackary.from camera_input_live import camera_input_live image = camera_input_live() st.image(value) Streamlit AceAce editor component for Streamlit. Created by @okld.from streamlit_ace import st_ace content = st_ace() content Streamlit ChatStreamlit Component for a Chatbot UI. Created by @AI-Yash.from streamlit_chat import message message("My message") message("Hello bot!", is_user=True) # align's the message to the right Streamlit Option MenuSelect a single item from a list of options in a menu. Created by @victoryhb.from streamlit_option_menu import option_menu option_menu("Main Menu", ["Home", 'Settings'], icons=['house', 'gear'], menu_icon="cast", default_index=1) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.stoggle import stoggle stoggle( "Click me!", """🥷 Surprise! Here's some additional content""",) Next Media elements ImageDisplay an image or list of images.st.image(numpy_array) st.image(image_bytes) st.image(file) st.image("https://example.com/myimage.jpg") AudioDisplay an audio player.st.audio(numpy_array) st.audio(audio_bytes) st.audio(file) st.audio("https://example.com/myaudio.mp3", format="audio/mp3") VideoDisplay a video player.st.video(numpy_array) st.video(video_bytes) st.video(file) st.video("https://example.com/myvideo.mp4", format="video/mp4") Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration! PreviousStreamlit CropperA simple image cropper for Streamlit. Created by @turner-anderson.from streamlit_cropper import st_cropper st_cropper(img, realtime_update=realtime_update, box_color=box_color, aspect_ratio=aspect_ratio) Image CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates streamlit_image_coordinates("https://placekitten.com/200/300") Streamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl("https://assets5.lottiefiles.com/packages/lf20_V9t630.json") st_lottie(lottie_hello, key="hello") Streamlit WebrtcHandling and transmitting real-time video/audio streams with Streamlit. Created by @whitphx.from streamlit_webrtc import webrtc_streamer webrtc_streamer(key="sample") Drawable CanvasProvides a sketching canvas using Fabric.js. Created by @andfanilo.from streamlit_drawable_canvas import st_canvas st_canvas(fill_color="rgba(255, 165, 0, 0.3)", stroke_width=stroke_width, stroke_color=stroke_color, background_color=bg_color, background_image=Image.open(bg_image) if bg_image else None, update_streamlit=realtime_update, height=150, drawing_mode=drawing_mode, point_display_radius=point_display_radius if drawing_mode == 'point' else 0, key="canvas",) Image ComparisonCompare images with a slider using JuxtaposeJS. Created by @fcakyon.from streamlit_image_comparison import image_comparison image_comparison(img1="image1.jpg", img2="image2.jpg",) Streamlit CropperA simple image cropper for Streamlit. Created by @turner-anderson.from streamlit_cropper import st_cropper st_cropper(img, realtime_update=realtime_update, box_color=box_color, aspect_ratio=aspect_ratio) Image CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates streamlit_image_coordinates("https://placekitten.com/200/300") Streamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl("https://assets5.lottiefiles.com/packages/lf20_V9t630.json") st_lottie(lottie_hello, key="hello") Streamlit WebrtcHandling and transmitting real-time video/audio streams with Streamlit. Created by @whitphx.from streamlit_webrtc import webrtc_streamer webrtc_streamer(key="sample") Drawable CanvasProvides a sketching canvas using Fabric.js. Created by @andfanilo.from streamlit_drawable_canvas import st_canvas st_canvas(fill_color="rgba(255, 165, 0, 0.3)", stroke_width=stroke_width, stroke_color=stroke_color, background_color=bg_color, background_image=Image.open(bg_image) if bg_image else None, update_streamlit=realtime_update, height=150, drawing_mode=drawing_mode, point_display_radius=point_display_radius if drawing_mode == 'point' else 0, key="canvas",) Image ComparisonCompare images with a slider using JuxtaposeJS. Created by @fcakyon.from streamlit_image_comparison import image_comparison image_comparison(img1="image1.jpg", img2="image2.jpg",) Streamlit CropperA simple image cropper for Streamlit. Created by @turner-anderson.from streamlit_cropper import st_cropper st_cropper(img, realtime_update=realtime_update, box_color=box_color, aspect_ratio=aspect_ratio) Image CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates streamlit_image_coordinates("https://placekitten.com/200/300") Streamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl("https://assets5.lottiefiles.com/packages/lf20_V9t630.json") st_lottie(lottie_hello, key="hello") Next Layouts and containers ColumnsInsert containers laid out as side-by-side columns.col1, col2 = st.columns(2) col1.write("this is column 1") col2.write("this is column 2") ContainerInsert a multi-element container.c = st.container() st.write("This will show last") c.write("This will show first") c.write("This will show second") Modal dialogsInsert a modal dialog that can rerun independently from the rest of the script.@st.experimental_dialog("Sign up") def email_form(): name = st.text_input("Name") email = st.text_input("Email") EmptyInsert a single-element container.c = st.empty() st.write("This will show last") c.write("This will be replaced") c.write("This will show first") ExpanderInsert a multi-element container that can be expanded/collapsed.with st.expander("Open to see more"): st.write("This is more content") PopoverInsert a multi-element popover container that can be opened/closed.with st.popover("Settings"): st.checkbox("Show completed") SidebarDisplay items in a sidebar.st.sidebar.write("This lives in the sidebar") st.sidebar.button("Click me!") TabsInsert containers separated into tabs.tab1, tab2 = st.tabs(["Tab 1", "Tab2"]) tab1.write("this is tab 1") tab2.write("this is tab 2") Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration!Streamlit ElementsCreate a draggable and resizable dashboard in Streamlit. Created by @okls.from streamlit_elements import elements, mui, html with elements("new_element"): mui.Typography("Hello world") PydanticAuto-generate Streamlit UI from Pydantic Models and Dataclasses. Created by @lukasmasuch.import streamlit_pydantic as sp sp.pydantic_form(key="my_form", model=ExampleModel) Streamlit PagesAn experimental version of Streamlit Multi-Page Apps. Created by @blackary.from st_pages import Page, show_pages, add_page_title show_pages([ Page("streamlit_app.py", "Home", "🏠"), Page("other_pages/page2.py", "Page 2", ":books:"), ]) Chat elements Streamlit provides a few commands to help you build conversational apps. These chat elements are designed to be used in conjunction with each other, but you can also use them separately. st.chat_message lets you insert a chat message container into the app so you can display messages from the user or the app. Chat containers can contain other Streamlit elements, including charts, tables, text, and more. st.chat_input lets you display a chat input widget so the user can type in a message. Chat inputDisplay a chat input widget.prompt = st.chat_input("Say something") if prompt: st.write(f"The user has sent: {prompt}") Chat messageInsert a chat message container.import numpy as np with st.chat_message("user"): st.write("Hello 👋") st.line_chart(np.random.randn(30, 3)) Status containerDisplay output of long-running tasks in a container.with st.status('Running'): do_something_slow() st.write_streamWrite generators or streams to the app with a typewriter effect.st.write_stream(my_generator) st.write_stream(my_llm_stream) Status elements Progress barDisplay a progress bar.for i in range(101): st.progress(i) do_something_slow() SpinnerTemporarily displays a message while executing a block of code.with st.spinner("Please wait..."): do_something_slow() Status containerDisplay output of long-running tasks in a container.with st.status('Running'): do_something_slow() ToastBriefly displays a toast message in the bottom-right corner.st.toast('Butter!', icon='🧈') BalloonsDisplay celebratory balloons!do_something() # Celebrate when all done! st.balloons() SnowflakesDisplay celebratory snowflakes!do_something() # Celebrate when all done! st.snow() Success boxDisplay a success message.st.success("Match found!") Info boxDisplay an informational message.st.info("Dataset is updated every day at midnight.") Warning boxDisplay warning message.st.warning("Unable to fetch image. Skipping...") Error boxDisplay error message.st.error("We encountered an error") Exception outputDisplay an exception.e = RuntimeError("This is an exception of type RuntimeError") st.exception(e) Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration!StqdmThe simplest way to handle a progress bar in streamlit app. Created by @Wirg.from stqdm import stqdm for _ in stqdm(range(50)): sleep(0.5) Custom notification boxA custom notification box with the ability to close it out. Created by @Socvest.from streamlit_custom_notification_box import custom_notification_box styles = {'material-icons':{'color': 'red'}, 'text-icon-link-close-container': {'box-shadow': '#3896de 0px 4px'}, 'notification-text': {'':''}, 'close-button':{'':''}, 'link':{'':''}} custom_notification_box(icon='info', textDisplay='We are almost done with your registration...', externalLink='more info', url='#', styles=styles, key="foo") Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.let_it_rain import rain rain(emoji="🎈", font_size=54, falling_speed=5, animation_length="infinite",) App logic and configuration Navigation and pages Switch pageProgrammatically navigates to a specified page.st.switch_page("pages/my_page.py") Page linkDisplay a link to another page in a multipage app.st.page_link("app.py", label="Home", icon="🏠") st.page_link("pages/profile.py", label="My profile") Execution flow Modal dialogsInsert a modal dialog that can rerun independently from the rest of the script.@st.experimental_dialog("Sign up") def email_form(): name = st.text_input("Name") email = st.text_input("Email") FormsCreate a form that batches elements together with a “Submit" button.with st.form(key='my_form'): name = st.text_input("Name") email = st.text_input("Email") st.form_submit_button("Sign up") Partial rerunsDefine a fragment to rerun independently from the rest of the script.@st.experimental_fragment(run_every="10s") def fragment(): df = get_data() st.line_chart(df) Rerun scriptRerun the script immediately.st.rerun() Stop executionStops execution immediately.st.stop() Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration!AutorefreshForce a refresh without tying up a script. Created by @kmcgrady.from streamlit_autorefresh import st_autorefresh st_autorefresh(interval=2000, limit=100, key="fizzbuzzcounter") PydanticAuto-generate Streamlit UI from Pydantic Models and Dataclasses. Created by @lukasmasuch.import streamlit_pydantic as sp sp.pydantic_form(key="my_form", model=ExampleModel) Streamlit PagesAn experimental version of Streamlit Multi-Page Apps. Created by @blackary.from st_pages import Page, show_pages, add_page_title show_pages([ Page("streamlit_app.py", "Home", "🏠"), Page("other_pages/page2.py", "Page 2", ":books:"), ]) Caching and state Cache dataFunction decorator to cache functions that return data (e.g. dataframe transforms, database queries, ML inference).@st.cache_data def long_function(param1, param2): # Perform expensive computation here or # fetch data from the web here return data Cache resourceFunction decorator to cache functions that return global resources (e.g. database connections, ML models).@st.cache_resource def init_model(): # Return a global resource here return pipeline( "sentiment-analysis", model="distilbert-base-uncased-finetuned-sst-2-english" ) Session stateSession state is a way to share variables between reruns, for each user session.st.session_state['key'] = value Query parametersGet, set, or clear the query parameters that are shown in the browser's URL bar.st.query_params[key] = value st.query_params.clear() Connections and databases Setup your connection Create a connectionConnect to a data source or APIconn = st.connection('pets_db', type='sql') pet_owners = conn.query('select * from pet_owners') st.dataframe(pet_owners) Built-in connections SnowflakeConnectionA connection to Snowflake.conn = st.connection('snowflake') SQLConnectionA connection to a SQL database using SQLAlchemy.conn = st.connection('sql') Build your own connections Connection base classBuild your own connection with BaseConnection.class MyConnection(BaseConnection[myconn.MyConnection]): def _connect(self, **kwargs) -> MyConnection: return myconn.connect(**self._secrets, **kwargs) def query(self, query): return self._instance.query(query) Secrets management Secrets singletonAccess secrets from a local TOML file.key = st.secrets["OpenAI_key"] Secrets fileSave your secrets in a per-project or per-profile TOML file.OpenAI_key = "<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/caching-and-state/st.experimental_memo#supported-widgets
DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceremovePAGE ELEMENTSWrite and magicaddText elementsaddData elementsaddChart elementsaddInput widgetsaddMedia elementsaddLayouts and containersaddChat elementsaddStatus elementsaddThird-party componentsopen_in_newAPPLICATION LOGICNavigation and pagesaddExecution flowaddCaching and stateremovest.cache_datast.cache_resourcest.cachedeletest.session_statest.query_paramsst.experimental_get_query_paramsdeletest.experimental_set_query_paramsdeleteConnections and secretsaddCustom componentsaddUtilitiesaddConfigurationaddTOOLSApp testingaddCommand lineaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Develop/API reference/Caching and state/st.experimental_memopriority_highImportantThis is an experimental feature. Experimental features and their APIs may change or be removed at any time. To learn more, click here. st.experimental_memoStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakedeleteDeprecation noticest.experimental_memo was deprecated in version 1.18.0. Use st.cache_data instead. Learn more in Caching.Decorator to cache functions that return data (e.g. dataframe transforms, database queries, ML inference). Cached objects are stored in "pickled" form, which means that the return value of a cached function must be pickleable. Each caller of the cached function gets its own copy of the cached data. You can clear a function's cache with func.clear() or clear the entire cache with st.cache_data.clear(). To cache global resources, use st.cache_resource instead. Learn more about caching at https://docs.streamlit.io/library/advanced-features/caching. Function signature[source] st.experimental_memo(func=None, *, ttl, max_entries, show_spinner, persist, experimental_allow_widgets, hash_funcs=None) Parameters func (callable) The function to cache. Streamlit hashes the function's source code. ttl (float, timedelta, str, or None) The maximum time to keep an entry in the cache. Can be one of: None if cache entries should never expire (default). A number specifying the time in seconds. A string specifying the time in a format supported by Pandas's Timedelta constructor, e.g. "1d", "1.5 days", or "1h23s". A timedelta object from Python's built-in datetime library, e.g. timedelta(days=1). Note that ttl will be ignored if persist="disk" or persist=True. max_entries (int or None) The maximum number of entries to keep in the cache, or None for an unbounded cache. When a new entry is added to a full cache, the oldest cached entry will be removed. Defaults to None. show_spinner (bool or str) Enable the spinner. Default is True to show a spinner when there is a "cache miss" and the cached data is being created. If string, value of show_spinner param will be used for spinner text. persist ("disk", bool, or None) Optional location to persist cached data to. Passing "disk" (or True) will persist the cached data to the local disk. None (or False) will disable persistence. The default is None. experimental_allow_widgets (bool) Allow widgets to be used in the cached function. Defaults to False. Support for widgets in cached functions is currently experimental. Setting this parameter to True may lead to excessive memory use since the widget value is treated as an additional input parameter to the cache. We may remove support for this option at any time without notice. hash_funcs (dict or None) Mapping of types or fully qualified names to hash functions. This is used to override the behavior of the hasher inside Streamlit's caching mechanism: when the hasher encounters an object, it will first check to see if its type matches a key in this dict and, if so, will use the provided function to generate a hash for it. See below for an example of how this can be used. Example import streamlit as st @st.cache_data def fetch_and_clean_data(url): # Fetch data from URL here, and then clean it up. return data d1 = fetch_and_clean_data(DATA_URL_1) # Actually executes the function, since this is the first time it was # encountered. d2 = fetch_and_clean_data(DATA_URL_1) # Does not execute the function. Instead, returns its previously computed # value. This means that now the data in d1 is the same as in d2. d3 = fetch_and_clean_data(DATA_URL_2) # This is a different URL, so the function executes. To set the persist parameter, use this command as follows: import streamlit as st @st.cache_data(persist="disk") def fetch_and_clean_data(url): # Fetch data from URL here, and then clean it up. return data By default, all parameters to a cached function must be hashable. Any parameter whose name begins with _ will not be hashed. You can use this as an "escape hatch" for parameters that are not hashable: import streamlit as st @st.cache_data def fetch_and_clean_data(_db_connection, num_rows): # Fetch data from _db_connection here, and then clean it up. return data connection = make_database_connection() d1 = fetch_and_clean_data(connection, num_rows=10) # Actually executes the function, since this is the first time it was # encountered. another_connection = make_database_connection() d2 = fetch_and_clean_data(another_connection, num_rows=10) # Does not execute the function. Instead, returns its previously computed # value - even though the _database_connection parameter was different # in both calls. A cached function's cache can be procedurally cleared: import streamlit as st @st.cache_data def fetch_and_clean_data(_db_connection, num_rows): # Fetch data from _db_connection here, and then clean it up. return data fetch_and_clean_data.clear(_db_connection, 50) # Clear the cached entry for the arguments provided. fetch_and_clean_data.clear() # Clear all cached entries for this function. To override the default hashing behavior, pass a custom hash function. You can do that by mapping a type (e.g. datetime.datetime) to a hash function (lambda dt: dt.isoformat()) like this: import streamlit as st import datetime @st.cache_data(hash_funcs={datetime.datetime: lambda dt: dt.isoformat()}) def convert_to_utc(dt: datetime.datetime): return dt.astimezone(datetime.timezone.utc) Alternatively, you can map the type's fully-qualified name (e.g. "datetime.datetime") to the hash function instead: import streamlit as st import datetime @st.cache_data(hash_funcs={"datetime.datetime": lambda dt: dt.isoformat()}) def convert_to_utc(dt: datetime.datetime): return dt.astimezone(datetime.timezone.utc) Persistent memo caches currently don't support TTL. ttl will be ignored if persist is specified: import streamlit as st @st.experimental_memo(ttl=60, persist="disk") def load_data(): return 42 st.write(load_data()) And a warning will be logged to your terminal: streamlit run app.py You can now view your Streamlit app in your browser. Local URL: http://localhost:8501 Network URL: http://192.168.1.1:8501 2022-09-22 13:35:41.587 The memoized function 'load_data' has a TTL that will be ignored. Persistent memo caches currently don't support TTL. st.experimental_memo.clearStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakedeleteDeprecation noticest.experimental_memo.clear was deprecated in version 1.18.0. Use st.cache_data.clear instead. Learn more in Caching.Clear all in-memory and on-disk data caches. Function signature[source] st.experimental_memo.clear() Example In the example below, pressing the "Clear All" button will clear memoized values from all functions decorated with @st.experimental_memo. import streamlit as st @st.experimental_memo def square(x): return x**2 @st.experimental_memo def cube(x): return x**3 if st.button("Clear All"): # Clear values from *all* memoized functions: # i.e. clear values from both square and cube st.experimental_memo.clear() Replay static st elements in cache-decorated functions Functions decorated with @st.experimental_memo can contain static st elements. When a cache-decorated function is executed, we record the element and block messages produced, so the elements will appear in the app even when execution of the function is skipped because the result was cached. In the example below, the @st.experimental_memo decorator is used to cache the execution of the load_data function, that returns a pandas DataFrame. Notice the cached function also contains a st.area_chart command, which will be replayed when the function is skipped because the result was cached. import numpy as np import pandas as pd import streamlit as st @st.experimental_memo def load_data(rows): chart_data = pd.DataFrame( np.random.randn(rows, 10), columns=["a", "b", "c", "d", "e", "f", "g", "h", "i", "j"], ) # Contains a static element st.area_chart st.area_chart(chart_data) # This will be recorded and displayed even when the function is skipped return chart_data df = load_data(20) st.dataframe(df) Supported static st elements in cache-decorated functions include: st.alert st.altair_chart st.area_chart st.audio st.bar_chart st.ballons st.bokeh_chart st.caption st.code st.components.v1.html st.components.v1.iframe st.container st.dataframe st.echo st.empty st.error st.exception st.expander st.experimental_get_query_params st.experimental_set_query_params st.form st.form_submit_button st.graphviz_chart st.help st.image st.info st.json st.latex st.line_chart st.markdown st.metric st.plotly_chart st.progress st.pydeck_chart st.snow st.spinner st.success st.table st.text st.vega_lite_chart st.video st.warning Replay input widgets in cache-decorated functions In addition to static elements, functions decorated with @st.experimental_memo can also contain input widgets! Replaying input widgets is disabled by default. To enable it, you can set the experimental_allow_widgets parameter for @st.experimental_memo to True. The example below enables widget replaying, and shows the use of a checkbox widget within a cache-decorated function. import streamlit as st # Enable widget replay @st.experimental_memo(experimental_allow_widgets=True) def func(): # Contains an input widget st.checkbox("Works!") func() If the cache decorated function contains input widgets, but experimental_allow_widgets is set to False or unset, Streamlit will throw a CachedStFunctionWarning, like the one below: import streamlit as st # Widget replay is disabled by default @st.experimental_memo def func(): # Streamlit will throw a CachedStFunctionWarning st.checkbox("Doesn't work") func() How widget replay works Let's demystify how widget replay in cache-decorated functions works and gain a conceptual understanding. Widget values are treated as additional inputs to the function, and are used to determine whether the function should be executed or not. Consider the following example: import streamlit as st @st.experimental_memo(experimental_allow_widgets=True) def plus_one(x): y = x + 1 if st.checkbox("Nuke the value 💥"): st.write("Value was nuked, returning 0") y = 0 return y st.write(plus_one(2)) The plus_one function takes an integer x as input, and returns x + 1. The function also contains a checkbox widget, which is used to "nuke" the value of x. i.e. the return value of plus_one depends on the state of the checkbox: if it is checked, the function returns 0, otherwise it returns 3. In order to know which value the cache should return (in case of a cache hit), Streamlit treats the checkbox state (checked / unchecked) as an additional input to the function plus_one (just like x). If the user checks the checkbox (thereby changing its state), we look up the cache for the same value of x (2) and the same checkbox state (checked). If the cache contains a value for this combination of inputs, we return it. Otherwise, we execute the function and store the result in the cache. Let's now understand how enabling and disabling widget replay changes the behavior of the function. Widget replay disabled Widgets in cached functions throw a CachedStFunctionWarning and are ignored. Other static elements in cached functions replay as expected. Widget replay enabled Widgets in cached functions don't lead to a warning, and are replayed as expected. Interacting with a widget in a cached function will cause the function to be executed again, and the cache to be updated. Widgets in cached functions retain their state across reruns. Each unique combination of widget values is treated as a separate input to the function, and is used to determine whether the function should be executed or not. i.e. Each unique combination of widget values has its own cache entry; the cached function runs the first time and the saved value is used afterwards. Calling a cached function multiple times in one script run with the same arguments triggers a DuplicateWidgetID error. If the arguments to a cached function change, widgets from that function that render again retain their state. Changing the source code of a cached function invalidates the cache. Both st.experimental_memo and st.experimental_singleton support widget replay. Fundamentally, the behavior of a function with (supported) widgets in it doesn't change when it is decorated with @st.experimental_memo or @st.experimental_singleton. The only difference is that the function is only executed when we detect a cache "miss". Supported widgets All input widgets are supported in cache-decorated functions. The following is an exhaustive list of supported widgets: st.button st.camera_input st.checkbox st.color_picker st.date_input st.download_button st.file_uploader st.multiselect st.number_input st.radio st.selectbox st.select_slider st.slider st.text_area st.text_input st.time_input Previous: st.cacheNext: st.experimental_singletonforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy
https://docs.streamlit.io/deploy/streamlit-community-cloud/get-started/connect-your-github-account#whats-next
DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudremoveGet startedremoveQuickstartCreate your accountConnect your GitHub accountExplore your workspaceFork and edit a public appTrust and securityDeploy your appaddManage your appaddShare your appaddManage your accountaddTroubleshootingStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Deploy/Streamlit Community Cloud/Get started/Connect your GitHub accountConnect your GitHub account Connecting GitHub to your Streamlit Community Cloud account allows you to deploy apps directly from the files you store in your repos. It also lets the system check for updates to those files and automatically update your app. There are two stages to this authorization: the first happens when you connect your account for the first time and the second happens when you deploy your first app. Everyone is prompted to connect GitHub when they create an account. If you need to connect GitHub to an existing primary identity, see Manage your GitHub connection. This page contains additional information about the authorization needed to connect GitHub. If you have just created your account, you are free to skip ahead and Explore your workspace. GitHub's authorization prompts occur automatically as needed. Authorize your GitHub account There are two different authorization prompts to grant access between Streamlit and your GitHub account. The first authorization—"Authorize Streamlit"—happens when you connect your GitHub account to Streamlit. The second authorization—"Streamlit is requesting additional permissions"—happens when you deploy your first app. You must click "Authorize streamlit" on both. If you are a member of any GitHub organizations, read below to understand the extras steps to authorize an organization. Questions about GitHub permissions? Read some frequently asked questions about our GitHub integration. priority_highImportantYou must have admin permissions to your repo in order to deploy apps. If you don't have admin access, talk to the repo's owner or reach out to us on the Community forum. Organization access If you are working in a repository that is owned by an organization, authorization must be granted by that organization. If you are an owner or member of a GitHub organization when you connect your GitHub account, your authorization prompts will include an extra section labeled "Organization access". Organizations you own For any organization you own, if authorization has not been previously granted or denied you can click "Grant" before you click "Authorize streamlit". Organizations owned by others For an organization you don't own, if authorization has not been previously granted or denied you can click "Request" before you click "Authorize streamlit". Previous or pending authorization If someone has already started the process of authorizing Streamlit for your organization, different options and statuses will display accordingly. Approved access If an organization has already granted Streamlit access, a green check is shown. Pending access If a request has been previously sent but not yet approved, a pending status shows. Denied access If a request has been previously sent and denied, no option to grant or request access is shown. In this case, the organization owner will need to authorize Streamlit from GitHub. See GitHub's documentation on OAuth apps and organizations. What's next? Now that you have your account you can Explore your workspace. Or if you're ready to go, jump right in and Deploy your app.Previous: Create your accountNext: Explore your workspaceforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy
https://docs.streamlit.io/develop/quick-reference/changelog#version-1280
DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceaddTutorialsaddQuick referenceremoveCheat sheetRelease notesPre-release featuresRoadmapopen_in_newweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Develop/Quick reference/Release notesRelease notes This page lists highlights, bug fixes, and known issues for official Streamlit releases. If you're looking for information about nightly releases, beta features, or experimental features, see Try pre-release features. starTipTo upgrade to the latest version of Streamlit, run:pip install --upgrade streamlit Version 1.34.0 Release date: May 2, 2024 Highlights 🍿 Introducing st.experimental_dialog! Create a modal overlay that can also rerun independently from the rest of your app. Check out the docs to learn how. Notable Changes 🔣 st.toast, st.chat_message, st.set_page_config, st.info, st.success, st.error, and st.warning can use Google Material Symbols for their icons. 🌈 Markdown supports background colors for text. Check out the feature demo app. 🎥 st.audio and st.video can now be set to autoplay. st.video can be muted. 🗃️ You can clear specific cached values for a cached function. Thanks, OscarSaharoy! ❓ You can now set all query parameters with a single call to st.query_params.from_dict. Thanks, Asaurus1! Other Changes 🔲 Streamlit supports Modin and Snowpark pandas DataFrames and Series (#8506). ⏱️ Improved support for period data types in st.dataframe and st.data_editor (#7987). 🗺️ Streamlit supports using pydeck-carto with st.pydeck_chart (#8422). ❄️ Additional snowflake requirements were updated to allow Python versions 3.8 to 3.11 (#8538). 🍞 st.toast received visual improvements and now appears in the top right (#8433). 🦋 Visual tweaks for dialogs and modals. 🦀 Bug fix: st.write_stream returns an empty string when passed a generator with no yield (#8560). 🦎 Bug fix: Widgets that support None values can be correctly set to None through Session State (#8529, #7649). 🐌 Bug fix: If the initial value for st.date_input is not set and today’s date falls outside the declared minimum or maximum, then the minimum or maximum will be used instead, whichever is closer (#8519, #6167). 🕸️ Bug fix: Altair’s resolve_scale method is handled correctly (#8497, #1667). 🦗 Bug fix: st.multiselects correctly handles sets when passed to options or default (#8471, #8466). 🦂 Bug fix: st.status does not show the expander toggle when empty (#8369). 🦟 Bug fix: The width of vconcat charts in Vega and Altair is set correctly (#8498, #2751). 🦠 Bug fix: Apps print beautifully and no longer show excessive whitespace (#8502, #7815). 🪰 Bug fix: Invalid escape sequences were removed to avoid warnings from pytest (#8510, #8501). 🪳 Bug fix: st.file_uploader callback is correctly executed once per file selection after the first selection (#8493, #4877). 🕷️ Bug fix: Streamlit is compatible down to pillow version 7.1.0 instead of 9.1.0 (#8492, #8486). 🐞 Bug fix: Widget values are correctly dropped when a script run is interrupted by switching pages (#8425, #7338). 🐝 Bug fix: Apps in dark mode will return to dark mode after printing (#8469, #7879). 🐜 Bug fix: Component ready state is dynamic to avoid race conditions that caused blank apps in Safari (#8434, #8362). 🪲 Bug fix: st.slider yields a Python error when min_value is less than or equal to max_value (#8413, #8342). 🐛 Bug fix: Time is offset correctly for Vega and Altair (#8278, #4342). Version 1.33.0 Release date: April 4, 2024 Highlights 👟 Introducing st.experimental_fragment to decorate functions and rerun them independently of the whole page. Check out the docs and give your apps a speed boost! 🌐 Introducing st.html to insert custom HTML into your app! Check out the docs for how to use it. Notable Changes 📺 st.audio and st.video allow looping and setting an end time (#8203, #8348). 🔁 AppTest allows switching pages with AppTest.switch_page (#8280). 🧪 format_func is accessible in AppTest for widgets that use it (#8189, #8019, #7679). 📈 Column configuration now includes AreaChartColumn. LineChartColumn no longer shows area (#8237). 🚧 Breaking change: st.write will no longer set unsafe_allow_html=True when passed an object containing a _repr_html_ method. For more information, see PR #8238. Other Changes 🖱️Users can click on the widget label to focus on input for st.number_input, st.text_input, and st.text_area (#8155). Thanks, filiptammergard! ⬆️ Streamlit supports packaging version 24.x (#8338, #8328). 🕸️ Bug fix: Streamlit now watches for changes to imported modules in addition to pages (#8372). Thanks, zyxue! 🦗 Bug fix: Overflowing toast messages are correctly truncated (#8337, #8330). 🦂 Bug fix: st.status correctly updates to complete when using LangChain's StreamlitCallbackHandler (#8331). 🦟 Bug fix: Custom components no longer show white backgrounds in dark themes (#8242, #8156, #7813). 🦠 Bug fix: Content area width is reduced when a fullscreen icon would otherwise cause horizontal overflow (#8279, #6990). 🪰 Bug fix: Custom components with undefined frame heights will render with a height of 0 (#8290, #8285). 🪳 Bug fix: Restored a check for active sessions to prevent apps from needlessly running when no users are connected (#8294). 🕷️ Bug fix: Custom themes have precedence over embedding options (#8021, #7118). 🐞 Bug fix: Reverted the async timer to expire session storage cache to address computational efficiency (#8281). 🐝 Bug fix: When using st.popover with use_container_width=True, the popover container's minimum width will match the popover button (#8266, #8261). 🐜 Bug fix: Using st.rerun with a triggering widget in AppTest no longer creates an infinite loop (#8264, #7768). 🪲 Bug fix: URLs are correctly decoded in LinkColumn if regex is used or if not using fully qualified URLs (#8258, #7064). 🐛 Bug fix: st.query_params only sends one ForwardMsg when updating multiple parameters (#8205, #8199). Thanks, Asaurus1! Version 1.32.0 Release date: March 7, 2024 Highlights 🍿 Introducing st.popover to create popover elements in your Streamlit apps. Check out the docs to see how to use it! Notable Changes 📺 You can now pass subtitles to st.video! Check out our feature demo. ⚗️ AppTest includes support for st.expander and st.status. 🧪 AppTest.from_function accepts a function that takes arguments and/or returns a value. 🧩 The timeout warning for custom components was replaced with an element skeleton to improve the UX for slow-loading components, especially in some cloud-hosted platforms (#8179, #7046). 📄 st.switch_page and st.page_link received significant improvements to path handling, performance, and visual appearance (see below for details). 🦀 Bug fix: Streamlit uses glide-data-grid version 6.0.4 to fix a variety of dataframe issues (#7779, #6900, #7032, #7727, #6810, #7930, #7949, #7831, #8168). 💦 Bug fix: We've plugged a significant memory leak in the coroutine loop. Apps that generate a large number of small messages between client and server will benefit greatly (#8068, #7989, #6510). Other Changes 💪 Multiple modules are now lazy-loaded to speed up Streamlit's import time (#8150, #8143, #8134, #8113, #8125, #8111, #8109, #6066). 🖼️ st.write supports PIL images (#8039). 🔗 st.radio allows markdown links within the items passed to options (#8028, #7992). 💀 The deprecation.showPyplotGlobalUse config option is deprecated and will be removed in the subsequent release (#8133). 🤖 Streamlit supports AzureOpenAI chat stream (#8107, #8084). 🌐 The /healthz endpoint supports the HTTP HEAD method (#8145, #8144). Thanks, rahulmistri1997! 🌀 The cache parameter for st.spinner is now private (_cache) since it's for internal use (#8118). 🏃 Session storage is checked and expired asynchronously to improve performance and efficiency of apps with lower traffic (#8083). 🐜 st.write_stream raises a descriptive Exception when the message cannot be parsed (#8036). 📘 Fixed a typo in the examples for st.switch_page and st.page_link (#8162). Thanks, t1emp0! 👻 Bug fix: st.help correctly displays conditional members (#8228). 🦋 Bug fix: App State fully clears on page change to prevent lingering stale elements (#8208). 🦎 Bug fix: st.info, st.success, st.warning, and st.error don't overflow with long markdown strings (#8194, #6394). 🐌 Bug fix: Streamlit shows a warning that port 3000 is reserved for development when the server port is set to 3000 (#8152, #8149). 🕸️ Bug fix: st.page_link and st.switch_page have improved path calculation for consistency (#8127). 🦗 Bug fix: st.page_link shows the correct path in browser on hover (#8086, #8080). 🦂 Bug fix: st.page_link and st.switch_page normalize paths for correct handling in Windows (#8103, #8070). 🦟 Bug fix: Script runner uses a while loop instead of recursion to avoid stack overflows (#8100). 🦠 Bug fix: st.page_link and st.switch_page correctly handle relative paths prefixed with "/" (#8085, #8081). 🪰 Bug fix: st.image parses paths in Windows correctly (#8092, #7271, #6066). 🪳 Bug fix: st.switch_page no longer waits for the current page to finish running before switching pages (#8054, #7954). 🕷️ Bug fix: st.map and other simple charts correctly handle color when data is not indexed starting from 0 (#8158, #8079, #8077). Thanks, awhazell! 🐞 Bug fix: st.selectbox, st.multiselect, st.select_slider, and st.radio use shallow copies of their options to prevent unexpected mutations (#8064, #7534). 🐝 Bug fix: The selected time in st.time_input displays correctly in dark mode (#8056, #7436). 🪲 Bug fix: Dataframe scrollbars display correctly in the latest version of Chrome (#8034). 🐛 Bug fix: Casting st.query_params to str will print the content of the query parameters instead of the class description (#8030). Version 1.31.0 Release date: February 1, 2024 Release videos What's new? Highlights 🔗 Introducing st.page_link! Now, you can build custom navigation menus for your multipage apps. Check out our docs to see how. 💦 Announcing st.write_stream to conveniently handle generators and streamed responses. Check out our docs to see how making chat apps just got easier. Notable Changes 📝 st.chat_input can be used inline and placed anywhere in the app. You can also have multiple st.chat_input widgets on a page (#7896). Other Changes 🧹 Internal refactoring and cleanup (#7980). Thanks, whitphx! ❄️ Bug fix: Snowpark is now an optional dependency for SnowflakeConnection (#7919). 🕷️ Bug fix: The watchdog suggestion is disabled when server.fileWatcherType is set to none or poll (#8024, #7999). 🐞 Bug fix: Required columns can be hidden when not using st.data_editor with dynamic rows (#7996, #7991). 🐝 Bug fix: New period types are supported for pandas 2.2.0 (#7988). 🐜 Bug fix: Custom components receive only the app's origin and path to avoid reloading components when query parameters change (#7951, #7503). Thanks, eric-skydio! 🪲 Bug fix: st.progress won't raise an exception when given a value above 1.0 due to float precision (#7953, #5517). Thanks, notiona! 📚 Streamlit supportsimportlib-metadata version 7 (#7925). Thanks, elgalu! 🐛 Bug fix: AppTest correctly sees widgets inside containers (#7923, #7711). 💿 Custom components no longer accumulate style elements when re-rendered for better performance (#7914). Thanks, Tom-Julux! Version 1.30.0 Release date: January 11, 2024 Release videos What's new? Highlights 🔄 Announcing st.switch_page to programmatically switch pages in multipage apps! Check out our docs to learn about this highly anticipated feature! ❓Introducing st.query_params to handle variables passed through your app's URL. Check out our docs to understand this feature and how it's been upgraded and improved from our experimental version! Notable Changes 📐 st.container can be configured with a height to create grids or scrolling containers (#7697, #2169, #2447). 🔗 For dataframes, LinkColumn has a simplified UI and can be configured with display text, including programmatically defined text through regular expressions (#7784, #7741, #6787). 🧭 Sidebar navigation for multipage apps can be hidden via configuration (#7852). ⏩ Plotly figures can load even faster when used in combination with orjson (#7860). Thanks, eric-skydio! ♻️ Behavior change: Query parameters are removed when changing pages (#7817, #6725, #5505). Other Changes 🛠️ showFooter is no longer an embed option since the footer no longer exists (#7902, #7785). 🕵️ All security concerns should be reported through HackerOne (#7783). 🕷️ Bug fix: Tabs are not disabled when stale to prevent flickering (#7905, #7820). 🛡️ Bug fix: The full file path is used instead of a prefix to prevent custom components from reaching beyond their own folders (#7901). 🪱 Bug fix: Widgets raise an exception if its values aren't Python comparable (#7840, #3714). 🐞 Bug fix: The down-arrow icons on expanders maintain a consistent size (#7596). Thanks, matiboux! 🐝 Bug fix: Tabs no longer flicker when switching between them (#7904). 🐜 Bug fix: Enter-to-submit is automatically disabled when the associated st.form_submit_button is disabled (#7827, #7822). 🪲 Bug fix: Required columns cannot be hidden with column configuration (#7888, #7559). 🐛 Bug fix: Using nan as a value in SelectboxColumn will raise an error instead of silently failing (#7887, #7558). 🌙 Bug fix: Custom component iframes allow dark mode (#7821, #7813). 🪰 Bug fix: The command to start Streamlit is not sent to the frontend (#7787). 💅 Bug fix: The background color of st.toggle is enhanced for better visibility (#7788). 🪳 Bug fix: Built-in charts can handle ordered categorical columns (#7771, #7776). Version 1.29.0 Release date: November 30, 2023 Highlights 🔲 st.container and st.form now have a border parameter to show or hide a border. 🐍 Streamlit supports Python 3.12! Notable Changes ⌛ st.dataframe, st.data_editor, and st.table support datetime.timedelta values (#7689, #4489). 💀 Streamlit apps preload skeleton elements for a smoother appearance when initializing (#7598). 🏃 Reduced the overhead of running AppTest-simulated apps, especially for fast-running apps (#7691). 🛁 String representations of AppTest data are improved for a better testing and debugging experience (#7658). 🔢 Apps can be configured to identify Enum classes as the same if they have matching member names (#7408, #4909). Thanks, Asaurus1! ❌ The "Made with Streamlit" footer no longer appears at the bottom of apps (#7583). 🧹 Unused config options have been deprecated (#7584). 🕳️ Query parameters can be empty (#7601, #7416). 💅 Visual tweaks (#7592, #7630). Other Changes 🦗 Bug fix: Convert floats to bytes instead of hashing to avoid hashing instability (#7754). Thanks, BlackHC! 🦎 Bug fix: Corrected broken URLs and typos in error messages (#7746, #7764, #7770). Thanks, ObservedObserver! 🐌 Bug fix: st.connection correctly caches results when using two connections of the same type (#7730, #7709). 🕸️ Bug fix: Using context managers with multithreading now displays content in the expected order (#7715, #7668). Thanks, eric-skydio! 🦂 Bug fix: Added https fallback when obtaining the host machine's address (#7712, #7703). Thanks, LarsHill! 🛡️ Bug fix: Added security patch for pyarrow vulnerability. Custom components using pyarrow table deserialization should require pyarrow>=14.0.1 (#7695, #7700). 🦟 Bug fix: Improved typing for st.connection (#7671). Thanks, thezanke! 🪰 Bug fix: Retries of SnowflakeConnection methods are narrowed to only occur with transient errors to avoid unnecessary repeated errors (#7645, #7637). 🏗️ Removed the v0 testing framework which was undocumented (#7657). 🪳 Bug fix: The navigation expander arrow no longer disappears (#7634, #7547). ❄️ Improved the error message for SnowflakeConnection when a configuration is not found (#7652). 🕷️ Bug fix: st.rerun no longer causes a RecursionError when used with st.chat_input (#7643, #7629). 🐞 Bug fix: st.file_uploader no longer causes an extra rerun and therefore doesn't conflict with st.chat_input (#7641, #7556). 🐝 Bug fix: AppTest no longer raises an error when encountering st.container (#7644, #7636). 🪲 Bug fix: Graphviz charts scale correctly when exiting fullscreen view (#7398, #7527). 🎥 Bug fix: "Record a screencast" is hidden when known to be unsupported in a browser (#7604). 🐛 Bug fix: Increased the top padding of embedded apps to better display the dataframe toolbar (#7681, #7609, #7607). 🐜 Bug fix: st.rerun uses NoReturn for improved type checking (#7422) Thanks, kongzii. Version 1.28.0 Release date: October 26, 2023 Release videos Introducing AppTest Highlights 🧪 Introducing a new testing framework for Streamlit apps! Check out our documentation to learn how to build automated tests for your apps. 💻 Announcing the general availability of st.connection, a command to conveniently manage connections in Streamlit apps. Check out the docs to learn more. ❄️ SnowparkConnection has been upgraded to the new and improved SnowflakeConnection — the same, great functionality plus more! Check out our built-in connections. 🛠️ st.dataframe and st.data_editor have a new toolbar! Users can search and download data in addition to enjoying improved UI for row additions and deletions. See our updated guide on Dataframes. Notable Changes 🌀 When using a spinner with cached functions, the spinner will be overlaid instead of pushing content down (#7488). 📅 st.data_editor now supports datetime index editing (#7483). 🔢 Improved support for decimal.Decimal in st.dataframe and st.data_editor (#7475). 🥸 Global kwargs were added for hashlib (#7527, #7526). Thanks, DueViktor! 📋 st.components.v1.iframe now permits writing to clipboard (#7487). Thanks, dilipthakkar! 📝 SafeSessionState disconnect was replaced with script runner yield points for improved efficiency and clarity (#7373). 🤖 The Langchain callback handler will show the full input string inside the body of a st.status when the input string is too long to show as a label (#7478). Thanks, pokidyshev! 📈 st.graphviz_chart now supports using different Graphviz layout engines (#7505, #4089). 🦋 Assorted visual tweaks (#7486, #7592). 📊 plotly.js was upgraded to version 2.26.1 (#7449, #7476, #7045). 💽 Legacy serialization for DataFrames was removed. All DataFrames will be serialized by Apache Arrow (#7429). 🖼️ Compatibility for Pillow 10.x was added (#7442). 📬 Migrated _stcore/allowed-message-origins endpoint to _stcore/host-config (#7342). 💬 Added post_parent_message platform command to send custom messages from a Streamlit app to its parent window (#7522). Other Changes ⌨️ Improved string dtype handling for DataFrames (#7479). ✒️ st.write will avoid using unsafe_allow_html=True if possible (#7432). 🐛 Bug fix: Implementation of st.expander was simplified for improved behavior and consistency (#7247, #2839, #4111, #4651, #5604). 🪲 Bug fix: Multipage links in the sidebar are now aligned with other sidebar elements (#7531). 🐜 Bug fix: st.chat_input won't incorrectly prompt for label parameter in IDEs (#7560). 🐝 Bug fix: Scroll bars correctly overlay st.dataframe and st.data_editor without adding empty space (#7090, #6888). 🐞 Bug fix: st.chat_message behaves correctly with the removal of AutoSizer (#7504, #7473). 🕷️ Bug fix: Anchor links are reliably produced for non-English headers (#7454, #5291). ☃️ Bug fix: st.connections.SnowparkConnection more accurately detects when it's running within Streamlit in Snowflake (#7502). 🪳 Bug fix: A user-friendly warning is shown when exceeding the size limitations of a pandas Styler object (#7497, #5953). 🪰 Bug fix: st.data_editor automatically converts non-string column names to strings (#7485, #6950). 🦠 Bug fix: st.data_editor correctly identifies non-range indices as a required column (#7481, #6995). 🦟 Bug fix: st.file_uploader displays compound file extensions like csv.gz correctly (#7362). Thanks, mo42! 🦂 Bug fix: Column Configuration no longer uses deprecated type checks (#7496, #7477, #7550). Thanks, c-bik! 🦗 Bug fix: Additional toolbar items no longer stack vertically (#7470, #7471). 🕸️ Bug fix: Column Configuration no longer causes a type warning in Mypy (#7457). Thanks, kopp! 🐌 Bug fix: Bokeh Sliders no longer cause JavaScript errors (#7441, #7171). 🦎 Bug fix: Caching now recognizes DataFrames with the same values but different column names as different (#7331, #7086). Version 1.27.0 Release date: September 21, 2023 Highlights ✨ Introducing st.scatter_chart — a new, simple chart element to build scatter charts Streamlit-y fast and easy! See our documentation. 🔗 Introducing st.link_button! Want to open an external link in a new tab with a bit more pizazz than a plain-text link? Check out our documentation to see how. 🏃 Announcing the general availability of st.rerun, a command to interrupt your script and trigger an immediate rerun. Notable Changes 👻 You can initialize widgets with an empty state by setting None as an initial value for st.number_input, st.selectbox, st.date_input, st.time_input, st.radio, st.text_input, and st.text_area! 📤 st.download_button now uses target="_self" instead of opening a new tab (#7151, #7132). 🧟 Removed unmaintained pympler dependency (#7193, #7131). Thanks, rudyardrichter! Other Changes 🐛 Bug fix: st.multiselect now shows a correct message when no result matches a user's search (#7205, #7116). 🪲 Bug fix: st.experimental_user now defaults to test@example.com (#7219, #7215). 🐜 Bug fix: st.slider labels don't overlap when small ranges are selected (#7221, #3385). 🐝 Bug fix: Type-checking correctly identifies all string types to avoid hashing errors (#7255, #6455). 🐞 Bug fix: JSON is parsed with JSON5 to avoid errors from null values when using st.pydeck_chart (#7256, #5799). 🕷️ Bug fix: Identical widgets on different pages are correctly interpreted by Streamlit as distinct (#7264, #6146). 🦋 Bug fix: Visual tweaks to widgets for responsive behavior (#7145). 🪳 Bug fix: SVGs are accurately displayed (#7183, #3882). 🪰 Bug fix: st.video correctly updates with changes to start_time (#7257, #7126). 🦠 Bug fix: Additional error handling was added to st.session_state (#7280, #7206). 🦟 Bug fix: st.map correctly refreshes with new data (#7307, #7294). 🦂 Bug fix: The decorative app header line is no longer covered by the sidebar (#7297, #6264). 🦗 Bug fix: st.code no longer triggers a CachedStFunctionWarning (#7306, #7055). 🕸️ Bug fix: st.download_button no longer resets with different data (#7316, #7308). 🐌 Bug fix: Widgets consistently recognize user interaction while a page is still running, with or without fastRerun enabled (#7283, #6643). 🦎 Bug fix: st.tabs was improved to better handle and render conditionally appearing tabs (#7287, #7310, #5454, #7040). Version 1.26.0 Release date: August 24, 2023 Highlights 🤖 Introducing st.status to display output from long-running processes and external API calls (#7140). Works great with st.chat_message! See our documentation for how to use this feature. 🚥 Introducing st.toggle — an alternative to st.checkbox when you need an on/off switch. Notable Changes 🎨 Simple chart elements have a color parameter to set the color of your data points or series (#7022). 🌈 Markdown supports rainbow and gray colors (#7106, #7179). 📏 st.header and st.subheader have optional, colored dividers (#7133). 🚀 Deploying to Community Cloud is even easier—locally running apps have a deploy button in their toolbars (#7085, #6935). 🖌️ st.download_button has a new parameter type for theming (#7056, #7038). 🤖 st.chat_message has ai and human presets for messages (#7094). 💅 st.radio options support markdown and have captions (#7018, #7105, #6085). 🧼 Assorted visual tweaks (#7050, #894). 🛏️ Replaced deprecated imghdr dependency with pillow (#7081, #7027). 🔢 st.number_input's step buttons (+/-) are ignored during tabbing navigation (#7154). Thanks @denck007! Other Changes 🍞 Bug fix: Toast messages are no longer blocked by st.chat_input (#7204, #7115). 🕸️ Bug fix: Widget IDs are now stable to prevent inconsistent statefulness (#7003). 🦟 Bug fix: Browser autofill is correctly recognized within forms now (#7150, #7101, #7084). 🪱 Bug fix: st.file_uploader no longer causes session state to reset when a websocket connection is dropped and reconnected (#7149, #7025). 🏎️ Bug fix: Pydeck JSON data is cached for improved performance (#7113, #5532). 🦋 Bug fix: st.chat_input no longer submits prematurely while typing with an input method editor (#6993). 🐞 Bug fix: Label backgrounds for st.tabs are now transparent (#7070, #5707). 🐝 Bug fix: Page width is no longer ignored when using the help parameter in st.button (#7033, #6161). 🐜 Bug fix: Tweaked Altair color specification for improved visibility in dark mode (#7061, #3343). 🪲 Bug fix: st.chat_message can correctly use local images as avatars (#7130). 🐛 Bug fix: Specified that MD5 is not used for security (#7122, #7120). 🪄 Bug fix: Async function docstrings are ignored by Streamlit magic (#7143, #7137). Version 1.25.0 Release date: July 20, 2023 Highlights 🍞 Introducing st.toast — a command to briefly show toast messages to users in the bottom-right corner of apps. See our documentation on how to use this feature. Notable Changes 🗺️ st.map now has parameters for latitude, longitude, color, and size to customize data points (#6896). 🚩 st.multiselect supports setting placeholders and specifying the maximum number of selections via the placeholder and max_selections keyword-only arguments, respectively (#6901, #4750). Thanks, @fhiroki! 📅 Customize the date format for st.date_input with the format parameter (#6974, #5234). ↩️ Forms can now be submitted with Enter/Return while inside st.text_input, st.number_input, or st.text_area (#6911, #3790). 🍢 The app menu icon in the upper-right corner of apps has been changed from "☰" to "⋮" (#6947). Other Changes ⛓️ Minimum required versions increased for multiple Python dependencies, including numpy>=1.19.3 and pandas>=1.3.0 (#6802). 🛡️ protobufjs was bumped from 7.2.1 to 7.2.4 (#6959). ✨ Visual design tweaks to Streamlit's input widgets (#6944). 🦋 Bug Fix: st.slider now accepts general number types like numpy.int64 instead of just int and float (#6816, #6815). Thanks, @milliams! 🐜 Bug Fix: Data labels for st.slider and st.select_slider no longer overflow when inside st.expander (#6828, #6297). 🐛 Bug Fix: Elements no longer re-render from scratch with each rerun (#6923, #6920). 🐞 Bug Fix: st.data_editor hashes styler objects correctly for stability across reruns (#6815, #6898). 🐝 Bug Fix: Fixed the padding for embedded apps using st.chat_input to prevent messages being cutoff (#6979). Version 1.24.0 Release date: June 27, 2023 Highlights 💬 Introducing st.chat_message and st.chat_input — two new chat elements that let you build conversational apps. Learn how to use these features in your LLM-powered chat apps in our tutorial. 💾 Streamlit's caching decorators now allow you to customize Streamlit's hashing of input parameters with the keyword-only argument hash_funcs. Notable Changes 🐍 We've deprecated support for Python 3.7 in the core library and Streamlit Community Cloud (#6868). 📅 st.cache_data and st.cache_resource can hash timezone-aware datetime objects (#6812, #6690, #5110). Other Changes ✨ Visual design tweaks to Streamlit's input widgets (#6817). 🐛 Bug fix: st.write pretty-prints dataclasses using st.help (#6750). 🪲 Bug fix: st.button's height is consistent with that of other widgets (#6738). 🐜 Bug fix: Upgraded the react-range frontend dependency to fix the memory usage of sliders (#6764, #5436). Thanks @wolfd! 🐝 Bug fix: Pydantic validators no longer result in exceptions on app reruns (#6664, #3218). 🐞 Bug fix: streamlit config show honors newlines (#6758, #2868). 🪰 Bug fix: Fixed a race condition to ensure Streamlit reruns the latest code when the file changes (#6884). 🦋 Bug fix: Apps no longer rerun when users click anchor links (#6834, #6500). 🕸️ Bug fix: Added robust out-of-bounds checks for min_value and max_value in st.number_input (#6847, #6797). Version 1.23.0 Release date: June 1, 2023 Highlights ✂️ Announcing the general availability of st.data_editor, a widget that allows you to edit DataFrames and many other data structures in a table-like UI. Breaking change: the data editor's representation used in st.session_state was altered. Find out more about the new format in Access edited data. ⚙️ Introducing the Column configuration API with a suite of methods to configure the display and editing behavior of st.dataframe and st.data_editor columns (e.g. their title, visibility, type, or format). Keep an eye out for a detailed blog post and in-depth documentation upcoming in the next two weeks. 🔌 Learn to use st.experimental_connection to create and manage data connections in your apps with the new Connecting to data docs and video tutorial. Notable Changes 📊 Streamlit now supports Protobuf 4 and Altair 5 (#6215, #6618, #5626, #6622). ☎️ st.dataframe and st.data_editor can hide index columns with hide_index, specify the display order of columns with column_order, and disable editing for individual columns with the disabled parameter. ⏱️ The ttl parameter in st.cache_data and st.cache_resource accepts formatted strings, so you can simply say ttl="30d", ttl="1h30m" and any other combination of w, d, h, m, s supported by Pandas's Timedelta constructor (#6560). 📂 st.file_uploader now interprets the type parameter more accurately. For example, "jpg" or ".jpg" now accept both "jpg" and "jpeg" extensions. This functionality has also been extended to "mpeg/mpg", "tiff/tif", "html/htm", and "mpeg4/mp4". 🤫 The new global.disableWidgetStateDuplicationWarning configuration option allows the silencing of warnings triggered by setting widget default values and keyed session state values concurrently (#3605, #6640). Thanks, @antonAce! Other Changes 🏃‍♀️Improved startup time by lazy loading some dependencies (#6531). 👋 Removed st.beta_* and st.experimental_show due to deprecation and low-use (#6558) 🚀 Further improvements to st.dataframe and st.data_editor: Improved editing on mobile devices for the data editor (#6548). All editable columns have an icon in their column header and support tooltips (#6550, #6561). Enable editing for columns containing datetime, date, or time values (#6025). New input validation options for columns in the data editor, such as max_chars and validate for text columns, and min_value, max_value and step for number columns (#6563). Improved type parsing capabilities in the data editor (#6551). Unified missing values to None in returned data structures (#6544). A warning is shown in cells when integers exceed the maximum safe value of (2^53) -1 (#6311, #6549). Prevented editing the sessions state by showing a warning (#6634). Fixed issues with list columns sometimes breaking the frontend (#6644). Fixed a display issue with index columns using category dtype (#6680, #6598). Fixed an issue that prevented a rerun when adding empty rows (#6598). Unified the behavior between st.data_editor and st.dataframe related to auto-hiding the index column(s) based on the input data (#6659, #6598) 🛡️ Streamlit's Security Policy can be found in its GitHub repository (#6666). 🤏 Documented the integer size limit for st.number_input and st.slider (#6724). 🐍 The majority of Streamlit's Python dependencies have set a maximum allowable version, with the standard upper limit set to the next major version, but not inclusive of it (#6691). 💅 UI design improvements to in-app modals (#6688). 🐞 Bug fix: st.date_input's date selector is equally visible in dark mode (#6072, #6630). 🐜 Bug fix: the sidebar navigation expansion indicator in multipage apps is restored (#6731). 🐛 Bug fix: The docstring and exception message for st.set_page_config have been updated to clarify that this command can be invoked once for each page within a multipage app, rather than once per entire app (#6594). 🐝 Bug fix: st.json no longer collapses multiple spaces in both keys and values with single space when rendered (#6657, #6663). Version 1.22.0 Release date: April 27, 2023 Highlights 🔌 Introducing st.experimental_connection: Easily connect your app to data sources and APIs using our new connection feature. Find more details in the API reference, and stay tuned for an upcoming blog post and in-depth documentation! In the meantime, explore our updated MySQL and Snowflake connection tutorials for examples of this feature. Notable Changes 🐼 Streamlit now supports Pandas 2.0 (#6413, #6378, #6507). Thanks, connortann! 🍔 Customize the visibility of items in the toolbar, options menu, and the settings dialog using the client.toolbarMode config option (#6174). 🪵 Streamlit logs now reside in the "streamlit" namespace instead of the root logger, enabling app developers to better manage log handling (#3978, #6377). Other Changes 🔏 CLI parameters can no longer be used to set sensitive configuration values (#6376). 🤖 Improved the debugging experience by reducing log noise (#6391). 🐞 Bug fix: @st.cache_data decorated functions support UUID objects as parameters (#6440, #6459). 🐛 Bug fix: Tabbing through buttons and other elements now displays a red border only when focused, not when clicked (#6373). 🪲 Bug fix: st.multiselect's clear icon is larger and includes a hover effect (#6471). 🐜 Bug fix: Custom theme font settings no longer apply to code blocks (#6484, #6535). ©️ Bug fix: st.code's copy-to-clipboard button appears when you hover on code blocks (#6490, #6498). Version 1.21.0 Release date: April 6, 2023 Highlights 📏 Introducing st.divider — a command that displays a horizontal line in your app. Learn how to use this command in its API reference. 🔏 Streamlit now supports the use of a global secrets.toml file, in addition to a project-level file, to easily store and securely access your secrets. Learn more in Secrets management. 🚀 st.help has been revamped to show more information about object methods, attributes, classes, and more, which is great for debugging (#5857, #6382)! Notable Changes 🪜 st.time_input supports adding a stepping interval with the keyword-only step parameter (#6071). ❓ Most text elements can include tooltips with the help parameter (#6043). ↔️ st.pyplot has a use_container_width parameter to set the chart to the container width (now all chart elements support this parameter) (#6067). 👩‍💻 st.code supports optionally displaying line numbers to the code block's left with the boolean line_numbers parameter (#5756, #6042). ⚓ Anchors in header elements can be turned off by setting anchor=False (#6158). Other Changes 🐼 st.table and st.dataframe support pandas.Period, and number and boolean types in categorical columns (#2547, #5429, #5329, #6248). 🕸️ Added .webp to the list of allowed static file extensions (#6331) 🐞 Bug fix: stop script execution on websocket close to immediately clear session information (#6166, #6204). 🐜 Bug fixes: updated allowed/disallowed label markdown behavior such that unsupported elements are unwrapped and only their children (text contents) render (#5872, #6036, #6054, #6163). 🪲 Bug fixes: don't push browser history states on rerun, use HTTPS to load external resources in streamlit hello, and make the browser back button work for multipage apps (#5292, #6266, #6232). Thanks, whitphx! 🐝 Bug fix: avoid showing emoji on non-UTF-8 terminals. (#2284, #6088). Thanks, kcarnold! 📁 Bug fix: override default use of File System Access API for react-dropzone so that st.file_uploader's File Selection Dialog only shows file types corresponding to those included in the type parameter (#6176, #6315). 💾 Bug fix: make the .clear() method on cache-decorated functions work (#6310, #6321). 🏃 Bug fix: st.experimental_get_query_params doesn't need reruns to work (#6347, #6348). Thanks, PaleNeutron! 🐛 Bug fix: CachedStFunctionWarning mentions experimental_allow_widgets instead of the deprecated suppress_st_warning (#6216, #6217). Version 1.20.0 Release date: March 09, 2023 Notable Changes 🔐 Added support for configuring SSL to serve apps directly over HTTPS (#5969). 🖼️ Granular control over app embedding behavior with the /?embed and /?embed_options query parameters. Learn how to use this feature in our docs (#6011, #6019). ⚡ Enabled the runner.fastReruns configuration option by default to make apps much more responsive to user interaction (#6200). Other Changes 🍔 Cleaned up the hamburger menu by removing the least used options (#6080). 🖨️ Design changes to ensure apps being printed or saved as a PDF look good (#6180). 🐞 Bug fix: improved dtypes checking in st.experimental_data_editor (#6185, #6188). 🐛 Bug fix: properly position st.metric's help tooltip when not inside columns (#6168). 🪲 Bug fix: regression in retrieving messages from the server's ForwardMsgCache (#6210). 🌀 Bug fix: st.cache_data docstring for the show_spinner param now lists str as a supported type (#6207, #6213). ⏱️ Made ping and websocket timeouts far more forgiving (#6212). 🗺️ st.map and st.pydeck_chart docs state that Streamlit's Mapbox token will not work indefinitely (#6143). Version 1.19.0 Release date: February 23, 2023 Highlights ✂️ Introducing st.experimental_data_editor, a widget that allows you to edit DataFrames and many other data structures in a table-like UI. Read more in our documentation and blog post. Other Changes ✨ Streamlit's GitHub README got a new look (#6016). 🌚 Improved readability of styled dataframe cells in dark mode (#6060, #6098). 🐛 Bug fix: make apps work again in the latest versions of Safari, and in Chrome with third-party cookies blocked (#6092, #6094, #6087, #6100). 🐞 Bug fix: refer to new cache primitives in the "Clear cache" dialog and error messages (#6082, #6128). 🐝 Bug fix: properly cache class member functions and instance methods (#6109, #6114). 🐜 Bug fix: regression in st.metric tooltip position (#6093, #6129). 🪲 Bug fix: allow fullscreen button to show for dataframes, charts, etc, in expander (#6083, #6148). Version 1.18.0 Release date: February 09, 2023 Highlights 🎊 Introducing @st.cache_data and @st.cache_resource — two new caching commands to replace st.cache! Check out our blog post and documentation for more information. Notable Changes 🪆 st.columns supports up to one level of column nesting (i.e., columns inside columns) in the main area of the app. ⏳ st.progress supports adding a message to display above the progress bar with the text keyword parameter. ↔️ st.button has an optional use_container_width parameter to allow you to stretch buttons across the full container width. 🐍 We formally added support for Python 3.11. 🖨️ Save your app as a PDF via the "Print" option in your app's hamburger menu. 🛎️ Apps can serve small, static media files via the enableStaticServing config option. See our documentation on how to use this feature and our demo app for an example. Other Changes 🏁 All Streamlit endpoints (including /healthz) have been renamed to have a consistent pattern and avoid any clashes with reserved endpoints of GCP (notably Cloud Run and App Engine) (#5534). ⚡ Improved caching performance when multiple sessions access an uncomputed cached value simultaneously (#6017). 🚧 Streamlit only displays deprecation warnings in the browser when the client.showErrorDetails config option is set to True. Deprecation warnings always get logged to the console, regardless of whether they're displayed in-browser (#5945). 🏓 Refactored the st.dataframe internals to improve dataframe handling and conversion, such as detecting more types, converting key-value dicts to dataframes, and more (#6026, #6023). 💽 The behavior of widget labels when they are passed unsupported Markdown elements is documented (#5978). 📊 Bug fix: Plotly improvements — upgraded multiple frontend dependencies, including Plotly, to the latest version to properly redraw cached charts, make Plotly mapbox animations work, and allow users to update the figure layout when using the Streamlit theme (#5885, #5967, #6055). 📶 Bug fix: allow browser tabs that transiently disconnect (due to a network blip, load balancer timeout, etc.) to avoid losing all of their state (#5856). 📱 Bug fix: the keyboard is hidden on mobile when st.selectbox and st.multiselect have less than 10 options (#5979). 🐝 Bug fix: design tweaks to st.metric, st.multiselect, st.tabs , and menu items to prevent label overflow and scrolling issues, especially with small viewport sizes (#5933, #6034). 🐞 Bug fix: switched to a functioning Twemoji URL from which page favicons are loaded in st.set_page_config (#5943). ✍️ More type hints (#5986). Thanks, harahu! Version 1.17.0 Release date: January 12, 2023 Notable Changes 🪄 @st.experimental_singleton supports an optional validate parameter that accepts a validation function for cached data and is called each time the cached value is accessed. 💾  @st.experimental_memo's persist parameter can also accept booleans. Other Changes 📟 Multipage apps exclude __init__.py from the page selector (#5890). 📐 The iframes of embedded apps have the ability to dynamically resize their height (#5894). 🐞 Bug fix: thumb values of range sliders respect the container width (#5913). 🪲 Bug fix: all examples in docstrings of Streamlit commands contain relevant imports to make them reproducible (#5877). Version 1.16.0 Release date: December 14, 2022 Highlights 👩‍🎨 Introducing a new Streamlit theme for Altair, Plotly, and Vega-Lite charts! Check out our blog post for more information. 🎨 Streamlit now supports colored text in all commands that accept Markdown, including st.markdown, st.header, and more. Learn more in our documentation. Notable Changes 🔁 Functions cached with st.experimental_memo or st.experimental_singleton can contain Streamlit media elements and forms. ⛄ All Streamlit commands that accept pandas DataFrames as input also support Snowpark and PySpark DataFrames. 🏷 st.checkbox and st.metric can customize how to hide their labels with the label_visibility parameter. Other Changes 🗺️ st.map improvements: support for upper case columns and better exception messages (#5679, #5792). 🐞 Bug fix: st.plotly_chart respects the figure's height attribute and the use_container_width parameter (#5779). 🪲 Bug fix: all commands with the icon parameter such as st.error, st.warning, etc, can contain emojis with variant selectors (#5583). 🐝 Bug fix: prevent st.camera_input from jittering when resizing the browser window (#5661). 🐜 Bug fix: update exception layout to avoid overflow of stack traces (#5700). Version 1.15.0 Release date: November 17, 2022 Notable Changes 💅 Widget labels can contain inline Markdown. See our docs and demo app for more info. 🎵 st.audio now supports playing audio data passed in as NumPy arrays with the keyword-only sample_rate parameter. 🔁 Functions cached with st.experimental_memo or st.experimental_singleton can contain Streamlit widgets using the experimental_allow_widgets parameter. This allows caching checkboxes, sliders, radio buttons, and more! Other Changes 👩‍🎨 Design tweak to prevent jittering in sliders (#5612). 🐛 Bug fix: links in headers are red, not blue (#5609). 🐞 Bug fix: properly resize Plotly charts when exiting fullscreen (#5645). 🐝: Bug fix: don't accidentally trigger st.balloons and st.snow (#5401). Version 1.14.0 Release date: October 27, 2022 Highlights 🎨 st.button and st.form_submit_button support designating buttons as "primary" (for additional emphasis) or "secondary" (for normal buttons) with the type keyword-only parameter. Notable Changes 🤏 st.multiselect has a keyword-only max_selections parameter to limit the number of options that can be selected at a time. 📄 st.form_submit_button now has the disabled parameter that removes interactivity. Other Changes 🏓 st.dataframe and st.table accept categorical intervals as input (#5395). ⚡ Performance improvements to Plotly charts (#5542). 🪲 Bug fix: st.download_button supports non-latin1 characters in filenames (#5465). 🐞 Bug fix: Allow st.image to render a local GIF as a GIF, not as a static PNG (#5438). 📱 Design tweaks to the sidebar in multipage apps (#5538, #5445, #5559). 📊 Improvements to the axis configuration for built-in charts (#5412). 🔧 Memo and singleton improvements: support text values for show_spinner, use datetime.timedelta objects as ttl parameter value, properly hash PIL images and Enum classes, show better error messages when returning unevaluated dataframes (#5447, #5413, #5504, #5426, #5515). 🔍 Zoom buttons in maps created with st.map and st.pydeck_chart use light or dark style based on the app's theme (#5479). 🗜 Websocket headers from the current session's incoming WebSocket request can be obtained from a new "internal" (i.e.: subject to change without deprecation) API (#5457). 📝 Improve the text that gets printed when you first install and use Streamlit (#5473). Version 1.13.0 Release date: September 22, 2022 Notable Changes 🏷 Widgets can customize how to hide their labels with the label_visibility parameter. 🔍 st.map adds zoom buttons to the map by default. ↔️ st.dataframe supports the use_container_width parameter to stretch across the full container width. 🪄 Improvements to st.dataframe sizing: Column width calculation respects column headers, supports double click between column headers to autosize, better fullscreen support, and fixes the issue with the width parameter. Other Changes ⌨️ st.time_input allows for keyboard-only input (#5194). 💿 st.memo will warn the user when using ttl and persist keyword argument together (#5032). 🔢 st.number_input returns consistent type after rerun (#5359). 🚒 st.sidebar UI fixes including a fix for scrollbars in Firefox browsers (#5157, #5324). 👩‍💻 Improvements to usage metrics to guide API development. ✍️ More type hints! (#5191, #5192, #5242, #5243, #5244, #5245, #5246) Thanks harahu! Older versions Are you curious about older versions? To see older release notes, see Release notes (historical).Previous: Cheat sheetNext: Release notes (historical)forumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy
https://docs.streamlit.io/develop/api-reference/connections/st.secrets#stsecrets
DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceremovePAGE ELEMENTSWrite and magicaddText elementsaddData elementsaddChart elementsaddInput widgetsaddMedia elementsaddLayouts and containersaddChat elementsaddStatus elementsaddThird-party componentsopen_in_newAPPLICATION LOGICNavigation and pagesaddExecution flowaddCaching and stateaddConnections and secretsremoveSECRETSst.secretssecrets.tomlCONNECTIONSst.connectionSnowflakeConnectionSQLConnectionBaseConnectionSnowparkConnectiondeleteCustom componentsaddUtilitiesaddConfigurationaddTOOLSApp testingaddCommand lineaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Develop/API reference/Connections and secrets/st.secretsst.secrets st.secrets provides a dictionary-like interface to access secrets stored in a secrets.toml file. It behaves similarly to st.session_state. st.secrets can be used with both key and attribute notation. For example, st.secrets.your_key and st.secrets["your_key"] refer to the same value. For more information about using st.secrets, see Secrets management. secrets.toml Secrets can be saved globally or per-project. When both types of secrets are saved, Streamlit will combine the saved values but give precedence to per-project secrets if there are duplicate keys. For information on how to format and locate your secrets.toml file for your development environment, see secrets.toml. Example OpenAI_key = "your OpenAI key" whitelist = ["sally", "bob", "joe"] [database] user = "your username" password = "your password" In your Streamlit app, the following values would be true: st.secrets["OpenAI_key"] == "your OpenAI key" "sally" in st.secrets.whitelist st.secrets["database"]["user"] == "your username" st.secrets.database.password == "your password" Previous: Connections and secretsNext: secrets.tomlforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy
https://docs.streamlit.io/develop/api-reference/custom-components
DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceremovePAGE ELEMENTSWrite and magicaddText elementsaddData elementsaddChart elementsaddInput widgetsaddMedia elementsaddLayouts and containersaddChat elementsaddStatus elementsaddThird-party componentsopen_in_newAPPLICATION LOGICNavigation and pagesaddExecution flowaddCaching and stateaddConnections and secretsaddCustom componentsremovest.components.v1​.declare_componentst.components.v1.htmlst.components.v1.iframeUtilitiesaddConfigurationaddTOOLSApp testingaddCommand lineaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Develop/API reference/Custom componentsCustom components Declare a componentCreate and register a custom component.st.components.v1.declare_component( "custom_slider", "/frontend", ) HTMLDisplay an HTML string in an iframe.st.components.v1.html( "<p>Foo bar.</p>" ) iframeLoad a remote URL in an iframe.st.components.v1.iframe( "docs.streamlit.io" ) Previous: Connections and secretsNext: st.components.v1​.declare_componentforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy
https://docs.streamlit.io/en/0.68.0/api.html#text-elements
DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceremovePAGE ELEMENTSWrite and magicaddText elementsaddData elementsaddChart elementsaddInput widgetsaddMedia elementsaddLayouts and containersaddChat elementsaddStatus elementsaddThird-party componentsopen_in_newAPPLICATION LOGICNavigation and pagesaddExecution flowaddCaching and stateaddConnections and secretsaddCustom componentsaddUtilitiesaddConfigurationaddTOOLSApp testingaddCommand lineaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Develop/API referenceAPI reference Streamlit makes it easy for you to visualize, mutate, and share data. The API reference is organized by activity type, like displaying data or optimizing performance. Each section includes methods associated with the activity type, including examples. Browse our API below and click to learn more about any of our available commands! 🎈 Display almost anything Write and magic st.writeWrite arguments to the app.st.write("Hello **world**!") st.write(my_data_frame) st.write(my_mpl_figure) st.write_streamWrite generators or streams to the app with a typewriter effect.st.write_stream(my_generator) st.write_stream(my_llm_stream) MagicAny time Streamlit sees either a variable or literal value on its own line, it automatically writes that to your app using st.write"Hello **world**!" my_data_frame my_mpl_figure Text elements MarkdownDisplay string formatted as Markdown.st.markdown("Hello **world**!") TitleDisplay text in title formatting.st.title("The app title") HeaderDisplay text in header formatting.st.header("This is a header") SubheaderDisplay text in subheader formatting.st.subheader("This is a subheader") CaptionDisplay text in small font.st.caption("This is written small caption text") Code blockDisplay a code block with optional syntax highlighting.st.code("a = 1234") EchoDisplay some code in the app, then execute it. Useful for tutorials.with st.echo(): st.write('This code will be printed') LaTeXDisplay mathematical expressions formatted as LaTeX.st.latex("\int a x^2 \,dx") Preformatted textWrite fixed-width and preformatted text.st.text("Hello world") DividerDisplay a horizontal rule.st.divider() Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration! PreviousTagsAdd tags to your Streamlit apps. Created by @gagan3012.st_tags(label='# Enter Keywords:', text='Press enter to add more', value=['Zero', 'One', 'Two'], suggestions=['five', 'six', 'seven', 'eight', 'nine', 'three', 'eleven', 'ten', 'four'], maxtags = 4, key='1') NLUApply text mining on a dataframe. Created by @JohnSnowLabs.nlu.load('sentiment').predict('I love NLU! <3') Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.mention(label="An awesome Streamlit App", icon="streamlit", url="https://extras.streamlit.app",) Annotated textDisplay annotated text in Streamlit apps. Created by @tvst.annotated_text("This ", ("is", "verb"), " some ", ("annotated", "adj"), ("text", "noun"), " for those of ", ("you", "pronoun"), " who ", ("like", "verb"), " this sort of ", ("thing", "noun"), ".") Drawable CanvasProvides a sketching canvas using Fabric.js. Created by @andfanilo.st_canvas(fill_color="rgba(255, 165, 0, 0.3)", stroke_width=stroke_width, stroke_color=stroke_color, background_color=bg_color, background_image=Image.open(bg_image) if bg_image else None, update_streamlit=realtime_update, height=150, drawing_mode=drawing_mode, point_display_radius=point_display_radius if drawing_mode == 'point' else 0, key="canvas",) TagsAdd tags to your Streamlit apps. Created by @gagan3012.st_tags(label='# Enter Keywords:', text='Press enter to add more', value=['Zero', 'One', 'Two'], suggestions=['five', 'six', 'seven', 'eight', 'nine', 'three', 'eleven', 'ten', 'four'], maxtags = 4, key='1') NLUApply text mining on a dataframe. Created by @JohnSnowLabs.nlu.load('sentiment').predict('I love NLU! <3') Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.mention(label="An awesome Streamlit App", icon="streamlit", url="https://extras.streamlit.app",) Annotated textDisplay annotated text in Streamlit apps. Created by @tvst.annotated_text("This ", ("is", "verb"), " some ", ("annotated", "adj"), ("text", "noun"), " for those of ", ("you", "pronoun"), " who ", ("like", "verb"), " this sort of ", ("thing", "noun"), ".") Drawable CanvasProvides a sketching canvas using Fabric.js. Created by @andfanilo.st_canvas(fill_color="rgba(255, 165, 0, 0.3)", stroke_width=stroke_width, stroke_color=stroke_color, background_color=bg_color, background_image=Image.open(bg_image) if bg_image else None, update_streamlit=realtime_update, height=150, drawing_mode=drawing_mode, point_display_radius=point_display_radius if drawing_mode == 'point' else 0, key="canvas",) TagsAdd tags to your Streamlit apps. Created by @gagan3012.st_tags(label='# Enter Keywords:', text='Press enter to add more', value=['Zero', 'One', 'Two'], suggestions=['five', 'six', 'seven', 'eight', 'nine', 'three', 'eleven', 'ten', 'four'], maxtags = 4, key='1') NLUApply text mining on a dataframe. Created by @JohnSnowLabs.nlu.load('sentiment').predict('I love NLU! <3') Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.mention(label="An awesome Streamlit App", icon="streamlit", url="https://extras.streamlit.app",) Next Data elements DataframesDisplay a dataframe as an interactive table.st.dataframe(my_data_frame) Data editorDisplay a data editor widget.edited = st.data_editor(df, num_rows="dynamic") Column configurationConfigure the display and editing behavior of dataframes and data editors.st.column_config.NumberColumn("Price (in USD)", min_value=0, format="$%d") Static tablesDisplay a static table.st.table(my_data_frame) MetricsDisplay a metric in big bold font, with an optional indicator of how the metric changed.st.metric("My metric", 42, 2) Dicts and JSONDisplay object or string as a pretty-printed JSON string.st.json(my_dict) Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration! PreviousImage CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates value = streamlit_image_coordinates("https://placekitten.com/200/300") st.write(value) Plotly EventsMake Plotly charts interactive!. Created by @null-jones.from streamlit_plotly_events import plotly_events fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.metric_cards import style_metric_cards col3.metric(label="No Change", value=5000, delta=0) style_metric_cards() Streamlit AggridImplementation of Ag-Grid component for Streamlit. Created by @PablocFonseca.df = pd.DataFrame({'col1': [1, 2, 3], 'col2': [4, 5, 6]}) grid_return = AgGrid(df, editable=True) new_df = grid_return['data'] Streamlit FoliumStreamlit Component for rendering Folium maps. Created by @randyzwitch.m = folium.Map(location=[39.949610, -75.150282], zoom_start=16) folium.Marker([39.949610, -75.150282], popup="Liberty Bell", tooltip="Liberty Bell").add_to(m) st_data = st_folium(m, width=725) Pandas ProfilingPandas profiling component for Streamlit. Created by @okld.df = pd.read_csv("https://storage.googleapis.com/tf-datasets/titanic/train.csv") pr = df.profile_report() st_profile_report(pr) Image CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates value = streamlit_image_coordinates("https://placekitten.com/200/300") st.write(value) Plotly EventsMake Plotly charts interactive!. Created by @null-jones.from streamlit_plotly_events import plotly_events fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.metric_cards import style_metric_cards col3.metric(label="No Change", value=5000, delta=0) style_metric_cards() Streamlit AggridImplementation of Ag-Grid component for Streamlit. Created by @PablocFonseca.df = pd.DataFrame({'col1': [1, 2, 3], 'col2': [4, 5, 6]}) grid_return = AgGrid(df, editable=True) new_df = grid_return['data'] Streamlit FoliumStreamlit Component for rendering Folium maps. Created by @randyzwitch.m = folium.Map(location=[39.949610, -75.150282], zoom_start=16) folium.Marker([39.949610, -75.150282], popup="Liberty Bell", tooltip="Liberty Bell").add_to(m) st_data = st_folium(m, width=725) Pandas ProfilingPandas profiling component for Streamlit. Created by @okld.df = pd.read_csv("https://storage.googleapis.com/tf-datasets/titanic/train.csv") pr = df.profile_report() st_profile_report(pr) Image CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates value = streamlit_image_coordinates("https://placekitten.com/200/300") st.write(value) Plotly EventsMake Plotly charts interactive!. Created by @null-jones.from streamlit_plotly_events import plotly_events fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.metric_cards import style_metric_cards col3.metric(label="No Change", value=5000, delta=0) style_metric_cards() Next Chart elements Simple area chartsDisplay an area chart.st.area_chart(my_data_frame) Simple bar chartsDisplay a bar chart.st.bar_chart(my_data_frame) Simple line chartsDisplay a line chart.st.line_chart(my_data_frame) Simple scatter chartsDisplay a line chart.st.scatter_chart(my_data_frame) Scatterplots on mapsDisplay a map with points on it.st.map(my_data_frame) MatplotlibDisplay a matplotlib.pyplot figure.st.pyplot(my_mpl_figure) AltairDisplay a chart using the Altair library.st.altair_chart(my_altair_chart) Vega-LiteDisplay a chart using the Vega-Lite library.st.vega_lite_chart(my_vega_lite_chart) PlotlyDisplay an interactive Plotly chart.st.plotly_chart(my_plotly_chart) BokehDisplay an interactive Bokeh chart.st.bokeh_chart(my_bokeh_chart) PyDeckDisplay a chart using the PyDeck library.st.pydeck_chart(my_pydeck_chart) GraphVizDisplay a graph using the dagre-d3 library.st.graphviz_chart(my_graphviz_spec) Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration! PreviousStreamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl("https://assets5.lottiefiles.com/packages/lf20_V9t630.json") st_lottie(lottie_hello, key="hello") Plotly EventsMake Plotly charts interactive!. Created by @null-jones.fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.chart += get_annotations_chart(annotations=[("Mar 01, 2008", "Pretty good day for GOOG"), ("Dec 01, 2007", "Something's going wrong for GOOG & AAPL"), ("Nov 01, 2008", "Market starts again thanks to..."), ("Dec 01, 2009", "Small crash for GOOG after..."),],) st.altair_chart(chart, use_container_width=True) PlostA deceptively simple plotting library for Streamlit. Created by @tvst.import plost plost.line_chart(my_dataframe, x='time', y='stock_value', color='stock_name',) HiPlotHigh dimensional Interactive Plotting. Created by @facebookresearch.data = [{'dropout':0.1, 'lr': 0.001, 'loss': 10.0, 'optimizer': 'SGD'}, {'dropout':0.15, 'lr': 0.01, 'loss': 3.5, 'optimizer': 'Adam'}, {'dropout':0.3, 'lr': 0.1, 'loss': 4.5, 'optimizer': 'Adam'}] hip.Experiment.from_iterable(data).display() EChartsHigh dimensional Interactive Plotting. Created by @andfanilo.from streamlit_echarts import st_echarts st_echarts(options=options) Streamlit FoliumStreamlit Component for rendering Folium maps. Created by @randyzwitch.m = folium.Map(location=[39.949610, -75.150282], zoom_start=16) st_data = st_folium(m, width=725) Spacy-StreamlitspaCy building blocks and visualizers for Streamlit apps. Created by @explosion.models = ["en_core_web_sm", "en_core_web_md"] spacy_streamlit.visualize(models, "Sundar Pichai is the CEO of Google.") Streamlit AgraphA Streamlit Graph Vis, based on react-grah-vis. Created by @ChrisDelClea.from streamlit_agraph import agraph, Node, Edge, Config agraph(nodes=nodes, edges=edges, config=config) Streamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl("https://assets5.lottiefiles.com/packages/lf20_V9t630.json") st_lottie(lottie_hello, key="hello") Plotly EventsMake Plotly charts interactive!. Created by @null-jones.fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.chart += get_annotations_chart(annotations=[("Mar 01, 2008", "Pretty good day for GOOG"), ("Dec 01, 2007", "Something's going wrong for GOOG & AAPL"), ("Nov 01, 2008", "Market starts again thanks to..."), ("Dec 01, 2009", "Small crash for GOOG after..."),],) st.altair_chart(chart, use_container_width=True) PlostA deceptively simple plotting library for Streamlit. Created by @tvst.import plost plost.line_chart(my_dataframe, x='time', y='stock_value', color='stock_name',) HiPlotHigh dimensional Interactive Plotting. Created by @facebookresearch.data = [{'dropout':0.1, 'lr': 0.001, 'loss': 10.0, 'optimizer': 'SGD'}, {'dropout':0.15, 'lr': 0.01, 'loss': 3.5, 'optimizer': 'Adam'}, {'dropout':0.3, 'lr': 0.1, 'loss': 4.5, 'optimizer': 'Adam'}] hip.Experiment.from_iterable(data).display() EChartsHigh dimensional Interactive Plotting. Created by @andfanilo.from streamlit_echarts import st_echarts st_echarts(options=options) Streamlit FoliumStreamlit Component for rendering Folium maps. Created by @randyzwitch.m = folium.Map(location=[39.949610, -75.150282], zoom_start=16) st_data = st_folium(m, width=725) Spacy-StreamlitspaCy building blocks and visualizers for Streamlit apps. Created by @explosion.models = ["en_core_web_sm", "en_core_web_md"] spacy_streamlit.visualize(models, "Sundar Pichai is the CEO of Google.") Streamlit AgraphA Streamlit Graph Vis, based on react-grah-vis. Created by @ChrisDelClea.from streamlit_agraph import agraph, Node, Edge, Config agraph(nodes=nodes, edges=edges, config=config) Streamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl("https://assets5.lottiefiles.com/packages/lf20_V9t630.json") st_lottie(lottie_hello, key="hello") Plotly EventsMake Plotly charts interactive!. Created by @null-jones.fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.chart += get_annotations_chart(annotations=[("Mar 01, 2008", "Pretty good day for GOOG"), ("Dec 01, 2007", "Something's going wrong for GOOG & AAPL"), ("Nov 01, 2008", "Market starts again thanks to..."), ("Dec 01, 2009", "Small crash for GOOG after..."),],) st.altair_chart(chart, use_container_width=True) Next Input widgets ButtonDisplay a button widget.clicked = st.button("Click me") Download buttonDisplay a download button widget.st.download_button("Download file", file) Form buttonDisplay a form submit button. For use with st.form.st.form_submit_button("Sign up") Link buttonDisplay a link button.st.link_button("Go to gallery", url) Page linkDisplay a link to another page in a multipage app.st.page_link("app.py", label="Home", icon="🏠") st.page_link("pages/profile.py", label="My profile") CheckboxDisplay a checkbox widget.selected = st.checkbox("I agree") Color pickerDisplay a color picker widget.color = st.color_picker("Pick a color") MultiselectDisplay a multiselect widget. The multiselect widget starts as empty.choices = st.multiselect("Buy", ["milk", "apples", "potatoes"]) RadioDisplay a radio button widget.choice = st.radio("Pick one", ["cats", "dogs"]) SelectboxDisplay a select widget.choice = st.selectbox("Pick one", ["cats", "dogs"]) Select-sliderDisplay a slider widget to select items from a list.size = st.select_slider("Pick a size", ["S", "M", "L"]) ToggleDisplay a toggle widget.activated = st.toggle("Activate") Number inputDisplay a numeric input widget.choice = st.number_input("Pick a number", 0, 10) SliderDisplay a slider widget.number = st.slider("Pick a number", 0, 100) Date inputDisplay a date input widget.date = st.date_input("Your birthday") Time inputDisplay a time input widget.time = st.time_input("Meeting time") Chat inputDisplay a chat input widget.prompt = st.chat_input("Say something") if prompt: st.write(f"The user has sent: {prompt}") Text-areaDisplay a multi-line text input widget.text = st.text_area("Text to translate") Text inputDisplay a single-line text input widget.name = st.text_input("First name") Data editorDisplay a data editor widget.edited = st.experimental_data_editor(df, num_rows="dynamic") File UploaderDisplay a file uploader widget.data = st.file_uploader("Upload a CSV") Camera inputDisplay a widget that allows users to upload images directly from a camera.image = st.camera_input("Take a picture") Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration! PreviousStreamlit ChatStreamlit Component for a Chatbot UI. Created by @AI-Yash.from streamlit_chat import message message("My message") message("Hello bot!", is_user=True) # align's the message to the right Streamlit Option MenuSelect a single item from a list of options in a menu. Created by @victoryhb.from streamlit_option_menu import option_menu option_menu("Main Menu", ["Home", 'Settings'], icons=['house', 'gear'], menu_icon="cast", default_index=1) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.stoggle import stoggle stoggle( "Click me!", """🥷 Surprise! Here's some additional content""",) Streamlit ElementsCreate a draggable and resizable dashboard in Streamlit. Created by @okls.from streamlit_elements import elements, mui, html with elements("new_element"): mui.Typography("Hello world") TagsAdd tags to your Streamlit apps. Created by @gagan3012.from streamlit_tags import st_tags st_tags(label='# Enter Keywords:', text='Press enter to add more', value=['Zero', 'One', 'Two'], suggestions=['five', 'six', 'seven', 'eight', 'nine', 'three', 'eleven', 'ten', 'four'], maxtags = 4, key='1') StqdmThe simplest way to handle a progress bar in streamlit app. Created by @Wirg.from stqdm import stqdm for _ in stqdm(range(50)): sleep(0.5) TimelineDisplay a Timeline in Streamlit apps using TimelineJS. Created by @innerdoc.from streamlit_timeline import timeline with open('example.json', "r") as f: timeline(f.read(), height=800) Camera input liveAlternative for st.camera_input which returns the webcam images live. Created by @blackary.from camera_input_live import camera_input_live image = camera_input_live() st.image(value) Streamlit AceAce editor component for Streamlit. Created by @okld.from streamlit_ace import st_ace content = st_ace() content Streamlit ChatStreamlit Component for a Chatbot UI. Created by @AI-Yash.from streamlit_chat import message message("My message") message("Hello bot!", is_user=True) # align's the message to the right Streamlit Option MenuSelect a single item from a list of options in a menu. Created by @victoryhb.from streamlit_option_menu import option_menu option_menu("Main Menu", ["Home", 'Settings'], icons=['house', 'gear'], menu_icon="cast", default_index=1) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.stoggle import stoggle stoggle( "Click me!", """🥷 Surprise! Here's some additional content""",) Streamlit ElementsCreate a draggable and resizable dashboard in Streamlit. Created by @okls.from streamlit_elements import elements, mui, html with elements("new_element"): mui.Typography("Hello world") TagsAdd tags to your Streamlit apps. Created by @gagan3012.from streamlit_tags import st_tags st_tags(label='# Enter Keywords:', text='Press enter to add more', value=['Zero', 'One', 'Two'], suggestions=['five', 'six', 'seven', 'eight', 'nine', 'three', 'eleven', 'ten', 'four'], maxtags = 4, key='1') StqdmThe simplest way to handle a progress bar in streamlit app. Created by @Wirg.from stqdm import stqdm for _ in stqdm(range(50)): sleep(0.5) TimelineDisplay a Timeline in Streamlit apps using TimelineJS. Created by @innerdoc.from streamlit_timeline import timeline with open('example.json', "r") as f: timeline(f.read(), height=800) Camera input liveAlternative for st.camera_input which returns the webcam images live. Created by @blackary.from camera_input_live import camera_input_live image = camera_input_live() st.image(value) Streamlit AceAce editor component for Streamlit. Created by @okld.from streamlit_ace import st_ace content = st_ace() content Streamlit ChatStreamlit Component for a Chatbot UI. Created by @AI-Yash.from streamlit_chat import message message("My message") message("Hello bot!", is_user=True) # align's the message to the right Streamlit Option MenuSelect a single item from a list of options in a menu. Created by @victoryhb.from streamlit_option_menu import option_menu option_menu("Main Menu", ["Home", 'Settings'], icons=['house', 'gear'], menu_icon="cast", default_index=1) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.stoggle import stoggle stoggle( "Click me!", """🥷 Surprise! Here's some additional content""",) Next Media elements ImageDisplay an image or list of images.st.image(numpy_array) st.image(image_bytes) st.image(file) st.image("https://example.com/myimage.jpg") AudioDisplay an audio player.st.audio(numpy_array) st.audio(audio_bytes) st.audio(file) st.audio("https://example.com/myaudio.mp3", format="audio/mp3") VideoDisplay a video player.st.video(numpy_array) st.video(video_bytes) st.video(file) st.video("https://example.com/myvideo.mp4", format="video/mp4") Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration! PreviousStreamlit CropperA simple image cropper for Streamlit. Created by @turner-anderson.from streamlit_cropper import st_cropper st_cropper(img, realtime_update=realtime_update, box_color=box_color, aspect_ratio=aspect_ratio) Image CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates streamlit_image_coordinates("https://placekitten.com/200/300") Streamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl("https://assets5.lottiefiles.com/packages/lf20_V9t630.json") st_lottie(lottie_hello, key="hello") Streamlit WebrtcHandling and transmitting real-time video/audio streams with Streamlit. Created by @whitphx.from streamlit_webrtc import webrtc_streamer webrtc_streamer(key="sample") Drawable CanvasProvides a sketching canvas using Fabric.js. Created by @andfanilo.from streamlit_drawable_canvas import st_canvas st_canvas(fill_color="rgba(255, 165, 0, 0.3)", stroke_width=stroke_width, stroke_color=stroke_color, background_color=bg_color, background_image=Image.open(bg_image) if bg_image else None, update_streamlit=realtime_update, height=150, drawing_mode=drawing_mode, point_display_radius=point_display_radius if drawing_mode == 'point' else 0, key="canvas",) Image ComparisonCompare images with a slider using JuxtaposeJS. Created by @fcakyon.from streamlit_image_comparison import image_comparison image_comparison(img1="image1.jpg", img2="image2.jpg",) Streamlit CropperA simple image cropper for Streamlit. Created by @turner-anderson.from streamlit_cropper import st_cropper st_cropper(img, realtime_update=realtime_update, box_color=box_color, aspect_ratio=aspect_ratio) Image CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates streamlit_image_coordinates("https://placekitten.com/200/300") Streamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl("https://assets5.lottiefiles.com/packages/lf20_V9t630.json") st_lottie(lottie_hello, key="hello") Streamlit WebrtcHandling and transmitting real-time video/audio streams with Streamlit. Created by @whitphx.from streamlit_webrtc import webrtc_streamer webrtc_streamer(key="sample") Drawable CanvasProvides a sketching canvas using Fabric.js. Created by @andfanilo.from streamlit_drawable_canvas import st_canvas st_canvas(fill_color="rgba(255, 165, 0, 0.3)", stroke_width=stroke_width, stroke_color=stroke_color, background_color=bg_color, background_image=Image.open(bg_image) if bg_image else None, update_streamlit=realtime_update, height=150, drawing_mode=drawing_mode, point_display_radius=point_display_radius if drawing_mode == 'point' else 0, key="canvas",) Image ComparisonCompare images with a slider using JuxtaposeJS. Created by @fcakyon.from streamlit_image_comparison import image_comparison image_comparison(img1="image1.jpg", img2="image2.jpg",) Streamlit CropperA simple image cropper for Streamlit. Created by @turner-anderson.from streamlit_cropper import st_cropper st_cropper(img, realtime_update=realtime_update, box_color=box_color, aspect_ratio=aspect_ratio) Image CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates streamlit_image_coordinates("https://placekitten.com/200/300") Streamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl("https://assets5.lottiefiles.com/packages/lf20_V9t630.json") st_lottie(lottie_hello, key="hello") Next Layouts and containers ColumnsInsert containers laid out as side-by-side columns.col1, col2 = st.columns(2) col1.write("this is column 1") col2.write("this is column 2") ContainerInsert a multi-element container.c = st.container() st.write("This will show last") c.write("This will show first") c.write("This will show second") Modal dialogsInsert a modal dialog that can rerun independently from the rest of the script.@st.experimental_dialog("Sign up") def email_form(): name = st.text_input("Name") email = st.text_input("Email") EmptyInsert a single-element container.c = st.empty() st.write("This will show last") c.write("This will be replaced") c.write("This will show first") ExpanderInsert a multi-element container that can be expanded/collapsed.with st.expander("Open to see more"): st.write("This is more content") PopoverInsert a multi-element popover container that can be opened/closed.with st.popover("Settings"): st.checkbox("Show completed") SidebarDisplay items in a sidebar.st.sidebar.write("This lives in the sidebar") st.sidebar.button("Click me!") TabsInsert containers separated into tabs.tab1, tab2 = st.tabs(["Tab 1", "Tab2"]) tab1.write("this is tab 1") tab2.write("this is tab 2") Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration!Streamlit ElementsCreate a draggable and resizable dashboard in Streamlit. Created by @okls.from streamlit_elements import elements, mui, html with elements("new_element"): mui.Typography("Hello world") PydanticAuto-generate Streamlit UI from Pydantic Models and Dataclasses. Created by @lukasmasuch.import streamlit_pydantic as sp sp.pydantic_form(key="my_form", model=ExampleModel) Streamlit PagesAn experimental version of Streamlit Multi-Page Apps. Created by @blackary.from st_pages import Page, show_pages, add_page_title show_pages([ Page("streamlit_app.py", "Home", "🏠"), Page("other_pages/page2.py", "Page 2", ":books:"), ]) Chat elements Streamlit provides a few commands to help you build conversational apps. These chat elements are designed to be used in conjunction with each other, but you can also use them separately. st.chat_message lets you insert a chat message container into the app so you can display messages from the user or the app. Chat containers can contain other Streamlit elements, including charts, tables, text, and more. st.chat_input lets you display a chat input widget so the user can type in a message. Chat inputDisplay a chat input widget.prompt = st.chat_input("Say something") if prompt: st.write(f"The user has sent: {prompt}") Chat messageInsert a chat message container.import numpy as np with st.chat_message("user"): st.write("Hello 👋") st.line_chart(np.random.randn(30, 3)) Status containerDisplay output of long-running tasks in a container.with st.status('Running'): do_something_slow() st.write_streamWrite generators or streams to the app with a typewriter effect.st.write_stream(my_generator) st.write_stream(my_llm_stream) Status elements Progress barDisplay a progress bar.for i in range(101): st.progress(i) do_something_slow() SpinnerTemporarily displays a message while executing a block of code.with st.spinner("Please wait..."): do_something_slow() Status containerDisplay output of long-running tasks in a container.with st.status('Running'): do_something_slow() ToastBriefly displays a toast message in the bottom-right corner.st.toast('Butter!', icon='🧈') BalloonsDisplay celebratory balloons!do_something() # Celebrate when all done! st.balloons() SnowflakesDisplay celebratory snowflakes!do_something() # Celebrate when all done! st.snow() Success boxDisplay a success message.st.success("Match found!") Info boxDisplay an informational message.st.info("Dataset is updated every day at midnight.") Warning boxDisplay warning message.st.warning("Unable to fetch image. Skipping...") Error boxDisplay error message.st.error("We encountered an error") Exception outputDisplay an exception.e = RuntimeError("This is an exception of type RuntimeError") st.exception(e) Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration!StqdmThe simplest way to handle a progress bar in streamlit app. Created by @Wirg.from stqdm import stqdm for _ in stqdm(range(50)): sleep(0.5) Custom notification boxA custom notification box with the ability to close it out. Created by @Socvest.from streamlit_custom_notification_box import custom_notification_box styles = {'material-icons':{'color': 'red'}, 'text-icon-link-close-container': {'box-shadow': '#3896de 0px 4px'}, 'notification-text': {'':''}, 'close-button':{'':''}, 'link':{'':''}} custom_notification_box(icon='info', textDisplay='We are almost done with your registration...', externalLink='more info', url='#', styles=styles, key="foo") Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.let_it_rain import rain rain(emoji="🎈", font_size=54, falling_speed=5, animation_length="infinite",) App logic and configuration Navigation and pages Switch pageProgrammatically navigates to a specified page.st.switch_page("pages/my_page.py") Page linkDisplay a link to another page in a multipage app.st.page_link("app.py", label="Home", icon="🏠") st.page_link("pages/profile.py", label="My profile") Execution flow Modal dialogsInsert a modal dialog that can rerun independently from the rest of the script.@st.experimental_dialog("Sign up") def email_form(): name = st.text_input("Name") email = st.text_input("Email") FormsCreate a form that batches elements together with a “Submit" button.with st.form(key='my_form'): name = st.text_input("Name") email = st.text_input("Email") st.form_submit_button("Sign up") Partial rerunsDefine a fragment to rerun independently from the rest of the script.@st.experimental_fragment(run_every="10s") def fragment(): df = get_data() st.line_chart(df) Rerun scriptRerun the script immediately.st.rerun() Stop executionStops execution immediately.st.stop() Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration!AutorefreshForce a refresh without tying up a script. Created by @kmcgrady.from streamlit_autorefresh import st_autorefresh st_autorefresh(interval=2000, limit=100, key="fizzbuzzcounter") PydanticAuto-generate Streamlit UI from Pydantic Models and Dataclasses. Created by @lukasmasuch.import streamlit_pydantic as sp sp.pydantic_form(key="my_form", model=ExampleModel) Streamlit PagesAn experimental version of Streamlit Multi-Page Apps. Created by @blackary.from st_pages import Page, show_pages, add_page_title show_pages([ Page("streamlit_app.py", "Home", "🏠"), Page("other_pages/page2.py", "Page 2", ":books:"), ]) Caching and state Cache dataFunction decorator to cache functions that return data (e.g. dataframe transforms, database queries, ML inference).@st.cache_data def long_function(param1, param2): # Perform expensive computation here or # fetch data from the web here return data Cache resourceFunction decorator to cache functions that return global resources (e.g. database connections, ML models).@st.cache_resource def init_model(): # Return a global resource here return pipeline( "sentiment-analysis", model="distilbert-base-uncased-finetuned-sst-2-english" ) Session stateSession state is a way to share variables between reruns, for each user session.st.session_state['key'] = value Query parametersGet, set, or clear the query parameters that are shown in the browser's URL bar.st.query_params[key] = value st.query_params.clear() Connections and databases Setup your connection Create a connectionConnect to a data source or APIconn = st.connection('pets_db', type='sql') pet_owners = conn.query('select * from pet_owners') st.dataframe(pet_owners) Built-in connections SnowflakeConnectionA connection to Snowflake.conn = st.connection('snowflake') SQLConnectionA connection to a SQL database using SQLAlchemy.conn = st.connection('sql') Build your own connections Connection base classBuild your own connection with BaseConnection.class MyConnection(BaseConnection[myconn.MyConnection]): def _connect(self, **kwargs) -> MyConnection: return myconn.connect(**self._secrets, **kwargs) def query(self, query): return self._instance.query(query) Secrets management Secrets singletonAccess secrets from a local TOML file.key = st.secrets["OpenAI_key"] Secrets fileSave your secrets in a per-project or per-profile TOML file.OpenAI_key = "<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/custom-components/st.components.v1.html
DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceremovePAGE ELEMENTSWrite and magicaddText elementsaddData elementsaddChart elementsaddInput widgetsaddMedia elementsaddLayouts and containersaddChat elementsaddStatus elementsaddThird-party componentsopen_in_newAPPLICATION LOGICNavigation and pagesaddExecution flowaddCaching and stateaddConnections and secretsaddCustom componentsremovest.components.v1​.declare_componentst.components.v1.htmlst.components.v1.iframeUtilitiesaddConfigurationaddTOOLSApp testingaddCommand lineaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Develop/API reference/Custom components/st.components.v1.htmlst.components.v1.htmlStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeDisplay an HTML string in an iframe. Function signature[source] st.components.v1.html(html, width=None, height=None, scrolling=False) Parameters html (str) The HTML string to embed in the iframe. width (int) The width of the frame in CSS pixels. Defaults to the app's default element width. height (int) The height of the frame in CSS pixels. Defaults to 150. scrolling (bool) If True, show a scrollbar when the content is larger than the iframe. Otherwise, do not show a scrollbar. Defaults to False. Example import streamlit as st import streamlit.components.v1 as components # bootstrap 4 collapse example components.html( """ <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, ) Previous: st.components.v1​.declare_componentNext: st.components.v1.iframeforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy
https://docs.streamlit.io/develop/tutorials/databases/gcs
DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceaddTutorialsremoveExecution flowaddConnect to data sourcesremoveAWS S3BigQueryDeta BaseFirestoreopen_in_newGoogle Cloud StorageMicrosoft SQL ServerMongoDBMySQLNeonPostgreSQLPrivate Google SheetPublic Google SheetSnowflakeSupabaseTableauTiDBTigerGraphMultipage appsaddWork with LLMsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Develop/Tutorials/Connect to data sources/Google Cloud StorageConnect Streamlit to Google Cloud Storage Introduction This guide explains how to securely access files on Google Cloud Storage from Streamlit Community Cloud. It uses Streamlit FilesConnection, the gcsfs library and Streamlit's Secrets management. Create a Google Cloud Storage bucket and add a file push_pinNoteIf you already have a bucket that you want to use, feel free to skip to the next step. First, sign up for Google Cloud Platform or log in. Go to the Google Cloud Storage console and create a new bucket. Navigate to the upload section of your new bucket: And upload the following CSV file, which contains some example data: myfile.csv Enable the Google Cloud Storage API The Google Cloud Storage API is enabled by default when you create a project through the Google Cloud Console or CLI. Feel free to skip to the next step. If you do need to enable the API for programmatic access in your project, head over to the APIs & Services dashboard (select or create a project if asked). Search for the Cloud Storage API and enable it. The screenshot below has a blue "Manage" button and indicates the "API is enabled" which means no further action needs to be taken. This is very likely what you have since the API is enabled by default. However, if that is not what you see and you have an "Enable" button, you'll need to enable the API: Create a service account and key file To use the Google Cloud Storage API from Streamlit, you need a Google Cloud Platform service account (a special type for programmatic data access). Go to the Service Accounts page and create an account with Viewer permission. push_pinNoteIf the button CREATE SERVICE ACCOUNT is gray, you don't have the correct permissions. Ask the admin of your Google Cloud project for help. After clicking DONE, you should be back on the service accounts overview. Create a JSON key file for the new account and download it: Add the key to your local app secrets Your local Streamlit app will read secrets from a file .streamlit/secrets.toml in your app's root directory. Create this file if it doesn't exist yet and add the access key to it as shown below: # .streamlit/secrets.toml [connections.gcs] type = "service_account" project_id = "xxx" private_key_id = "xxx" private_key = "xxx" client_email = "xxx" client_id = "xxx" auth_uri = "https://accounts.google.com/o/oauth2/auth" token_uri = "https://oauth2.googleapis.com/token" auth_provider_x509_cert_url = "https://www.googleapis.com/oauth2/v1/certs" client_x509_cert_url = "xxx" priority_highImportantAdd this file to .gitignore and don't commit it to your GitHub repo! Copy your app secrets to the cloud As the secrets.toml file above is not committed to GitHub, you need to pass its content to your deployed app (on Streamlit Community Cloud) separately. Go to the app dashboard and in the app's dropdown menu, click on Edit Secrets. Copy the content of secrets.toml into the text area. More information is available at Secrets management. Add FilesConnection and gcsfs to your requirements file Add the FilesConnection and gcsfs packages to your requirements.txt file, preferably pinning the versions (replace x.x.x with the version you want installed): # requirements.txt gcsfs==x.x.x st-files-connection Write your Streamlit app Copy the code below to your Streamlit app and run it. Make sure to adapt the name of your bucket and file. Note that Streamlit automatically turns the access keys from your secrets file into environment variables. # streamlit_app.py import streamlit as st from st_files_connection import FilesConnection # Create connection object and retrieve file contents. # Specify input format is a csv and to cache the result for 600 seconds. conn = st.connection('gcs', type=FilesConnection) df = conn.read("streamlit-bucket/myfile.csv", input_format="csv", ttl=600) # Print results. for row in df.itertuples(): st.write(f"{row.Owner} has a :{row.Pet}:") See st.connection above? This handles secrets retrieval, setup, result caching and retries. By default, read() results are cached without expiring. In this case, we set ttl=600 to ensure the file contents is cached for no longer than 10 minutes. You can also set ttl=0 to disable caching. Learn more in Caching. If everything worked out (and you used the example file given above), your app should look like this: Previous: FirestoreNext: Microsoft SQL ServerforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy
https://docs.streamlit.io/en/latest/api.html#streamlit.write
DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceremovePAGE ELEMENTSWrite and magicaddText elementsaddData elementsaddChart elementsaddInput widgetsaddMedia elementsaddLayouts and containersaddChat elementsaddStatus elementsaddThird-party componentsopen_in_newAPPLICATION LOGICNavigation and pagesaddExecution flowaddCaching and stateaddConnections and secretsaddCustom componentsaddUtilitiesaddConfigurationaddTOOLSApp testingaddCommand lineaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Develop/API referenceAPI reference Streamlit makes it easy for you to visualize, mutate, and share data. The API reference is organized by activity type, like displaying data or optimizing performance. Each section includes methods associated with the activity type, including examples. Browse our API below and click to learn more about any of our available commands! 🎈 Display almost anything Write and magic st.writeWrite arguments to the app.st.write("Hello **world**!") st.write(my_data_frame) st.write(my_mpl_figure) st.write_streamWrite generators or streams to the app with a typewriter effect.st.write_stream(my_generator) st.write_stream(my_llm_stream) MagicAny time Streamlit sees either a variable or literal value on its own line, it automatically writes that to your app using st.write"Hello **world**!" my_data_frame my_mpl_figure Text elements MarkdownDisplay string formatted as Markdown.st.markdown("Hello **world**!") TitleDisplay text in title formatting.st.title("The app title") HeaderDisplay text in header formatting.st.header("This is a header") SubheaderDisplay text in subheader formatting.st.subheader("This is a subheader") CaptionDisplay text in small font.st.caption("This is written small caption text") Code blockDisplay a code block with optional syntax highlighting.st.code("a = 1234") EchoDisplay some code in the app, then execute it. Useful for tutorials.with st.echo(): st.write('This code will be printed') LaTeXDisplay mathematical expressions formatted as LaTeX.st.latex("\int a x^2 \,dx") Preformatted textWrite fixed-width and preformatted text.st.text("Hello world") DividerDisplay a horizontal rule.st.divider() Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration! PreviousTagsAdd tags to your Streamlit apps. Created by @gagan3012.st_tags(label='# Enter Keywords:', text='Press enter to add more', value=['Zero', 'One', 'Two'], suggestions=['five', 'six', 'seven', 'eight', 'nine', 'three', 'eleven', 'ten', 'four'], maxtags = 4, key='1') NLUApply text mining on a dataframe. Created by @JohnSnowLabs.nlu.load('sentiment').predict('I love NLU! <3') Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.mention(label="An awesome Streamlit App", icon="streamlit", url="https://extras.streamlit.app",) Annotated textDisplay annotated text in Streamlit apps. Created by @tvst.annotated_text("This ", ("is", "verb"), " some ", ("annotated", "adj"), ("text", "noun"), " for those of ", ("you", "pronoun"), " who ", ("like", "verb"), " this sort of ", ("thing", "noun"), ".") Drawable CanvasProvides a sketching canvas using Fabric.js. Created by @andfanilo.st_canvas(fill_color="rgba(255, 165, 0, 0.3)", stroke_width=stroke_width, stroke_color=stroke_color, background_color=bg_color, background_image=Image.open(bg_image) if bg_image else None, update_streamlit=realtime_update, height=150, drawing_mode=drawing_mode, point_display_radius=point_display_radius if drawing_mode == 'point' else 0, key="canvas",) TagsAdd tags to your Streamlit apps. Created by @gagan3012.st_tags(label='# Enter Keywords:', text='Press enter to add more', value=['Zero', 'One', 'Two'], suggestions=['five', 'six', 'seven', 'eight', 'nine', 'three', 'eleven', 'ten', 'four'], maxtags = 4, key='1') NLUApply text mining on a dataframe. Created by @JohnSnowLabs.nlu.load('sentiment').predict('I love NLU! <3') Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.mention(label="An awesome Streamlit App", icon="streamlit", url="https://extras.streamlit.app",) Annotated textDisplay annotated text in Streamlit apps. Created by @tvst.annotated_text("This ", ("is", "verb"), " some ", ("annotated", "adj"), ("text", "noun"), " for those of ", ("you", "pronoun"), " who ", ("like", "verb"), " this sort of ", ("thing", "noun"), ".") Drawable CanvasProvides a sketching canvas using Fabric.js. Created by @andfanilo.st_canvas(fill_color="rgba(255, 165, 0, 0.3)", stroke_width=stroke_width, stroke_color=stroke_color, background_color=bg_color, background_image=Image.open(bg_image) if bg_image else None, update_streamlit=realtime_update, height=150, drawing_mode=drawing_mode, point_display_radius=point_display_radius if drawing_mode == 'point' else 0, key="canvas",) TagsAdd tags to your Streamlit apps. Created by @gagan3012.st_tags(label='# Enter Keywords:', text='Press enter to add more', value=['Zero', 'One', 'Two'], suggestions=['five', 'six', 'seven', 'eight', 'nine', 'three', 'eleven', 'ten', 'four'], maxtags = 4, key='1') NLUApply text mining on a dataframe. Created by @JohnSnowLabs.nlu.load('sentiment').predict('I love NLU! <3') Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.mention(label="An awesome Streamlit App", icon="streamlit", url="https://extras.streamlit.app",) Next Data elements DataframesDisplay a dataframe as an interactive table.st.dataframe(my_data_frame) Data editorDisplay a data editor widget.edited = st.data_editor(df, num_rows="dynamic") Column configurationConfigure the display and editing behavior of dataframes and data editors.st.column_config.NumberColumn("Price (in USD)", min_value=0, format="$%d") Static tablesDisplay a static table.st.table(my_data_frame) MetricsDisplay a metric in big bold font, with an optional indicator of how the metric changed.st.metric("My metric", 42, 2) Dicts and JSONDisplay object or string as a pretty-printed JSON string.st.json(my_dict) Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration! PreviousImage CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates value = streamlit_image_coordinates("https://placekitten.com/200/300") st.write(value) Plotly EventsMake Plotly charts interactive!. Created by @null-jones.from streamlit_plotly_events import plotly_events fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.metric_cards import style_metric_cards col3.metric(label="No Change", value=5000, delta=0) style_metric_cards() Streamlit AggridImplementation of Ag-Grid component for Streamlit. Created by @PablocFonseca.df = pd.DataFrame({'col1': [1, 2, 3], 'col2': [4, 5, 6]}) grid_return = AgGrid(df, editable=True) new_df = grid_return['data'] Streamlit FoliumStreamlit Component for rendering Folium maps. Created by @randyzwitch.m = folium.Map(location=[39.949610, -75.150282], zoom_start=16) folium.Marker([39.949610, -75.150282], popup="Liberty Bell", tooltip="Liberty Bell").add_to(m) st_data = st_folium(m, width=725) Pandas ProfilingPandas profiling component for Streamlit. Created by @okld.df = pd.read_csv("https://storage.googleapis.com/tf-datasets/titanic/train.csv") pr = df.profile_report() st_profile_report(pr) Image CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates value = streamlit_image_coordinates("https://placekitten.com/200/300") st.write(value) Plotly EventsMake Plotly charts interactive!. Created by @null-jones.from streamlit_plotly_events import plotly_events fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.metric_cards import style_metric_cards col3.metric(label="No Change", value=5000, delta=0) style_metric_cards() Streamlit AggridImplementation of Ag-Grid component for Streamlit. Created by @PablocFonseca.df = pd.DataFrame({'col1': [1, 2, 3], 'col2': [4, 5, 6]}) grid_return = AgGrid(df, editable=True) new_df = grid_return['data'] Streamlit FoliumStreamlit Component for rendering Folium maps. Created by @randyzwitch.m = folium.Map(location=[39.949610, -75.150282], zoom_start=16) folium.Marker([39.949610, -75.150282], popup="Liberty Bell", tooltip="Liberty Bell").add_to(m) st_data = st_folium(m, width=725) Pandas ProfilingPandas profiling component for Streamlit. Created by @okld.df = pd.read_csv("https://storage.googleapis.com/tf-datasets/titanic/train.csv") pr = df.profile_report() st_profile_report(pr) Image CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates value = streamlit_image_coordinates("https://placekitten.com/200/300") st.write(value) Plotly EventsMake Plotly charts interactive!. Created by @null-jones.from streamlit_plotly_events import plotly_events fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.metric_cards import style_metric_cards col3.metric(label="No Change", value=5000, delta=0) style_metric_cards() Next Chart elements Simple area chartsDisplay an area chart.st.area_chart(my_data_frame) Simple bar chartsDisplay a bar chart.st.bar_chart(my_data_frame) Simple line chartsDisplay a line chart.st.line_chart(my_data_frame) Simple scatter chartsDisplay a line chart.st.scatter_chart(my_data_frame) Scatterplots on mapsDisplay a map with points on it.st.map(my_data_frame) MatplotlibDisplay a matplotlib.pyplot figure.st.pyplot(my_mpl_figure) AltairDisplay a chart using the Altair library.st.altair_chart(my_altair_chart) Vega-LiteDisplay a chart using the Vega-Lite library.st.vega_lite_chart(my_vega_lite_chart) PlotlyDisplay an interactive Plotly chart.st.plotly_chart(my_plotly_chart) BokehDisplay an interactive Bokeh chart.st.bokeh_chart(my_bokeh_chart) PyDeckDisplay a chart using the PyDeck library.st.pydeck_chart(my_pydeck_chart) GraphVizDisplay a graph using the dagre-d3 library.st.graphviz_chart(my_graphviz_spec) Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration! PreviousStreamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl("https://assets5.lottiefiles.com/packages/lf20_V9t630.json") st_lottie(lottie_hello, key="hello") Plotly EventsMake Plotly charts interactive!. Created by @null-jones.fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.chart += get_annotations_chart(annotations=[("Mar 01, 2008", "Pretty good day for GOOG"), ("Dec 01, 2007", "Something's going wrong for GOOG & AAPL"), ("Nov 01, 2008", "Market starts again thanks to..."), ("Dec 01, 2009", "Small crash for GOOG after..."),],) st.altair_chart(chart, use_container_width=True) PlostA deceptively simple plotting library for Streamlit. Created by @tvst.import plost plost.line_chart(my_dataframe, x='time', y='stock_value', color='stock_name',) HiPlotHigh dimensional Interactive Plotting. Created by @facebookresearch.data = [{'dropout':0.1, 'lr': 0.001, 'loss': 10.0, 'optimizer': 'SGD'}, {'dropout':0.15, 'lr': 0.01, 'loss': 3.5, 'optimizer': 'Adam'}, {'dropout':0.3, 'lr': 0.1, 'loss': 4.5, 'optimizer': 'Adam'}] hip.Experiment.from_iterable(data).display() EChartsHigh dimensional Interactive Plotting. Created by @andfanilo.from streamlit_echarts import st_echarts st_echarts(options=options) Streamlit FoliumStreamlit Component for rendering Folium maps. Created by @randyzwitch.m = folium.Map(location=[39.949610, -75.150282], zoom_start=16) st_data = st_folium(m, width=725) Spacy-StreamlitspaCy building blocks and visualizers for Streamlit apps. Created by @explosion.models = ["en_core_web_sm", "en_core_web_md"] spacy_streamlit.visualize(models, "Sundar Pichai is the CEO of Google.") Streamlit AgraphA Streamlit Graph Vis, based on react-grah-vis. Created by @ChrisDelClea.from streamlit_agraph import agraph, Node, Edge, Config agraph(nodes=nodes, edges=edges, config=config) Streamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl("https://assets5.lottiefiles.com/packages/lf20_V9t630.json") st_lottie(lottie_hello, key="hello") Plotly EventsMake Plotly charts interactive!. Created by @null-jones.fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.chart += get_annotations_chart(annotations=[("Mar 01, 2008", "Pretty good day for GOOG"), ("Dec 01, 2007", "Something's going wrong for GOOG & AAPL"), ("Nov 01, 2008", "Market starts again thanks to..."), ("Dec 01, 2009", "Small crash for GOOG after..."),],) st.altair_chart(chart, use_container_width=True) PlostA deceptively simple plotting library for Streamlit. Created by @tvst.import plost plost.line_chart(my_dataframe, x='time', y='stock_value', color='stock_name',) HiPlotHigh dimensional Interactive Plotting. Created by @facebookresearch.data = [{'dropout':0.1, 'lr': 0.001, 'loss': 10.0, 'optimizer': 'SGD'}, {'dropout':0.15, 'lr': 0.01, 'loss': 3.5, 'optimizer': 'Adam'}, {'dropout':0.3, 'lr': 0.1, 'loss': 4.5, 'optimizer': 'Adam'}] hip.Experiment.from_iterable(data).display() EChartsHigh dimensional Interactive Plotting. Created by @andfanilo.from streamlit_echarts import st_echarts st_echarts(options=options) Streamlit FoliumStreamlit Component for rendering Folium maps. Created by @randyzwitch.m = folium.Map(location=[39.949610, -75.150282], zoom_start=16) st_data = st_folium(m, width=725) Spacy-StreamlitspaCy building blocks and visualizers for Streamlit apps. Created by @explosion.models = ["en_core_web_sm", "en_core_web_md"] spacy_streamlit.visualize(models, "Sundar Pichai is the CEO of Google.") Streamlit AgraphA Streamlit Graph Vis, based on react-grah-vis. Created by @ChrisDelClea.from streamlit_agraph import agraph, Node, Edge, Config agraph(nodes=nodes, edges=edges, config=config) Streamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl("https://assets5.lottiefiles.com/packages/lf20_V9t630.json") st_lottie(lottie_hello, key="hello") Plotly EventsMake Plotly charts interactive!. Created by @null-jones.fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.chart += get_annotations_chart(annotations=[("Mar 01, 2008", "Pretty good day for GOOG"), ("Dec 01, 2007", "Something's going wrong for GOOG & AAPL"), ("Nov 01, 2008", "Market starts again thanks to..."), ("Dec 01, 2009", "Small crash for GOOG after..."),],) st.altair_chart(chart, use_container_width=True) Next Input widgets ButtonDisplay a button widget.clicked = st.button("Click me") Download buttonDisplay a download button widget.st.download_button("Download file", file) Form buttonDisplay a form submit button. For use with st.form.st.form_submit_button("Sign up") Link buttonDisplay a link button.st.link_button("Go to gallery", url) Page linkDisplay a link to another page in a multipage app.st.page_link("app.py", label="Home", icon="🏠") st.page_link("pages/profile.py", label="My profile") CheckboxDisplay a checkbox widget.selected = st.checkbox("I agree") Color pickerDisplay a color picker widget.color = st.color_picker("Pick a color") MultiselectDisplay a multiselect widget. The multiselect widget starts as empty.choices = st.multiselect("Buy", ["milk", "apples", "potatoes"]) RadioDisplay a radio button widget.choice = st.radio("Pick one", ["cats", "dogs"]) SelectboxDisplay a select widget.choice = st.selectbox("Pick one", ["cats", "dogs"]) Select-sliderDisplay a slider widget to select items from a list.size = st.select_slider("Pick a size", ["S", "M", "L"]) ToggleDisplay a toggle widget.activated = st.toggle("Activate") Number inputDisplay a numeric input widget.choice = st.number_input("Pick a number", 0, 10) SliderDisplay a slider widget.number = st.slider("Pick a number", 0, 100) Date inputDisplay a date input widget.date = st.date_input("Your birthday") Time inputDisplay a time input widget.time = st.time_input("Meeting time") Chat inputDisplay a chat input widget.prompt = st.chat_input("Say something") if prompt: st.write(f"The user has sent: {prompt}") Text-areaDisplay a multi-line text input widget.text = st.text_area("Text to translate") Text inputDisplay a single-line text input widget.name = st.text_input("First name") Data editorDisplay a data editor widget.edited = st.experimental_data_editor(df, num_rows="dynamic") File UploaderDisplay a file uploader widget.data = st.file_uploader("Upload a CSV") Camera inputDisplay a widget that allows users to upload images directly from a camera.image = st.camera_input("Take a picture") Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration! PreviousStreamlit ChatStreamlit Component for a Chatbot UI. Created by @AI-Yash.from streamlit_chat import message message("My message") message("Hello bot!", is_user=True) # align's the message to the right Streamlit Option MenuSelect a single item from a list of options in a menu. Created by @victoryhb.from streamlit_option_menu import option_menu option_menu("Main Menu", ["Home", 'Settings'], icons=['house', 'gear'], menu_icon="cast", default_index=1) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.stoggle import stoggle stoggle( "Click me!", """🥷 Surprise! Here's some additional content""",) Streamlit ElementsCreate a draggable and resizable dashboard in Streamlit. Created by @okls.from streamlit_elements import elements, mui, html with elements("new_element"): mui.Typography("Hello world") TagsAdd tags to your Streamlit apps. Created by @gagan3012.from streamlit_tags import st_tags st_tags(label='# Enter Keywords:', text='Press enter to add more', value=['Zero', 'One', 'Two'], suggestions=['five', 'six', 'seven', 'eight', 'nine', 'three', 'eleven', 'ten', 'four'], maxtags = 4, key='1') StqdmThe simplest way to handle a progress bar in streamlit app. Created by @Wirg.from stqdm import stqdm for _ in stqdm(range(50)): sleep(0.5) TimelineDisplay a Timeline in Streamlit apps using TimelineJS. Created by @innerdoc.from streamlit_timeline import timeline with open('example.json', "r") as f: timeline(f.read(), height=800) Camera input liveAlternative for st.camera_input which returns the webcam images live. Created by @blackary.from camera_input_live import camera_input_live image = camera_input_live() st.image(value) Streamlit AceAce editor component for Streamlit. Created by @okld.from streamlit_ace import st_ace content = st_ace() content Streamlit ChatStreamlit Component for a Chatbot UI. Created by @AI-Yash.from streamlit_chat import message message("My message") message("Hello bot!", is_user=True) # align's the message to the right Streamlit Option MenuSelect a single item from a list of options in a menu. Created by @victoryhb.from streamlit_option_menu import option_menu option_menu("Main Menu", ["Home", 'Settings'], icons=['house', 'gear'], menu_icon="cast", default_index=1) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.stoggle import stoggle stoggle( "Click me!", """🥷 Surprise! Here's some additional content""",) Streamlit ElementsCreate a draggable and resizable dashboard in Streamlit. Created by @okls.from streamlit_elements import elements, mui, html with elements("new_element"): mui.Typography("Hello world") TagsAdd tags to your Streamlit apps. Created by @gagan3012.from streamlit_tags import st_tags st_tags(label='# Enter Keywords:', text='Press enter to add more', value=['Zero', 'One', 'Two'], suggestions=['five', 'six', 'seven', 'eight', 'nine', 'three', 'eleven', 'ten', 'four'], maxtags = 4, key='1') StqdmThe simplest way to handle a progress bar in streamlit app. Created by @Wirg.from stqdm import stqdm for _ in stqdm(range(50)): sleep(0.5) TimelineDisplay a Timeline in Streamlit apps using TimelineJS. Created by @innerdoc.from streamlit_timeline import timeline with open('example.json', "r") as f: timeline(f.read(), height=800) Camera input liveAlternative for st.camera_input which returns the webcam images live. Created by @blackary.from camera_input_live import camera_input_live image = camera_input_live() st.image(value) Streamlit AceAce editor component for Streamlit. Created by @okld.from streamlit_ace import st_ace content = st_ace() content Streamlit ChatStreamlit Component for a Chatbot UI. Created by @AI-Yash.from streamlit_chat import message message("My message") message("Hello bot!", is_user=True) # align's the message to the right Streamlit Option MenuSelect a single item from a list of options in a menu. Created by @victoryhb.from streamlit_option_menu import option_menu option_menu("Main Menu", ["Home", 'Settings'], icons=['house', 'gear'], menu_icon="cast", default_index=1) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.stoggle import stoggle stoggle( "Click me!", """🥷 Surprise! Here's some additional content""",) Next Media elements ImageDisplay an image or list of images.st.image(numpy_array) st.image(image_bytes) st.image(file) st.image("https://example.com/myimage.jpg") AudioDisplay an audio player.st.audio(numpy_array) st.audio(audio_bytes) st.audio(file) st.audio("https://example.com/myaudio.mp3", format="audio/mp3") VideoDisplay a video player.st.video(numpy_array) st.video(video_bytes) st.video(file) st.video("https://example.com/myvideo.mp4", format="video/mp4") Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration! PreviousStreamlit CropperA simple image cropper for Streamlit. Created by @turner-anderson.from streamlit_cropper import st_cropper st_cropper(img, realtime_update=realtime_update, box_color=box_color, aspect_ratio=aspect_ratio) Image CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates streamlit_image_coordinates("https://placekitten.com/200/300") Streamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl("https://assets5.lottiefiles.com/packages/lf20_V9t630.json") st_lottie(lottie_hello, key="hello") Streamlit WebrtcHandling and transmitting real-time video/audio streams with Streamlit. Created by @whitphx.from streamlit_webrtc import webrtc_streamer webrtc_streamer(key="sample") Drawable CanvasProvides a sketching canvas using Fabric.js. Created by @andfanilo.from streamlit_drawable_canvas import st_canvas st_canvas(fill_color="rgba(255, 165, 0, 0.3)", stroke_width=stroke_width, stroke_color=stroke_color, background_color=bg_color, background_image=Image.open(bg_image) if bg_image else None, update_streamlit=realtime_update, height=150, drawing_mode=drawing_mode, point_display_radius=point_display_radius if drawing_mode == 'point' else 0, key="canvas",) Image ComparisonCompare images with a slider using JuxtaposeJS. Created by @fcakyon.from streamlit_image_comparison import image_comparison image_comparison(img1="image1.jpg", img2="image2.jpg",) Streamlit CropperA simple image cropper for Streamlit. Created by @turner-anderson.from streamlit_cropper import st_cropper st_cropper(img, realtime_update=realtime_update, box_color=box_color, aspect_ratio=aspect_ratio) Image CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates streamlit_image_coordinates("https://placekitten.com/200/300") Streamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl("https://assets5.lottiefiles.com/packages/lf20_V9t630.json") st_lottie(lottie_hello, key="hello") Streamlit WebrtcHandling and transmitting real-time video/audio streams with Streamlit. Created by @whitphx.from streamlit_webrtc import webrtc_streamer webrtc_streamer(key="sample") Drawable CanvasProvides a sketching canvas using Fabric.js. Created by @andfanilo.from streamlit_drawable_canvas import st_canvas st_canvas(fill_color="rgba(255, 165, 0, 0.3)", stroke_width=stroke_width, stroke_color=stroke_color, background_color=bg_color, background_image=Image.open(bg_image) if bg_image else None, update_streamlit=realtime_update, height=150, drawing_mode=drawing_mode, point_display_radius=point_display_radius if drawing_mode == 'point' else 0, key="canvas",) Image ComparisonCompare images with a slider using JuxtaposeJS. Created by @fcakyon.from streamlit_image_comparison import image_comparison image_comparison(img1="image1.jpg", img2="image2.jpg",) Streamlit CropperA simple image cropper for Streamlit. Created by @turner-anderson.from streamlit_cropper import st_cropper st_cropper(img, realtime_update=realtime_update, box_color=box_color, aspect_ratio=aspect_ratio) Image CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates streamlit_image_coordinates("https://placekitten.com/200/300") Streamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl("https://assets5.lottiefiles.com/packages/lf20_V9t630.json") st_lottie(lottie_hello, key="hello") Next Layouts and containers ColumnsInsert containers laid out as side-by-side columns.col1, col2 = st.columns(2) col1.write("this is column 1") col2.write("this is column 2") ContainerInsert a multi-element container.c = st.container() st.write("This will show last") c.write("This will show first") c.write("This will show second") Modal dialogsInsert a modal dialog that can rerun independently from the rest of the script.@st.experimental_dialog("Sign up") def email_form(): name = st.text_input("Name") email = st.text_input("Email") EmptyInsert a single-element container.c = st.empty() st.write("This will show last") c.write("This will be replaced") c.write("This will show first") ExpanderInsert a multi-element container that can be expanded/collapsed.with st.expander("Open to see more"): st.write("This is more content") PopoverInsert a multi-element popover container that can be opened/closed.with st.popover("Settings"): st.checkbox("Show completed") SidebarDisplay items in a sidebar.st.sidebar.write("This lives in the sidebar") st.sidebar.button("Click me!") TabsInsert containers separated into tabs.tab1, tab2 = st.tabs(["Tab 1", "Tab2"]) tab1.write("this is tab 1") tab2.write("this is tab 2") Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration!Streamlit ElementsCreate a draggable and resizable dashboard in Streamlit. Created by @okls.from streamlit_elements import elements, mui, html with elements("new_element"): mui.Typography("Hello world") PydanticAuto-generate Streamlit UI from Pydantic Models and Dataclasses. Created by @lukasmasuch.import streamlit_pydantic as sp sp.pydantic_form(key="my_form", model=ExampleModel) Streamlit PagesAn experimental version of Streamlit Multi-Page Apps. Created by @blackary.from st_pages import Page, show_pages, add_page_title show_pages([ Page("streamlit_app.py", "Home", "🏠"), Page("other_pages/page2.py", "Page 2", ":books:"), ]) Chat elements Streamlit provides a few commands to help you build conversational apps. These chat elements are designed to be used in conjunction with each other, but you can also use them separately. st.chat_message lets you insert a chat message container into the app so you can display messages from the user or the app. Chat containers can contain other Streamlit elements, including charts, tables, text, and more. st.chat_input lets you display a chat input widget so the user can type in a message. Chat inputDisplay a chat input widget.prompt = st.chat_input("Say something") if prompt: st.write(f"The user has sent: {prompt}") Chat messageInsert a chat message container.import numpy as np with st.chat_message("user"): st.write("Hello 👋") st.line_chart(np.random.randn(30, 3)) Status containerDisplay output of long-running tasks in a container.with st.status('Running'): do_something_slow() st.write_streamWrite generators or streams to the app with a typewriter effect.st.write_stream(my_generator) st.write_stream(my_llm_stream) Status elements Progress barDisplay a progress bar.for i in range(101): st.progress(i) do_something_slow() SpinnerTemporarily displays a message while executing a block of code.with st.spinner("Please wait..."): do_something_slow() Status containerDisplay output of long-running tasks in a container.with st.status('Running'): do_something_slow() ToastBriefly displays a toast message in the bottom-right corner.st.toast('Butter!', icon='🧈') BalloonsDisplay celebratory balloons!do_something() # Celebrate when all done! st.balloons() SnowflakesDisplay celebratory snowflakes!do_something() # Celebrate when all done! st.snow() Success boxDisplay a success message.st.success("Match found!") Info boxDisplay an informational message.st.info("Dataset is updated every day at midnight.") Warning boxDisplay warning message.st.warning("Unable to fetch image. Skipping...") Error boxDisplay error message.st.error("We encountered an error") Exception outputDisplay an exception.e = RuntimeError("This is an exception of type RuntimeError") st.exception(e) Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration!StqdmThe simplest way to handle a progress bar in streamlit app. Created by @Wirg.from stqdm import stqdm for _ in stqdm(range(50)): sleep(0.5) Custom notification boxA custom notification box with the ability to close it out. Created by @Socvest.from streamlit_custom_notification_box import custom_notification_box styles = {'material-icons':{'color': 'red'}, 'text-icon-link-close-container': {'box-shadow': '#3896de 0px 4px'}, 'notification-text': {'':''}, 'close-button':{'':''}, 'link':{'':''}} custom_notification_box(icon='info', textDisplay='We are almost done with your registration...', externalLink='more info', url='#', styles=styles, key="foo") Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.let_it_rain import rain rain(emoji="🎈", font_size=54, falling_speed=5, animation_length="infinite",) App logic and configuration Navigation and pages Switch pageProgrammatically navigates to a specified page.st.switch_page("pages/my_page.py") Page linkDisplay a link to another page in a multipage app.st.page_link("app.py", label="Home", icon="🏠") st.page_link("pages/profile.py", label="My profile") Execution flow Modal dialogsInsert a modal dialog that can rerun independently from the rest of the script.@st.experimental_dialog("Sign up") def email_form(): name = st.text_input("Name") email = st.text_input("Email") FormsCreate a form that batches elements together with a “Submit" button.with st.form(key='my_form'): name = st.text_input("Name") email = st.text_input("Email") st.form_submit_button("Sign up") Partial rerunsDefine a fragment to rerun independently from the rest of the script.@st.experimental_fragment(run_every="10s") def fragment(): df = get_data() st.line_chart(df) Rerun scriptRerun the script immediately.st.rerun() Stop executionStops execution immediately.st.stop() Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration!AutorefreshForce a refresh without tying up a script. Created by @kmcgrady.from streamlit_autorefresh import st_autorefresh st_autorefresh(interval=2000, limit=100, key="fizzbuzzcounter") PydanticAuto-generate Streamlit UI from Pydantic Models and Dataclasses. Created by @lukasmasuch.import streamlit_pydantic as sp sp.pydantic_form(key="my_form", model=ExampleModel) Streamlit PagesAn experimental version of Streamlit Multi-Page Apps. Created by @blackary.from st_pages import Page, show_pages, add_page_title show_pages([ Page("streamlit_app.py", "Home", "🏠"), Page("other_pages/page2.py", "Page 2", ":books:"), ]) Caching and state Cache dataFunction decorator to cache functions that return data (e.g. dataframe transforms, database queries, ML inference).@st.cache_data def long_function(param1, param2): # Perform expensive computation here or # fetch data from the web here return data Cache resourceFunction decorator to cache functions that return global resources (e.g. database connections, ML models).@st.cache_resource def init_model(): # Return a global resource here return pipeline( "sentiment-analysis", model="distilbert-base-uncased-finetuned-sst-2-english" ) Session stateSession state is a way to share variables between reruns, for each user session.st.session_state['key'] = value Query parametersGet, set, or clear the query parameters that are shown in the browser's URL bar.st.query_params[key] = value st.query_params.clear() Connections and databases Setup your connection Create a connectionConnect to a data source or APIconn = st.connection('pets_db', type='sql') pet_owners = conn.query('select * from pet_owners') st.dataframe(pet_owners) Built-in connections SnowflakeConnectionA connection to Snowflake.conn = st.connection('snowflake') SQLConnectionA connection to a SQL database using SQLAlchemy.conn = st.connection('sql') Build your own connections Connection base classBuild your own connection with BaseConnection.class MyConnection(BaseConnection[myconn.MyConnection]): def _connect(self, **kwargs) -> MyConnection: return myconn.connect(**self._secrets, **kwargs) def query(self, query): return self._instance.query(query) Secrets management Secrets singletonAccess secrets from a local TOML file.key = st.secrets["OpenAI_key"] Secrets fileSave your secrets in a per-project or per-profile TOML file.OpenAI_key = "<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/share-apps-with-viewers-outside-organization#invite-viewers-from-your-app-settings
DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudremoveGet startedaddDeploy your appaddManage your appaddShare your appremoveEmbed your appSearch indexabilityShare previewsManage your accountaddTroubleshootingStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Deploy/Streamlit Community Cloud/Share your appShare your app Now that your app is deployed you can easily share it and collaborate on it. But first, let's take a moment and do a little joy dance for getting that app deployed! 🕺💃 Your app is now live at a fixed URL, so go wild and share it with whomever you want. Your app will inherit permissions from your GitHub repo, meaning that if your repo is private your app will be private and if your repo is public your app will be public. If you want to change that you can simply do so from the app settings menu. You are only allowed one private app at a time. If you've deployed from a private repository, you will have to make that app public or delete it before you can deploy another app from a private repository. Only developers can change your app between public and private. Make your app public or private Share your public app Share your private app Make your app public or private If you deployed your app from a public repository, your app will be public by default. If you deployed your app from a private repository, you will need to make the app public if you want to freely share it with the community at large. Set privacy from your app settings Access your App settings and go to the "Sharing" section. Set your app's privacy under "Who can view this app." Select "This app is public and searchable" to make your app public. Select "Only specific people can view this app" to make your app private. Set privacy from the share button From your app at <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/develop/tutorials/databases/private-gsheet
DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceaddTutorialsremoveExecution flowaddConnect to data sourcesremoveAWS S3BigQueryDeta BaseFirestoreopen_in_newGoogle Cloud StorageMicrosoft SQL ServerMongoDBMySQLNeonPostgreSQLPrivate Google SheetPublic Google SheetSnowflakeSupabaseTableauTiDBTigerGraphMultipage appsaddWork with LLMsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Develop/Tutorials/Connect to data sources/Private Google SheetConnect Streamlit to a private Google Sheet Introduction This guide explains how to securely access a private Google Sheet from Streamlit Community Cloud. It uses st.connection, Streamlit GSheetsConnection, and Streamlit's Secrets management. If you are fine with enabling link sharing for your Google Sheet (i.e. everyone with the link can view it), the guide Connect Streamlit to a public Google Sheet shows a simpler method of doing this. If your Sheet contains sensitive information and you cannot enable link sharing, keep on reading. Prerequisites This tutorial requires streamlit>=1.28 and st-gsheets-connection in your Python environment. Create a Google Sheet If you already have a Sheet that you want to use, feel free to skip to the next step. Create a spreadsheet with this example data. namepetMarydogJohncatRobertbird Enable the Sheets API Programmatic access to Google Sheets is controlled through Google Cloud Platform. Create an account or sign in and head over to the APIs & Services dashboard (select or create a project if asked). As shown below, search for the Sheets API and enable it: Create a service account & key file To use the Sheets API from Streamlit Community Cloud, you need a Google Cloud Platform service account (a special account type for programmatic data access). Go to the Service Accounts page and create an account with the Viewer permission (this will let the account access data but not change it): push_pinNoteThe button "CREATE SERVICE ACCOUNT" is gray, you don't have the correct permissions. Ask the admin of your Google Cloud project for help. After clicking "DONE", you should be back on the service accounts overview. First, note down the email address of the account you just created (important for next step!). Then, create a JSON key file for the new account and download it: Share the Google Sheet with the service account By default, the service account you just created cannot access your Google Sheet. To give it access, click on the "Share" button in the Google Sheet, add the email of the service account (noted down in step 2), and choose the correct permission (if you just want to read the data, "Viewer" is enough): Add the key file to your local app secrets Your local Streamlit app will read secrets from a file .streamlit/secrets.toml in your app's root directory. Create this file if it doesn't exist yet and add the URL of your Google Sheet plus the content of the key file you downloaded to it as shown below: # .streamlit/secrets.toml [connections.gsheets] spreadsheet = "https://docs.google.com/spreadsheets/d/xxxxxxx/edit#gid=0" # From your JSON key file type = "service_account" project_id = "xxx" private_key_id = "xxx" private_key = "xxx" client_email = "xxx" client_id = "xxx" auth_uri = "https://accounts.google.com/o/oauth2/auth" token_uri = "https://oauth2.googleapis.com/token" auth_provider_x509_cert_url = "https://www.googleapis.com/oauth2/v1/certs" client_x509_cert_url = "xxx" priority_highImportantAdd this file to .gitignore and don't commit it to your GitHub repo! Write your Streamlit app Copy the code below to your Streamlit app and run it. # streamlit_app.py import streamlit as st from streamlit_gsheets import GSheetsConnection # Create a connection object. conn = st.connection("gsheets", type=GSheetsConnection) df = conn.read() # Print results. for row in df.itertuples(): st.write(f"{row.name} has a :{row.pet}:") See st.connection above? This handles secrets retrieval, setup, query caching and retries. By default, .read() results are cached without expiring. You can pass optional parameters to .read() to customize your connection. For example, you can specify the name of a worksheet, cache expiration time, or pass-through parameters for pandas.read_csv like this: df = conn.read( worksheet="Sheet1", ttl="10m", usecols=[0, 1], nrows=3, ) In this case, we set ttl="10m" to ensure the query result is cached for no longer than 10 minutes. You can also set ttl=0 to disable caching. Learn more in Caching. We've declared optional parameters usecols=[0,1] and nrows=3 for pandas to use under the hood. If everything worked out (and you used the example table we created above), your app should look like this: Connecting to a Google Sheet from Community Cloud This tutorial assumes a local Streamlit app, however you can also connect to Google Sheets from apps hosted in Community Cloud. The main additional steps are: Include information about dependencies using a requirements.txt file with st-gsheets-connection and any other dependencies. Add your secrets to your Community Cloud app. Previous: PostgreSQLNext: Public Google SheetforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy
https://docs.streamlit.io/develop/concepts/architecture/fragments#limitations-and-unsupported-behavior
DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsremoveCOREArchitecture & executionremoveRunning your appStreamlit's architectureThe app chromeCachingSession StateFormsFragmentsWidget behaviorMultipage appsaddApp designaddADDITIONALConnections and secretsaddCustom componentsaddConfiguration and themingaddApp testingaddAPI referenceaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Develop/Concepts/Architecture & execution/FragmentsWorking with fragments and partial reruns Reruns are a central part of every Streamlit app. When users interact with widgets, your script reruns from top to bottom, and your app's frontend is updated. Streamlit provides several features to help you develop your app within this execution model. Streamlit version 1.33.0 introduced fragments to allow rerunning a portion of your code instead of your full script. As your app grows larger and more complex, these partial reruns help your app be efficient and performant. Fragments give you finer, easy-to-understand control over your app's execution flow. Before you read about fragments, we recommend having a basic understanding of caching, Session State, and forms. Use cases for fragments Fragments are versatile and applicable to a wide variety of circumstances. Here are just a few, common scenarios where fragments are useful: Your app has multiple visualizations and each one takes time to load, but you have a filter input that only updates one of them. You have a dynamic form that doesn't need to update the rest of your app (until the form is complete). You want to automatically update a single component or group of components to stream data. Defining and calling a fragment Streamlit provides a decorator (st.experimental_fragment) to turn any function into a fragment function. When you call a fragment function that contains a widget function, a user triggers a partial rerun instead of a full rerun when they interact with that fragment's widget. During a partial rerun, your fragment function is re-executed. Anything within the main body of your fragment is updated on the frontend, while the rest of your app remains the same. We'll describe fragments written across multiple containers later on. Here is a basic example of defining and calling a fragment function. Just like with caching, remember to call your function after defining it. import streamlit as st @st.experimental_fragment def fragment_function(): if st.button("Hi!"): st.write("Hi back!") fragment_function() If you want the main body of your fragment to appear in the sidebar or another container, call your fragment function inside a context manager. with st.sidebar: fragment_function() Partial rerun execution flow Consider the following code with the explanation and diagram below. import streamlit as st st.title("My Awesome App") @st.experimental_fragment() def toggle_and_text(): cols = st.columns(2) cols[0].toggle("Toggle") cols[1].text_area("Enter text") @st.experimental_fragment() def filter_and_file(): cols = st.columns(2) cols[0].checkbox("Filter") cols[1].file_uploader("Upload image") toggle_and_text() cols = st.columns(2) cols[0].selectbox("Select", [1,2,3], None) cols[1].button("Update") filter_and_file() When a user interacts with an input widget inside a fragment, only the fragment reruns instead of the full script. When a user interacts with an input widget outside a fragment, the full script reruns as usual. If you run the code above, the full script will run top to bottom on your app's initial load. If you flip the toggle button in your running app, the first fragment (toggle_and_text()) will rerun, redrawing the toggle and text area while leaving everything else unchanged. If you click the checkbox, the second fragment (filter_and_file()) will rerun and consequently redraw the checkbox and file uploader. Everything else remains unchanged. Finally, if you click the update button, the full script will rerun, and Streamlit will redraw everything. Fragment return values and interacting with the rest of your app Streamlit ignores fragment return values during fragment reruns, so defining return values for your fragment functions is not recommended. Instead, if your fragment needs to share data with the rest of your app, use Session State. Fragments are just functions in your script, so they can access Session State, imported modules, and other Streamlit elements like containers. If your fragment writes to any container created outside of itself, note the following difference in behavior: Elements drawn in the main body of your fragment are cleared and redrawn in place during a fragment rerun. Repeated fragment reruns will not cause additional elements to appear. Elements drawn to containers outside the main body of fragment will not be cleared with each fragment rerun. Instead, Streamlit will draw them additively and these elements will accumulate until the next full-script rerun. To prevent elements from accumulating in outside containers, use st.empty containers. For a related tutorial, see Create a fragment across multiple containers. If you need to trigger a full-script rerun from inside a fragment, call st.rerun. For a related tutorial, see Trigger a full-script rerun from inside a fragment. Automate fragment reruns st.experimental_fragment includes a convenient run_every parameter that causes the fragment to rerun automatically at the specified time interval. These reruns are in addition to any reruns (fragment or full-script) triggered by your user. The automatic fragment reruns will continue even if your user is not interacting with your app. This is a great way to show a live data stream or status on a running background job, efficiently updating your rendered data and only your rendered data. @st.experimental_fragment(run_every="10s") def auto_function(): # This will update every 10 seconds! df = get_latest_updates() st.line_chart(df) auto_function() For a related tutorial, see Start and stop a streaming fragment. Compare fragments to other Streamlit features Fragments vs forms Here is a comparison between fragments and forms: Forms allow users to interact with widgets without rerunning your app. Streamlit does not send user actions within a form to your app's Python backend until the form is submitted. Widgets within a form can not dynamically update other widgets (in or out of the form) in real-time. Fragments run independently from the rest of your code. As your users interact with fragment widgets, their actions are immediately processed by your app's Python backend and your fragment code is rerun. Widgets within a fragment can dynamically update other widgets within the same fragment in real-time. A form batches user input without interaction between any widgets. A fragment immediately processes user input but limits the scope of the rerun. Fragments vs callbacks Here is a comparison between fragments and callbacks: Callbacks allow you to execute a function at the beginning of a script rerun. A callback is a single prefix to your script rerun. Fragments allow you to rerun a portion of your script. A fragment is a repeatable postfix to your script, running each time a user interacts with a fragment widget, or automatically in sequence when run_every is set. When callbacks render elements to your page, they are rendered before the rest of your page elements. When fragments render elements to your page, they are updated with each fragment rerun (unless they are written to containers outside of the fragment, in which case they accumulate there). Fragments vs custom components Here is a comparison between fragments and custom components: Components are custom frontend code that can interact with the Python code, native elements, and widgets in your Streamlit app. Custom components extend what’s possible with Streamlit. They follow the normal Streamlit execution flow. Fragments are parts of your app that can rerun independently of the full app. Fragments can be composed of multiple Streamlit elements, widgets, or any Python code. A fragment can include one or more custom components. A custom component could not easily include a fragment! Fragments vs caching Here is a comparison between fragments and caching: Caching: allows you to skip over a function and return a previously computed value. When you use caching, you execute everything except the cached function (if you've already run it before). Fragments: allow you to freeze most of your app and just execute the fragment. When you use fragments, you execute only the fragment (when triggering a fragment rerun). Caching saves you from unnecessarily running a piece of your app while the rest runs. Fragments save you from running your full app when you only want to run one piece. Limitations and unsupported behavior Fragments can't detect a change in input values. It is best to use Session State for dynamic input and output for fragment functions. Calling fragments within fragments is unsupported. Using caching and fragments on the same function is unsupported. Previous: FormsNext: Widget behaviorforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy
https://docs.streamlit.io/develop/concepts/architecture/forms#use-a-callback-with-session-state
DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsremoveCOREArchitecture & executionremoveRunning your appStreamlit's architectureThe app chromeCachingSession StateFormsFragmentsWidget behaviorMultipage appsaddApp designaddADDITIONALConnections and secretsaddCustom componentsaddConfiguration and themingaddApp testingaddAPI referenceaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Develop/Concepts/Architecture & execution/FormsUsing forms When you don't want to rerun your script with each input made by a user, st.form is here to help! Forms make it easy to batch user input into a single rerun. This guide to using forms provides examples and explains how users interact with forms. Example In the following example, a user can set multiple parameters to update the map. As the user changes the parameters, the script will not rerun and the map will not update. When the user submits the form with the button labeled "Update map", the script reruns and the map updates. If at any time the user clicks "Generate new points" which is outside of the form, the script will rerun. If the user has any unsubmitted changes within the form, these will not be sent with the rerun. All changes made to a form will only be sent to the Python backend when the form itself is submitted. View source codeexpand_moreimport streamlit as st import pandas as pd import numpy as np def get_data(): df = pd.DataFrame({ "lat": np.random.randn(200) / 50 + 37.76, "lon": np.random.randn(200) / 50 + -122.4, "team": ['A','B']*100 }) return df if st.button('Generate new points'): st.session_state.df = get_data() if 'df' not in st.session_state: st.session_state.df = get_data() df = st.session_state.df with st.form("my_form"): header = st.columns([1,2,2]) header[0].subheader('Color') header[1].subheader('Opacity') header[2].subheader('Size') row1 = st.columns([1,2,2]) colorA = row1[0].color_picker('Team A', '#0000FF') opacityA = row1[1].slider('A opacity', 20, 100, 50, label_visibility='hidden') sizeA = row1[2].slider('A size', 50, 200, 100, step=10, label_visibility='hidden') row2 = st.columns([1,2,2]) colorB = row2[0].color_picker('Team B', '#FF0000') opacityB = row2[1].slider('B opacity', 20, 100, 50, label_visibility='hidden') sizeB = row2[2].slider('B size', 50, 200, 100, step=10, label_visibility='hidden') st.form_submit_button('Update map') alphaA = int(opacityA*255/100) alphaB = int(opacityB*255/100) df['color'] = np.where(df.team=='A',colorA+f'{alphaA:02x}',colorB+f'{alphaB:02x}') df['size'] = np.where(df.team=='A',sizeA, sizeB) st.map(df, size='size', color='color') Built with Streamlit 🎈Fullscreen open_in_new User interaction If a widget is not in a form, that widget will trigger a script rerun whenever a user changes its value. For widgets with keyed input (st.number_input, st.text_input, st.text_area), a new value triggers a rerun when the user clicks or tabs out of the widget. A user can also submit a change by pressing Enter while thier cursor is active in the widget. On the other hand if a widget is inside of a form, the script will not rerun when a user clicks or tabs out of that widget. For widgets inside a form, the script will rerun when the form is submitted and all widgets within the form will send their updated values to the Python backend. A user can submit a form using Enter on their keyboard if their cursor active in a widget that accepts keyed input. Within st.number_input and st.text_input a user presses Enter to submit the form. Within st.text_area a user presses Ctrl+Enter/⌘+Enter to submit the form. Widget values Before a form is submitted, all widgets within that form will have default values, just like widgets outside of a form have default values. import streamlit as st with st.form("my_form"): st.write("Inside the form") my_number = st.slider('Pick a number', 1, 10) my_color = st.selectbox('Pick a color', ['red','orange','green','blue','violet']) st.form_submit_button('Submit my picks') # This is outside the form st.write(my_number) st.write(my_color) Built with Streamlit 🎈Fullscreen open_in_new Forms are containers When st.form is called, a container is created on the frontend. You can write to that container like you do with other container elements. That is, you can use Python's with statement as shown in the example above, or you can assign the form container to a variable and call methods on it directly. Additionally, you can place st.form_submit_button anywhere in the form container. import streamlit as st animal = st.form('my_animal') # This is writing directly to the main body. Since the form container is # defined above, this will appear below everything written in the form. sound = st.selectbox('Sounds like', ['meow','woof','squeak','tweet']) # These methods called on the form container, so they appear inside the form. submit = animal.form_submit_button(f'Say it with {sound}!') sentence = animal.text_input('Your sentence:', 'Where\'s the tuna?') say_it = sentence.rstrip('.,!?') + f', {sound}!' if submit: animal.subheader(say_it) else: animal.subheader('&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/en/0.68.0/api.html#configuration
DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceremovePAGE ELEMENTSWrite and magicaddText elementsaddData elementsaddChart elementsaddInput widgetsaddMedia elementsaddLayouts and containersaddChat elementsaddStatus elementsaddThird-party componentsopen_in_newAPPLICATION LOGICNavigation and pagesaddExecution flowaddCaching and stateaddConnections and secretsaddCustom componentsaddUtilitiesaddConfigurationaddTOOLSApp testingaddCommand lineaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Develop/API referenceAPI reference Streamlit makes it easy for you to visualize, mutate, and share data. The API reference is organized by activity type, like displaying data or optimizing performance. Each section includes methods associated with the activity type, including examples. Browse our API below and click to learn more about any of our available commands! 🎈 Display almost anything Write and magic st.writeWrite arguments to the app.st.write("Hello **world**!") st.write(my_data_frame) st.write(my_mpl_figure) st.write_streamWrite generators or streams to the app with a typewriter effect.st.write_stream(my_generator) st.write_stream(my_llm_stream) MagicAny time Streamlit sees either a variable or literal value on its own line, it automatically writes that to your app using st.write"Hello **world**!" my_data_frame my_mpl_figure Text elements MarkdownDisplay string formatted as Markdown.st.markdown("Hello **world**!") TitleDisplay text in title formatting.st.title("The app title") HeaderDisplay text in header formatting.st.header("This is a header") SubheaderDisplay text in subheader formatting.st.subheader("This is a subheader") CaptionDisplay text in small font.st.caption("This is written small caption text") Code blockDisplay a code block with optional syntax highlighting.st.code("a = 1234") EchoDisplay some code in the app, then execute it. Useful for tutorials.with st.echo(): st.write('This code will be printed') LaTeXDisplay mathematical expressions formatted as LaTeX.st.latex("\int a x^2 \,dx") Preformatted textWrite fixed-width and preformatted text.st.text("Hello world") DividerDisplay a horizontal rule.st.divider() Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration! PreviousTagsAdd tags to your Streamlit apps. Created by @gagan3012.st_tags(label='# Enter Keywords:', text='Press enter to add more', value=['Zero', 'One', 'Two'], suggestions=['five', 'six', 'seven', 'eight', 'nine', 'three', 'eleven', 'ten', 'four'], maxtags = 4, key='1') NLUApply text mining on a dataframe. Created by @JohnSnowLabs.nlu.load('sentiment').predict('I love NLU! <3') Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.mention(label="An awesome Streamlit App", icon="streamlit", url="https://extras.streamlit.app",) Annotated textDisplay annotated text in Streamlit apps. Created by @tvst.annotated_text("This ", ("is", "verb"), " some ", ("annotated", "adj"), ("text", "noun"), " for those of ", ("you", "pronoun"), " who ", ("like", "verb"), " this sort of ", ("thing", "noun"), ".") Drawable CanvasProvides a sketching canvas using Fabric.js. Created by @andfanilo.st_canvas(fill_color="rgba(255, 165, 0, 0.3)", stroke_width=stroke_width, stroke_color=stroke_color, background_color=bg_color, background_image=Image.open(bg_image) if bg_image else None, update_streamlit=realtime_update, height=150, drawing_mode=drawing_mode, point_display_radius=point_display_radius if drawing_mode == 'point' else 0, key="canvas",) TagsAdd tags to your Streamlit apps. Created by @gagan3012.st_tags(label='# Enter Keywords:', text='Press enter to add more', value=['Zero', 'One', 'Two'], suggestions=['five', 'six', 'seven', 'eight', 'nine', 'three', 'eleven', 'ten', 'four'], maxtags = 4, key='1') NLUApply text mining on a dataframe. Created by @JohnSnowLabs.nlu.load('sentiment').predict('I love NLU! <3') Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.mention(label="An awesome Streamlit App", icon="streamlit", url="https://extras.streamlit.app",) Annotated textDisplay annotated text in Streamlit apps. Created by @tvst.annotated_text("This ", ("is", "verb"), " some ", ("annotated", "adj"), ("text", "noun"), " for those of ", ("you", "pronoun"), " who ", ("like", "verb"), " this sort of ", ("thing", "noun"), ".") Drawable CanvasProvides a sketching canvas using Fabric.js. Created by @andfanilo.st_canvas(fill_color="rgba(255, 165, 0, 0.3)", stroke_width=stroke_width, stroke_color=stroke_color, background_color=bg_color, background_image=Image.open(bg_image) if bg_image else None, update_streamlit=realtime_update, height=150, drawing_mode=drawing_mode, point_display_radius=point_display_radius if drawing_mode == 'point' else 0, key="canvas",) TagsAdd tags to your Streamlit apps. Created by @gagan3012.st_tags(label='# Enter Keywords:', text='Press enter to add more', value=['Zero', 'One', 'Two'], suggestions=['five', 'six', 'seven', 'eight', 'nine', 'three', 'eleven', 'ten', 'four'], maxtags = 4, key='1') NLUApply text mining on a dataframe. Created by @JohnSnowLabs.nlu.load('sentiment').predict('I love NLU! <3') Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.mention(label="An awesome Streamlit App", icon="streamlit", url="https://extras.streamlit.app",) Next Data elements DataframesDisplay a dataframe as an interactive table.st.dataframe(my_data_frame) Data editorDisplay a data editor widget.edited = st.data_editor(df, num_rows="dynamic") Column configurationConfigure the display and editing behavior of dataframes and data editors.st.column_config.NumberColumn("Price (in USD)", min_value=0, format="$%d") Static tablesDisplay a static table.st.table(my_data_frame) MetricsDisplay a metric in big bold font, with an optional indicator of how the metric changed.st.metric("My metric", 42, 2) Dicts and JSONDisplay object or string as a pretty-printed JSON string.st.json(my_dict) Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration! PreviousImage CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates value = streamlit_image_coordinates("https://placekitten.com/200/300") st.write(value) Plotly EventsMake Plotly charts interactive!. Created by @null-jones.from streamlit_plotly_events import plotly_events fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.metric_cards import style_metric_cards col3.metric(label="No Change", value=5000, delta=0) style_metric_cards() Streamlit AggridImplementation of Ag-Grid component for Streamlit. Created by @PablocFonseca.df = pd.DataFrame({'col1': [1, 2, 3], 'col2': [4, 5, 6]}) grid_return = AgGrid(df, editable=True) new_df = grid_return['data'] Streamlit FoliumStreamlit Component for rendering Folium maps. Created by @randyzwitch.m = folium.Map(location=[39.949610, -75.150282], zoom_start=16) folium.Marker([39.949610, -75.150282], popup="Liberty Bell", tooltip="Liberty Bell").add_to(m) st_data = st_folium(m, width=725) Pandas ProfilingPandas profiling component for Streamlit. Created by @okld.df = pd.read_csv("https://storage.googleapis.com/tf-datasets/titanic/train.csv") pr = df.profile_report() st_profile_report(pr) Image CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates value = streamlit_image_coordinates("https://placekitten.com/200/300") st.write(value) Plotly EventsMake Plotly charts interactive!. Created by @null-jones.from streamlit_plotly_events import plotly_events fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.metric_cards import style_metric_cards col3.metric(label="No Change", value=5000, delta=0) style_metric_cards() Streamlit AggridImplementation of Ag-Grid component for Streamlit. Created by @PablocFonseca.df = pd.DataFrame({'col1': [1, 2, 3], 'col2': [4, 5, 6]}) grid_return = AgGrid(df, editable=True) new_df = grid_return['data'] Streamlit FoliumStreamlit Component for rendering Folium maps. Created by @randyzwitch.m = folium.Map(location=[39.949610, -75.150282], zoom_start=16) folium.Marker([39.949610, -75.150282], popup="Liberty Bell", tooltip="Liberty Bell").add_to(m) st_data = st_folium(m, width=725) Pandas ProfilingPandas profiling component for Streamlit. Created by @okld.df = pd.read_csv("https://storage.googleapis.com/tf-datasets/titanic/train.csv") pr = df.profile_report() st_profile_report(pr) Image CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates value = streamlit_image_coordinates("https://placekitten.com/200/300") st.write(value) Plotly EventsMake Plotly charts interactive!. Created by @null-jones.from streamlit_plotly_events import plotly_events fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.metric_cards import style_metric_cards col3.metric(label="No Change", value=5000, delta=0) style_metric_cards() Next Chart elements Simple area chartsDisplay an area chart.st.area_chart(my_data_frame) Simple bar chartsDisplay a bar chart.st.bar_chart(my_data_frame) Simple line chartsDisplay a line chart.st.line_chart(my_data_frame) Simple scatter chartsDisplay a line chart.st.scatter_chart(my_data_frame) Scatterplots on mapsDisplay a map with points on it.st.map(my_data_frame) MatplotlibDisplay a matplotlib.pyplot figure.st.pyplot(my_mpl_figure) AltairDisplay a chart using the Altair library.st.altair_chart(my_altair_chart) Vega-LiteDisplay a chart using the Vega-Lite library.st.vega_lite_chart(my_vega_lite_chart) PlotlyDisplay an interactive Plotly chart.st.plotly_chart(my_plotly_chart) BokehDisplay an interactive Bokeh chart.st.bokeh_chart(my_bokeh_chart) PyDeckDisplay a chart using the PyDeck library.st.pydeck_chart(my_pydeck_chart) GraphVizDisplay a graph using the dagre-d3 library.st.graphviz_chart(my_graphviz_spec) Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration! PreviousStreamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl("https://assets5.lottiefiles.com/packages/lf20_V9t630.json") st_lottie(lottie_hello, key="hello") Plotly EventsMake Plotly charts interactive!. Created by @null-jones.fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.chart += get_annotations_chart(annotations=[("Mar 01, 2008", "Pretty good day for GOOG"), ("Dec 01, 2007", "Something's going wrong for GOOG & AAPL"), ("Nov 01, 2008", "Market starts again thanks to..."), ("Dec 01, 2009", "Small crash for GOOG after..."),],) st.altair_chart(chart, use_container_width=True) PlostA deceptively simple plotting library for Streamlit. Created by @tvst.import plost plost.line_chart(my_dataframe, x='time', y='stock_value', color='stock_name',) HiPlotHigh dimensional Interactive Plotting. Created by @facebookresearch.data = [{'dropout':0.1, 'lr': 0.001, 'loss': 10.0, 'optimizer': 'SGD'}, {'dropout':0.15, 'lr': 0.01, 'loss': 3.5, 'optimizer': 'Adam'}, {'dropout':0.3, 'lr': 0.1, 'loss': 4.5, 'optimizer': 'Adam'}] hip.Experiment.from_iterable(data).display() EChartsHigh dimensional Interactive Plotting. Created by @andfanilo.from streamlit_echarts import st_echarts st_echarts(options=options) Streamlit FoliumStreamlit Component for rendering Folium maps. Created by @randyzwitch.m = folium.Map(location=[39.949610, -75.150282], zoom_start=16) st_data = st_folium(m, width=725) Spacy-StreamlitspaCy building blocks and visualizers for Streamlit apps. Created by @explosion.models = ["en_core_web_sm", "en_core_web_md"] spacy_streamlit.visualize(models, "Sundar Pichai is the CEO of Google.") Streamlit AgraphA Streamlit Graph Vis, based on react-grah-vis. Created by @ChrisDelClea.from streamlit_agraph import agraph, Node, Edge, Config agraph(nodes=nodes, edges=edges, config=config) Streamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl("https://assets5.lottiefiles.com/packages/lf20_V9t630.json") st_lottie(lottie_hello, key="hello") Plotly EventsMake Plotly charts interactive!. Created by @null-jones.fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.chart += get_annotations_chart(annotations=[("Mar 01, 2008", "Pretty good day for GOOG"), ("Dec 01, 2007", "Something's going wrong for GOOG & AAPL"), ("Nov 01, 2008", "Market starts again thanks to..."), ("Dec 01, 2009", "Small crash for GOOG after..."),],) st.altair_chart(chart, use_container_width=True) PlostA deceptively simple plotting library for Streamlit. Created by @tvst.import plost plost.line_chart(my_dataframe, x='time', y='stock_value', color='stock_name',) HiPlotHigh dimensional Interactive Plotting. Created by @facebookresearch.data = [{'dropout':0.1, 'lr': 0.001, 'loss': 10.0, 'optimizer': 'SGD'}, {'dropout':0.15, 'lr': 0.01, 'loss': 3.5, 'optimizer': 'Adam'}, {'dropout':0.3, 'lr': 0.1, 'loss': 4.5, 'optimizer': 'Adam'}] hip.Experiment.from_iterable(data).display() EChartsHigh dimensional Interactive Plotting. Created by @andfanilo.from streamlit_echarts import st_echarts st_echarts(options=options) Streamlit FoliumStreamlit Component for rendering Folium maps. Created by @randyzwitch.m = folium.Map(location=[39.949610, -75.150282], zoom_start=16) st_data = st_folium(m, width=725) Spacy-StreamlitspaCy building blocks and visualizers for Streamlit apps. Created by @explosion.models = ["en_core_web_sm", "en_core_web_md"] spacy_streamlit.visualize(models, "Sundar Pichai is the CEO of Google.") Streamlit AgraphA Streamlit Graph Vis, based on react-grah-vis. Created by @ChrisDelClea.from streamlit_agraph import agraph, Node, Edge, Config agraph(nodes=nodes, edges=edges, config=config) Streamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl("https://assets5.lottiefiles.com/packages/lf20_V9t630.json") st_lottie(lottie_hello, key="hello") Plotly EventsMake Plotly charts interactive!. Created by @null-jones.fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.chart += get_annotations_chart(annotations=[("Mar 01, 2008", "Pretty good day for GOOG"), ("Dec 01, 2007", "Something's going wrong for GOOG & AAPL"), ("Nov 01, 2008", "Market starts again thanks to..."), ("Dec 01, 2009", "Small crash for GOOG after..."),],) st.altair_chart(chart, use_container_width=True) Next Input widgets ButtonDisplay a button widget.clicked = st.button("Click me") Download buttonDisplay a download button widget.st.download_button("Download file", file) Form buttonDisplay a form submit button. For use with st.form.st.form_submit_button("Sign up") Link buttonDisplay a link button.st.link_button("Go to gallery", url) Page linkDisplay a link to another page in a multipage app.st.page_link("app.py", label="Home", icon="🏠") st.page_link("pages/profile.py", label="My profile") CheckboxDisplay a checkbox widget.selected = st.checkbox("I agree") Color pickerDisplay a color picker widget.color = st.color_picker("Pick a color") MultiselectDisplay a multiselect widget. The multiselect widget starts as empty.choices = st.multiselect("Buy", ["milk", "apples", "potatoes"]) RadioDisplay a radio button widget.choice = st.radio("Pick one", ["cats", "dogs"]) SelectboxDisplay a select widget.choice = st.selectbox("Pick one", ["cats", "dogs"]) Select-sliderDisplay a slider widget to select items from a list.size = st.select_slider("Pick a size", ["S", "M", "L"]) ToggleDisplay a toggle widget.activated = st.toggle("Activate") Number inputDisplay a numeric input widget.choice = st.number_input("Pick a number", 0, 10) SliderDisplay a slider widget.number = st.slider("Pick a number", 0, 100) Date inputDisplay a date input widget.date = st.date_input("Your birthday") Time inputDisplay a time input widget.time = st.time_input("Meeting time") Chat inputDisplay a chat input widget.prompt = st.chat_input("Say something") if prompt: st.write(f"The user has sent: {prompt}") Text-areaDisplay a multi-line text input widget.text = st.text_area("Text to translate") Text inputDisplay a single-line text input widget.name = st.text_input("First name") Data editorDisplay a data editor widget.edited = st.experimental_data_editor(df, num_rows="dynamic") File UploaderDisplay a file uploader widget.data = st.file_uploader("Upload a CSV") Camera inputDisplay a widget that allows users to upload images directly from a camera.image = st.camera_input("Take a picture") Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration! PreviousStreamlit ChatStreamlit Component for a Chatbot UI. Created by @AI-Yash.from streamlit_chat import message message("My message") message("Hello bot!", is_user=True) # align's the message to the right Streamlit Option MenuSelect a single item from a list of options in a menu. Created by @victoryhb.from streamlit_option_menu import option_menu option_menu("Main Menu", ["Home", 'Settings'], icons=['house', 'gear'], menu_icon="cast", default_index=1) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.stoggle import stoggle stoggle( "Click me!", """🥷 Surprise! Here's some additional content""",) Streamlit ElementsCreate a draggable and resizable dashboard in Streamlit. Created by @okls.from streamlit_elements import elements, mui, html with elements("new_element"): mui.Typography("Hello world") TagsAdd tags to your Streamlit apps. Created by @gagan3012.from streamlit_tags import st_tags st_tags(label='# Enter Keywords:', text='Press enter to add more', value=['Zero', 'One', 'Two'], suggestions=['five', 'six', 'seven', 'eight', 'nine', 'three', 'eleven', 'ten', 'four'], maxtags = 4, key='1') StqdmThe simplest way to handle a progress bar in streamlit app. Created by @Wirg.from stqdm import stqdm for _ in stqdm(range(50)): sleep(0.5) TimelineDisplay a Timeline in Streamlit apps using TimelineJS. Created by @innerdoc.from streamlit_timeline import timeline with open('example.json', "r") as f: timeline(f.read(), height=800) Camera input liveAlternative for st.camera_input which returns the webcam images live. Created by @blackary.from camera_input_live import camera_input_live image = camera_input_live() st.image(value) Streamlit AceAce editor component for Streamlit. Created by @okld.from streamlit_ace import st_ace content = st_ace() content Streamlit ChatStreamlit Component for a Chatbot UI. Created by @AI-Yash.from streamlit_chat import message message("My message") message("Hello bot!", is_user=True) # align's the message to the right Streamlit Option MenuSelect a single item from a list of options in a menu. Created by @victoryhb.from streamlit_option_menu import option_menu option_menu("Main Menu", ["Home", 'Settings'], icons=['house', 'gear'], menu_icon="cast", default_index=1) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.stoggle import stoggle stoggle( "Click me!", """🥷 Surprise! Here's some additional content""",) Streamlit ElementsCreate a draggable and resizable dashboard in Streamlit. Created by @okls.from streamlit_elements import elements, mui, html with elements("new_element"): mui.Typography("Hello world") TagsAdd tags to your Streamlit apps. Created by @gagan3012.from streamlit_tags import st_tags st_tags(label='# Enter Keywords:', text='Press enter to add more', value=['Zero', 'One', 'Two'], suggestions=['five', 'six', 'seven', 'eight', 'nine', 'three', 'eleven', 'ten', 'four'], maxtags = 4, key='1') StqdmThe simplest way to handle a progress bar in streamlit app. Created by @Wirg.from stqdm import stqdm for _ in stqdm(range(50)): sleep(0.5) TimelineDisplay a Timeline in Streamlit apps using TimelineJS. Created by @innerdoc.from streamlit_timeline import timeline with open('example.json', "r") as f: timeline(f.read(), height=800) Camera input liveAlternative for st.camera_input which returns the webcam images live. Created by @blackary.from camera_input_live import camera_input_live image = camera_input_live() st.image(value) Streamlit AceAce editor component for Streamlit. Created by @okld.from streamlit_ace import st_ace content = st_ace() content Streamlit ChatStreamlit Component for a Chatbot UI. Created by @AI-Yash.from streamlit_chat import message message("My message") message("Hello bot!", is_user=True) # align's the message to the right Streamlit Option MenuSelect a single item from a list of options in a menu. Created by @victoryhb.from streamlit_option_menu import option_menu option_menu("Main Menu", ["Home", 'Settings'], icons=['house', 'gear'], menu_icon="cast", default_index=1) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.stoggle import stoggle stoggle( "Click me!", """🥷 Surprise! Here's some additional content""",) Next Media elements ImageDisplay an image or list of images.st.image(numpy_array) st.image(image_bytes) st.image(file) st.image("https://example.com/myimage.jpg") AudioDisplay an audio player.st.audio(numpy_array) st.audio(audio_bytes) st.audio(file) st.audio("https://example.com/myaudio.mp3", format="audio/mp3") VideoDisplay a video player.st.video(numpy_array) st.video(video_bytes) st.video(file) st.video("https://example.com/myvideo.mp4", format="video/mp4") Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration! PreviousStreamlit CropperA simple image cropper for Streamlit. Created by @turner-anderson.from streamlit_cropper import st_cropper st_cropper(img, realtime_update=realtime_update, box_color=box_color, aspect_ratio=aspect_ratio) Image CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates streamlit_image_coordinates("https://placekitten.com/200/300") Streamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl("https://assets5.lottiefiles.com/packages/lf20_V9t630.json") st_lottie(lottie_hello, key="hello") Streamlit WebrtcHandling and transmitting real-time video/audio streams with Streamlit. Created by @whitphx.from streamlit_webrtc import webrtc_streamer webrtc_streamer(key="sample") Drawable CanvasProvides a sketching canvas using Fabric.js. Created by @andfanilo.from streamlit_drawable_canvas import st_canvas st_canvas(fill_color="rgba(255, 165, 0, 0.3)", stroke_width=stroke_width, stroke_color=stroke_color, background_color=bg_color, background_image=Image.open(bg_image) if bg_image else None, update_streamlit=realtime_update, height=150, drawing_mode=drawing_mode, point_display_radius=point_display_radius if drawing_mode == 'point' else 0, key="canvas",) Image ComparisonCompare images with a slider using JuxtaposeJS. Created by @fcakyon.from streamlit_image_comparison import image_comparison image_comparison(img1="image1.jpg", img2="image2.jpg",) Streamlit CropperA simple image cropper for Streamlit. Created by @turner-anderson.from streamlit_cropper import st_cropper st_cropper(img, realtime_update=realtime_update, box_color=box_color, aspect_ratio=aspect_ratio) Image CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates streamlit_image_coordinates("https://placekitten.com/200/300") Streamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl("https://assets5.lottiefiles.com/packages/lf20_V9t630.json") st_lottie(lottie_hello, key="hello") Streamlit WebrtcHandling and transmitting real-time video/audio streams with Streamlit. Created by @whitphx.from streamlit_webrtc import webrtc_streamer webrtc_streamer(key="sample") Drawable CanvasProvides a sketching canvas using Fabric.js. Created by @andfanilo.from streamlit_drawable_canvas import st_canvas st_canvas(fill_color="rgba(255, 165, 0, 0.3)", stroke_width=stroke_width, stroke_color=stroke_color, background_color=bg_color, background_image=Image.open(bg_image) if bg_image else None, update_streamlit=realtime_update, height=150, drawing_mode=drawing_mode, point_display_radius=point_display_radius if drawing_mode == 'point' else 0, key="canvas",) Image ComparisonCompare images with a slider using JuxtaposeJS. Created by @fcakyon.from streamlit_image_comparison import image_comparison image_comparison(img1="image1.jpg", img2="image2.jpg",) Streamlit CropperA simple image cropper for Streamlit. Created by @turner-anderson.from streamlit_cropper import st_cropper st_cropper(img, realtime_update=realtime_update, box_color=box_color, aspect_ratio=aspect_ratio) Image CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates streamlit_image_coordinates("https://placekitten.com/200/300") Streamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl("https://assets5.lottiefiles.com/packages/lf20_V9t630.json") st_lottie(lottie_hello, key="hello") Next Layouts and containers ColumnsInsert containers laid out as side-by-side columns.col1, col2 = st.columns(2) col1.write("this is column 1") col2.write("this is column 2") ContainerInsert a multi-element container.c = st.container() st.write("This will show last") c.write("This will show first") c.write("This will show second") Modal dialogsInsert a modal dialog that can rerun independently from the rest of the script.@st.experimental_dialog("Sign up") def email_form(): name = st.text_input("Name") email = st.text_input("Email") EmptyInsert a single-element container.c = st.empty() st.write("This will show last") c.write("This will be replaced") c.write("This will show first") ExpanderInsert a multi-element container that can be expanded/collapsed.with st.expander("Open to see more"): st.write("This is more content") PopoverInsert a multi-element popover container that can be opened/closed.with st.popover("Settings"): st.checkbox("Show completed") SidebarDisplay items in a sidebar.st.sidebar.write("This lives in the sidebar") st.sidebar.button("Click me!") TabsInsert containers separated into tabs.tab1, tab2 = st.tabs(["Tab 1", "Tab2"]) tab1.write("this is tab 1") tab2.write("this is tab 2") Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration!Streamlit ElementsCreate a draggable and resizable dashboard in Streamlit. Created by @okls.from streamlit_elements import elements, mui, html with elements("new_element"): mui.Typography("Hello world") PydanticAuto-generate Streamlit UI from Pydantic Models and Dataclasses. Created by @lukasmasuch.import streamlit_pydantic as sp sp.pydantic_form(key="my_form", model=ExampleModel) Streamlit PagesAn experimental version of Streamlit Multi-Page Apps. Created by @blackary.from st_pages import Page, show_pages, add_page_title show_pages([ Page("streamlit_app.py", "Home", "🏠"), Page("other_pages/page2.py", "Page 2", ":books:"), ]) Chat elements Streamlit provides a few commands to help you build conversational apps. These chat elements are designed to be used in conjunction with each other, but you can also use them separately. st.chat_message lets you insert a chat message container into the app so you can display messages from the user or the app. Chat containers can contain other Streamlit elements, including charts, tables, text, and more. st.chat_input lets you display a chat input widget so the user can type in a message. Chat inputDisplay a chat input widget.prompt = st.chat_input("Say something") if prompt: st.write(f"The user has sent: {prompt}") Chat messageInsert a chat message container.import numpy as np with st.chat_message("user"): st.write("Hello 👋") st.line_chart(np.random.randn(30, 3)) Status containerDisplay output of long-running tasks in a container.with st.status('Running'): do_something_slow() st.write_streamWrite generators or streams to the app with a typewriter effect.st.write_stream(my_generator) st.write_stream(my_llm_stream) Status elements Progress barDisplay a progress bar.for i in range(101): st.progress(i) do_something_slow() SpinnerTemporarily displays a message while executing a block of code.with st.spinner("Please wait..."): do_something_slow() Status containerDisplay output of long-running tasks in a container.with st.status('Running'): do_something_slow() ToastBriefly displays a toast message in the bottom-right corner.st.toast('Butter!', icon='🧈') BalloonsDisplay celebratory balloons!do_something() # Celebrate when all done! st.balloons() SnowflakesDisplay celebratory snowflakes!do_something() # Celebrate when all done! st.snow() Success boxDisplay a success message.st.success("Match found!") Info boxDisplay an informational message.st.info("Dataset is updated every day at midnight.") Warning boxDisplay warning message.st.warning("Unable to fetch image. Skipping...") Error boxDisplay error message.st.error("We encountered an error") Exception outputDisplay an exception.e = RuntimeError("This is an exception of type RuntimeError") st.exception(e) Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration!StqdmThe simplest way to handle a progress bar in streamlit app. Created by @Wirg.from stqdm import stqdm for _ in stqdm(range(50)): sleep(0.5) Custom notification boxA custom notification box with the ability to close it out. Created by @Socvest.from streamlit_custom_notification_box import custom_notification_box styles = {'material-icons':{'color': 'red'}, 'text-icon-link-close-container': {'box-shadow': '#3896de 0px 4px'}, 'notification-text': {'':''}, 'close-button':{'':''}, 'link':{'':''}} custom_notification_box(icon='info', textDisplay='We are almost done with your registration...', externalLink='more info', url='#', styles=styles, key="foo") Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.let_it_rain import rain rain(emoji="🎈", font_size=54, falling_speed=5, animation_length="infinite",) App logic and configuration Navigation and pages Switch pageProgrammatically navigates to a specified page.st.switch_page("pages/my_page.py") Page linkDisplay a link to another page in a multipage app.st.page_link("app.py", label="Home", icon="🏠") st.page_link("pages/profile.py", label="My profile") Execution flow Modal dialogsInsert a modal dialog that can rerun independently from the rest of the script.@st.experimental_dialog("Sign up") def email_form(): name = st.text_input("Name") email = st.text_input("Email") FormsCreate a form that batches elements together with a “Submit" button.with st.form(key='my_form'): name = st.text_input("Name") email = st.text_input("Email") st.form_submit_button("Sign up") Partial rerunsDefine a fragment to rerun independently from the rest of the script.@st.experimental_fragment(run_every="10s") def fragment(): df = get_data() st.line_chart(df) Rerun scriptRerun the script immediately.st.rerun() Stop executionStops execution immediately.st.stop() Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration!AutorefreshForce a refresh without tying up a script. Created by @kmcgrady.from streamlit_autorefresh import st_autorefresh st_autorefresh(interval=2000, limit=100, key="fizzbuzzcounter") PydanticAuto-generate Streamlit UI from Pydantic Models and Dataclasses. Created by @lukasmasuch.import streamlit_pydantic as sp sp.pydantic_form(key="my_form", model=ExampleModel) Streamlit PagesAn experimental version of Streamlit Multi-Page Apps. Created by @blackary.from st_pages import Page, show_pages, add_page_title show_pages([ Page("streamlit_app.py", "Home", "🏠"), Page("other_pages/page2.py", "Page 2", ":books:"), ]) Caching and state Cache dataFunction decorator to cache functions that return data (e.g. dataframe transforms, database queries, ML inference).@st.cache_data def long_function(param1, param2): # Perform expensive computation here or # fetch data from the web here return data Cache resourceFunction decorator to cache functions that return global resources (e.g. database connections, ML models).@st.cache_resource def init_model(): # Return a global resource here return pipeline( "sentiment-analysis", model="distilbert-base-uncased-finetuned-sst-2-english" ) Session stateSession state is a way to share variables between reruns, for each user session.st.session_state['key'] = value Query parametersGet, set, or clear the query parameters that are shown in the browser's URL bar.st.query_params[key] = value st.query_params.clear() Connections and databases Setup your connection Create a connectionConnect to a data source or APIconn = st.connection('pets_db', type='sql') pet_owners = conn.query('select * from pet_owners') st.dataframe(pet_owners) Built-in connections SnowflakeConnectionA connection to Snowflake.conn = st.connection('snowflake') SQLConnectionA connection to a SQL database using SQLAlchemy.conn = st.connection('sql') Build your own connections Connection base classBuild your own connection with BaseConnection.class MyConnection(BaseConnection[myconn.MyConnection]): def _connect(self, **kwargs) -> MyConnection: return myconn.connect(**self._secrets, **kwargs) def query(self, query): return self._instance.query(query) Secrets management Secrets singletonAccess secrets from a local TOML file.key = st.secrets["OpenAI_key"] Secrets fileSave your secrets in a per-project or per-profile TOML file.OpenAI_key = "<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/using-streamlit/how-download-pandas-dataframe-csv#how-to-download-a-pandas-dataframe-as-a-csv
DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Knowledge base/FAQ/How to download a Pandas DataFrame as a CSV?How to download a Pandas DataFrame as a CSV? Use the st.download_button widget that is natively built into Streamlit. Check out a sample app demonstrating how you can use st.download_button to download common file formats. Example usage import streamlit as st import pandas as pd df = pd.read_csv("dir/file.csv") @st.experimental_memo def convert_df(df): return df.to_csv(index=False).encode('utf-8') csv = convert_df(df) st.download_button( "Press to Download", csv, "file.csv", "text/csv", key='download-csv' ) Additional resources: https://blog.streamlit.io/0-88-0-release-notes/ https://streamlit-release-demos-0-88streamlit-app-0-88-v8ram3.streamlit.app/ https://docs.streamlit.io/develop/api-reference/widgets/st.download_button Previous: How to download a file in Streamlit?Next: How do I get dataframe row-selections from a user?forumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy
https://docs.streamlit.io/deploy/streamlit-community-cloud/get-started/connect-your-github-account#approved-access
DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudremoveGet startedremoveQuickstartCreate your accountConnect your GitHub accountExplore your workspaceFork and edit a public appTrust and securityDeploy your appaddManage your appaddShare your appaddManage your accountaddTroubleshootingStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Deploy/Streamlit Community Cloud/Get started/Connect your GitHub accountConnect your GitHub account Connecting GitHub to your Streamlit Community Cloud account allows you to deploy apps directly from the files you store in your repos. It also lets the system check for updates to those files and automatically update your app. There are two stages to this authorization: the first happens when you connect your account for the first time and the second happens when you deploy your first app. Everyone is prompted to connect GitHub when they create an account. If you need to connect GitHub to an existing primary identity, see Manage your GitHub connection. This page contains additional information about the authorization needed to connect GitHub. If you have just created your account, you are free to skip ahead and Explore your workspace. GitHub's authorization prompts occur automatically as needed. Authorize your GitHub account There are two different authorization prompts to grant access between Streamlit and your GitHub account. The first authorization—"Authorize Streamlit"—happens when you connect your GitHub account to Streamlit. The second authorization—"Streamlit is requesting additional permissions"—happens when you deploy your first app. You must click "Authorize streamlit" on both. If you are a member of any GitHub organizations, read below to understand the extras steps to authorize an organization. Questions about GitHub permissions? Read some frequently asked questions about our GitHub integration. priority_highImportantYou must have admin permissions to your repo in order to deploy apps. If you don't have admin access, talk to the repo's owner or reach out to us on the Community forum. Organization access If you are working in a repository that is owned by an organization, authorization must be granted by that organization. If you are an owner or member of a GitHub organization when you connect your GitHub account, your authorization prompts will include an extra section labeled "Organization access". Organizations you own For any organization you own, if authorization has not been previously granted or denied you can click "Grant" before you click "Authorize streamlit". Organizations owned by others For an organization you don't own, if authorization has not been previously granted or denied you can click "Request" before you click "Authorize streamlit". Previous or pending authorization If someone has already started the process of authorizing Streamlit for your organization, different options and statuses will display accordingly. Approved access If an organization has already granted Streamlit access, a green check is shown. Pending access If a request has been previously sent but not yet approved, a pending status shows. Denied access If a request has been previously sent and denied, no option to grant or request access is shown. In this case, the organization owner will need to authorize Streamlit from GitHub. See GitHub's documentation on OAuth apps and organizations. What's next? Now that you have your account you can Explore your workspace. Or if you're ready to go, jump right in and Deploy your app.Previous: Create your accountNext: Explore your workspaceforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy
https://docs.streamlit.io/develop/tutorials/multipage/st.page_link-nav#build-a-custom-navigation-menu-with-stpage_link
DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceaddTutorialsremoveExecution flowaddConnect to data sourcesaddMultipage appsremoveBuild navigation with st.page_linkWork with LLMsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Develop/Tutorials/Multipage apps/Build navigation with st.page_linkBuild a custom navigation menu with st.page_link Streamlit lets you build custom navigation menus and elements with st.page_link. Introduced in Streamlit version 1.31.0, st.page_link can link to other pages in your multipage app or to external sites. When linked to another page in your app, st.page_link will show a highlight effect to indicate the current page. When combined with the client.showSidebarNavigation configuration option, you can build sleek, dynamic navigation in your app. Prerequisites Create a new working directory in your development environment. We'll call this directory your-repository. Summary In this example, we'll build a dynamic navigation menu for a multipage app that depends on the current user's role. We've abstracted away the use of username and creditials to simplify the example. Instead, we'll use a selectbox on the main page of the app to switch between roles. Session State will carry this selection between pages. The app will have a main page (app.py) which serves as the abstracted log-in page. There will be three additional pages which will be hidden or accessible, depending on the current role. The file structure will be as follows: your-repository/ ├── .streamlit/ │ └── config.toml ├── pages/ │ ├── admin.py │ ├── super-admin.py │ └── user.py ├── menu.py └── app.py Here's a look at what we'll build: Built with Streamlit 🎈Fullscreen open_in_new Build the example Hide the default sidebar navigation When creating a custom navigation menu, you need to hide the default sidebar navigation using client.showSidebarNavigation. Add the following .streamlit/config.toml file to your working directory: [client] showSidebarNavigation = false Create a menu function You can write different menu logic for different pages or you can create a single menu function to call on multiple pages. In this example, we'll use the same menu logic on all pages, including a redirect to the main page when a user isn't logged in. We'll build a few helper functions to do this. menu_with_redirect() checks if a user is logged in, then either redirects them to the main page or renders the menu. menu() will call the correct helper function to render the menu based on whether the user is logged in or not. authenticated_menu() will display a menu based on an authenticated user's role. unauthenticated_menu() will display a menu for unauthenticated users. We'll call menu() on the main page and call menu_with_redirect() on the other pages. st.session_state.role will store the current selected role. If this value does not exist or is set to None, then the user is not logged in. Otherwise, it will hold the user's role as a string: "user", "admin", or "super-admin". Add the following menu.py file to your working directory. (We'll describe the functions in more detail below.) import streamlit as st def authenticated_menu(): # Show a navigation menu for authenticated users st.sidebar.page_link("app.py", label="Switch accounts") st.sidebar.page_link("pages/user.py", label="Your profile") if st.session_state.role in ["admin", "super-admin"]: st.sidebar.page_link("pages/admin.py", label="Manage users") st.sidebar.page_link( "pages/super-admin.py", label="Manage admin access", disabled=st.session_state.role != "super-admin", ) def unauthenticated_menu(): # Show a navigation menu for unauthenticated users st.sidebar.page_link("app.py", label="Log in") def menu(): # Determine if a user is logged in or not, then show the correct # navigation menu if "role" not in st.session_state or st.session_state.role is None: unauthenticated_menu() return authenticated_menu() def menu_with_redirect(): # Redirect users to the main page if not logged in, otherwise continue to # render the navigation menu if "role" not in st.session_state or st.session_state.role is None: st.switch_page("app.py") menu() Let's take a closer look at authenticated_menu(). When this function is called, st.session_state.role exists and has a value other than None. def authenticated_menu(): # Show a navigation menu for authenticated users The first two pages in the navigation menu are available to all users. Since we know a user is logged in when this function is called, we'll use the label "Switch accounts" for the main page. (If you don't use the label parameter, the page name will be derived from the file name like it is with the default sidebar navigation.) st.sidebar.page_link("app.py", label="Switch accounts") st.sidebar.page_link("pages/user.py", label="Your profile") We only want to show the next two pages to admins. Furthermore, we've chosen to disable—but not hide—the super-admin page when the admin user is not a super-admin. We do this using the disabled parameter. (disabled=True when the role is not "super-admin".) if st.session_state.role in ["admin", "super-admin"]: st.sidebar.page_link("pages/admin.py", label="Manage users") st.sidebar.page_link( "pages/super-admin.py", label="Manage admin access", disabled=st.session_state.role != "super-admin", ) It's that simple! unauthenticated_menu() will only show a link to the main page of the app with the label "Log in." menu() does a simple inspection of st.session_state.role to switch between the two menu-rendering functions. Finally, menu_with_redirect() extends menu() to redirect users to app.py if they aren't logged in. starTipIf you want to include emojis in your page labels, you can use the icon parameter. There's no need to include emojis in your file name or the label parameter. Create the main file of your app The main app.py file will serve as a pseudo-login page. The user can choose a role from the st.selectbox widget. A few bits of logic will save that role into Session State to preserve it while navigating between pages—even when returning to app.py. Add the following app.py file to your working directory: import streamlit as st from menu import menu # Initialize st.session_state.role to None if "role" not in st.session_state: st.session_state.role = None # Retrieve the role from Session State to initialize the widget st.session_state._role = st.session_state.role def set_role(): # Callback function to save the role selection to Session State st.session_state.role = st.session_state._role # Selectbox to choose role st.selectbox( "Select your role:", [None, "user", "admin", "super-admin"], key="_role", on_change=set_role, ) menu() # Render the dynamic menu! Add other pages to your app Add the following pages/user.py file: import streamlit as st from menu import menu_with_redirect # Redirect to app.py if not logged in, otherwise show the navigation menu menu_with_redirect() st.title("This page is available to all users") st.markdown(f"You are currently logged with the role of {st.session_state.role}.") Session State resets if a user manually navigates to a page by URL. Therefore, if a user tries to access an admin page in this example, Session State will be cleared, and they will be redirected to the main page as an unauthenicated user. However, it's still good practice to include a check of the role at the top of each restricted page. You can use st.stop to halt an app if a role is not whitelisted. pages/admin.py: import streamlit as st from menu import menu_with_redirect # Redirect to app.py if not logged in, otherwise show the navigation menu menu_with_redirect() # Verify the user's role if st.session_state.role not in ["admin", "super-admin"]: st.warning("You do not have permission to view this page.") st.stop() st.title("This page is available to all admins") st.markdown(f"You are currently logged with the role of {st.session_state.role}.") pages/super-admin.py: import streamlit as st from menu import menu_with_redirect # Redirect to app.py if not logged in, otherwise show the navigation menu menu_with_redirect() # Verify the user's role if st.session_state.role not in ["super-admin"]: st.warning("You do not have permission to view this page.") st.stop() st.title("This page is available to super-admins") st.markdown(f"You are currently logged with the role of {st.session_state.role}.") As noted above, the redirect in menu_with_redirect() will prevent a user from ever seeing the warning messages on the admin pages. If you want to see the warning, just add another st.page_link("pages/admin.py") button at the bottom of app.py so you can navigate to the admin page after selecting the "user" role. 😉Previous: Multipage appsNext: Work with LLMsforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy
https://docs.streamlit.io/deploy/streamlit-community-cloud/get-started/trust-and-security#product-security
DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudremoveGet startedremoveQuickstartCreate your accountConnect your GitHub accountExplore your workspaceFork and edit a public appTrust and securityDeploy your appaddManage your appaddShare your appaddManage your accountaddTroubleshootingStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Deploy/Streamlit Community Cloud/Get started/Trust and securityStreamlit trust and security Streamlit is a framework that turns Python scripts into interactive apps, giving data scientists the ability to quickly create data and model-based apps for the entire company. A simple Streamlit app is: import streamlit as st number = st.slider("Pick a number: ", min_value=1, max_value=10) st.text("Your number is " + str(number)) When you streamlit run my_app.py, you start a web server that runs the interactive application on your local computer at http://localhost:8501. This is great for local development. When you want to share with your colleagues, Streamlit Community Cloud enables you to deploy and run these applications in the cloud. Streamlit Community Cloud handles the details of containerization and provides you an interface for easily managing your deployed apps. This document provides an overview of the security safeguards we've implemented to protect you and your data. Security, however, is a shared responsibility and you are ultimately responsible for making appropriate use of Streamlit and the Streamlit Community Cloud, including implementation of appropriate user-configurable security safeguards and best practices. Product security Authentication You must authenticate through GitHub to deploy or administer an app. Authentication through Google or single-use emailed links are required to view a private app when you don't have push or admin permissions on the associated GitHub repository. The single-use emailed links are valid for 15 minutes once requested. Permissions Streamlit Community Cloud inherits the permissions you have assigned in GitHub. Users with write access to a GitHub repository for a given app will be able to make changes in the Streamlit administrative console. However, only users with admin access to a repository are able to deploy and delete apps. Network and application security Data hosting Our physical infrastructure is hosted and managed within secure data centers maintained by infrastructure-as-a-service cloud providers. Streamlit leverages many of these platforms' built-in security, privacy, and redundancy features. Our cloud providers continually monitor their data centers for risk and undergo assessments to ensure compliance with industry standards. Data deletion Community Cloud users have the option to delete any apps they’ve deployed as well as their entire account. When a user deletes their application from the admin console, we delete their source code, including any files copied from their GitHub repository or created within our system from the running app. However, we keep a record representing the application in our database. This record contains the coordinates of the application: the GitHub organization or user, the GitHub repository, the branch, and the path of the main module file. When a user deletes their account, we perform a hard deletion of their data and a hard deletion of all the apps that belong to the GitHub identity associated with their account. In this case, we do not maintain the records of application coordinates described above. When an account is deleted, we also delete any HubSpot contact associated with the Community Cloud account. Virtual private cloud All of our servers are within a virtual private cloud (VPC) with firewalls and network access control lists (ACLs) to allow external access to a select few API endpoints; all other internal services are only accessible within the VPC. Encryption Streamlit apps are served entirely over HTTPS. We use only strong cipher suites and HTTP Strict Transport Security (HSTS) to ensure browsers interact with Streamlit apps over HTTPS. All data sent to or from Streamlit over the public internet is encrypted in transit using 256-bit encryption. Our API and application endpoints use Transport Layer Security (TLS) 1.2 (or better). We also encrypt data at rest on disk using AES-256. Permissions and authentication Access to Community Cloud user account data is limited to authorized personnel. We run a zero-trust corporate network, utilize single sign-on and multi-factor authentication (MFA), and enforce strong password policies to ensure access to cloud-related services is protected. Incident response Our internal protocol for handling security events includes detection, analysis, response, escalation, and mitigation. Security advisories are made available at https://streamlit.io/advisories. Penetration testing Streamlit uses third-party security tools to scan for vulnerabilities on a regular basis. Our security teams conduct periodic, intensive penetration tests on the Streamlit platform. Our product development team responds to any identified issues or potential vulnerabilities to ensure the quality, security, and availability of Streamlit applications. Vulnerability management We keep our systems up-to-date with the latest security patches and continuously monitor for new vulnerabilities. This includes automated scanning of our code repositories for vulnerable dependencies. If you discover a vulnerability in one of our products or websites, please report the issue to HackerOne.Previous: Fork and edit a public appNext: Deploy your appforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy
https://docs.streamlit.io/get-started/installation#install-streamlit
DocumentationsearchSearchrocket_launchGet startedInstallationremoveUse command lineUse Anaconda DistributionUse GitHub CodespacesUse SnowflakeFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Get started/InstallationInstall Streamlit There are multiple ways to set up your development environment and install Streamlit. Read below to understand these options. Developing locally with Python installed on your own computer is the most common scenario. Summary for experts Set up your Python development environment. Run: pip install streamlit Validate the installation by running our Hello app: streamlit hello Jump to our Basic concepts. Installation steps for the rest of us Option 1: I'm comfortable with the command lineInstall Streamlit on your own machine using tools like venv and pip.Option 2: I prefer a graphical interfaceInstall Streamlit using the Anaconda Distribution graphical user interface. This is also the best approach if you're on Windows or don't have Python set up.Option 3: I'd rather use a cloud-based environmentUse Streamlit Community Cloud with GitHub Codespaces so you don't have to go through the trouble of installing Python and setting up an environment.Option 4: I need something secure, controlled, and in the cloudUse Streamlit in Snowflake to code your apps in the cloud, right alongside your data with role-based access controls.Previous: Get startedNext: Use command lineforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy
https://docs.streamlit.io/develop/api-reference/status/st.warning#stwarning
DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceremovePAGE ELEMENTSWrite and magicaddText elementsaddData elementsaddChart elementsaddInput widgetsaddMedia elementsaddLayouts and containersaddChat elementsaddStatus elementsremoveCALLOUTSst.successst.infost.warningst.errorst.exceptionOTHERst.progressst.spinnerst.statusst.toastst.balloonsst.snowThird-party componentsopen_in_newAPPLICATION LOGICNavigation and pagesaddExecution flowaddCaching and stateaddConnections and secretsaddCustom componentsaddUtilitiesaddConfigurationaddTOOLSApp testingaddCommand lineaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Develop/API reference/Status elements/st.warningst.warningStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeDisplay warning message. Function signature[source] st.warning(body, *, icon=None) Parameters body (str) The warning text to display. icon (str, None) An optional emoji or icon to display next to the alert. If icon is None (default), no icon is displayed. If icon is a string, the following options are valid: A single-character emoji. For example, you can set icon="🚨" or icon="🔥". Emoji short codes are not supported. An icon from the Material Symbols library (outlined style) in the format ":material/icon_name:" where "icon_name" is the name of the icon in snake case. For example, icon=":material/thumb_up:" will display the Thumb Up icon. Find additional icons in the Material Symbols font library. Example import streamlit as st st.warning('This is a warning', icon="⚠️") Previous: st.infoNext: st.errorforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy
https://docs.streamlit.io/get-started/installation/command-line#create-an-environment-using-venv
DocumentationsearchSearchrocket_launchGet startedInstallationremoveUse command lineUse Anaconda DistributionUse GitHub CodespacesUse SnowflakeFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Get started/Installation/Use command lineInstall Streamlit using command line This page will walk you through creating an environment with venv and installing Streamlit with pip. These are our recommended tools, but if you are familiar with others you can use your favorite ones too. At the end, you'll build a simple "Hello world" app and run it. If you prefer to have a graphical interface to manage your Python environments, check out how to Install Streamlit using Anaconda Distribution. Prerequisites As with any programming tool, in order to install Streamlit you first need to make sure your computer is properly set up. More specifically, you’ll need: Python We support version 3.8 to 3.12. A Python environment manager (recommended) Environment managers create virtual environments to isolate Python package installations between projects. We recommend using virtual environments because installing or upgrading a Python package may cause unintentional effects on another package. For a detailed introduction to Python environments, check out Python Virtual Environments: A Primer. For this guide, we'll be using venv, which comes with Python. A Python package manager Package managers handle installing each of your Python packages, including Streamlit. For this guide, we'll be using pip, which comes with Python. Only on MacOS: Xcode command line tools Download Xcode command line tools using these instructions in order to let the package manager install some of Streamlit's dependencies. A code editor Our favorite editor is VS Code, which is also what we use in all our tutorials. Create an environment using venv Open a terminal and navigate to your project folder. cd myproject In your terminal, type: python -m venv .venv A folder named ".venv" will appear in your project. This directory is where your virtual environment and its dependencies are installed. Activate your environment In your terminal, activate your environment with one of the following commands, depending on your operating system. # Windows command prompt .venv\Scripts\activate.bat # Windows PowerShell .venv\Scripts\Activate.ps1 # macOS and Linux source .venv/bin/activate Once activated, you will see your environment name in parentheses before your prompt. "(.venv)" Install Streamlit in your environment In the terminal with your environment activated, type: pip install streamlit Test that the installation worked by launching the Streamlit Hello example app: streamlit hello If this doesn't work, use the long-form command: python -m streamlit hello Streamlit's Hello app should appear in a new tab in your web browser! Built with Streamlit 🎈Fullscreen open_in_new Close your terminal when you are done. Create a "Hello World" app and run it Create a file named app.py in your project folder. import streamlit as st st.write("Hello world") Any time you want to use your new environment, you first need to go to your project folder (where the .venv directory lives) and run the command to activate it: # Windows command prompt .venv\Scripts\activate.bat # Windows PowerShell .venv\Scripts\Activate.ps1 # macOS and Linux source .venv/bin/activate Once activated, you will see your environment's name in parentheses at the beginning of your terminal prompt. "(.venv)" Run your Streamlit app. streamlit run app.py If this doesn't work, use the long-form command: python -m streamlit run app.py To stop the Streamlit server, press Ctrl+C in the terminal. When you're done using this environment, return to your normal shell by typing: deactivate What's next? Read about our Basic concepts to understand Streamlit's dataflow model.Previous: InstallationNext: Use Anaconda DistributionforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy
https://docs.streamlit.io/get-started/fundamentals/main-concepts#write-a-data-frame
DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsremoveBasic conceptsAdvanced conceptsAdditional featuresSummaryFirst stepsaddcodeDevelopConceptsaddAPI referenceaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Get started/Fundamentals/Basic conceptsBasic concepts of Streamlit Working with Streamlit is simple. First you sprinkle a few Streamlit commands into a normal Python script, then you run it with streamlit run: streamlit run your_script.py [-- script args] As soon as you run the script as shown above, a local Streamlit server will spin up and your app will open in a new tab in your default web browser. The app is your canvas, where you'll draw charts, text, widgets, tables, and more. What gets drawn in the app is up to you. For example st.text writes raw text to your app, and st.line_chart draws — you guessed it — a line chart. Refer to our API documentation to see all commands that are available to you. push_pinNoteWhen passing your script some custom arguments, they must be passed after two dashes. Otherwise the arguments get interpreted as arguments to Streamlit itself. Another way of running Streamlit is to run it as a Python module. This can be useful when configuring an IDE like PyCharm to work with Streamlit: # Running python -m streamlit run your_script.py # is equivalent to: streamlit run your_script.py starTipYou can also pass a URL to streamlit run! This is great when combined with GitHub Gists. For example:streamlit run https://raw.githubusercontent.com/streamlit/demo-uber-nyc-pickups/master/streamlit_app.py Development flow Every time you want to update your app, save the source file. When you do that, Streamlit detects if there is a change and asks you whether you want to rerun your app. Choose "Always rerun" at the top-right of your screen to automatically update your app every time you change its source code. This allows you to work in a fast interactive loop: you type some code, save it, try it out live, then type some more code, save it, try it out, and so on until you're happy with the results. This tight loop between coding and viewing results live is one of the ways Streamlit makes your life easier. starTipWhile developing a Streamlit app, it's recommended to lay out your editor and browser windows side by side, so the code and the app can be seen at the same time. Give it a try! As of Streamlit version 1.10.0 and higher, Streamlit apps cannot be run from the root directory of Linux distributions. If you try to run a Streamlit app from the root directory, Streamlit will throw a FileNotFoundError: [Errno 2] No such file or directory error. For more information, see GitHub issue #5239. If you are using Streamlit version 1.10.0 or higher, your main script should live in a directory other than the root directory. When using Docker, you can use the WORKDIR command to specify the directory where your main script lives. For an example of how to do this, read Create a Dockerfile. Data flow Streamlit's architecture allows you to write apps the same way you write plain Python scripts. To unlock this, Streamlit apps have a unique data flow: any time something must be updated on the screen, Streamlit reruns your entire Python script from top to bottom. This can happen in two situations: Whenever you modify your app's source code. Whenever a user interacts with widgets in the app. For example, when dragging a slider, entering text in an input box, or clicking a button. Whenever a callback is passed to a widget via the on_change (or on_click) parameter, the callback will always run before the rest of your script. For details on the Callbacks API, please refer to our Session State API Reference Guide. And to make all of this fast and seamless, Streamlit does some heavy lifting for you behind the scenes. A big player in this story is the @st.cache_data decorator, which allows developers to skip certain costly computations when their apps rerun. We'll cover caching later in this page. Display and style data There are a few ways to display data (tables, arrays, data frames) in Streamlit apps. Below, you will be introduced to magic and st.write(), which can be used to write anything from text to tables. After that, let's take a look at methods designed specifically for visualizing data. Use magic You can also write to your app without calling any Streamlit methods. Streamlit supports "magic commands," which means you don't have to use st.write() at all! To see this in action try this snippet: """ # My first app Here's our first attempt at using data to create a table: """ import streamlit as st import pandas as pd df = pd.DataFrame({ 'first column': [1, 2, 3, 4], 'second column': [10, 20, 30, 40] }) df Any time that Streamlit sees a variable or a literal value on its own line, it automatically writes that to your app using st.write(). For more information, refer to the documentation on magic commands. Write a data frame Along with magic commands, st.write() is Streamlit's "Swiss Army knife". You can pass almost anything to st.write(): text, data, Matplotlib figures, Altair charts, and more. Don't worry, Streamlit will figure it out and render things the right way. import streamlit as st import pandas as pd st.write("Here's our first attempt at using data to create a table:") st.write(pd.DataFrame({ 'first column': [1, 2, 3, 4], 'second column': [10, 20, 30, 40] })) There are other data specific functions like st.dataframe() and st.table() that you can also use for displaying data. Let's understand when to use these features and how to add colors and styling to your data frames. You might be asking yourself, "why wouldn't I always use st.write()?" There are a few reasons: Magic and st.write() inspect the type of data that you've passed in, and then decide how to best render it in the app. Sometimes you want to draw it another way. For example, instead of drawing a dataframe as an interactive table, you may want to draw it as a static table by using st.table(df). The second reason is that other methods return an object that can be used and modified, either by adding data to it or replacing it. Finally, if you use a more specific Streamlit method you can pass additional arguments to customize its behavior. For example, let's create a data frame and change its formatting with a Pandas Styler object. In this example, you'll use Numpy to generate a random sample, and the st.dataframe() method to draw an interactive table. push_pinNoteThis example uses Numpy to generate a random sample, but you can use Pandas DataFrames, Numpy arrays, or plain Python arrays. import streamlit as st import numpy as np dataframe = np.random.randn(10, 20) st.dataframe(dataframe) Let's expand on the first example using the Pandas Styler object to highlight some elements in the interactive table. import streamlit as st import numpy as np import pandas as pd dataframe = pd.DataFrame( np.random.randn(10, 20), columns=('col %d' % i for i in range(20))) st.dataframe(dataframe.style.highlight_max(axis=0)) Streamlit also has a method for static table generation: st.table(). import streamlit as st import numpy as np import pandas as pd dataframe = pd.DataFrame( np.random.randn(10, 20), columns=('col %d' % i for i in range(20))) st.table(dataframe) Draw charts and maps Streamlit supports several popular data charting libraries like Matplotlib, Altair, deck.gl, and more. In this section, you'll add a bar chart, line chart, and a map to your app. Draw a line chart You can easily add a line chart to your app with st.line_chart(). We'll generate a random sample using Numpy and then chart it. import streamlit as st import numpy as np import pandas as pd chart_data = pd.DataFrame( np.random.randn(20, 3), columns=['a', 'b', 'c']) st.line_chart(chart_data) Plot a map With st.map() you can display data points on a map. Let's use Numpy to generate some sample data and plot it on a map of San Francisco. import streamlit as st import numpy as np import pandas as pd map_data = pd.DataFrame( np.random.randn(1000, 2) / [50, 50] + [37.76, -122.4], columns=['lat', 'lon']) st.map(map_data) Widgets When you've got the data or model into the state that you want to explore, you can add in widgets like st.slider(), st.button() or st.selectbox(). It's really straightforward — treat widgets as variables: import streamlit as st x = st.slider('x') # 👈 this is a widget st.write(x, 'squared is', x * x) On first run, the app above should output the text "0 squared is 0". Then every time a user interacts with a widget, Streamlit simply reruns your script from top to bottom, assigning the current state of the widget to your variable in the process. For example, if the user moves the slider to position 10, Streamlit will rerun the code above and set x to 10 accordingly. So now you should see the text "10 squared is 100". Widgets can also be accessed by key, if you choose to specify a string to use as the unique key for the widget: import streamlit as st st.text_input("Your name", key="name") # You can access the value at any point with: st.session_state.name Every widget with a key is automatically added to Session State. For more information about Session State, its association with widget state, and its limitations, see Session State API Reference Guide. Use checkboxes to show/hide data One use case for checkboxes is to hide or show a specific chart or section in an app. st.checkbox() takes a single argument, which is the widget label. In this sample, the checkbox is used to toggle a conditional statement. import streamlit as st import numpy as np import pandas as pd if st.checkbox('Show dataframe'): chart_data = pd.DataFrame( np.random.randn(20, 3), columns=['a', 'b', 'c']) chart_data Use a selectbox for options Use st.selectbox to choose from a series. You can write in the options you want, or pass through an array or data frame column. Let's use the df data frame we created earlier. import streamlit as st import pandas as pd df = pd.DataFrame({ 'first column': [1, 2, 3, 4], 'second column': [10, 20, 30, 40] }) option = st.selectbox( 'Which number do you like best?', df['first column']) 'You selected: ', option Layout Streamlit makes it easy to organize your widgets in a left panel sidebar with st.sidebar. Each element that's passed to st.sidebar is pinned to the left, allowing users to focus on the content in your app while still having access to UI controls. For example, if you want to add a selectbox and a slider to a sidebar, use st.sidebar.slider and st.sidebar.selectbox instead of st.slider and st.selectbox: import streamlit as st # Add a selectbox to the sidebar: add_selectbox = st.sidebar.selectbox( 'How would you like to be contacted?', ('Email', 'Home phone', 'Mobile phone') ) # Add a slider to the sidebar: add_slider = st.sidebar.slider( 'Select a range of values', 0.0, 100.0, (25.0, 75.0) ) Beyond the sidebar, Streamlit offers several other ways to control the layout of your app. st.columns lets you place widgets side-by-side, and st.expander lets you conserve space by hiding away large content. import streamlit as st left_column, right_column = st.columns(2) # You can use a column just like st.sidebar: left_column.button('Press me!') # Or even better, call Streamlit functions inside a "with" block: with right_column: chosen = st.radio( 'Sorting hat', ("Gryffindor", "Ravenclaw", "Hufflepuff", "Slytherin")) st.write(f"You are in {chosen} house!") push_pinNotest.echo and st.spinner are not currently supported inside the sidebar or layout options. Rest assured, though, we're currently working on adding support for those too! Show progress When adding long running computations to an app, you can use st.progress() to display status in real time. First, let's import time. We're going to use the time.sleep() method to simulate a long running computation: import time Now, let's create a progress bar: import streamlit as st import time 'Starting a long computation...' # Add a placeholder latest_iteration = st.empty() bar = st.progress(0) for i in range(100): # Update the progress bar with each iteration. latest_iteration.text(f'Iteration {i+1}') bar.progress(i + 1) time.sleep(0.1) '...and now we\'re done!' Previous: FundamentalsNext: Advanced conceptsforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy
https://docs.streamlit.io/develop/tutorials/databases/supabase#sign-in-to-supabase-and-create-a-project
DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceaddTutorialsremoveExecution flowaddConnect to data sourcesremoveAWS S3BigQueryDeta BaseFirestoreopen_in_newGoogle Cloud StorageMicrosoft SQL ServerMongoDBMySQLNeonPostgreSQLPrivate Google SheetPublic Google SheetSnowflakeSupabaseTableauTiDBTigerGraphMultipage appsaddWork with LLMsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Develop/Tutorials/Connect to data sources/SupabaseConnect Streamlit to Supabase Introduction This guide explains how to securely access a Supabase instance from Streamlit Community Cloud. It uses st.connection, Streamlit Supabase Connector (a community-built connection developed by @SiddhantSadangi) and Streamlit's Secrets management. Supabase is the open source Firebase alternative and is based on PostgreSQL. push_pinNoteCommunity-built connections, such as the Streamlit Supabase Connector, extend and build on the st.connection interface and make it easier than ever to build Streamlit apps with a wide variety of data sources. These type of connections work exactly the same as the ones built into Streamlit and have access to all the same capabilities. Sign in to Supabase and create a project First, head over to Supabase and sign up for a free account using your GitHub. Sign in with GitHubAuthorize Supabase Once you're signed in, you can create a project. Your Supabase accountCreate a new project Your screen should look like this once your project has been created: priority_highImportantMake sure to note down your Project API Key and Project URL highlighted in the above screenshot. ☝️You will need these to connect to your Supabase instance from Streamlit. Create a Supabase database Now that you have a project, you can create a database and populate it with some sample data. To do so, click on the SQL editor button on the same project page, followed by the New query button in the SQL editor. Open the SQL editorCreate a new query In the SQL editor, enter the following queries to create a database and a table with some example values: CREATE TABLE mytable ( name varchar(80), pet varchar(80) ); INSERT INTO mytable VALUES ('Mary', 'dog'), ('John', 'cat'), ('Robert', 'bird'); Click Run to execute the queries. To verify that the queries were executed successfully, click on the Table Editor button on the left menu, followed by your newly created table mytable. Write and run your queriesView your table in the Table Editor With your Supabase database created, you can now connect to it from Streamlit! Add Supabase Project URL and API key to your local app secrets Your local Streamlit app will read secrets from a file .streamlit/secrets.toml in your app's root directory. Create this file if it doesn't exist yet and add the SUPABASE_URL and SUPABASE_KEY here: # .streamlit/secrets.toml [connections.supabase] SUPABASE_URL = "xxxx" SUPABASE_KEY = "xxxx" Replace xxxx above with your Project URL and API key from Step 1. priority_highImportantAdd this file to .gitignore and don't commit it to your GitHub repo! Copy your app secrets to the cloud As the secrets.toml file above is not committed to GitHub, you need to pass its content to your deployed app (on Streamlit Community Cloud) separately. Go to the app dashboard and in the app's dropdown menu, click on Edit Secrets. Copy the content of secrets.toml into the text area. More information is available at Secrets management. Add st-supabase-connection to your requirements file Add the st-supabase-connection community-built connection library to your requirements.txt file, preferably pinning its version (replace x.x.x with the version you want installed): # requirements.txt st-supabase-connection==x.x.x starTipWe've used the st-supabase-connection library here in combination with st.connection to benefit from the ease of setting up the data connection, managing your credentials, and Streamlit's caching capabilities that native and community-built connections provide.You can however still directly use the Supabase Python Client Library library if you prefer, but you'll need to write more code to set up the connection and cache the results. See Using the Supabase Python Client Library below for an example. Write your Streamlit app Copy the code below to your Streamlit app and run it. # streamlit_app.py import streamlit as st from st_supabase_connection import SupabaseConnection # Initialize connection. conn = st.connection("supabase",type=SupabaseConnection) # Perform query. rows = conn.query("*", table="mytable", ttl="10m").execute() # Print results. for row in rows.data: st.write(f"{row['name']} has a :{row['pet']}:") See st.connection above? This handles secrets retrieval, setup, query caching and retries. By default, query() results are cached without expiring. In this case, we set ttl="10m" to ensure the query result is cached for no longer than 10 minutes. You can also set ttl=0 to disable caching. Learn more in Caching. If everything worked out (and you used the example table we created above), your app should look like this: As Supabase uses PostgresSQL under the hood, you can also connect to Supabase by using the connection string Supabase provides under Settings > Databases. From there, you can refer to the PostgresSQL tutorial to connect to your database. Using the Supabase Python Client Library If you prefer to use the Supabase Python Client Library directly, you can do so by following the steps below. Add your Supabase Project URL and API key to your local app secrets: Your local Streamlit app will read secrets from a file .streamlit/secrets.toml in your app's root directory. Create this file if it doesn't exist yet and add the SUPABASE_URL and SUPABASE_KEY here: # .streamlit/secrets.toml SUPABASE_URL = "xxxx" SUPABASE_KEY = "xxxx" Add supabase to your requirements file: Add the supabase Python Client Library to your requirements.txt file, preferably pinning its version (replace x.x.x with the version you want installed): # requirements.txt supabase==x.x.x Write your Streamlit app: Copy the code below to your Streamlit app and run it. # streamlit_app.py import streamlit as st from supabase import create_client, Client # Initialize connection. # Uses st.cache_resource to only run once. @st.cache_resource def init_connection(): url = st.secrets["SUPABASE_URL"] key = st.secrets["SUPABASE_KEY"] return create_client(url, key) supabase = init_connection() # Perform query. # Uses st.cache_data to only rerun when the query changes or after 10 min. @st.cache_data(ttl=600) def run_query(): return supabase.table("mytable").select("*").execute() rows = run_query() # Print results. for row in rows.data: st.write(f"{row['name']} has a :{row['pet']}:") See st.cache_data above? Without it, Streamlit would run the query every time the app reruns (e.g. on a widget interaction). With st.cache_data, it only runs when the query changes or after 10 minutes (that's what ttl is for). Watch out: If your database updates more frequently, you should adapt ttl or remove caching so viewers always see the latest data. Learn more in Caching. Previous: SnowflakeNext: TableauforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy
https://docs.streamlit.io/en/0.65.0/api.html#built-in-connections
DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceremovePAGE ELEMENTSWrite and magicaddText elementsaddData elementsaddChart elementsaddInput widgetsaddMedia elementsaddLayouts and containersaddChat elementsaddStatus elementsaddThird-party componentsopen_in_newAPPLICATION LOGICNavigation and pagesaddExecution flowaddCaching and stateaddConnections and secretsaddCustom componentsaddUtilitiesaddConfigurationaddTOOLSApp testingaddCommand lineaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Develop/API referenceAPI reference Streamlit makes it easy for you to visualize, mutate, and share data. The API reference is organized by activity type, like displaying data or optimizing performance. Each section includes methods associated with the activity type, including examples. Browse our API below and click to learn more about any of our available commands! 🎈 Display almost anything Write and magic st.writeWrite arguments to the app.st.write("Hello **world**!") st.write(my_data_frame) st.write(my_mpl_figure) st.write_streamWrite generators or streams to the app with a typewriter effect.st.write_stream(my_generator) st.write_stream(my_llm_stream) MagicAny time Streamlit sees either a variable or literal value on its own line, it automatically writes that to your app using st.write"Hello **world**!" my_data_frame my_mpl_figure Text elements MarkdownDisplay string formatted as Markdown.st.markdown("Hello **world**!") TitleDisplay text in title formatting.st.title("The app title") HeaderDisplay text in header formatting.st.header("This is a header") SubheaderDisplay text in subheader formatting.st.subheader("This is a subheader") CaptionDisplay text in small font.st.caption("This is written small caption text") Code blockDisplay a code block with optional syntax highlighting.st.code("a = 1234") EchoDisplay some code in the app, then execute it. Useful for tutorials.with st.echo(): st.write('This code will be printed') LaTeXDisplay mathematical expressions formatted as LaTeX.st.latex("\int a x^2 \,dx") Preformatted textWrite fixed-width and preformatted text.st.text("Hello world") DividerDisplay a horizontal rule.st.divider() Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration! PreviousTagsAdd tags to your Streamlit apps. Created by @gagan3012.st_tags(label='# Enter Keywords:', text='Press enter to add more', value=['Zero', 'One', 'Two'], suggestions=['five', 'six', 'seven', 'eight', 'nine', 'three', 'eleven', 'ten', 'four'], maxtags = 4, key='1') NLUApply text mining on a dataframe. Created by @JohnSnowLabs.nlu.load('sentiment').predict('I love NLU! <3') Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.mention(label="An awesome Streamlit App", icon="streamlit", url="https://extras.streamlit.app",) Annotated textDisplay annotated text in Streamlit apps. Created by @tvst.annotated_text("This ", ("is", "verb"), " some ", ("annotated", "adj"), ("text", "noun"), " for those of ", ("you", "pronoun"), " who ", ("like", "verb"), " this sort of ", ("thing", "noun"), ".") Drawable CanvasProvides a sketching canvas using Fabric.js. Created by @andfanilo.st_canvas(fill_color="rgba(255, 165, 0, 0.3)", stroke_width=stroke_width, stroke_color=stroke_color, background_color=bg_color, background_image=Image.open(bg_image) if bg_image else None, update_streamlit=realtime_update, height=150, drawing_mode=drawing_mode, point_display_radius=point_display_radius if drawing_mode == 'point' else 0, key="canvas",) TagsAdd tags to your Streamlit apps. Created by @gagan3012.st_tags(label='# Enter Keywords:', text='Press enter to add more', value=['Zero', 'One', 'Two'], suggestions=['five', 'six', 'seven', 'eight', 'nine', 'three', 'eleven', 'ten', 'four'], maxtags = 4, key='1') NLUApply text mining on a dataframe. Created by @JohnSnowLabs.nlu.load('sentiment').predict('I love NLU! <3') Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.mention(label="An awesome Streamlit App", icon="streamlit", url="https://extras.streamlit.app",) Annotated textDisplay annotated text in Streamlit apps. Created by @tvst.annotated_text("This ", ("is", "verb"), " some ", ("annotated", "adj"), ("text", "noun"), " for those of ", ("you", "pronoun"), " who ", ("like", "verb"), " this sort of ", ("thing", "noun"), ".") Drawable CanvasProvides a sketching canvas using Fabric.js. Created by @andfanilo.st_canvas(fill_color="rgba(255, 165, 0, 0.3)", stroke_width=stroke_width, stroke_color=stroke_color, background_color=bg_color, background_image=Image.open(bg_image) if bg_image else None, update_streamlit=realtime_update, height=150, drawing_mode=drawing_mode, point_display_radius=point_display_radius if drawing_mode == 'point' else 0, key="canvas",) TagsAdd tags to your Streamlit apps. Created by @gagan3012.st_tags(label='# Enter Keywords:', text='Press enter to add more', value=['Zero', 'One', 'Two'], suggestions=['five', 'six', 'seven', 'eight', 'nine', 'three', 'eleven', 'ten', 'four'], maxtags = 4, key='1') NLUApply text mining on a dataframe. Created by @JohnSnowLabs.nlu.load('sentiment').predict('I love NLU! <3') Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.mention(label="An awesome Streamlit App", icon="streamlit", url="https://extras.streamlit.app",) Next Data elements DataframesDisplay a dataframe as an interactive table.st.dataframe(my_data_frame) Data editorDisplay a data editor widget.edited = st.data_editor(df, num_rows="dynamic") Column configurationConfigure the display and editing behavior of dataframes and data editors.st.column_config.NumberColumn("Price (in USD)", min_value=0, format="$%d") Static tablesDisplay a static table.st.table(my_data_frame) MetricsDisplay a metric in big bold font, with an optional indicator of how the metric changed.st.metric("My metric", 42, 2) Dicts and JSONDisplay object or string as a pretty-printed JSON string.st.json(my_dict) Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration! PreviousImage CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates value = streamlit_image_coordinates("https://placekitten.com/200/300") st.write(value) Plotly EventsMake Plotly charts interactive!. Created by @null-jones.from streamlit_plotly_events import plotly_events fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.metric_cards import style_metric_cards col3.metric(label="No Change", value=5000, delta=0) style_metric_cards() Streamlit AggridImplementation of Ag-Grid component for Streamlit. Created by @PablocFonseca.df = pd.DataFrame({'col1': [1, 2, 3], 'col2': [4, 5, 6]}) grid_return = AgGrid(df, editable=True) new_df = grid_return['data'] Streamlit FoliumStreamlit Component for rendering Folium maps. Created by @randyzwitch.m = folium.Map(location=[39.949610, -75.150282], zoom_start=16) folium.Marker([39.949610, -75.150282], popup="Liberty Bell", tooltip="Liberty Bell").add_to(m) st_data = st_folium(m, width=725) Pandas ProfilingPandas profiling component for Streamlit. Created by @okld.df = pd.read_csv("https://storage.googleapis.com/tf-datasets/titanic/train.csv") pr = df.profile_report() st_profile_report(pr) Image CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates value = streamlit_image_coordinates("https://placekitten.com/200/300") st.write(value) Plotly EventsMake Plotly charts interactive!. Created by @null-jones.from streamlit_plotly_events import plotly_events fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.metric_cards import style_metric_cards col3.metric(label="No Change", value=5000, delta=0) style_metric_cards() Streamlit AggridImplementation of Ag-Grid component for Streamlit. Created by @PablocFonseca.df = pd.DataFrame({'col1': [1, 2, 3], 'col2': [4, 5, 6]}) grid_return = AgGrid(df, editable=True) new_df = grid_return['data'] Streamlit FoliumStreamlit Component for rendering Folium maps. Created by @randyzwitch.m = folium.Map(location=[39.949610, -75.150282], zoom_start=16) folium.Marker([39.949610, -75.150282], popup="Liberty Bell", tooltip="Liberty Bell").add_to(m) st_data = st_folium(m, width=725) Pandas ProfilingPandas profiling component for Streamlit. Created by @okld.df = pd.read_csv("https://storage.googleapis.com/tf-datasets/titanic/train.csv") pr = df.profile_report() st_profile_report(pr) Image CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates value = streamlit_image_coordinates("https://placekitten.com/200/300") st.write(value) Plotly EventsMake Plotly charts interactive!. Created by @null-jones.from streamlit_plotly_events import plotly_events fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.metric_cards import style_metric_cards col3.metric(label="No Change", value=5000, delta=0) style_metric_cards() Next Chart elements Simple area chartsDisplay an area chart.st.area_chart(my_data_frame) Simple bar chartsDisplay a bar chart.st.bar_chart(my_data_frame) Simple line chartsDisplay a line chart.st.line_chart(my_data_frame) Simple scatter chartsDisplay a line chart.st.scatter_chart(my_data_frame) Scatterplots on mapsDisplay a map with points on it.st.map(my_data_frame) MatplotlibDisplay a matplotlib.pyplot figure.st.pyplot(my_mpl_figure) AltairDisplay a chart using the Altair library.st.altair_chart(my_altair_chart) Vega-LiteDisplay a chart using the Vega-Lite library.st.vega_lite_chart(my_vega_lite_chart) PlotlyDisplay an interactive Plotly chart.st.plotly_chart(my_plotly_chart) BokehDisplay an interactive Bokeh chart.st.bokeh_chart(my_bokeh_chart) PyDeckDisplay a chart using the PyDeck library.st.pydeck_chart(my_pydeck_chart) GraphVizDisplay a graph using the dagre-d3 library.st.graphviz_chart(my_graphviz_spec) Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration! PreviousStreamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl("https://assets5.lottiefiles.com/packages/lf20_V9t630.json") st_lottie(lottie_hello, key="hello") Plotly EventsMake Plotly charts interactive!. Created by @null-jones.fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.chart += get_annotations_chart(annotations=[("Mar 01, 2008", "Pretty good day for GOOG"), ("Dec 01, 2007", "Something's going wrong for GOOG & AAPL"), ("Nov 01, 2008", "Market starts again thanks to..."), ("Dec 01, 2009", "Small crash for GOOG after..."),],) st.altair_chart(chart, use_container_width=True) PlostA deceptively simple plotting library for Streamlit. Created by @tvst.import plost plost.line_chart(my_dataframe, x='time', y='stock_value', color='stock_name',) HiPlotHigh dimensional Interactive Plotting. Created by @facebookresearch.data = [{'dropout':0.1, 'lr': 0.001, 'loss': 10.0, 'optimizer': 'SGD'}, {'dropout':0.15, 'lr': 0.01, 'loss': 3.5, 'optimizer': 'Adam'}, {'dropout':0.3, 'lr': 0.1, 'loss': 4.5, 'optimizer': 'Adam'}] hip.Experiment.from_iterable(data).display() EChartsHigh dimensional Interactive Plotting. Created by @andfanilo.from streamlit_echarts import st_echarts st_echarts(options=options) Streamlit FoliumStreamlit Component for rendering Folium maps. Created by @randyzwitch.m = folium.Map(location=[39.949610, -75.150282], zoom_start=16) st_data = st_folium(m, width=725) Spacy-StreamlitspaCy building blocks and visualizers for Streamlit apps. Created by @explosion.models = ["en_core_web_sm", "en_core_web_md"] spacy_streamlit.visualize(models, "Sundar Pichai is the CEO of Google.") Streamlit AgraphA Streamlit Graph Vis, based on react-grah-vis. Created by @ChrisDelClea.from streamlit_agraph import agraph, Node, Edge, Config agraph(nodes=nodes, edges=edges, config=config) Streamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl("https://assets5.lottiefiles.com/packages/lf20_V9t630.json") st_lottie(lottie_hello, key="hello") Plotly EventsMake Plotly charts interactive!. Created by @null-jones.fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.chart += get_annotations_chart(annotations=[("Mar 01, 2008", "Pretty good day for GOOG"), ("Dec 01, 2007", "Something's going wrong for GOOG & AAPL"), ("Nov 01, 2008", "Market starts again thanks to..."), ("Dec 01, 2009", "Small crash for GOOG after..."),],) st.altair_chart(chart, use_container_width=True) PlostA deceptively simple plotting library for Streamlit. Created by @tvst.import plost plost.line_chart(my_dataframe, x='time', y='stock_value', color='stock_name',) HiPlotHigh dimensional Interactive Plotting. Created by @facebookresearch.data = [{'dropout':0.1, 'lr': 0.001, 'loss': 10.0, 'optimizer': 'SGD'}, {'dropout':0.15, 'lr': 0.01, 'loss': 3.5, 'optimizer': 'Adam'}, {'dropout':0.3, 'lr': 0.1, 'loss': 4.5, 'optimizer': 'Adam'}] hip.Experiment.from_iterable(data).display() EChartsHigh dimensional Interactive Plotting. Created by @andfanilo.from streamlit_echarts import st_echarts st_echarts(options=options) Streamlit FoliumStreamlit Component for rendering Folium maps. Created by @randyzwitch.m = folium.Map(location=[39.949610, -75.150282], zoom_start=16) st_data = st_folium(m, width=725) Spacy-StreamlitspaCy building blocks and visualizers for Streamlit apps. Created by @explosion.models = ["en_core_web_sm", "en_core_web_md"] spacy_streamlit.visualize(models, "Sundar Pichai is the CEO of Google.") Streamlit AgraphA Streamlit Graph Vis, based on react-grah-vis. Created by @ChrisDelClea.from streamlit_agraph import agraph, Node, Edge, Config agraph(nodes=nodes, edges=edges, config=config) Streamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl("https://assets5.lottiefiles.com/packages/lf20_V9t630.json") st_lottie(lottie_hello, key="hello") Plotly EventsMake Plotly charts interactive!. Created by @null-jones.fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.chart += get_annotations_chart(annotations=[("Mar 01, 2008", "Pretty good day for GOOG"), ("Dec 01, 2007", "Something's going wrong for GOOG & AAPL"), ("Nov 01, 2008", "Market starts again thanks to..."), ("Dec 01, 2009", "Small crash for GOOG after..."),],) st.altair_chart(chart, use_container_width=True) Next Input widgets ButtonDisplay a button widget.clicked = st.button("Click me") Download buttonDisplay a download button widget.st.download_button("Download file", file) Form buttonDisplay a form submit button. For use with st.form.st.form_submit_button("Sign up") Link buttonDisplay a link button.st.link_button("Go to gallery", url) Page linkDisplay a link to another page in a multipage app.st.page_link("app.py", label="Home", icon="🏠") st.page_link("pages/profile.py", label="My profile") CheckboxDisplay a checkbox widget.selected = st.checkbox("I agree") Color pickerDisplay a color picker widget.color = st.color_picker("Pick a color") MultiselectDisplay a multiselect widget. The multiselect widget starts as empty.choices = st.multiselect("Buy", ["milk", "apples", "potatoes"]) RadioDisplay a radio button widget.choice = st.radio("Pick one", ["cats", "dogs"]) SelectboxDisplay a select widget.choice = st.selectbox("Pick one", ["cats", "dogs"]) Select-sliderDisplay a slider widget to select items from a list.size = st.select_slider("Pick a size", ["S", "M", "L"]) ToggleDisplay a toggle widget.activated = st.toggle("Activate") Number inputDisplay a numeric input widget.choice = st.number_input("Pick a number", 0, 10) SliderDisplay a slider widget.number = st.slider("Pick a number", 0, 100) Date inputDisplay a date input widget.date = st.date_input("Your birthday") Time inputDisplay a time input widget.time = st.time_input("Meeting time") Chat inputDisplay a chat input widget.prompt = st.chat_input("Say something") if prompt: st.write(f"The user has sent: {prompt}") Text-areaDisplay a multi-line text input widget.text = st.text_area("Text to translate") Text inputDisplay a single-line text input widget.name = st.text_input("First name") Data editorDisplay a data editor widget.edited = st.experimental_data_editor(df, num_rows="dynamic") File UploaderDisplay a file uploader widget.data = st.file_uploader("Upload a CSV") Camera inputDisplay a widget that allows users to upload images directly from a camera.image = st.camera_input("Take a picture") Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration! PreviousStreamlit ChatStreamlit Component for a Chatbot UI. Created by @AI-Yash.from streamlit_chat import message message("My message") message("Hello bot!", is_user=True) # align's the message to the right Streamlit Option MenuSelect a single item from a list of options in a menu. Created by @victoryhb.from streamlit_option_menu import option_menu option_menu("Main Menu", ["Home", 'Settings'], icons=['house', 'gear'], menu_icon="cast", default_index=1) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.stoggle import stoggle stoggle( "Click me!", """🥷 Surprise! Here's some additional content""",) Streamlit ElementsCreate a draggable and resizable dashboard in Streamlit. Created by @okls.from streamlit_elements import elements, mui, html with elements("new_element"): mui.Typography("Hello world") TagsAdd tags to your Streamlit apps. Created by @gagan3012.from streamlit_tags import st_tags st_tags(label='# Enter Keywords:', text='Press enter to add more', value=['Zero', 'One', 'Two'], suggestions=['five', 'six', 'seven', 'eight', 'nine', 'three', 'eleven', 'ten', 'four'], maxtags = 4, key='1') StqdmThe simplest way to handle a progress bar in streamlit app. Created by @Wirg.from stqdm import stqdm for _ in stqdm(range(50)): sleep(0.5) TimelineDisplay a Timeline in Streamlit apps using TimelineJS. Created by @innerdoc.from streamlit_timeline import timeline with open('example.json', "r") as f: timeline(f.read(), height=800) Camera input liveAlternative for st.camera_input which returns the webcam images live. Created by @blackary.from camera_input_live import camera_input_live image = camera_input_live() st.image(value) Streamlit AceAce editor component for Streamlit. Created by @okld.from streamlit_ace import st_ace content = st_ace() content Streamlit ChatStreamlit Component for a Chatbot UI. Created by @AI-Yash.from streamlit_chat import message message("My message") message("Hello bot!", is_user=True) # align's the message to the right Streamlit Option MenuSelect a single item from a list of options in a menu. Created by @victoryhb.from streamlit_option_menu import option_menu option_menu("Main Menu", ["Home", 'Settings'], icons=['house', 'gear'], menu_icon="cast", default_index=1) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.stoggle import stoggle stoggle( "Click me!", """🥷 Surprise! Here's some additional content""",) Streamlit ElementsCreate a draggable and resizable dashboard in Streamlit. Created by @okls.from streamlit_elements import elements, mui, html with elements("new_element"): mui.Typography("Hello world") TagsAdd tags to your Streamlit apps. Created by @gagan3012.from streamlit_tags import st_tags st_tags(label='# Enter Keywords:', text='Press enter to add more', value=['Zero', 'One', 'Two'], suggestions=['five', 'six', 'seven', 'eight', 'nine', 'three', 'eleven', 'ten', 'four'], maxtags = 4, key='1') StqdmThe simplest way to handle a progress bar in streamlit app. Created by @Wirg.from stqdm import stqdm for _ in stqdm(range(50)): sleep(0.5) TimelineDisplay a Timeline in Streamlit apps using TimelineJS. Created by @innerdoc.from streamlit_timeline import timeline with open('example.json', "r") as f: timeline(f.read(), height=800) Camera input liveAlternative for st.camera_input which returns the webcam images live. Created by @blackary.from camera_input_live import camera_input_live image = camera_input_live() st.image(value) Streamlit AceAce editor component for Streamlit. Created by @okld.from streamlit_ace import st_ace content = st_ace() content Streamlit ChatStreamlit Component for a Chatbot UI. Created by @AI-Yash.from streamlit_chat import message message("My message") message("Hello bot!", is_user=True) # align's the message to the right Streamlit Option MenuSelect a single item from a list of options in a menu. Created by @victoryhb.from streamlit_option_menu import option_menu option_menu("Main Menu", ["Home", 'Settings'], icons=['house', 'gear'], menu_icon="cast", default_index=1) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.stoggle import stoggle stoggle( "Click me!", """🥷 Surprise! Here's some additional content""",) Next Media elements ImageDisplay an image or list of images.st.image(numpy_array) st.image(image_bytes) st.image(file) st.image("https://example.com/myimage.jpg") AudioDisplay an audio player.st.audio(numpy_array) st.audio(audio_bytes) st.audio(file) st.audio("https://example.com/myaudio.mp3", format="audio/mp3") VideoDisplay a video player.st.video(numpy_array) st.video(video_bytes) st.video(file) st.video("https://example.com/myvideo.mp4", format="video/mp4") Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration! PreviousStreamlit CropperA simple image cropper for Streamlit. Created by @turner-anderson.from streamlit_cropper import st_cropper st_cropper(img, realtime_update=realtime_update, box_color=box_color, aspect_ratio=aspect_ratio) Image CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates streamlit_image_coordinates("https://placekitten.com/200/300") Streamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl("https://assets5.lottiefiles.com/packages/lf20_V9t630.json") st_lottie(lottie_hello, key="hello") Streamlit WebrtcHandling and transmitting real-time video/audio streams with Streamlit. Created by @whitphx.from streamlit_webrtc import webrtc_streamer webrtc_streamer(key="sample") Drawable CanvasProvides a sketching canvas using Fabric.js. Created by @andfanilo.from streamlit_drawable_canvas import st_canvas st_canvas(fill_color="rgba(255, 165, 0, 0.3)", stroke_width=stroke_width, stroke_color=stroke_color, background_color=bg_color, background_image=Image.open(bg_image) if bg_image else None, update_streamlit=realtime_update, height=150, drawing_mode=drawing_mode, point_display_radius=point_display_radius if drawing_mode == 'point' else 0, key="canvas",) Image ComparisonCompare images with a slider using JuxtaposeJS. Created by @fcakyon.from streamlit_image_comparison import image_comparison image_comparison(img1="image1.jpg", img2="image2.jpg",) Streamlit CropperA simple image cropper for Streamlit. Created by @turner-anderson.from streamlit_cropper import st_cropper st_cropper(img, realtime_update=realtime_update, box_color=box_color, aspect_ratio=aspect_ratio) Image CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates streamlit_image_coordinates("https://placekitten.com/200/300") Streamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl("https://assets5.lottiefiles.com/packages/lf20_V9t630.json") st_lottie(lottie_hello, key="hello") Streamlit WebrtcHandling and transmitting real-time video/audio streams with Streamlit. Created by @whitphx.from streamlit_webrtc import webrtc_streamer webrtc_streamer(key="sample") Drawable CanvasProvides a sketching canvas using Fabric.js. Created by @andfanilo.from streamlit_drawable_canvas import st_canvas st_canvas(fill_color="rgba(255, 165, 0, 0.3)", stroke_width=stroke_width, stroke_color=stroke_color, background_color=bg_color, background_image=Image.open(bg_image) if bg_image else None, update_streamlit=realtime_update, height=150, drawing_mode=drawing_mode, point_display_radius=point_display_radius if drawing_mode == 'point' else 0, key="canvas",) Image ComparisonCompare images with a slider using JuxtaposeJS. Created by @fcakyon.from streamlit_image_comparison import image_comparison image_comparison(img1="image1.jpg", img2="image2.jpg",) Streamlit CropperA simple image cropper for Streamlit. Created by @turner-anderson.from streamlit_cropper import st_cropper st_cropper(img, realtime_update=realtime_update, box_color=box_color, aspect_ratio=aspect_ratio) Image CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates streamlit_image_coordinates("https://placekitten.com/200/300") Streamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl("https://assets5.lottiefiles.com/packages/lf20_V9t630.json") st_lottie(lottie_hello, key="hello") Next Layouts and containers ColumnsInsert containers laid out as side-by-side columns.col1, col2 = st.columns(2) col1.write("this is column 1") col2.write("this is column 2") ContainerInsert a multi-element container.c = st.container() st.write("This will show last") c.write("This will show first") c.write("This will show second") Modal dialogsInsert a modal dialog that can rerun independently from the rest of the script.@st.experimental_dialog("Sign up") def email_form(): name = st.text_input("Name") email = st.text_input("Email") EmptyInsert a single-element container.c = st.empty() st.write("This will show last") c.write("This will be replaced") c.write("This will show first") ExpanderInsert a multi-element container that can be expanded/collapsed.with st.expander("Open to see more"): st.write("This is more content") PopoverInsert a multi-element popover container that can be opened/closed.with st.popover("Settings"): st.checkbox("Show completed") SidebarDisplay items in a sidebar.st.sidebar.write("This lives in the sidebar") st.sidebar.button("Click me!") TabsInsert containers separated into tabs.tab1, tab2 = st.tabs(["Tab 1", "Tab2"]) tab1.write("this is tab 1") tab2.write("this is tab 2") Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration!Streamlit ElementsCreate a draggable and resizable dashboard in Streamlit. Created by @okls.from streamlit_elements import elements, mui, html with elements("new_element"): mui.Typography("Hello world") PydanticAuto-generate Streamlit UI from Pydantic Models and Dataclasses. Created by @lukasmasuch.import streamlit_pydantic as sp sp.pydantic_form(key="my_form", model=ExampleModel) Streamlit PagesAn experimental version of Streamlit Multi-Page Apps. Created by @blackary.from st_pages import Page, show_pages, add_page_title show_pages([ Page("streamlit_app.py", "Home", "🏠"), Page("other_pages/page2.py", "Page 2", ":books:"), ]) Chat elements Streamlit provides a few commands to help you build conversational apps. These chat elements are designed to be used in conjunction with each other, but you can also use them separately. st.chat_message lets you insert a chat message container into the app so you can display messages from the user or the app. Chat containers can contain other Streamlit elements, including charts, tables, text, and more. st.chat_input lets you display a chat input widget so the user can type in a message. Chat inputDisplay a chat input widget.prompt = st.chat_input("Say something") if prompt: st.write(f"The user has sent: {prompt}") Chat messageInsert a chat message container.import numpy as np with st.chat_message("user"): st.write("Hello 👋") st.line_chart(np.random.randn(30, 3)) Status containerDisplay output of long-running tasks in a container.with st.status('Running'): do_something_slow() st.write_streamWrite generators or streams to the app with a typewriter effect.st.write_stream(my_generator) st.write_stream(my_llm_stream) Status elements Progress barDisplay a progress bar.for i in range(101): st.progress(i) do_something_slow() SpinnerTemporarily displays a message while executing a block of code.with st.spinner("Please wait..."): do_something_slow() Status containerDisplay output of long-running tasks in a container.with st.status('Running'): do_something_slow() ToastBriefly displays a toast message in the bottom-right corner.st.toast('Butter!', icon='🧈') BalloonsDisplay celebratory balloons!do_something() # Celebrate when all done! st.balloons() SnowflakesDisplay celebratory snowflakes!do_something() # Celebrate when all done! st.snow() Success boxDisplay a success message.st.success("Match found!") Info boxDisplay an informational message.st.info("Dataset is updated every day at midnight.") Warning boxDisplay warning message.st.warning("Unable to fetch image. Skipping...") Error boxDisplay error message.st.error("We encountered an error") Exception outputDisplay an exception.e = RuntimeError("This is an exception of type RuntimeError") st.exception(e) Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration!StqdmThe simplest way to handle a progress bar in streamlit app. Created by @Wirg.from stqdm import stqdm for _ in stqdm(range(50)): sleep(0.5) Custom notification boxA custom notification box with the ability to close it out. Created by @Socvest.from streamlit_custom_notification_box import custom_notification_box styles = {'material-icons':{'color': 'red'}, 'text-icon-link-close-container': {'box-shadow': '#3896de 0px 4px'}, 'notification-text': {'':''}, 'close-button':{'':''}, 'link':{'':''}} custom_notification_box(icon='info', textDisplay='We are almost done with your registration...', externalLink='more info', url='#', styles=styles, key="foo") Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.let_it_rain import rain rain(emoji="🎈", font_size=54, falling_speed=5, animation_length="infinite",) App logic and configuration Navigation and pages Switch pageProgrammatically navigates to a specified page.st.switch_page("pages/my_page.py") Page linkDisplay a link to another page in a multipage app.st.page_link("app.py", label="Home", icon="🏠") st.page_link("pages/profile.py", label="My profile") Execution flow Modal dialogsInsert a modal dialog that can rerun independently from the rest of the script.@st.experimental_dialog("Sign up") def email_form(): name = st.text_input("Name") email = st.text_input("Email") FormsCreate a form that batches elements together with a “Submit" button.with st.form(key='my_form'): name = st.text_input("Name") email = st.text_input("Email") st.form_submit_button("Sign up") Partial rerunsDefine a fragment to rerun independently from the rest of the script.@st.experimental_fragment(run_every="10s") def fragment(): df = get_data() st.line_chart(df) Rerun scriptRerun the script immediately.st.rerun() Stop executionStops execution immediately.st.stop() Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration!AutorefreshForce a refresh without tying up a script. Created by @kmcgrady.from streamlit_autorefresh import st_autorefresh st_autorefresh(interval=2000, limit=100, key="fizzbuzzcounter") PydanticAuto-generate Streamlit UI from Pydantic Models and Dataclasses. Created by @lukasmasuch.import streamlit_pydantic as sp sp.pydantic_form(key="my_form", model=ExampleModel) Streamlit PagesAn experimental version of Streamlit Multi-Page Apps. Created by @blackary.from st_pages import Page, show_pages, add_page_title show_pages([ Page("streamlit_app.py", "Home", "🏠"), Page("other_pages/page2.py", "Page 2", ":books:"), ]) Caching and state Cache dataFunction decorator to cache functions that return data (e.g. dataframe transforms, database queries, ML inference).@st.cache_data def long_function(param1, param2): # Perform expensive computation here or # fetch data from the web here return data Cache resourceFunction decorator to cache functions that return global resources (e.g. database connections, ML models).@st.cache_resource def init_model(): # Return a global resource here return pipeline( "sentiment-analysis", model="distilbert-base-uncased-finetuned-sst-2-english" ) Session stateSession state is a way to share variables between reruns, for each user session.st.session_state['key'] = value Query parametersGet, set, or clear the query parameters that are shown in the browser's URL bar.st.query_params[key] = value st.query_params.clear() Connections and databases Setup your connection Create a connectionConnect to a data source or APIconn = st.connection('pets_db', type='sql') pet_owners = conn.query('select * from pet_owners') st.dataframe(pet_owners) Built-in connections SnowflakeConnectionA connection to Snowflake.conn = st.connection('snowflake') SQLConnectionA connection to a SQL database using SQLAlchemy.conn = st.connection('sql') Build your own connections Connection base classBuild your own connection with BaseConnection.class MyConnection(BaseConnection[myconn.MyConnection]): def _connect(self, **kwargs) -> MyConnection: return myconn.connect(**self._secrets, **kwargs) def query(self, query): return self._instance.query(query) Secrets management Secrets singletonAccess secrets from a local TOML file.key = st.secrets["OpenAI_key"] Secrets fileSave your secrets in a per-project or per-profile TOML file.OpenAI_key = "<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#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/api-reference/navigation#navigation-and-pages
DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceremovePAGE ELEMENTSWrite and magicaddText elementsaddData elementsaddChart elementsaddInput widgetsaddMedia elementsaddLayouts and containersaddChat elementsaddStatus elementsaddThird-party componentsopen_in_newAPPLICATION LOGICNavigation and pagesremovest.page_linklinkst.switch_pageExecution flowaddCaching and stateaddConnections and secretsaddCustom componentsaddUtilitiesaddConfigurationaddTOOLSApp testingaddCommand lineaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Develop/API reference/Navigation and pagesNavigation and pages Page linkDisplay a link to another page in a multipage app.st.page_link("app.py", label="Home", icon="🏠") st.page_link("pages/profile.py", label="Profile") Switch pageProgrammatically navigates to a specified page.st.switch_page("pages/my_page.py") Previous: Third-party componentsNext: st.page_linkforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy
https://docs.streamlit.io/develop/api-reference/connections/st.connection
DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceremovePAGE ELEMENTSWrite and magicaddText elementsaddData elementsaddChart elementsaddInput widgetsaddMedia elementsaddLayouts and containersaddChat elementsaddStatus elementsaddThird-party componentsopen_in_newAPPLICATION LOGICNavigation and pagesaddExecution flowaddCaching and stateaddConnections and secretsremoveSECRETSst.secretssecrets.tomlCONNECTIONSst.connectionSnowflakeConnectionSQLConnectionBaseConnectionSnowparkConnectiondeleteCustom componentsaddUtilitiesaddConfigurationaddTOOLSApp testingaddCommand lineaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Develop/API reference/Connections and secrets/st.connectionstarTipThis page only contains the st.connection API. For a deeper dive into creating and managing data connections within Streamlit apps, read Connecting to data. st.connectionStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeCreate a new connection to a data store or API, or return an existing one. Config options, credentials, secrets, etc. for connections are taken from various sources: Any connection-specific configuration files. An app's secrets.toml files. The kwargs passed to this function. Function signature[source] st.connection(name, type=None, max_entries=None, ttl=None, **kwargs) Parameters name (str) The connection name used for secrets lookup in [connections.<name>]. Type will be inferred from passing "sql", "snowflake", or "snowpark". type (str, connection class, or None) The type of connection to create. It can be a keyword ("sql", "snowflake", or "snowpark"), a path to an importable class, or an imported class reference. All classes must extend st.connections.BaseConnection and implement the _connect() method. If the type kwarg is None, a type field must be set in the connection's section in secrets.toml. max_entries (int or None) The maximum number of connections to keep in the cache, or None for an unbounded cache. (When a new entry is added to a full cache, the oldest cached entry will be removed.) The default is None. ttl (float, timedelta, or None) The maximum number of seconds to keep results in the cache, or None if cached results should not expire. The default is None. **kwargs (any) Additional connection specific kwargs that are passed to the Connection's _connect() method. Learn more from the specific Connection's documentation. Returns(Connection object) An initialized Connection object of the specified type. Examples The easiest way to create a first-party (SQL, Snowflake, or Snowpark) connection is to use their default names and define corresponding sections in your secrets.toml file. import streamlit as st conn = st.connection("sql") # Config section defined in [connections.sql] in secrets.toml. Creating a SQLConnection with a custom name requires you to explicitly specify the type. If type is not passed as a kwarg, it must be set in the appropriate section of secrets.toml. import streamlit as st conn1 = st.connection("my_sql_connection", type="sql") # Config section defined in [connections.my_sql_connection]. conn2 = st.connection("my_other_sql_connection") # type must be set in [connections.my_other_sql_connection]. Passing the full module path to the connection class that you want to use can be useful, especially when working with a custom connection: import streamlit as st conn = st.connection("my_sql_connection", type="streamlit.connections.SQLConnection") Finally, you can pass the connection class to use directly to this function. Doing so allows static type checking tools such as mypy to infer the exact return type of st.connection. import streamlit as st from streamlit.connections import SQLConnection conn = st.connection("my_sql_connection", type=SQLConnection) For a comprehensive overview of this feature, check out this video tutorial by Joshua Carroll, Streamlit's Product Manager for Developer Experience. You'll learn about the feature's utility in creating and managing data connections within your apps by using real-world examples. Previous: secrets.tomlNext: SnowflakeConnectionforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy
https://docs.streamlit.io/get-started/installation/anaconda-distribution#install-streamlit-in-your-environment
DocumentationsearchSearchrocket_launchGet startedInstallationremoveUse command lineUse Anaconda DistributionUse GitHub CodespacesUse SnowflakeFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Get started/Installation/Use Anaconda DistributionInstall Streamlit using Anaconda Distribution This page walks you through installing Streamlit locally using Anaconda Distribution. At the end, you'll build a simple "Hello world" app and run it. You can read more about Getting started with Anaconda Distribution in Anaconda's docs. If you prefer to manage your Python environments via command line, check out how to Install Streamlit using command line. Prerequisites A code editor Anaconda Distribution includes Python and basically everything you need to get started. The only thing left for you to choose is a code editor. Our favorite editor is VS Code, which is also what we use in all our tutorials. Knowledge about environment managers Environment managers create virtual environments to isolate Python package installations between projects. For a detailed introduction to Python environments, check out Python Virtual Environments: A Primer. But don't worry! In this guide we'll teach you how to install and use an environment manager (Anaconda). Install Anaconda Distribution Go to anaconda.com/download. Install Anaconda Distribution for your OS. Create an environment using Anaconda Navigator Open Anaconda Navigator (the graphical interface included with Anaconda Distribution). You can decline signing in to Anaconda if prompted. In the left menu, click "Environments". At the bottom of your environments list, click "Create". Enter "streamlitenv" for the name of your environment. Click "Create." Activate your environment Click the green play icon (play_circle) next to your environment. Click "Open Terminal." A terminal will open with your environment activated. Your environment's name will appear in parentheses at the beginning of your terminal's prompt to show that it's activated. Install Streamlit in your environment In your terminal, type: pip install streamlit To validate your installation, enter: streamlit hello If this doesn't work, use the long-form command: python -m streamlit hello The Streamlit Hello example app will automatically open in your browser. If it doesn't, open your browser and go to the localhost address indicated in your terminal, typically http://localhost:8501. Play around with the app! Close your terminal. Create a Hello World app and run it Open VS Code with a new project. Create a Python file named app.py in your project folder. Copy the following code into app.py and save it. import streamlit as st st.write("Hello World") Click your Python interpreter in the lower-right corner, then choose your streamlitenv environment from the drop-down. Right-click app.py in your file navigation and click "Open in integrated terminal". A terminal will open with your environment activated. Confirm this by looking for "(streamlitenv)" at the beginning of your next prompt. If it is not there, manually activate your environment with the command: conda activate streamlitenv In your terminal, type: streamlit run app.py If this doesn't work, use the long-form command: python -m streamlit run app.py Your app will automatically open in your browser. If it doesn't for any reason, open your browser and go to the localhost address indicated in your terminal, typically http://localhost:8501. Change st.write to st.title and save your file: import streamlit as st st.title("Hello World") In your browser, click "Always rerun" to instantly rerun your app whenever you save a change to your file. Your app will update! Keep making changes and you will see your changes as soon as you save your file. When you're done, you can stop your app with Ctrl+C in your terminal or just by closing your terminal. What's next? Read about our Basic concepts and try out more commands in your app.Previous: Use command lineNext: Use GitHub CodespacesforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy
https://docs.streamlit.io/develop/api-reference/app-testing/st.testing.v1.apptest#apptesttext_area
DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceremovePAGE ELEMENTSWrite and magicaddText elementsaddData elementsaddChart elementsaddInput widgetsaddMedia elementsaddLayouts and containersaddChat elementsaddStatus elementsaddThird-party componentsopen_in_newAPPLICATION LOGICNavigation and pagesaddExecution flowaddCaching and stateaddConnections and secretsaddCustom componentsaddUtilitiesaddConfigurationaddTOOLSApp testingremovest.testing.v1.AppTestTesting element classesCommand lineaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Develop/API reference/App testing/st.testing.v1.AppTest The AppTest class st.testing.v1.AppTestStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA simulated Streamlit app to check the correctness of displayed elements and outputs. An instance of AppTest simulates a running Streamlit app. This class provides methods to set up, manipulate, and inspect the app contents via API instead of a browser UI. It can be used to write automated tests of an app in various scenarios. These can then be run using a tool like pytest. AppTest can be initialized by one of three class methods: st.testing.v1.AppTest.from_file (recommended) st.testing.v1.AppTest.from_string st.testing.v1.AppTest.from_function Once initialized, Session State and widget values can be updated and the script can be run. Unlike an actual live-running Streamlit app, you need to call AppTest.run() explicitly to re-run the app after changing a widget value. Switching pages also requires an explicit, follow-up call to AppTest.run(). AppTest enables developers to build tests on their app as-is, in the familiar python test format, without major refactoring or abstracting out logic to be tested separately from the UI. Tests can run quickly with very low overhead. A typical pattern is to build a suite of tests for an app that ensure consistent functionality as the app evolves, and run the tests locally and/or in a CI environment like Github Actions. Note AppTest only supports testing a single page of an app per instance. For multipage apps, each page will need to be tested separately. No methods exist to programatically switch pages within AppTest. Class description[source] st.testing.v1.AppTest(script_path, *, default_timeout, args=None, kwargs=None) Methods get(element_type) Get elements or widgets of the specified type. run(*, timeout=None) Run the script from the current state. switch_page(page_path) Switch to another page of the app. Attributes secrets (dict[str, Any]) Dictionary of secrets to be used the simulated app. Use dict-like syntax to set secret values for the simulated app. session_state (SafeSessionState) Session State for the simulated app. SafeSessionState object supports read and write operations as usual for Streamlit apps. query_params (dict[str, Any]) Dictionary of query parameters to be used by the simluated app. Use dict-like syntax to set query_params values for the simulated app. button Sequence of all st.button and st.form_submit_button widgets. caption Sequence of all st.caption elements. chat_input Sequence of all st.chat_input widgets. chat_message Sequence of all st.chat_message elements. checkbox Sequence of all st.checkbox widgets. code Sequence of all st.code elements. color_picker Sequence of all st.color_picker widgets. columns Sequence of all columns within st.columns elements. dataframe Sequence of all st.dataframe elements. date_input Sequence of all st.date_input widgets. divider Sequence of all st.divider elements. error Sequence of all st.error elements. exception Sequence of all st.exception elements. expander Sequence of all st.expander elements. header Sequence of all st.header elements. info Sequence of all st.info elements. json Sequence of all st.json elements. latex Sequence of all st.latex elements. main Sequence of elements within the main body of the app. markdown Sequence of all st.markdown elements. metric Sequence of all st.metric elements. multiselect Sequence of all st.multiselect widgets. number_input Sequence of all st.number_input widgets. radio Sequence of all st.radio widgets. select_slider Sequence of all st.select_slider widgets. selectbox Sequence of all st.selectbox widgets. sidebar Sequence of all elements within st.sidebar. slider Sequence of all st.slider widgets. status Sequence of all st.status elements. subheader Sequence of all st.subheader elements. success Sequence of all st.success elements. table Sequence of all st.table elements. tabs Sequence of all tabs within st.tabs elements. text Sequence of all st.text elements. text_area Sequence of all st.text_area widgets. text_input Sequence of all st.text_input widgets. time_input Sequence of all st.time_input widgets. title Sequence of all st.title elements. toast Sequence of all st.toast elements. toggle Sequence of all st.toggle widgets. warning Sequence of all st.warning elements. Initialize a simulated app using AppTest AppTest.from_fileStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeCreate an instance of AppTest to simulate an app page defined within a file. This option is most convenient for CI workflows and testing of published apps. The script must be executable on its own and so must contain all necessary imports. Function signature[source] AppTest.from_file(cls, script_path, *, default_timeout=3) Parameters script_path (str) Path to a script file. The path should be absolute or relative to the file calling .from_file. default_timeout (float) Default time in seconds before a script run is timed out. Can be overridden for individual .run() calls. Returns(AppTest) A simulated Streamlit app for testing. The simulated app can be executed via .run(). AppTest.from_stringStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeCreate an instance of AppTest to simulate an app page defined within a string. This is useful for testing short scripts that fit comfortably as an inline string in the test itself, without having to create a separate file for it. The script must be executable on its own and so must contain all necessary imports. Function signature[source] AppTest.from_string(cls, script, *, default_timeout=3) Parameters script (str) The string contents of the script to be run. default_timeout (float) Default time in seconds before a script run is timed out. Can be overridden for individual .run() calls. Returns(AppTest) A simulated Streamlit app for testing. The simulated app can be executed via .run(). AppTest.from_functionStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeCreate an instance of AppTest to simulate an app page defined within a function. This is similar to AppTest.from_string(), but more convenient to write with IDE assistance. The script must be executable on its own and so must contain all necessary imports. Function signature[source] AppTest.from_function(cls, script, *, default_timeout=3, args=None, kwargs=None) Parameters script (Callable) A function whose body will be used as a script. Must be runnable in isolation, so it must include any necessary imports. default_timeout (float) Default time in seconds before a script run is timed out. Can be overridden for individual .run() calls. args (tuple) An optional tuple of args to pass to the script function. kwargs (dict) An optional dict of kwargs to pass to the script function. Returns(AppTest) A simulated Streamlit app for testing. The simulated app can be executed via .run(). Run an AppTest script AppTest.runStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeRun the script from the current state. This is equivalent to manually rerunning the app or the rerun that occurs upon user interaction. AppTest.run() must be manually called after updating a widget value or switching pages as script reruns do not occur automatically as they do for live-running Streamlit apps. Function signature[source] AppTest.run(*, timeout=None) Parameters timeout (null) The maximum number of seconds to run the script. None means use the default timeout set for the instance of AppTest. Returns(AppTest) self AppTest.switch_pageStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSwitch to another page of the app. This method does not automatically rerun the app. Use a follow-up call to AppTest.run() to obtain the elements on the selected page. Function signature[source] AppTest.switch_page(page_path) Parameters page_path (str) Path of the page to switch to. The path must be relative to the main script's location (e.g. "pages/my_page.py"). Returns(AppTest) self Get AppTest script elements The main value of AppTest is providing an API to programmatically inspect and interact with the elements and widgets produced by a running Streamlit app. Using the AppTest.<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/api-reference/app-testing/testing-element-classes#buttonclick
DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceremovePAGE ELEMENTSWrite and magicaddText elementsaddData elementsaddChart elementsaddInput widgetsaddMedia elementsaddLayouts and containersaddChat elementsaddStatus elementsaddThird-party componentsopen_in_newAPPLICATION LOGICNavigation and pagesaddExecution flowaddCaching and stateaddConnections and secretsaddCustom componentsaddUtilitiesaddConfigurationaddTOOLSApp testingremovest.testing.v1.AppTestTesting element classesCommand lineaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Develop/API reference/App testing/Testing element classesTesting element classes st.testing.v1.element_tree.Block The Block class has the same methods and attributes as AppTest. A Block instance represents a container of elements just as AppTest represents the entire app. For example, Block.button will produce a WidgetList of Button in the same manner as AppTest.button. ChatMessage, Column, and Tab all inherit from Block. For all container classes, parameters of the original element can be obtained as properties. For example, ChatMessage.avatar and Tab.label. st.testing.v1.element_tree.ElementStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeElement base class for testing. This class's methods and attributes are universal for all elements implemented in testing. For example, Caption, Code, Text, and Title inherit from Element. All widget classes also inherit from Element, but have additional methods specific to each widget type. See the AppTest class for the full list of supported elements. For all element classes, parameters of the original element can be obtained as properties. For example, Button.label, Caption.help, and Toast.icon. Class description[source] st.testing.v1.element_tree.Element(proto, root) Methods run(*, timeout=None) Run the AppTest script which contains the element. Attributes value The value or contents of the element. st.testing.v1.element_tree.ButtonStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.button and st.form_submit_button. Class description[source] st.testing.v1.element_tree.Button(proto, root) Methods click() Set the value of the button to True. run(*, timeout=None) Run the AppTest script which contains the element. set_value(v) Set the value of the button. Attributes value The value of the button. (bool) st.testing.v1.element_tree.ChatInputStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.chat_input. Class description[source] st.testing.v1.element_tree.ChatInput(proto, root) Methods run(*, timeout=None) Run the AppTest script which contains the element. set_value(v) Set the value of the widget. Attributes value The value of the widget. (str) st.testing.v1.element_tree.CheckboxStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.checkbox. Class description[source] st.testing.v1.element_tree.Checkbox(proto, root) Methods check() Set the value of the widget to True. run(*, timeout=None) Run the AppTest script which contains the element. set_value(v) Set the value of the widget. uncheck() Set the value of the widget to False. Attributes value The value of the widget. (bool) st.testing.v1.element_tree.ColorPickerStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.color_picker. Class description[source] st.testing.v1.element_tree.ColorPicker(proto, root) Methods pick(v) Set the value of the widget as a hex string. May omit the "#" prefix. run(*, timeout=None) Run the AppTest script which contains the element. set_value(v) Set the value of the widget as a hex string. Attributes value The currently selected value as a hex string. (str) st.testing.v1.element_tree.DateInputStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.date_input. Class description[source] st.testing.v1.element_tree.DateInput(proto, root) Methods run(*, timeout=None) Run the AppTest script which contains the element. set_value(v) Set the value of the widget. Attributes value The value of the widget. (date or Tuple of date) st.testing.v1.element_tree.MultiselectStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.multiselect. Class description[source] st.testing.v1.element_tree.Multiselect(proto, root) Methods run(*, timeout=None) Run the AppTest script which contains the element. select(v) Add a selection to the widget. Do nothing if the value is already selected. If testing a multiselect widget with repeated options, use set_value instead. set_value(v) Set the value of the multiselect widget. (list) unselect(v) Remove a selection from the widget. Do nothing if the value is not already selected. If a value is selected multiple times, the first instance is removed. Attributes format_func The widget's formatting function for displaying options. (callable) indices The indices of the currently selected values from the options. (list) value The currently selected values from the options. (list) st.testing.v1.element_tree.NumberInputStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.number_input. Class description[source] st.testing.v1.element_tree.NumberInput(proto, root) Methods decrement() Decrement the st.number_input widget as if the user clicked "-". increment() Increment the st.number_input widget as if the user clicked "+". run(*, timeout=None) Run the AppTest script which contains the element. set_value(v) Set the value of the st.number_input widget. Attributes value Get the current value of the st.number_input widget. st.testing.v1.element_tree.RadioStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.radio. Class description[source] st.testing.v1.element_tree.Radio(proto, root) Methods run(*, timeout=None) Run the AppTest script which contains the element. set_value(v) Set the selection by value. Attributes format_func The widget's formatting function for displaying options. (callable) index The index of the current selection. (int) value The currently selected value from the options. (Any) st.testing.v1.element_tree.SelectSliderStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.select_slider. Class description[source] st.testing.v1.element_tree.SelectSlider(proto, root) Methods run(*, timeout=None) Run the AppTest script which contains the element. set_range(lower, upper) Set the ranged selection by values. set_value(v) Set the (single) selection by value. Attributes format_func The widget's formatting function for displaying options. (callable) value The currently selected value or range. (Any or Sequence of Any) st.testing.v1.element_tree.SelectboxStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.selectbox. Class description[source] st.testing.v1.element_tree.Selectbox(proto, root) Methods run(*, timeout=None) Run the AppTest script which contains the element. select(v) Set the selection by value. select_index(index) Set the selection by index. set_value(v) Set the selection by value. Attributes format_func The widget's formatting function for displaying options. (callable) index The index of the current selection. (int) value The currently selected value from the options. (Any) st.testing.v1.element_tree.SliderStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.slider. Class description[source] st.testing.v1.element_tree.Slider(proto, root) Methods run(*, timeout=None) Run the AppTest script which contains the element. set_range(lower, upper) Set the ranged value of the slider. set_value(v) Set the (single) value of the slider. Attributes value The currently selected value or range. (Any or Sequence of Any) st.testing.v1.element_tree.TextAreaStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.text_area. Class description[source] st.testing.v1.element_tree.TextArea(proto, root) Methods input(v) Set the value of the widget only if the value does not exceed the maximum allowed characters. run(*, timeout=None) Run the AppTest script which contains the element. set_value(v) Set the value of the widget. Attributes value The current value of the widget. (str) st.testing.v1.element_tree.TextInputStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.text_input. Class description[source] st.testing.v1.element_tree.TextInput(proto, root) Methods input(v) Set the value of the widget only if the value does not exceed the maximum allowed characters. run(*, timeout=None) Run the AppTest script which contains the element. set_value(v) Set the value of the widget. Attributes value The current value of the widget. (str) st.testing.v1.element_tree.TimeInputStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.time_input. Class description[source] st.testing.v1.element_tree.TimeInput(proto, root) Methods decrement() Select the previous available time. increment() Select the next available time. run(*, timeout=None) Run the AppTest script which contains the element. set_value(v) Set the value of the widget. Attributes value The current value of the widget. (time) st.testing.v1.element_tree.ToggleStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.toggle. Class description[source] st.testing.v1.element_tree.Toggle(proto, root) Methods run(*, timeout=None) Run the AppTest script which contains the element. set_value(v) Set the value of the widget. Attributes value The current value of the widget. (bool) Previous: st.testing.v1.AppTestNext: Command lineforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy
https://docs.streamlit.io/develop/tutorials/databases/private-gsheet#enable-the-sheets-api
DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceaddTutorialsremoveExecution flowaddConnect to data sourcesremoveAWS S3BigQueryDeta BaseFirestoreopen_in_newGoogle Cloud StorageMicrosoft SQL ServerMongoDBMySQLNeonPostgreSQLPrivate Google SheetPublic Google SheetSnowflakeSupabaseTableauTiDBTigerGraphMultipage appsaddWork with LLMsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Develop/Tutorials/Connect to data sources/Private Google SheetConnect Streamlit to a private Google Sheet Introduction This guide explains how to securely access a private Google Sheet from Streamlit Community Cloud. It uses st.connection, Streamlit GSheetsConnection, and Streamlit's Secrets management. If you are fine with enabling link sharing for your Google Sheet (i.e. everyone with the link can view it), the guide Connect Streamlit to a public Google Sheet shows a simpler method of doing this. If your Sheet contains sensitive information and you cannot enable link sharing, keep on reading. Prerequisites This tutorial requires streamlit>=1.28 and st-gsheets-connection in your Python environment. Create a Google Sheet If you already have a Sheet that you want to use, feel free to skip to the next step. Create a spreadsheet with this example data. namepetMarydogJohncatRobertbird Enable the Sheets API Programmatic access to Google Sheets is controlled through Google Cloud Platform. Create an account or sign in and head over to the APIs & Services dashboard (select or create a project if asked). As shown below, search for the Sheets API and enable it: Create a service account & key file To use the Sheets API from Streamlit Community Cloud, you need a Google Cloud Platform service account (a special account type for programmatic data access). Go to the Service Accounts page and create an account with the Viewer permission (this will let the account access data but not change it): push_pinNoteThe button "CREATE SERVICE ACCOUNT" is gray, you don't have the correct permissions. Ask the admin of your Google Cloud project for help. After clicking "DONE", you should be back on the service accounts overview. First, note down the email address of the account you just created (important for next step!). Then, create a JSON key file for the new account and download it: Share the Google Sheet with the service account By default, the service account you just created cannot access your Google Sheet. To give it access, click on the "Share" button in the Google Sheet, add the email of the service account (noted down in step 2), and choose the correct permission (if you just want to read the data, "Viewer" is enough): Add the key file to your local app secrets Your local Streamlit app will read secrets from a file .streamlit/secrets.toml in your app's root directory. Create this file if it doesn't exist yet and add the URL of your Google Sheet plus the content of the key file you downloaded to it as shown below: # .streamlit/secrets.toml [connections.gsheets] spreadsheet = "https://docs.google.com/spreadsheets/d/xxxxxxx/edit#gid=0" # From your JSON key file type = "service_account" project_id = "xxx" private_key_id = "xxx" private_key = "xxx" client_email = "xxx" client_id = "xxx" auth_uri = "https://accounts.google.com/o/oauth2/auth" token_uri = "https://oauth2.googleapis.com/token" auth_provider_x509_cert_url = "https://www.googleapis.com/oauth2/v1/certs" client_x509_cert_url = "xxx" priority_highImportantAdd this file to .gitignore and don't commit it to your GitHub repo! Write your Streamlit app Copy the code below to your Streamlit app and run it. # streamlit_app.py import streamlit as st from streamlit_gsheets import GSheetsConnection # Create a connection object. conn = st.connection("gsheets", type=GSheetsConnection) df = conn.read() # Print results. for row in df.itertuples(): st.write(f"{row.name} has a :{row.pet}:") See st.connection above? This handles secrets retrieval, setup, query caching and retries. By default, .read() results are cached without expiring. You can pass optional parameters to .read() to customize your connection. For example, you can specify the name of a worksheet, cache expiration time, or pass-through parameters for pandas.read_csv like this: df = conn.read( worksheet="Sheet1", ttl="10m", usecols=[0, 1], nrows=3, ) In this case, we set ttl="10m" to ensure the query result is cached for no longer than 10 minutes. You can also set ttl=0 to disable caching. Learn more in Caching. We've declared optional parameters usecols=[0,1] and nrows=3 for pandas to use under the hood. If everything worked out (and you used the example table we created above), your app should look like this: Connecting to a Google Sheet from Community Cloud This tutorial assumes a local Streamlit app, however you can also connect to Google Sheets from apps hosted in Community Cloud. The main additional steps are: Include information about dependencies using a requirements.txt file with st-gsheets-connection and any other dependencies. Add your secrets to your Community Cloud app. Previous: PostgreSQLNext: Public Google SheetforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy
https://docs.streamlit.io/develop/api-reference/execution-flow
DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceremovePAGE ELEMENTSWrite and magicaddText elementsaddData elementsaddChart elementsaddInput widgetsaddMedia elementsaddLayouts and containersaddChat elementsaddStatus elementsaddThird-party componentsopen_in_newAPPLICATION LOGICNavigation and pagesaddExecution flowremovest.dialogst.formst.form_submit_buttonst.fragmentst.rerunst.stopCaching and stateaddConnections and secretsaddCustom componentsaddUtilitiesaddConfigurationaddTOOLSApp testingaddCommand lineaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Develop/API reference/Execution flowExecution flow Change execution By default, Streamlit apps execute the script entirely, but we allow some functionality to handle control flow in your applications. Modal dialogsInsert a modal dialog that can rerun independently from the rest of the script.@st.experimental_dialog("Sign up") def email_form(): name = st.text_input("Name") email = st.text_input("Email") Partial rerunsDefine a fragment to rerun independently from the rest of the script.@st.experimental_fragment(run_every="10s") def fragment(): df = get_data() st.line_chart(df) Rerun scriptRerun the script immediately.st.rerun() Stop executionStops execution immediately.st.stop() Group multiple widgets By default, Streamlit reruns your script everytime a user interacts with your app. However, sometimes it's a better user experience to wait until a group of related widgets is filled before actually rerunning the script. That's what st.form is for! FormsCreate a form that batches elements together with a “Submit" button.with st.form(key='my_form'): name = st.text_input("Name") email = st.text_input("Email") st.form_submit_button("Sign up") Form submit buttonDisplay a form submit button.with st.form(key='my_form'): name = st.text_input("Name") email = st.text_input("Email") st.form_submit_button("Sign up") Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration!AutorefreshForce a refresh without tying up a script. Created by @kmcgrady.from streamlit_autorefresh import st_autorefresh st_autorefresh(interval=2000, limit=100, key="fizzbuzzcounter") PydanticAuto-generate Streamlit UI from Pydantic Models and Dataclasses. Created by @lukasmasuch.import streamlit_pydantic as sp sp.pydantic_form(key="my_form", model=ExampleModel) Streamlit PagesAn experimental version of Streamlit Multi-Page Apps. Created by @blackary.from st_pages import Page, show_pages, add_page_title show_pages([ Page("streamlit_app.py", "Home", "🏠"), Page("other_pages/page2.py", "Page 2", ":books:"), ]) Previous: Navigation and pagesNext: st.dialogforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy
https://docs.streamlit.io/develop/tutorials/execution-flow/start-and-stop-fragment-auto-reruns#start-and-stop-a-streaming-fragment
DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceaddTutorialsremoveExecution flowremoveFRAGMENTSRerun your app from a fragmentCreate a multiple-container fragmentStart and stop a streaming fragmentConnect to data sourcesaddMultipage appsaddWork with LLMsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Develop/Tutorials/Execution flow/Start and stop a streaming fragmentStart and stop a streaming fragment Streamlit lets you turn functions into fragments, which can rerun independently from the full script. Additionally, you can tell Streamlit to rerun a fragment at a set time interval. This is great for streaming data or monitoring processes. You may want the user to start and stop this live streaming. To do this, programmatically set the run_every parameter for your fragment. Applied concepts Use a fragment to stream live data. Start and stop a fragment from automatically rerunning. Prerequisites streamlit>=1.33.0 This tutorial uses fragments, which require Streamlit version 1.33.0 or later. This tutorial assumes you have a clean working directory called your-repository. You should have a basic understanding of fragments. Summary In this example, you'll build an app that streams two data series in a line chart. Your app will gather recent data on the first load of a session and statically display the line chart. Two buttons in the sidebar will allow users to start and stop data streaming to update the chart in real time. You'll use a fragment to manage the frequency and scope of the live updates. Here's a look at what you'll build: Complete codeexpand_moreimport streamlit as st import pandas as pd import numpy as np from datetime import datetime, timedelta def get_recent_data(last_timestamp): """Generate and return data from last timestamp to now, at most 60 seconds.""" now = datetime.now() if now - last_timestamp > timedelta(seconds=60): last_timestamp = now - timedelta(seconds=60) sample_time = timedelta(seconds=0.5) # time between data points next_timestamp = last_timestamp + sample_time timestamps = np.arange(next_timestamp, now, sample_time) sample_values = np.random.randn(len(timestamps), 2) data = pd.DataFrame(sample_values, index=timestamps, columns=["A", "B"]) return data if "data" not in st.session_state: st.session_state.data = get_recent_data(datetime.now() - timedelta(seconds=60)) if "stream" not in st.session_state: st.session_state.stream = False def toggle_streaming(): st.session_state.stream = not st.session_state.stream st.title("Data feed") st.sidebar.slider( "Check for updates every: (seconds)", 0.5, 5.0, value=1.0, key="run_every" ) st.sidebar.button( "Start streaming", disabled=st.session_state.stream, on_click=toggle_streaming ) st.sidebar.button( "Stop streaming", disabled=not st.session_state.stream, on_click=toggle_streaming ) if st.session_state.stream is True: run_every = st.session_state.run_every else: run_every = None @st.experimental_fragment(run_every=run_every) def show_latest_data(): last_timestamp = st.session_state.data.index[-1] st.session_state.data = pd.concat( [st.session_state.data, get_recent_data(last_timestamp)] ) st.session_state.data = st.session_state.data[-100:] st.line_chart(st.session_state.data) show_latest_data() Built with Streamlit 🎈Fullscreen open_in_new Build the example Initialize your app In your_repository, create a file named app.py. In a terminal, change directories to your_repository and start your app. streamlit run app.py Your app will be blank since you still need to add code. In app.py, write the following: import streamlit as st import pandas as pd import numpy as np from datetime import datetime, timedelta You'll be using these libraries as follows: You'll work with two data series in a pandas.DataFrame. You'll generate random data with numpy. The data will have datetime.datetime index values. Save your app.py file and view your running app. Click "Always rerun" or hit your "A" key in your running app. Your running preview will automatically update as you save changes to app.py. Your preview will still be blank. Return to your code. Build a function to generate random, recent data To begin with, you'll define a function to randomly generate some data for two time series, which you'll call "A" and "B." It's okay to skip this section if you just want to copy the function. Complete function to randomly generate sales dataexpand_moredef get_recent_data(last_timestamp): """Generate and return data from last timestamp to now, at most 60 seconds.""" now = datetime.now() if now - last_timestamp > timedelta(seconds=60): last_timestamp = now - timedelta(seconds=60) sample_time = timedelta(seconds=0.5) # time between data points next_timestamp = last_timestamp + sample_time timestamps = np.arange(next_timestamp, now, sample_time) sample_values = np.random.randn(len(timestamps), 2) data = pd.DataFrame(sample_values, index=timestamps, columns=["A", "B"]) return data Start your function definition. def get_recent_data(last_timestamp): """Generate and return data from last timestamp to now, at most 60 seconds.""" You'll pass the timestamp of your most recent datapoint to your data-generating function. Your function will use this to only return new data. Get the current time and adjust the last timestamp if it is over 60 seconds ago. now = datetime.now() if now - last_timestamp > timedelta(seconds=60): last_timestamp = now - timedelta(seconds=60) By updating the last timestamp, you'll ensure the function never returns more than 60 seconds of data. Declare a new variable, sample_time, to define the time between datapoints. Calculate the timestamp of the first, new datapoint. sample_time = timedelta(seconds=0.5) # time between data points next_timestamp = last_timestamp + sample_time Create a datetime.datetime index and generate two data series of the same length. timestamps = np.arange(next_timestamp, now, sample_time) sample_values = np.random.randn(len(timestamps), 2) Combine the data series with the index into a pandas.DataFrame and return the data. data = pd.DataFrame(sample_values, index=timestamps, columns=["A", "B"]) return data (Optional) Test out your function by calling it and displaying the data. data = get_recent_data(datetime.now() - timedelta(seconds=60)) data Save your app.py file to see the preview. Delete these two lines when finished. Initialize Session State values for your app Since you will dynamically change the run_every parameter of @st.experimental_fragment(), you'll need to initialize the associated variables and Session State values before defining your fragment function. Your fragment function will also read and update values in Session State, so you can define those now to make the fragment function easier to understand. Initialize your data for the first app load in a session. if "data" not in st.session_state: st.session_state.data = get_recent_data(datetime.now() - timedelta(seconds=60)) Your app will display this initial data in a static line chart before a user starts streaming data. Initialize "stream" in Session State to turn streaming on and off. Set the default to off (False). if "stream" not in st.session_state: st.session_state.stream = False Create a callback function to toggle "stream" between True and False. def toggle_streaming(): st.session_state.stream = not st.session_state.stream Add a title to your app. st.title("Data feed") Add a slider to the sidebar to set how frequently to check for data while streaming. st.sidebar.slider( "Check for updates every: (seconds)", 0.5, 5.0, value=1.0, key="run_every" ) Add buttons to the sidebar to turn streaming on and off. st.sidebar.button( "Start streaming", disabled=st.session_state.stream, on_click=toggle_streaming ) st.sidebar.button( "Stop streaming", disabled=not st.session_state.stream, on_click=toggle_streaming ) Both functions use the same callback to toggle "stream" in Session State. Use the current value "stream" to disable one of the buttons. This ensures the buttons are always consistent with the current state; "Start streaming" is only clickable when streaming is off, and "Stop streaming" is only clickable when streaming is on. The buttons also provide status to the user by highlighting which action is available to them. Create and set a new variable, run_every, that will determine whether or not the fragment function will rerun automatically (and how fast). if st.session_state.stream is True: run_every = st.session_state.run_every else: run_every = None Build a fragment function to stream data To allow the user to turn data streaming on and off, you must set the run_every parameter in the @st.experimental_fragment() decorator. Complete function to show and stream dataexpand_more@st.experimental_fragment(run_every=run_every) def show_latest_data(): last_timestamp = st.session_state.data.index[-1] st.session_state.data = pd.concat( [st.session_state.data, get_recent_data(last_timestamp)] ) st.session_state.data = st.session_state.data[-100:] st.line_chart(st.session_state.data) Use an @st.experimental_fragment decorator and start your function definition. @st.experimental_fragment(run_every=run_every) def show_latest_data(): Use the run_every variable declared above to set the parameter of the same name. Retrieve the timestamp of the last datapoint in Session State. last_timestamp = st.session_state.data.index[-1] Update the data in Session State and trim to keep only the last 100 timestamps. st.session_state.data = pd.concat( [st.session_state.data, get_recent_data(last_timestamp)] ) st.session_state.data = st.session_state.data[-100:] Show the data in a line chart. st.line_chart(st.session_state.data) Your fragment-function definition is complete. Call and test out your fragment function Call your function at the bottom of your code. show_latest_data() Test out your app by clicking "Start streaming." Try adjusting the frequency of updates. Next steps Try adjusting the frequency of data generation or how much data is kept in Session State. Within get_recent_data try setting sample_time with a widget. Try using st.plotly_chart or st.altair_chart to add labels to your chart.Previous: Create a multiple-container fragmentNext: Connect to data sourcesforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy
https://docs.streamlit.io/develop/api-reference/text/st.title#sttitle
DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceremovePAGE ELEMENTSWrite and magicaddText elementsremoveHEADINGS & BODYst.titlest.headerst.subheaderst.markdownFORMATTED TEXTst.captionst.codest.dividerst.echost.latexst.textData elementsaddChart elementsaddInput widgetsaddMedia elementsaddLayouts and containersaddChat elementsaddStatus elementsaddThird-party componentsopen_in_newAPPLICATION LOGICNavigation and pagesaddExecution flowaddCaching and stateaddConnections and secretsaddCustom componentsaddUtilitiesaddConfigurationaddTOOLSApp testingaddCommand lineaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Develop/API reference/Text elements/st.titlest.titleStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeDisplay text in title formatting. Each document should have a single st.title(), although this is not enforced. Function signature[source] st.title(body, anchor=None, *, help=None) Parameters body (str) The text to display as Github-flavored Markdown. Syntax information can be found at: https://github.github.com/gfm. This also supports: Emoji shortcodes, such as :+1: and :sunglasses:. For a list of all supported codes, see https://share.streamlit.io/streamlit/emoji-shortcodes. LaTeX expressions, by wrapping them in "$" or "$$" (the "$$" must be on their own lines). Supported LaTeX functions are listed at https://katex.org/docs/supported.html. Colored text and background colors for text, using the syntax :color[text to be colored] and :color-background[text to be colored], respectively. color must be replaced with any of the following supported colors: blue, green, orange, red, violet, gray/grey, rainbow. For example, you can use :orange[your text here] or :blue-background[your text here]. anchor (str or False) The anchor name of the header that can be accessed with #anchor in the URL. If omitted, it generates an anchor using the body. If False, the anchor is not shown in the UI. help (str) An optional tooltip that gets displayed next to the title. Examples import streamlit as st st.title('This is a title') st.title('_Streamlit_ is :blue[cool] :sunglasses:') Built with Streamlit 🎈Fullscreen open_in_new Previous: Text elementsNext: st.headerforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy
https://docs.streamlit.io/develop/api-reference/connections/st.connections.sqlconnection#stconnectionssqlconnection
DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceremovePAGE ELEMENTSWrite and magicaddText elementsaddData elementsaddChart elementsaddInput widgetsaddMedia elementsaddLayouts and containersaddChat elementsaddStatus elementsaddThird-party componentsopen_in_newAPPLICATION LOGICNavigation and pagesaddExecution flowaddCaching and stateaddConnections and secretsremoveSECRETSst.secretssecrets.tomlCONNECTIONSst.connectionSnowflakeConnectionSQLConnectionBaseConnectionSnowparkConnectiondeleteCustom componentsaddUtilitiesaddConfigurationaddTOOLSApp testingaddCommand lineaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Develop/API reference/Connections and secrets/SQLConnectionstarTipThis page only contains the st.connections.SQLConnection class. For a deeper dive into creating and managing data connections within Streamlit apps, read Connecting to data. st.connections.SQLConnectionStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA connection to a SQL database using a SQLAlchemy Engine. Initialize using st.connection("<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#timeinputvalue
DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceremovePAGE ELEMENTSWrite and magicaddText elementsaddData elementsaddChart elementsaddInput widgetsaddMedia elementsaddLayouts and containersaddChat elementsaddStatus elementsaddThird-party componentsopen_in_newAPPLICATION LOGICNavigation and pagesaddExecution flowaddCaching and stateaddConnections and secretsaddCustom componentsaddUtilitiesaddConfigurationaddTOOLSApp testingremovest.testing.v1.AppTestTesting element classesCommand lineaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Develop/API reference/App testing/Testing element classesTesting element classes st.testing.v1.element_tree.Block The Block class has the same methods and attributes as AppTest. A Block instance represents a container of elements just as AppTest represents the entire app. For example, Block.button will produce a WidgetList of Button in the same manner as AppTest.button. ChatMessage, Column, and Tab all inherit from Block. For all container classes, parameters of the original element can be obtained as properties. For example, ChatMessage.avatar and Tab.label. st.testing.v1.element_tree.ElementStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeElement base class for testing. This class's methods and attributes are universal for all elements implemented in testing. For example, Caption, Code, Text, and Title inherit from Element. All widget classes also inherit from Element, but have additional methods specific to each widget type. See the AppTest class for the full list of supported elements. For all element classes, parameters of the original element can be obtained as properties. For example, Button.label, Caption.help, and Toast.icon. Class description[source] st.testing.v1.element_tree.Element(proto, root) Methods run(*, timeout=None) Run the AppTest script which contains the element. Attributes value The value or contents of the element. st.testing.v1.element_tree.ButtonStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.button and st.form_submit_button. Class description[source] st.testing.v1.element_tree.Button(proto, root) Methods click() Set the value of the button to True. run(*, timeout=None) Run the AppTest script which contains the element. set_value(v) Set the value of the button. Attributes value The value of the button. (bool) st.testing.v1.element_tree.ChatInputStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.chat_input. Class description[source] st.testing.v1.element_tree.ChatInput(proto, root) Methods run(*, timeout=None) Run the AppTest script which contains the element. set_value(v) Set the value of the widget. Attributes value The value of the widget. (str) st.testing.v1.element_tree.CheckboxStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.checkbox. Class description[source] st.testing.v1.element_tree.Checkbox(proto, root) Methods check() Set the value of the widget to True. run(*, timeout=None) Run the AppTest script which contains the element. set_value(v) Set the value of the widget. uncheck() Set the value of the widget to False. Attributes value The value of the widget. (bool) st.testing.v1.element_tree.ColorPickerStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.color_picker. Class description[source] st.testing.v1.element_tree.ColorPicker(proto, root) Methods pick(v) Set the value of the widget as a hex string. May omit the "#" prefix. run(*, timeout=None) Run the AppTest script which contains the element. set_value(v) Set the value of the widget as a hex string. Attributes value The currently selected value as a hex string. (str) st.testing.v1.element_tree.DateInputStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.date_input. Class description[source] st.testing.v1.element_tree.DateInput(proto, root) Methods run(*, timeout=None) Run the AppTest script which contains the element. set_value(v) Set the value of the widget. Attributes value The value of the widget. (date or Tuple of date) st.testing.v1.element_tree.MultiselectStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.multiselect. Class description[source] st.testing.v1.element_tree.Multiselect(proto, root) Methods run(*, timeout=None) Run the AppTest script which contains the element. select(v) Add a selection to the widget. Do nothing if the value is already selected. If testing a multiselect widget with repeated options, use set_value instead. set_value(v) Set the value of the multiselect widget. (list) unselect(v) Remove a selection from the widget. Do nothing if the value is not already selected. If a value is selected multiple times, the first instance is removed. Attributes format_func The widget's formatting function for displaying options. (callable) indices The indices of the currently selected values from the options. (list) value The currently selected values from the options. (list) st.testing.v1.element_tree.NumberInputStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.number_input. Class description[source] st.testing.v1.element_tree.NumberInput(proto, root) Methods decrement() Decrement the st.number_input widget as if the user clicked "-". increment() Increment the st.number_input widget as if the user clicked "+". run(*, timeout=None) Run the AppTest script which contains the element. set_value(v) Set the value of the st.number_input widget. Attributes value Get the current value of the st.number_input widget. st.testing.v1.element_tree.RadioStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.radio. Class description[source] st.testing.v1.element_tree.Radio(proto, root) Methods run(*, timeout=None) Run the AppTest script which contains the element. set_value(v) Set the selection by value. Attributes format_func The widget's formatting function for displaying options. (callable) index The index of the current selection. (int) value The currently selected value from the options. (Any) st.testing.v1.element_tree.SelectSliderStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.select_slider. Class description[source] st.testing.v1.element_tree.SelectSlider(proto, root) Methods run(*, timeout=None) Run the AppTest script which contains the element. set_range(lower, upper) Set the ranged selection by values. set_value(v) Set the (single) selection by value. Attributes format_func The widget's formatting function for displaying options. (callable) value The currently selected value or range. (Any or Sequence of Any) st.testing.v1.element_tree.SelectboxStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.selectbox. Class description[source] st.testing.v1.element_tree.Selectbox(proto, root) Methods run(*, timeout=None) Run the AppTest script which contains the element. select(v) Set the selection by value. select_index(index) Set the selection by index. set_value(v) Set the selection by value. Attributes format_func The widget's formatting function for displaying options. (callable) index The index of the current selection. (int) value The currently selected value from the options. (Any) st.testing.v1.element_tree.SliderStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.slider. Class description[source] st.testing.v1.element_tree.Slider(proto, root) Methods run(*, timeout=None) Run the AppTest script which contains the element. set_range(lower, upper) Set the ranged value of the slider. set_value(v) Set the (single) value of the slider. Attributes value The currently selected value or range. (Any or Sequence of Any) st.testing.v1.element_tree.TextAreaStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.text_area. Class description[source] st.testing.v1.element_tree.TextArea(proto, root) Methods input(v) Set the value of the widget only if the value does not exceed the maximum allowed characters. run(*, timeout=None) Run the AppTest script which contains the element. set_value(v) Set the value of the widget. Attributes value The current value of the widget. (str) st.testing.v1.element_tree.TextInputStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.text_input. Class description[source] st.testing.v1.element_tree.TextInput(proto, root) Methods input(v) Set the value of the widget only if the value does not exceed the maximum allowed characters. run(*, timeout=None) Run the AppTest script which contains the element. set_value(v) Set the value of the widget. Attributes value The current value of the widget. (str) st.testing.v1.element_tree.TimeInputStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.time_input. Class description[source] st.testing.v1.element_tree.TimeInput(proto, root) Methods decrement() Select the previous available time. increment() Select the next available time. run(*, timeout=None) Run the AppTest script which contains the element. set_value(v) Set the value of the widget. Attributes value The current value of the widget. (time) st.testing.v1.element_tree.ToggleStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.toggle. Class description[source] st.testing.v1.element_tree.Toggle(proto, root) Methods run(*, timeout=None) Run the AppTest script which contains the element. set_value(v) Set the value of the widget. Attributes value The current value of the widget. (bool) Previous: st.testing.v1.AppTestNext: Command lineforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy
https://docs.streamlit.io/develop/api-reference/layout#layouts-and-containers
DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceremovePAGE ELEMENTSWrite and magicaddText elementsaddData elementsaddChart elementsaddInput widgetsaddMedia elementsaddLayouts and containersremovest.columnsst.containerst.dialoglinkst.emptyst.expanderst.formlinkst.popoverst.sidebarst.tabsChat elementsaddStatus elementsaddThird-party componentsopen_in_newAPPLICATION LOGICNavigation and pagesaddExecution flowaddCaching and stateaddConnections and secretsaddCustom componentsaddUtilitiesaddConfigurationaddTOOLSApp testingaddCommand lineaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Develop/API reference/Layouts and containersLayouts and Containers Complex layouts Streamlit provides several options for controlling how different elements are laid out on the screen. ColumnsInsert containers laid out as side-by-side columns.col1, col2 = st.columns(2) col1.write("this is column 1") col2.write("this is column 2") ContainerInsert a multi-element container.c = st.container() st.write("This will show last") c.write("This will show first") c.write("This will show second") Modal dialogsInsert a modal dialog that can rerun independently from the rest of the script.@st.experimental_dialog() def email_form(): name = st.text_input("Name") email = st.text_input("Email") EmptyInsert a single-element container.c = st.empty() st.write("This will show last") c.write("This will be replaced") c.write("This will show first") ExpanderInsert a multi-element container that can be expanded/collapsed.with st.expander("Open to see more"): st.write("This is more content") PopoverInsert a multi-element popover container that can be opened/closed.with st.popover("Settings"): st.checkbox("Show completed") SidebarDisplay items in a sidebar.st.sidebar.write("This lives in the sidebar") st.sidebar.button("Click me!") TabsInsert containers separated into tabs.tab1, tab2 = st.tabs(["Tab 1", "Tab2"]) tab1.write("this is tab 1") tab2.write("this is tab 2") Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration!Streamlit ElementsCreate a draggable and resizable dashboard in Streamlit. Created by @okls.from streamlit_elements import elements, mui, html with elements("new_element"): mui.Typography("Hello world") PydanticAuto-generate Streamlit UI from Pydantic Models and Dataclasses. Created by @lukasmasuch.import streamlit_pydantic as sp sp.pydantic_form(key="my_form", model=ExampleModel) Streamlit PagesAn experimental version of Streamlit Multi-Page Apps. Created by @blackary.from st_pages import Page, show_pages, add_page_title show_pages([ Page("streamlit_app.py", "Home", "🏠"), Page("other_pages/page2.py", "Page 2", ":books:"), ]) Previous: Media elementsNext: st.columnsforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy
https://docs.streamlit.io/develop/concepts/app-testing/get-started#handling-file-paths-and-imports-with-pytest
DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsremoveCOREArchitecture & executionaddMultipage appsaddApp designaddADDITIONALConnections and secretsaddCustom componentsaddConfiguration and themingaddApp testingremoveGet startedBeyond the basicsAutomate your testsExampleCheat sheetAPI referenceaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Develop/Concepts/App testing/Get startedGet started with app testing This guide will cover a simple example of how tests are structured within a project and how to execute them with pytest. After seeing the big picture, keep reading to learn about the Fundamentals of app testing: Initializing and running a simulated app Retrieving elements Manipulating widgets Inspecting the results Streamlit's app testing framework is not tied to any particular testing tool, but we'll use pytest for our examples since it is one of the most common Python test frameworks. To try out the examples in this guide, be sure to install pytest into your Streamlit development environment before you begin: pip install pytest A simple testing example with pytest This section explains how a simple test is structured and executed with pytest. For a comprehensive introduction to pytest, check out Real Python's guide to Effective Python testing with pytest. How pytest is structured pytest uses a naming convention for files and functions to execute tests conveniently. Name your test scripts of the form test_<name>.py or <name>_test.py. For example, you can use test_myapp.py or myapp_test.py. Within your test scripts, each test is written as a function. Each function is named to begin or end with test. We will prefix all our test scripts and test functions with test_ for our examples in this guide. You can write as many tests (functions) within a single test script as you want. When calling pytest in a directory, all test_<name>.py files within it will be used for testing. This includes files within subdirectories. Each test_<something> function within those files will be executed as a test. You can place test files anywhere in your project directory, but it is common to collect tests into a designated tests/ directory. For other ways to structure and execute tests, check out How to invoke pytest in the pytest docs. Example project with app testing Consider the following project: myproject/ ├── app.py └── tests/ └── test_app.py Main app file: """app.py""" import streamlit as st # Initialize st.session_state.beans st.session_state.beans = st.session_state.get("beans", 0) st.title("Bean counter :paw_prints:") addend = st.number_input("Beans to add", 0, 10) if st.button("Add"): st.session_state.beans += addend st.markdown(f"Beans counted: {st.session_state.beans}") Testing file: """test_app.py""" from streamlit.testing.v1 import AppTest def test_increment_and_add(): """A user increments the number input, then clicks Add""" at = AppTest.from_file("app.py").run() at.number_input[0].increment().run() at.button[0].click().run() assert at.markdown[0].value == "Beans counted: 1" Let's take a quick look at what's in this app and test before we run it. The main app file (app.py) contains four elements when rendered: st.title, st.number_input, st.button, and st.markdown. The test script (test_app.py) includes a single test (the function named test_increment_and_add). We'll cover test syntax in more detail in the latter half of this guide, but here's a brief explanation of what this test does: Initialize the simulated app and execute the first script run. at = AppTest.from_file("app.py").run() Simulate a user clicking the plus icon (add) to increment the number input (and the resulting script rerun). at.number_input[0].increment().run() Simulate a user clicking the "Add" button (and the resulting script rerun). at.button[0].click().run() Check if the correct message is displayed at the end. assert at.markdown[0].value == "Beans counted: 1" Assertions are the heart of tests. When the assertion is true, the test passes. When the assertion is false, the test fails. A test can have multiple assertions, but keeping tests tightly focused is good practice. When tests focus on a single behavior, it is easier to understand and respond to failure. Try out a simple test with pytest Copy the files above into a new "myproject" directory. Open a terminal and change directory to your project. cd myproject Execute pytest: pytest The test should execute successfully. Your terminal should show something like this: By executing pytest at the root of your project directory, all Python files with the test prefix (test_<name>.py) will be scanned for test functions. Within each test file, each function with the test prefix will be executed as a test. pytest then counts successes and itemizes failures. You can also direct pytest to only scan your testing directory. For example, from the root of your project directory, execute: pytest tests/ Handling file paths and imports with pytest Imports and paths within a test script should be relative to the directory where pytest is called. That is why the test function uses the path app.py instead of ../app.py even though the app file is one directory up from the test script. You'll usually call pytest from the directory containing your main app file. This is typically the root of your project directory. Additionally, if .streamlit/ is present in the directory where you call pytest, any config.toml and secrets.toml within it will be accessible to your simulated app. For example, your simulated app will have access to the config.toml and secrets.toml files in this common setup: Project structure: myproject/ ├── .streamlit/ │ ├── config.toml │ └── secrets.toml ├── app.py └── tests/ └── test_app.py Initialization within test_app.py: # Path to app file is relative to myproject/ at = AppTest.from_file("app.py").run() Command to execute tests: cd myproject pytest tests/ Fundamentals of app testing Now that you understand the basics of pytest let's dive into using Streamlit's app testing framework. Every test begins with initializing and running your simulated app. Additional commands are used to retrieve, manipulate, and inspect elements. On the next page, we'll go Beyond the basics and cover more advanced scenarios like working with secrets, Session State, or multipage apps. How to initialize and run a simulated app To test a Streamlit app, you must first initialize an instance of AppTest with the code for one page of your app. There are three methods for initializing a simulated app. These are provided as class methods to AppTest. We will focus on AppTest.from_file() which allows you to provide a path to a page of your app. This is the most common scenario for building automated tests during app development. AppTest.from_string() and AppTest.from_function() may be helpful for some simple or experimental scenarios. Let's continue with the example from above. Recall the testing file: """test_app.py""" from streamlit.testing.v1 import AppTest def test_increment_and_add(): """A user increments the number input, then clicks Add""" at = AppTest.from_file("app.py").run() at.number_input[0].increment().run() at.button[0].click().run() assert at.markdown[0].value == "Beans counted: 1" Look at the first line in the test function: at = AppTest.from_file("app.py").run() This is doing two things and is equivalent to: # Initialize the app. at = AppTest.from_file("app.py") # Run the app. at.run() AppTest.from_file() returns an instance of AppTest, initialized with the contents of app.py. The .run() method is used to run the app for the first time. Looking at the test, notice that the .run() method manually executes each script run. A test must explicitly run the app each time. This applies to the app's first run and any rerun resulting from simulated user input. How to retrieve elements The attributes of the AppTest class return sequences of elements. The elements are sorted according to display order in the rendered app. Specific elements can be retrieved by index. Additionally, widgets with keys can be retrieved by key. Retrieve elements by index Each attribute of AppTest returns a sequence of the associated element type. Specific elements can be retrieved by index. In the above example, at.number_input returns a sequence of all st.number_input elements in the app. Thus, at.number_input[0] is the first such element in the app. Similarly, at.markdown returns a collection of all st.markdown elements where at.markdown[0] is the first such element. Check out the current list of supported elements in the "Attributes" section of the AppTest class or the App testing cheat sheet. You can also use the .get() method and pass the attribute's name. at.get("number_input") and at.get("markdown") are equivalent to at.number_input and at.markdown, respectively. The returned sequence of elements is ordered by appearance on the page. If containers are used to insert elements in a different order, these sequences may not match the order within your code. Consider the following example where containers are used to switch the order of two buttons on the page: import streamlit as st first = st.container() second = st.container() second.button("A") first.button("B") If the above app was tested, the first button (at.button[0]) would be labeled "B" and the second button (at.button[1]) would be labeled "A." As true assertions, these would be: assert at.button[0].label == "B" assert at.button[1].label == "A" Retrieve widgets by key You can retrieve keyed widgets by their keys instead of their order on the page. The key of the widget is passed as either an arg or kwarg. For example, look at this app and the following (true) assertions: import streamlit as st st.button("Next", key="submit") st.button("Back", key="cancel") assert at.button(key="submit").label == "Next" assert at.button("cancel").label == "Back" Retrieve containers You can also narrow down your sequences of elements by retrieving specific containers. Each retrieved container has the same attributes as AppTest. For example, at.sidebar.checkbox returns a sequence of all checkboxes in the sidebar. at.main.selectbox returns the sequence of all selectboxes in the main body of the app (not in the sidebar). For AppTest.columns and AppTest.tabs, a sequence of containers is returned. So at.columns[0].button would be the sequence of all buttons in the first column appearing in the app. How to manipulate widgets All widgets have a universal .set_value() method. Additionally, many widgets have specific methods for manipulating their value. The names of Testing element classes closely match the names of the AppTest attributes. For example, look at the return type of AppTest.button to see the corresponding class of Button. Aside from setting the value of a button with .set_value(), you can also use .click(). Check out each testing element class for its specific methods. How to inspect elements All elements, including widgets, have a universal .value property. This returns the contents of the element. For widgets, this is the same as the return value or value in Session State. For non-input elements, this will be the value of the primary contents argument. For example, .value returns the value of body for st.markdown or st.error. It returns the value of data for st.dataframe or st.table. Additionally, you can check many other details for widgets like labels or disabled status. Many parameters are available for inspection, but not all. Use linting software to see what is currently supported. Here's an example: import streamlit as st st.selectbox("A", [1,2,3], None, help="Pick a number", placeholder="Pick me") assert at.selectbox[0].value == None assert at.selectbox[0].label == "A" assert at.selectbox[0].options == ["1","2","3"] assert at.selectbox[0].index == None assert at.selectbox[0].help == "Pick a number" assert at.selectbox[0].placeholder == "Pick me" assert at.selectbox[0].disabled == False starTipNote that the options for st.selectbox were declared as integers but asserted as strings. As noted in the documentation for st.selectbox, options are cast internally to strings. If you ever find yourself getting unexpected results, check the documentation carefully for any notes about recasting types internally.Previous: App testingNext: Beyond the basicsforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy
https://docs.streamlit.io/develop/api-reference/execution-flow/st.stop
DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceremovePAGE ELEMENTSWrite and magicaddText elementsaddData elementsaddChart elementsaddInput widgetsaddMedia elementsaddLayouts and containersaddChat elementsaddStatus elementsaddThird-party componentsopen_in_newAPPLICATION LOGICNavigation and pagesaddExecution flowremovest.dialogst.formst.form_submit_buttonst.fragmentst.rerunst.stopCaching and stateaddConnections and secretsaddCustom componentsaddUtilitiesaddConfigurationaddTOOLSApp testingaddCommand lineaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Develop/API reference/Execution flow/st.stopst.stopStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeStops execution immediately. Streamlit will not run any statements after st.stop(). We recommend rendering a message to explain why the script has stopped. Function signature[source] st.stop() Example import streamlit as st name = st.text_input('Name') if not name: st.warning('Please input a name.') st.stop() st.success('Thank you for inputting a name.') Previous: st.rerunNext: st.experimental_rerunforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy
https://docs.streamlit.io/deploy/streamlit-community-cloud/manage-your-app/app-settings#change-your-app-settings
DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudremoveGet startedaddDeploy your appaddManage your appremoveApp analyticsApp settingsDelete your appEdit your appFavorite your appReboot your appShare your appaddManage your accountaddTroubleshootingStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Deploy/Streamlit Community Cloud/Manage your app/App settingsApp settings This page is about your app settings on Streamlit Community Cloud. From your app settings you can view or modify your app's URL, manage public or private access to your apps and update your saved secrets for your apps. If you access "Settings" from your App menu in the upper-right corner of your running app, you can access features to control the appearance of your app while its running. Access your app settings You can get to your app's settings: From your workspace. From your Cloud logs. Access app settings from your workspace From your workspace at share.streamlit.io, click the overflow icon (more_vert) next to your app. Click "Settings". Access app settings from your Cloud logs From your app at <your-custom-subdomain>.streamlit.app, click "Manage app" in the lower-right corner. Click the overflow menu icon (more_vert) and click "Settings". Change your app settings View or change your app's URL Read more about Custom subdomains. Update your app's share settings Learn how to Share your app. Update your secrets Learn more about Secrets management. Previous: App analyticsNext: Delete your appforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy
https://docs.streamlit.io/develop/api-reference/charts/st.area_chart#elementadd_rows
DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceremovePAGE ELEMENTSWrite and magicaddText elementsaddData elementsaddChart elementsremoveSIMPLEst.area_chartst.bar_chartst.line_chartst.mapst.scatter_chartADVANCEDst.altair_chartst.bokeh_chartst.graphviz_chartst.plotly_chartst.pydeck_chartst.pyplotst.vega_lite_chartInput widgetsaddMedia elementsaddLayouts and containersaddChat elementsaddStatus elementsaddThird-party componentsopen_in_newAPPLICATION LOGICNavigation and pagesaddExecution flowaddCaching and stateaddConnections and secretsaddCustom componentsaddUtilitiesaddConfigurationaddTOOLSApp testingaddCommand lineaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Develop/API reference/Chart elements/st.area_chartst.area_chartStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeDisplay an area chart. This is syntax-sugar around st.altair_chart. The main difference is this command uses the data's own column and indices to figure out the chart's spec. As a result this is easier to use for many "just plot this" scenarios, while being less customizable. If st.area_chart does not guess the data specification correctly, try specifying your desired chart using st.altair_chart. Function signature[source] st.area_chart(data=None, *, x=None, y=None, color=None, width=0, height=0, use_container_width=True) Parameters data (pandas.DataFrame, pandas.Styler, pyarrow.Table, numpy.ndarray, pyspark.sql.DataFrame, snowflake.snowpark.dataframe.DataFrame, snowflake.snowpark.table.Table, Iterable, or dict) Data to be plotted. x (str or None) Column name to use for the x-axis. If None, uses the data index for the x-axis. y (str, Sequence of str, or None) Column name(s) to use for the y-axis. If a Sequence of strings, draws several series on the same chart by melting your wide-format table into a long-format table behind the scenes. If None, draws the data of all remaining columns as data series. color (str, tuple, Sequence of str, Sequence of tuple, or None) The color to use for different series in this chart. For an area chart with just 1 series, this can be: None, to use the default color. A hex string like "#ffaa00" or "#ffaa0088". An RGB or RGBA tuple with the red, green, blue, and alpha components specified as ints from 0 to 255 or floats from 0.0 to 1.0. For an area chart with multiple series, where the dataframe is in long format (that is, y is None or just one column), this can be: None, to use the default colors. The name of a column in the dataset. Data points will be grouped into series of the same color based on the value of this column. In addition, if the values in this column match one of the color formats above (hex string or color tuple), then that color will be used. For example: if the dataset has 1000 rows, but this column only contains the values "adult", "child", and "baby", then those 1000 datapoints will be grouped into three series whose colors will be automatically selected from the default palette. But, if for the same 1000-row dataset, this column contained the values "#ffaa00", "#f0f", "#0000ff", then then those 1000 datapoints would still be grouped into 3 series, but their colors would be "#ffaa00", "#f0f", "#0000ff" this time around. For an area chart with multiple series, where the dataframe is in wide format (that is, y is a Sequence of columns), this can be: None, to use the default colors. A list of string colors or color tuples to be used for each of the series in the chart. This list should have the same length as the number of y values (e.g. color=["#fd0", "#f0f", "#04f"] for three lines). width (int) The chart width in pixels. If 0, selects the width automatically. height (int) The chart height in pixels. If 0, selects the height automatically. use_container_width (bool) If True, set the chart width to the column width. This takes precedence over the width argument. Examples import streamlit as st import pandas as pd import numpy as np chart_data = pd.DataFrame(np.random.randn(20, 3), columns=["a", "b", "c"]) st.area_chart(chart_data) Built with Streamlit 🎈Fullscreen open_in_new You can also choose different columns to use for x and y, as well as set the color dynamically based on a 3rd column (assuming your dataframe is in long format): import streamlit as st import pandas as pd import numpy as np chart_data = pd.DataFrame( { "col1": np.random.randn(20), "col2": np.random.randn(20), "col3": np.random.choice(["A", "B", "C"], 20), } ) st.area_chart(chart_data, x="col1", y="col2", color="col3") Built with Streamlit 🎈Fullscreen open_in_new Finally, if your dataframe is in wide format, you can group multiple columns under the y argument to show multiple series with different colors: import streamlit as st import pandas as pd import numpy as np chart_data = pd.DataFrame(np.random.randn(20, 3), columns=["col1", "col2", "col3"]) st.area_chart( chart_data, x="col1", y=["col2", "col3"], color=["#FF0000", "#0000FF"] # Optional ) Built with Streamlit 🎈Fullscreen open_in_new element.add_rowsStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeConcatenate a dataframe to the bottom of the current one. Function signature[source] element.add_rows(data=None, **kwargs) Parameters data (pandas.DataFrame, pandas.Styler, pyarrow.Table, numpy.ndarray, pyspark.sql.DataFrame, snowflake.snowpark.dataframe.DataFrame, Iterable, dict, or None) Table to concat. Optional. **kwargs (pandas.DataFrame, numpy.ndarray, Iterable, dict, or None) The named dataset to concat. Optional. You can only pass in 1 dataset (including the one in the data parameter). Example import streamlit as st import pandas as pd import numpy as np df1 = pd.DataFrame(np.random.randn(50, 20), columns=("col %d" % i for i in range(20))) my_table = st.table(df1) df2 = pd.DataFrame(np.random.randn(50, 20), columns=("col %d" % i for i in range(20))) my_table.add_rows(df2) # Now the table shown in the Streamlit app contains the data for # df1 followed by the data for df2. You can do the same thing with plots. For example, if you want to add more data to a line chart: # Assuming df1 and df2 from the example above still exist... my_chart = st.line_chart(df1) my_chart.add_rows(df2) # Now the chart shown in the Streamlit app contains the data for # df1 followed by the data for df2. And for plots whose datasets are named, you can pass the data with a keyword argument where the key is the name: my_chart = st.vega_lite_chart({ 'mark': 'line', 'encoding': {'x': 'a', 'y': 'b'}, 'datasets': { 'some_fancy_name': df1, # <-- named dataset }, 'data': {'name': 'some_fancy_name'}, }), my_chart.add_rows(some_fancy_name=df2) # <-- name used as keyword Previous: Chart elementsNext: st.bar_chartforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy
https://docs.streamlit.io/develop/tutorials/databases/tidb
DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceaddTutorialsremoveExecution flowaddConnect to data sourcesremoveAWS S3BigQueryDeta BaseFirestoreopen_in_newGoogle Cloud StorageMicrosoft SQL ServerMongoDBMySQLNeonPostgreSQLPrivate Google SheetPublic Google SheetSnowflakeSupabaseTableauTiDBTigerGraphMultipage appsaddWork with LLMsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Develop/Tutorials/Connect to data sources/TiDBConnect Streamlit to TiDB Introduction This guide explains how to securely access a remote TiDB database from Streamlit Community Cloud. It uses st.connection and Streamlit's Secrets management. The below example code will only work on Streamlit version >= 1.28, when st.connection was added. TiDB is an open-source, MySQL-compatible database that supports Hybrid Transactional and Analytical Processing (HTAP) workloads. TiDB Cloud is a fully managed cloud database service that simplifies the deployment and management of TiDB databases for developers. Sign in to TiDB Cloud and create a cluster First, head over to TiDB Cloud and sign up for a free account, using either Google, GitHub, Microsoft or E-mail: Once you've signed in, you will already have a TiDB cluster: You can create more clusters if you want to. Click the cluster name to enter cluster overview page: Then click Connect to easily get the connection arguments to access the cluster. On the popup, click Generate password to set the password. priority_highImportantMake sure to note down the password. It won't be available on TiDB Cloud after this step. Create a TiDB database push_pinNoteIf you already have a database that you want to use, feel free to skip to the next step. Once your TiDB cluster is up and running, connect to it with the mysql client(or with Chat2Query tab on the console) and enter the following commands to create a database and a table with some example values: CREATE DATABASE pets; USE pets; CREATE TABLE mytable ( name varchar(80), pet varchar(80) ); INSERT INTO mytable VALUES ('Mary', 'dog'), ('John', 'cat'), ('Robert', 'bird'); Add username and password to your local app secrets Your local Streamlit app will read secrets from a file .streamlit/secrets.toml in your app's root directory. Learn more about Streamlit secrets management here. Create this file if it doesn't exist yet and add host, username and password of your TiDB cluster as shown below: # .streamlit/secrets.toml [connections.tidb] dialect = "mysql" host = "<TiDB_cluster_host>" port = 4000 database = "pets" username = "<TiDB_cluster_user>" password = "<TiDB_cluster_password>" priority_highImportantWhen copying your app secrets to Streamlit Community Cloud, be sure to replace the values of host, username and password with those of your remote TiDB cluster!Add this file to .gitignore and don't commit it to your GitHub repo! Copy your app secrets to the cloud As the secrets.toml file above is not committed to GitHub, you need to pass its content to your deployed app (on Streamlit Community Cloud) separately. Go to the app dashboard and in the app's dropdown menu, click on Edit Secrets. Copy the content of secrets.toml into the text area. More information is available at Secrets management. Add dependencies to your requirements file Add the mysqlclient and SQLAlchemy packages to your requirements.txt file, preferably pinning its version (replace x.x.x with the version you want installed): # requirements.txt mysqlclient==x.x.x SQLAlchemy==x.x.x Write your Streamlit app Copy the code below to your Streamlit app and run it. Make sure to adapt query to use the name of your table. # streamlit_app.py import streamlit as st # Initialize connection. conn = st.connection('tidb', type='sql') # Perform query. df = conn.query('SELECT * from mytable;', ttl=600) # Print results. for row in df.itertuples(): st.write(f"{row.name} has a :{row.pet}:") See st.connection above? This handles secrets retrieval, setup, query caching and retries. By default, query() results are cached without expiring. In this case, we set ttl=600 to ensure the query result is cached for no longer than 10 minutes. You can also set ttl=0 to disable caching. Learn more in Caching. If everything worked out (and you used the example table we created above), your app should look like this: Connect with PyMySQL Other than mysqlclient, PyMySQL is another popular MySQL Python client. To use PyMySQL, first you need to adapt your requirements file: # requirements.txt PyMySQL==x.x.x SQLAlchemy==x.x.x Then adapt your secrets file: # .streamlit/secrets.toml [connections.tidb] dialect = "mysql" driver = "pymysql" host = "<TiDB_cluster_host>" port = 4000 database = "pets" username = "<TiDB_cluster_user>" password = "<TiDB_cluster_password>" create_engine_kwargs = { connect_args = { ssl = { ca = "<path_to_CA_store>" }}} Previous: TableauNext: TigerGraphforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy
https://docs.streamlit.io/deploy/concepts/secrets#managing-secrets-when-deploying-your-app
DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceaddTutorialsaddQuick referenceaddweb_assetDeployConceptsremoveDependenciesSecretsStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Deploy/Concepts/SecretsManaging secrets when deploying your app If you are connecting to data sources or external services, you will likely be handling secret information like credentials or keys. Secret information should be stored and transmitted in a secure manner. When you deploy your app, ensure that you understand your platform's features and mechanisms for handling secrets so you can follow best practice. Avoid saving secrets directly in your code and keep .gitignore updated to prevent accidentally committing a local secret to your repository. For helpful reminders, see Security reminders. If you are using Streamlit Community Cloud, Secrets management allows you save environment variables and store secrets outside of your code. If you are using another platform designed for Streamlit, check if they have a built-in mechanism for working with secrets. In some cases, they may even support st.secrets or securely uploading your secrets.toml file. For information about using st.connection with environment variables, see Global secrets, managing multiple apps and multiple data stores.Previous: DependenciesNext: Streamlit Community CloudforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy
https://docs.streamlit.io/develop/api-reference/app-testing/st.testing.v1.apptest#apptesttable
DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceremovePAGE ELEMENTSWrite and magicaddText elementsaddData elementsaddChart elementsaddInput widgetsaddMedia elementsaddLayouts and containersaddChat elementsaddStatus elementsaddThird-party componentsopen_in_newAPPLICATION LOGICNavigation and pagesaddExecution flowaddCaching and stateaddConnections and secretsaddCustom componentsaddUtilitiesaddConfigurationaddTOOLSApp testingremovest.testing.v1.AppTestTesting element classesCommand lineaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Develop/API reference/App testing/st.testing.v1.AppTest The AppTest class st.testing.v1.AppTestStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA simulated Streamlit app to check the correctness of displayed elements and outputs. An instance of AppTest simulates a running Streamlit app. This class provides methods to set up, manipulate, and inspect the app contents via API instead of a browser UI. It can be used to write automated tests of an app in various scenarios. These can then be run using a tool like pytest. AppTest can be initialized by one of three class methods: st.testing.v1.AppTest.from_file (recommended) st.testing.v1.AppTest.from_string st.testing.v1.AppTest.from_function Once initialized, Session State and widget values can be updated and the script can be run. Unlike an actual live-running Streamlit app, you need to call AppTest.run() explicitly to re-run the app after changing a widget value. Switching pages also requires an explicit, follow-up call to AppTest.run(). AppTest enables developers to build tests on their app as-is, in the familiar python test format, without major refactoring or abstracting out logic to be tested separately from the UI. Tests can run quickly with very low overhead. A typical pattern is to build a suite of tests for an app that ensure consistent functionality as the app evolves, and run the tests locally and/or in a CI environment like Github Actions. Note AppTest only supports testing a single page of an app per instance. For multipage apps, each page will need to be tested separately. No methods exist to programatically switch pages within AppTest. Class description[source] st.testing.v1.AppTest(script_path, *, default_timeout, args=None, kwargs=None) Methods get(element_type) Get elements or widgets of the specified type. run(*, timeout=None) Run the script from the current state. switch_page(page_path) Switch to another page of the app. Attributes secrets (dict[str, Any]) Dictionary of secrets to be used the simulated app. Use dict-like syntax to set secret values for the simulated app. session_state (SafeSessionState) Session State for the simulated app. SafeSessionState object supports read and write operations as usual for Streamlit apps. query_params (dict[str, Any]) Dictionary of query parameters to be used by the simluated app. Use dict-like syntax to set query_params values for the simulated app. button Sequence of all st.button and st.form_submit_button widgets. caption Sequence of all st.caption elements. chat_input Sequence of all st.chat_input widgets. chat_message Sequence of all st.chat_message elements. checkbox Sequence of all st.checkbox widgets. code Sequence of all st.code elements. color_picker Sequence of all st.color_picker widgets. columns Sequence of all columns within st.columns elements. dataframe Sequence of all st.dataframe elements. date_input Sequence of all st.date_input widgets. divider Sequence of all st.divider elements. error Sequence of all st.error elements. exception Sequence of all st.exception elements. expander Sequence of all st.expander elements. header Sequence of all st.header elements. info Sequence of all st.info elements. json Sequence of all st.json elements. latex Sequence of all st.latex elements. main Sequence of elements within the main body of the app. markdown Sequence of all st.markdown elements. metric Sequence of all st.metric elements. multiselect Sequence of all st.multiselect widgets. number_input Sequence of all st.number_input widgets. radio Sequence of all st.radio widgets. select_slider Sequence of all st.select_slider widgets. selectbox Sequence of all st.selectbox widgets. sidebar Sequence of all elements within st.sidebar. slider Sequence of all st.slider widgets. status Sequence of all st.status elements. subheader Sequence of all st.subheader elements. success Sequence of all st.success elements. table Sequence of all st.table elements. tabs Sequence of all tabs within st.tabs elements. text Sequence of all st.text elements. text_area Sequence of all st.text_area widgets. text_input Sequence of all st.text_input widgets. time_input Sequence of all st.time_input widgets. title Sequence of all st.title elements. toast Sequence of all st.toast elements. toggle Sequence of all st.toggle widgets. warning Sequence of all st.warning elements. Initialize a simulated app using AppTest AppTest.from_fileStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeCreate an instance of AppTest to simulate an app page defined within a file. This option is most convenient for CI workflows and testing of published apps. The script must be executable on its own and so must contain all necessary imports. Function signature[source] AppTest.from_file(cls, script_path, *, default_timeout=3) Parameters script_path (str) Path to a script file. The path should be absolute or relative to the file calling .from_file. default_timeout (float) Default time in seconds before a script run is timed out. Can be overridden for individual .run() calls. Returns(AppTest) A simulated Streamlit app for testing. The simulated app can be executed via .run(). AppTest.from_stringStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeCreate an instance of AppTest to simulate an app page defined within a string. This is useful for testing short scripts that fit comfortably as an inline string in the test itself, without having to create a separate file for it. The script must be executable on its own and so must contain all necessary imports. Function signature[source] AppTest.from_string(cls, script, *, default_timeout=3) Parameters script (str) The string contents of the script to be run. default_timeout (float) Default time in seconds before a script run is timed out. Can be overridden for individual .run() calls. Returns(AppTest) A simulated Streamlit app for testing. The simulated app can be executed via .run(). AppTest.from_functionStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeCreate an instance of AppTest to simulate an app page defined within a function. This is similar to AppTest.from_string(), but more convenient to write with IDE assistance. The script must be executable on its own and so must contain all necessary imports. Function signature[source] AppTest.from_function(cls, script, *, default_timeout=3, args=None, kwargs=None) Parameters script (Callable) A function whose body will be used as a script. Must be runnable in isolation, so it must include any necessary imports. default_timeout (float) Default time in seconds before a script run is timed out. Can be overridden for individual .run() calls. args (tuple) An optional tuple of args to pass to the script function. kwargs (dict) An optional dict of kwargs to pass to the script function. Returns(AppTest) A simulated Streamlit app for testing. The simulated app can be executed via .run(). Run an AppTest script AppTest.runStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeRun the script from the current state. This is equivalent to manually rerunning the app or the rerun that occurs upon user interaction. AppTest.run() must be manually called after updating a widget value or switching pages as script reruns do not occur automatically as they do for live-running Streamlit apps. Function signature[source] AppTest.run(*, timeout=None) Parameters timeout (null) The maximum number of seconds to run the script. None means use the default timeout set for the instance of AppTest. Returns(AppTest) self AppTest.switch_pageStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeSwitch to another page of the app. This method does not automatically rerun the app. Use a follow-up call to AppTest.run() to obtain the elements on the selected page. Function signature[source] AppTest.switch_page(page_path) Parameters page_path (str) Path of the page to switch to. The path must be relative to the main script's location (e.g. "pages/my_page.py"). Returns(AppTest) self Get AppTest script elements The main value of AppTest is providing an API to programmatically inspect and interact with the elements and widgets produced by a running Streamlit app. Using the AppTest.<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/api-reference#app-logic-and-configuration
DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceremovePAGE ELEMENTSWrite and magicaddText elementsaddData elementsaddChart elementsaddInput widgetsaddMedia elementsaddLayouts and containersaddChat elementsaddStatus elementsaddThird-party componentsopen_in_newAPPLICATION LOGICNavigation and pagesaddExecution flowaddCaching and stateaddConnections and secretsaddCustom componentsaddUtilitiesaddConfigurationaddTOOLSApp testingaddCommand lineaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Develop/API referenceAPI reference Streamlit makes it easy for you to visualize, mutate, and share data. The API reference is organized by activity type, like displaying data or optimizing performance. Each section includes methods associated with the activity type, including examples. Browse our API below and click to learn more about any of our available commands! 🎈 Display almost anything Write and magic st.writeWrite arguments to the app.st.write("Hello **world**!") st.write(my_data_frame) st.write(my_mpl_figure) st.write_streamWrite generators or streams to the app with a typewriter effect.st.write_stream(my_generator) st.write_stream(my_llm_stream) MagicAny time Streamlit sees either a variable or literal value on its own line, it automatically writes that to your app using st.write"Hello **world**!" my_data_frame my_mpl_figure Text elements MarkdownDisplay string formatted as Markdown.st.markdown("Hello **world**!") TitleDisplay text in title formatting.st.title("The app title") HeaderDisplay text in header formatting.st.header("This is a header") SubheaderDisplay text in subheader formatting.st.subheader("This is a subheader") CaptionDisplay text in small font.st.caption("This is written small caption text") Code blockDisplay a code block with optional syntax highlighting.st.code("a = 1234") EchoDisplay some code in the app, then execute it. Useful for tutorials.with st.echo(): st.write('This code will be printed') LaTeXDisplay mathematical expressions formatted as LaTeX.st.latex("\int a x^2 \,dx") Preformatted textWrite fixed-width and preformatted text.st.text("Hello world") DividerDisplay a horizontal rule.st.divider() Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration! PreviousTagsAdd tags to your Streamlit apps. Created by @gagan3012.st_tags(label='# Enter Keywords:', text='Press enter to add more', value=['Zero', 'One', 'Two'], suggestions=['five', 'six', 'seven', 'eight', 'nine', 'three', 'eleven', 'ten', 'four'], maxtags = 4, key='1') NLUApply text mining on a dataframe. Created by @JohnSnowLabs.nlu.load('sentiment').predict('I love NLU! <3') Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.mention(label="An awesome Streamlit App", icon="streamlit", url="https://extras.streamlit.app",) Annotated textDisplay annotated text in Streamlit apps. Created by @tvst.annotated_text("This ", ("is", "verb"), " some ", ("annotated", "adj"), ("text", "noun"), " for those of ", ("you", "pronoun"), " who ", ("like", "verb"), " this sort of ", ("thing", "noun"), ".") Drawable CanvasProvides a sketching canvas using Fabric.js. Created by @andfanilo.st_canvas(fill_color="rgba(255, 165, 0, 0.3)", stroke_width=stroke_width, stroke_color=stroke_color, background_color=bg_color, background_image=Image.open(bg_image) if bg_image else None, update_streamlit=realtime_update, height=150, drawing_mode=drawing_mode, point_display_radius=point_display_radius if drawing_mode == 'point' else 0, key="canvas",) TagsAdd tags to your Streamlit apps. Created by @gagan3012.st_tags(label='# Enter Keywords:', text='Press enter to add more', value=['Zero', 'One', 'Two'], suggestions=['five', 'six', 'seven', 'eight', 'nine', 'three', 'eleven', 'ten', 'four'], maxtags = 4, key='1') NLUApply text mining on a dataframe. Created by @JohnSnowLabs.nlu.load('sentiment').predict('I love NLU! <3') Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.mention(label="An awesome Streamlit App", icon="streamlit", url="https://extras.streamlit.app",) Annotated textDisplay annotated text in Streamlit apps. Created by @tvst.annotated_text("This ", ("is", "verb"), " some ", ("annotated", "adj"), ("text", "noun"), " for those of ", ("you", "pronoun"), " who ", ("like", "verb"), " this sort of ", ("thing", "noun"), ".") Drawable CanvasProvides a sketching canvas using Fabric.js. Created by @andfanilo.st_canvas(fill_color="rgba(255, 165, 0, 0.3)", stroke_width=stroke_width, stroke_color=stroke_color, background_color=bg_color, background_image=Image.open(bg_image) if bg_image else None, update_streamlit=realtime_update, height=150, drawing_mode=drawing_mode, point_display_radius=point_display_radius if drawing_mode == 'point' else 0, key="canvas",) TagsAdd tags to your Streamlit apps. Created by @gagan3012.st_tags(label='# Enter Keywords:', text='Press enter to add more', value=['Zero', 'One', 'Two'], suggestions=['five', 'six', 'seven', 'eight', 'nine', 'three', 'eleven', 'ten', 'four'], maxtags = 4, key='1') NLUApply text mining on a dataframe. Created by @JohnSnowLabs.nlu.load('sentiment').predict('I love NLU! <3') Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.mention(label="An awesome Streamlit App", icon="streamlit", url="https://extras.streamlit.app",) Next Data elements DataframesDisplay a dataframe as an interactive table.st.dataframe(my_data_frame) Data editorDisplay a data editor widget.edited = st.data_editor(df, num_rows="dynamic") Column configurationConfigure the display and editing behavior of dataframes and data editors.st.column_config.NumberColumn("Price (in USD)", min_value=0, format="$%d") Static tablesDisplay a static table.st.table(my_data_frame) MetricsDisplay a metric in big bold font, with an optional indicator of how the metric changed.st.metric("My metric", 42, 2) Dicts and JSONDisplay object or string as a pretty-printed JSON string.st.json(my_dict) Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration! PreviousImage CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates value = streamlit_image_coordinates("https://placekitten.com/200/300") st.write(value) Plotly EventsMake Plotly charts interactive!. Created by @null-jones.from streamlit_plotly_events import plotly_events fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.metric_cards import style_metric_cards col3.metric(label="No Change", value=5000, delta=0) style_metric_cards() Streamlit AggridImplementation of Ag-Grid component for Streamlit. Created by @PablocFonseca.df = pd.DataFrame({'col1': [1, 2, 3], 'col2': [4, 5, 6]}) grid_return = AgGrid(df, editable=True) new_df = grid_return['data'] Streamlit FoliumStreamlit Component for rendering Folium maps. Created by @randyzwitch.m = folium.Map(location=[39.949610, -75.150282], zoom_start=16) folium.Marker([39.949610, -75.150282], popup="Liberty Bell", tooltip="Liberty Bell").add_to(m) st_data = st_folium(m, width=725) Pandas ProfilingPandas profiling component for Streamlit. Created by @okld.df = pd.read_csv("https://storage.googleapis.com/tf-datasets/titanic/train.csv") pr = df.profile_report() st_profile_report(pr) Image CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates value = streamlit_image_coordinates("https://placekitten.com/200/300") st.write(value) Plotly EventsMake Plotly charts interactive!. Created by @null-jones.from streamlit_plotly_events import plotly_events fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.metric_cards import style_metric_cards col3.metric(label="No Change", value=5000, delta=0) style_metric_cards() Streamlit AggridImplementation of Ag-Grid component for Streamlit. Created by @PablocFonseca.df = pd.DataFrame({'col1': [1, 2, 3], 'col2': [4, 5, 6]}) grid_return = AgGrid(df, editable=True) new_df = grid_return['data'] Streamlit FoliumStreamlit Component for rendering Folium maps. Created by @randyzwitch.m = folium.Map(location=[39.949610, -75.150282], zoom_start=16) folium.Marker([39.949610, -75.150282], popup="Liberty Bell", tooltip="Liberty Bell").add_to(m) st_data = st_folium(m, width=725) Pandas ProfilingPandas profiling component for Streamlit. Created by @okld.df = pd.read_csv("https://storage.googleapis.com/tf-datasets/titanic/train.csv") pr = df.profile_report() st_profile_report(pr) Image CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates value = streamlit_image_coordinates("https://placekitten.com/200/300") st.write(value) Plotly EventsMake Plotly charts interactive!. Created by @null-jones.from streamlit_plotly_events import plotly_events fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.metric_cards import style_metric_cards col3.metric(label="No Change", value=5000, delta=0) style_metric_cards() Next Chart elements Simple area chartsDisplay an area chart.st.area_chart(my_data_frame) Simple bar chartsDisplay a bar chart.st.bar_chart(my_data_frame) Simple line chartsDisplay a line chart.st.line_chart(my_data_frame) Simple scatter chartsDisplay a line chart.st.scatter_chart(my_data_frame) Scatterplots on mapsDisplay a map with points on it.st.map(my_data_frame) MatplotlibDisplay a matplotlib.pyplot figure.st.pyplot(my_mpl_figure) AltairDisplay a chart using the Altair library.st.altair_chart(my_altair_chart) Vega-LiteDisplay a chart using the Vega-Lite library.st.vega_lite_chart(my_vega_lite_chart) PlotlyDisplay an interactive Plotly chart.st.plotly_chart(my_plotly_chart) BokehDisplay an interactive Bokeh chart.st.bokeh_chart(my_bokeh_chart) PyDeckDisplay a chart using the PyDeck library.st.pydeck_chart(my_pydeck_chart) GraphVizDisplay a graph using the dagre-d3 library.st.graphviz_chart(my_graphviz_spec) Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration! PreviousStreamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl("https://assets5.lottiefiles.com/packages/lf20_V9t630.json") st_lottie(lottie_hello, key="hello") Plotly EventsMake Plotly charts interactive!. Created by @null-jones.fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.chart += get_annotations_chart(annotations=[("Mar 01, 2008", "Pretty good day for GOOG"), ("Dec 01, 2007", "Something's going wrong for GOOG & AAPL"), ("Nov 01, 2008", "Market starts again thanks to..."), ("Dec 01, 2009", "Small crash for GOOG after..."),],) st.altair_chart(chart, use_container_width=True) PlostA deceptively simple plotting library for Streamlit. Created by @tvst.import plost plost.line_chart(my_dataframe, x='time', y='stock_value', color='stock_name',) HiPlotHigh dimensional Interactive Plotting. Created by @facebookresearch.data = [{'dropout':0.1, 'lr': 0.001, 'loss': 10.0, 'optimizer': 'SGD'}, {'dropout':0.15, 'lr': 0.01, 'loss': 3.5, 'optimizer': 'Adam'}, {'dropout':0.3, 'lr': 0.1, 'loss': 4.5, 'optimizer': 'Adam'}] hip.Experiment.from_iterable(data).display() EChartsHigh dimensional Interactive Plotting. Created by @andfanilo.from streamlit_echarts import st_echarts st_echarts(options=options) Streamlit FoliumStreamlit Component for rendering Folium maps. Created by @randyzwitch.m = folium.Map(location=[39.949610, -75.150282], zoom_start=16) st_data = st_folium(m, width=725) Spacy-StreamlitspaCy building blocks and visualizers for Streamlit apps. Created by @explosion.models = ["en_core_web_sm", "en_core_web_md"] spacy_streamlit.visualize(models, "Sundar Pichai is the CEO of Google.") Streamlit AgraphA Streamlit Graph Vis, based on react-grah-vis. Created by @ChrisDelClea.from streamlit_agraph import agraph, Node, Edge, Config agraph(nodes=nodes, edges=edges, config=config) Streamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl("https://assets5.lottiefiles.com/packages/lf20_V9t630.json") st_lottie(lottie_hello, key="hello") Plotly EventsMake Plotly charts interactive!. Created by @null-jones.fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.chart += get_annotations_chart(annotations=[("Mar 01, 2008", "Pretty good day for GOOG"), ("Dec 01, 2007", "Something's going wrong for GOOG & AAPL"), ("Nov 01, 2008", "Market starts again thanks to..."), ("Dec 01, 2009", "Small crash for GOOG after..."),],) st.altair_chart(chart, use_container_width=True) PlostA deceptively simple plotting library for Streamlit. Created by @tvst.import plost plost.line_chart(my_dataframe, x='time', y='stock_value', color='stock_name',) HiPlotHigh dimensional Interactive Plotting. Created by @facebookresearch.data = [{'dropout':0.1, 'lr': 0.001, 'loss': 10.0, 'optimizer': 'SGD'}, {'dropout':0.15, 'lr': 0.01, 'loss': 3.5, 'optimizer': 'Adam'}, {'dropout':0.3, 'lr': 0.1, 'loss': 4.5, 'optimizer': 'Adam'}] hip.Experiment.from_iterable(data).display() EChartsHigh dimensional Interactive Plotting. Created by @andfanilo.from streamlit_echarts import st_echarts st_echarts(options=options) Streamlit FoliumStreamlit Component for rendering Folium maps. Created by @randyzwitch.m = folium.Map(location=[39.949610, -75.150282], zoom_start=16) st_data = st_folium(m, width=725) Spacy-StreamlitspaCy building blocks and visualizers for Streamlit apps. Created by @explosion.models = ["en_core_web_sm", "en_core_web_md"] spacy_streamlit.visualize(models, "Sundar Pichai is the CEO of Google.") Streamlit AgraphA Streamlit Graph Vis, based on react-grah-vis. Created by @ChrisDelClea.from streamlit_agraph import agraph, Node, Edge, Config agraph(nodes=nodes, edges=edges, config=config) Streamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl("https://assets5.lottiefiles.com/packages/lf20_V9t630.json") st_lottie(lottie_hello, key="hello") Plotly EventsMake Plotly charts interactive!. Created by @null-jones.fig = px.line(x=[1], y=[1]) selected_points = plotly_events(fig) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.chart += get_annotations_chart(annotations=[("Mar 01, 2008", "Pretty good day for GOOG"), ("Dec 01, 2007", "Something's going wrong for GOOG & AAPL"), ("Nov 01, 2008", "Market starts again thanks to..."), ("Dec 01, 2009", "Small crash for GOOG after..."),],) st.altair_chart(chart, use_container_width=True) Next Input widgets ButtonDisplay a button widget.clicked = st.button("Click me") Download buttonDisplay a download button widget.st.download_button("Download file", file) Form buttonDisplay a form submit button. For use with st.form.st.form_submit_button("Sign up") Link buttonDisplay a link button.st.link_button("Go to gallery", url) Page linkDisplay a link to another page in a multipage app.st.page_link("app.py", label="Home", icon="🏠") st.page_link("pages/profile.py", label="My profile") CheckboxDisplay a checkbox widget.selected = st.checkbox("I agree") Color pickerDisplay a color picker widget.color = st.color_picker("Pick a color") MultiselectDisplay a multiselect widget. The multiselect widget starts as empty.choices = st.multiselect("Buy", ["milk", "apples", "potatoes"]) RadioDisplay a radio button widget.choice = st.radio("Pick one", ["cats", "dogs"]) SelectboxDisplay a select widget.choice = st.selectbox("Pick one", ["cats", "dogs"]) Select-sliderDisplay a slider widget to select items from a list.size = st.select_slider("Pick a size", ["S", "M", "L"]) ToggleDisplay a toggle widget.activated = st.toggle("Activate") Number inputDisplay a numeric input widget.choice = st.number_input("Pick a number", 0, 10) SliderDisplay a slider widget.number = st.slider("Pick a number", 0, 100) Date inputDisplay a date input widget.date = st.date_input("Your birthday") Time inputDisplay a time input widget.time = st.time_input("Meeting time") Chat inputDisplay a chat input widget.prompt = st.chat_input("Say something") if prompt: st.write(f"The user has sent: {prompt}") Text-areaDisplay a multi-line text input widget.text = st.text_area("Text to translate") Text inputDisplay a single-line text input widget.name = st.text_input("First name") Data editorDisplay a data editor widget.edited = st.experimental_data_editor(df, num_rows="dynamic") File UploaderDisplay a file uploader widget.data = st.file_uploader("Upload a CSV") Camera inputDisplay a widget that allows users to upload images directly from a camera.image = st.camera_input("Take a picture") Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration! PreviousStreamlit ChatStreamlit Component for a Chatbot UI. Created by @AI-Yash.from streamlit_chat import message message("My message") message("Hello bot!", is_user=True) # align's the message to the right Streamlit Option MenuSelect a single item from a list of options in a menu. Created by @victoryhb.from streamlit_option_menu import option_menu option_menu("Main Menu", ["Home", 'Settings'], icons=['house', 'gear'], menu_icon="cast", default_index=1) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.stoggle import stoggle stoggle( "Click me!", """🥷 Surprise! Here's some additional content""",) Streamlit ElementsCreate a draggable and resizable dashboard in Streamlit. Created by @okls.from streamlit_elements import elements, mui, html with elements("new_element"): mui.Typography("Hello world") TagsAdd tags to your Streamlit apps. Created by @gagan3012.from streamlit_tags import st_tags st_tags(label='# Enter Keywords:', text='Press enter to add more', value=['Zero', 'One', 'Two'], suggestions=['five', 'six', 'seven', 'eight', 'nine', 'three', 'eleven', 'ten', 'four'], maxtags = 4, key='1') StqdmThe simplest way to handle a progress bar in streamlit app. Created by @Wirg.from stqdm import stqdm for _ in stqdm(range(50)): sleep(0.5) TimelineDisplay a Timeline in Streamlit apps using TimelineJS. Created by @innerdoc.from streamlit_timeline import timeline with open('example.json', "r") as f: timeline(f.read(), height=800) Camera input liveAlternative for st.camera_input which returns the webcam images live. Created by @blackary.from camera_input_live import camera_input_live image = camera_input_live() st.image(value) Streamlit AceAce editor component for Streamlit. Created by @okld.from streamlit_ace import st_ace content = st_ace() content Streamlit ChatStreamlit Component for a Chatbot UI. Created by @AI-Yash.from streamlit_chat import message message("My message") message("Hello bot!", is_user=True) # align's the message to the right Streamlit Option MenuSelect a single item from a list of options in a menu. Created by @victoryhb.from streamlit_option_menu import option_menu option_menu("Main Menu", ["Home", 'Settings'], icons=['house', 'gear'], menu_icon="cast", default_index=1) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.stoggle import stoggle stoggle( "Click me!", """🥷 Surprise! Here's some additional content""",) Streamlit ElementsCreate a draggable and resizable dashboard in Streamlit. Created by @okls.from streamlit_elements import elements, mui, html with elements("new_element"): mui.Typography("Hello world") TagsAdd tags to your Streamlit apps. Created by @gagan3012.from streamlit_tags import st_tags st_tags(label='# Enter Keywords:', text='Press enter to add more', value=['Zero', 'One', 'Two'], suggestions=['five', 'six', 'seven', 'eight', 'nine', 'three', 'eleven', 'ten', 'four'], maxtags = 4, key='1') StqdmThe simplest way to handle a progress bar in streamlit app. Created by @Wirg.from stqdm import stqdm for _ in stqdm(range(50)): sleep(0.5) TimelineDisplay a Timeline in Streamlit apps using TimelineJS. Created by @innerdoc.from streamlit_timeline import timeline with open('example.json', "r") as f: timeline(f.read(), height=800) Camera input liveAlternative for st.camera_input which returns the webcam images live. Created by @blackary.from camera_input_live import camera_input_live image = camera_input_live() st.image(value) Streamlit AceAce editor component for Streamlit. Created by @okld.from streamlit_ace import st_ace content = st_ace() content Streamlit ChatStreamlit Component for a Chatbot UI. Created by @AI-Yash.from streamlit_chat import message message("My message") message("Hello bot!", is_user=True) # align's the message to the right Streamlit Option MenuSelect a single item from a list of options in a menu. Created by @victoryhb.from streamlit_option_menu import option_menu option_menu("Main Menu", ["Home", 'Settings'], icons=['house', 'gear'], menu_icon="cast", default_index=1) Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.stoggle import stoggle stoggle( "Click me!", """🥷 Surprise! Here's some additional content""",) Next Media elements ImageDisplay an image or list of images.st.image(numpy_array) st.image(image_bytes) st.image(file) st.image("https://example.com/myimage.jpg") AudioDisplay an audio player.st.audio(numpy_array) st.audio(audio_bytes) st.audio(file) st.audio("https://example.com/myaudio.mp3", format="audio/mp3") VideoDisplay a video player.st.video(numpy_array) st.video(video_bytes) st.video(file) st.video("https://example.com/myvideo.mp4", format="video/mp4") Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration! PreviousStreamlit CropperA simple image cropper for Streamlit. Created by @turner-anderson.from streamlit_cropper import st_cropper st_cropper(img, realtime_update=realtime_update, box_color=box_color, aspect_ratio=aspect_ratio) Image CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates streamlit_image_coordinates("https://placekitten.com/200/300") Streamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl("https://assets5.lottiefiles.com/packages/lf20_V9t630.json") st_lottie(lottie_hello, key="hello") Streamlit WebrtcHandling and transmitting real-time video/audio streams with Streamlit. Created by @whitphx.from streamlit_webrtc import webrtc_streamer webrtc_streamer(key="sample") Drawable CanvasProvides a sketching canvas using Fabric.js. Created by @andfanilo.from streamlit_drawable_canvas import st_canvas st_canvas(fill_color="rgba(255, 165, 0, 0.3)", stroke_width=stroke_width, stroke_color=stroke_color, background_color=bg_color, background_image=Image.open(bg_image) if bg_image else None, update_streamlit=realtime_update, height=150, drawing_mode=drawing_mode, point_display_radius=point_display_radius if drawing_mode == 'point' else 0, key="canvas",) Image ComparisonCompare images with a slider using JuxtaposeJS. Created by @fcakyon.from streamlit_image_comparison import image_comparison image_comparison(img1="image1.jpg", img2="image2.jpg",) Streamlit CropperA simple image cropper for Streamlit. Created by @turner-anderson.from streamlit_cropper import st_cropper st_cropper(img, realtime_update=realtime_update, box_color=box_color, aspect_ratio=aspect_ratio) Image CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates streamlit_image_coordinates("https://placekitten.com/200/300") Streamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl("https://assets5.lottiefiles.com/packages/lf20_V9t630.json") st_lottie(lottie_hello, key="hello") Streamlit WebrtcHandling and transmitting real-time video/audio streams with Streamlit. Created by @whitphx.from streamlit_webrtc import webrtc_streamer webrtc_streamer(key="sample") Drawable CanvasProvides a sketching canvas using Fabric.js. Created by @andfanilo.from streamlit_drawable_canvas import st_canvas st_canvas(fill_color="rgba(255, 165, 0, 0.3)", stroke_width=stroke_width, stroke_color=stroke_color, background_color=bg_color, background_image=Image.open(bg_image) if bg_image else None, update_streamlit=realtime_update, height=150, drawing_mode=drawing_mode, point_display_radius=point_display_radius if drawing_mode == 'point' else 0, key="canvas",) Image ComparisonCompare images with a slider using JuxtaposeJS. Created by @fcakyon.from streamlit_image_comparison import image_comparison image_comparison(img1="image1.jpg", img2="image2.jpg",) Streamlit CropperA simple image cropper for Streamlit. Created by @turner-anderson.from streamlit_cropper import st_cropper st_cropper(img, realtime_update=realtime_update, box_color=box_color, aspect_ratio=aspect_ratio) Image CoordinatesGet the coordinates of clicks on an image. Created by @blackary.from streamlit_image_coordinates import streamlit_image_coordinates streamlit_image_coordinates("https://placekitten.com/200/300") Streamlit LottieIntegrate Lottie animations inside your Streamlit app. Created by @andfanilo.lottie_hello = load_lottieurl("https://assets5.lottiefiles.com/packages/lf20_V9t630.json") st_lottie(lottie_hello, key="hello") Next Layouts and containers ColumnsInsert containers laid out as side-by-side columns.col1, col2 = st.columns(2) col1.write("this is column 1") col2.write("this is column 2") ContainerInsert a multi-element container.c = st.container() st.write("This will show last") c.write("This will show first") c.write("This will show second") Modal dialogsInsert a modal dialog that can rerun independently from the rest of the script.@st.experimental_dialog("Sign up") def email_form(): name = st.text_input("Name") email = st.text_input("Email") EmptyInsert a single-element container.c = st.empty() st.write("This will show last") c.write("This will be replaced") c.write("This will show first") ExpanderInsert a multi-element container that can be expanded/collapsed.with st.expander("Open to see more"): st.write("This is more content") PopoverInsert a multi-element popover container that can be opened/closed.with st.popover("Settings"): st.checkbox("Show completed") SidebarDisplay items in a sidebar.st.sidebar.write("This lives in the sidebar") st.sidebar.button("Click me!") TabsInsert containers separated into tabs.tab1, tab2 = st.tabs(["Tab 1", "Tab2"]) tab1.write("this is tab 1") tab2.write("this is tab 2") Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration!Streamlit ElementsCreate a draggable and resizable dashboard in Streamlit. Created by @okls.from streamlit_elements import elements, mui, html with elements("new_element"): mui.Typography("Hello world") PydanticAuto-generate Streamlit UI from Pydantic Models and Dataclasses. Created by @lukasmasuch.import streamlit_pydantic as sp sp.pydantic_form(key="my_form", model=ExampleModel) Streamlit PagesAn experimental version of Streamlit Multi-Page Apps. Created by @blackary.from st_pages import Page, show_pages, add_page_title show_pages([ Page("streamlit_app.py", "Home", "🏠"), Page("other_pages/page2.py", "Page 2", ":books:"), ]) Chat elements Streamlit provides a few commands to help you build conversational apps. These chat elements are designed to be used in conjunction with each other, but you can also use them separately. st.chat_message lets you insert a chat message container into the app so you can display messages from the user or the app. Chat containers can contain other Streamlit elements, including charts, tables, text, and more. st.chat_input lets you display a chat input widget so the user can type in a message. Chat inputDisplay a chat input widget.prompt = st.chat_input("Say something") if prompt: st.write(f"The user has sent: {prompt}") Chat messageInsert a chat message container.import numpy as np with st.chat_message("user"): st.write("Hello 👋") st.line_chart(np.random.randn(30, 3)) Status containerDisplay output of long-running tasks in a container.with st.status('Running'): do_something_slow() st.write_streamWrite generators or streams to the app with a typewriter effect.st.write_stream(my_generator) st.write_stream(my_llm_stream) Status elements Progress barDisplay a progress bar.for i in range(101): st.progress(i) do_something_slow() SpinnerTemporarily displays a message while executing a block of code.with st.spinner("Please wait..."): do_something_slow() Status containerDisplay output of long-running tasks in a container.with st.status('Running'): do_something_slow() ToastBriefly displays a toast message in the bottom-right corner.st.toast('Butter!', icon='🧈') BalloonsDisplay celebratory balloons!do_something() # Celebrate when all done! st.balloons() SnowflakesDisplay celebratory snowflakes!do_something() # Celebrate when all done! st.snow() Success boxDisplay a success message.st.success("Match found!") Info boxDisplay an informational message.st.info("Dataset is updated every day at midnight.") Warning boxDisplay warning message.st.warning("Unable to fetch image. Skipping...") Error boxDisplay error message.st.error("We encountered an error") Exception outputDisplay an exception.e = RuntimeError("This is an exception of type RuntimeError") st.exception(e) Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration!StqdmThe simplest way to handle a progress bar in streamlit app. Created by @Wirg.from stqdm import stqdm for _ in stqdm(range(50)): sleep(0.5) Custom notification boxA custom notification box with the ability to close it out. Created by @Socvest.from streamlit_custom_notification_box import custom_notification_box styles = {'material-icons':{'color': 'red'}, 'text-icon-link-close-container': {'box-shadow': '#3896de 0px 4px'}, 'notification-text': {'':''}, 'close-button':{'':''}, 'link':{'':''}} custom_notification_box(icon='info', textDisplay='We are almost done with your registration...', externalLink='more info', url='#', styles=styles, key="foo") Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.from streamlit_extras.let_it_rain import rain rain(emoji="🎈", font_size=54, falling_speed=5, animation_length="infinite",) App logic and configuration Navigation and pages Switch pageProgrammatically navigates to a specified page.st.switch_page("pages/my_page.py") Page linkDisplay a link to another page in a multipage app.st.page_link("app.py", label="Home", icon="🏠") st.page_link("pages/profile.py", label="My profile") Execution flow Modal dialogsInsert a modal dialog that can rerun independently from the rest of the script.@st.experimental_dialog("Sign up") def email_form(): name = st.text_input("Name") email = st.text_input("Email") FormsCreate a form that batches elements together with a “Submit" button.with st.form(key='my_form'): name = st.text_input("Name") email = st.text_input("Email") st.form_submit_button("Sign up") Partial rerunsDefine a fragment to rerun independently from the rest of the script.@st.experimental_fragment(run_every="10s") def fragment(): df = get_data() st.line_chart(df) Rerun scriptRerun the script immediately.st.rerun() Stop executionStops execution immediately.st.stop() Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration!AutorefreshForce a refresh without tying up a script. Created by @kmcgrady.from streamlit_autorefresh import st_autorefresh st_autorefresh(interval=2000, limit=100, key="fizzbuzzcounter") PydanticAuto-generate Streamlit UI from Pydantic Models and Dataclasses. Created by @lukasmasuch.import streamlit_pydantic as sp sp.pydantic_form(key="my_form", model=ExampleModel) Streamlit PagesAn experimental version of Streamlit Multi-Page Apps. Created by @blackary.from st_pages import Page, show_pages, add_page_title show_pages([ Page("streamlit_app.py", "Home", "🏠"), Page("other_pages/page2.py", "Page 2", ":books:"), ]) Caching and state Cache dataFunction decorator to cache functions that return data (e.g. dataframe transforms, database queries, ML inference).@st.cache_data def long_function(param1, param2): # Perform expensive computation here or # fetch data from the web here return data Cache resourceFunction decorator to cache functions that return global resources (e.g. database connections, ML models).@st.cache_resource def init_model(): # Return a global resource here return pipeline( "sentiment-analysis", model="distilbert-base-uncased-finetuned-sst-2-english" ) Session stateSession state is a way to share variables between reruns, for each user session.st.session_state['key'] = value Query parametersGet, set, or clear the query parameters that are shown in the browser's URL bar.st.query_params[key] = value st.query_params.clear() Connections and databases Setup your connection Create a connectionConnect to a data source or APIconn = st.connection('pets_db', type='sql') pet_owners = conn.query('select * from pet_owners') st.dataframe(pet_owners) Built-in connections SnowflakeConnectionA connection to Snowflake.conn = st.connection('snowflake') SQLConnectionA connection to a SQL database using SQLAlchemy.conn = st.connection('sql') Build your own connections Connection base classBuild your own connection with BaseConnection.class MyConnection(BaseConnection[myconn.MyConnection]): def _connect(self, **kwargs) -> MyConnection: return myconn.connect(**self._secrets, **kwargs) def query(self, query): return self._instance.query(query) Secrets management Secrets singletonAccess secrets from a local TOML file.key = st.secrets["OpenAI_key"] Secrets fileSave your secrets in a per-project or per-profile TOML file.OpenAI_key = "<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_treebutton
DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceremovePAGE ELEMENTSWrite and magicaddText elementsaddData elementsaddChart elementsaddInput widgetsaddMedia elementsaddLayouts and containersaddChat elementsaddStatus elementsaddThird-party componentsopen_in_newAPPLICATION LOGICNavigation and pagesaddExecution flowaddCaching and stateaddConnections and secretsaddCustom componentsaddUtilitiesaddConfigurationaddTOOLSApp testingremovest.testing.v1.AppTestTesting element classesCommand lineaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Develop/API reference/App testing/Testing element classesTesting element classes st.testing.v1.element_tree.Block The Block class has the same methods and attributes as AppTest. A Block instance represents a container of elements just as AppTest represents the entire app. For example, Block.button will produce a WidgetList of Button in the same manner as AppTest.button. ChatMessage, Column, and Tab all inherit from Block. For all container classes, parameters of the original element can be obtained as properties. For example, ChatMessage.avatar and Tab.label. st.testing.v1.element_tree.ElementStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeElement base class for testing. This class's methods and attributes are universal for all elements implemented in testing. For example, Caption, Code, Text, and Title inherit from Element. All widget classes also inherit from Element, but have additional methods specific to each widget type. See the AppTest class for the full list of supported elements. For all element classes, parameters of the original element can be obtained as properties. For example, Button.label, Caption.help, and Toast.icon. Class description[source] st.testing.v1.element_tree.Element(proto, root) Methods run(*, timeout=None) Run the AppTest script which contains the element. Attributes value The value or contents of the element. st.testing.v1.element_tree.ButtonStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.button and st.form_submit_button. Class description[source] st.testing.v1.element_tree.Button(proto, root) Methods click() Set the value of the button to True. run(*, timeout=None) Run the AppTest script which contains the element. set_value(v) Set the value of the button. Attributes value The value of the button. (bool) st.testing.v1.element_tree.ChatInputStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.chat_input. Class description[source] st.testing.v1.element_tree.ChatInput(proto, root) Methods run(*, timeout=None) Run the AppTest script which contains the element. set_value(v) Set the value of the widget. Attributes value The value of the widget. (str) st.testing.v1.element_tree.CheckboxStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.checkbox. Class description[source] st.testing.v1.element_tree.Checkbox(proto, root) Methods check() Set the value of the widget to True. run(*, timeout=None) Run the AppTest script which contains the element. set_value(v) Set the value of the widget. uncheck() Set the value of the widget to False. Attributes value The value of the widget. (bool) st.testing.v1.element_tree.ColorPickerStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.color_picker. Class description[source] st.testing.v1.element_tree.ColorPicker(proto, root) Methods pick(v) Set the value of the widget as a hex string. May omit the "#" prefix. run(*, timeout=None) Run the AppTest script which contains the element. set_value(v) Set the value of the widget as a hex string. Attributes value The currently selected value as a hex string. (str) st.testing.v1.element_tree.DateInputStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.date_input. Class description[source] st.testing.v1.element_tree.DateInput(proto, root) Methods run(*, timeout=None) Run the AppTest script which contains the element. set_value(v) Set the value of the widget. Attributes value The value of the widget. (date or Tuple of date) st.testing.v1.element_tree.MultiselectStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.multiselect. Class description[source] st.testing.v1.element_tree.Multiselect(proto, root) Methods run(*, timeout=None) Run the AppTest script which contains the element. select(v) Add a selection to the widget. Do nothing if the value is already selected. If testing a multiselect widget with repeated options, use set_value instead. set_value(v) Set the value of the multiselect widget. (list) unselect(v) Remove a selection from the widget. Do nothing if the value is not already selected. If a value is selected multiple times, the first instance is removed. Attributes format_func The widget's formatting function for displaying options. (callable) indices The indices of the currently selected values from the options. (list) value The currently selected values from the options. (list) st.testing.v1.element_tree.NumberInputStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.number_input. Class description[source] st.testing.v1.element_tree.NumberInput(proto, root) Methods decrement() Decrement the st.number_input widget as if the user clicked "-". increment() Increment the st.number_input widget as if the user clicked "+". run(*, timeout=None) Run the AppTest script which contains the element. set_value(v) Set the value of the st.number_input widget. Attributes value Get the current value of the st.number_input widget. st.testing.v1.element_tree.RadioStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.radio. Class description[source] st.testing.v1.element_tree.Radio(proto, root) Methods run(*, timeout=None) Run the AppTest script which contains the element. set_value(v) Set the selection by value. Attributes format_func The widget's formatting function for displaying options. (callable) index The index of the current selection. (int) value The currently selected value from the options. (Any) st.testing.v1.element_tree.SelectSliderStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.select_slider. Class description[source] st.testing.v1.element_tree.SelectSlider(proto, root) Methods run(*, timeout=None) Run the AppTest script which contains the element. set_range(lower, upper) Set the ranged selection by values. set_value(v) Set the (single) selection by value. Attributes format_func The widget's formatting function for displaying options. (callable) value The currently selected value or range. (Any or Sequence of Any) st.testing.v1.element_tree.SelectboxStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.selectbox. Class description[source] st.testing.v1.element_tree.Selectbox(proto, root) Methods run(*, timeout=None) Run the AppTest script which contains the element. select(v) Set the selection by value. select_index(index) Set the selection by index. set_value(v) Set the selection by value. Attributes format_func The widget's formatting function for displaying options. (callable) index The index of the current selection. (int) value The currently selected value from the options. (Any) st.testing.v1.element_tree.SliderStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.slider. Class description[source] st.testing.v1.element_tree.Slider(proto, root) Methods run(*, timeout=None) Run the AppTest script which contains the element. set_range(lower, upper) Set the ranged value of the slider. set_value(v) Set the (single) value of the slider. Attributes value The currently selected value or range. (Any or Sequence of Any) st.testing.v1.element_tree.TextAreaStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.text_area. Class description[source] st.testing.v1.element_tree.TextArea(proto, root) Methods input(v) Set the value of the widget only if the value does not exceed the maximum allowed characters. run(*, timeout=None) Run the AppTest script which contains the element. set_value(v) Set the value of the widget. Attributes value The current value of the widget. (str) st.testing.v1.element_tree.TextInputStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.text_input. Class description[source] st.testing.v1.element_tree.TextInput(proto, root) Methods input(v) Set the value of the widget only if the value does not exceed the maximum allowed characters. run(*, timeout=None) Run the AppTest script which contains the element. set_value(v) Set the value of the widget. Attributes value The current value of the widget. (str) st.testing.v1.element_tree.TimeInputStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.time_input. Class description[source] st.testing.v1.element_tree.TimeInput(proto, root) Methods decrement() Select the previous available time. increment() Select the next available time. run(*, timeout=None) Run the AppTest script which contains the element. set_value(v) Set the value of the widget. Attributes value The current value of the widget. (time) st.testing.v1.element_tree.ToggleStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA representation of st.toggle. Class description[source] st.testing.v1.element_tree.Toggle(proto, root) Methods run(*, timeout=None) Run the AppTest script which contains the element. set_value(v) Set the value of the widget. Attributes value The current value of the widget. (bool) Previous: st.testing.v1.AppTestNext: Command lineforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy
https://docs.streamlit.io/develop/concepts/custom-components#custom-components
DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsremoveCOREArchitecture & executionaddMultipage appsaddApp designaddADDITIONALConnections and secretsaddCustom componentsremoveIntro to custom componentsCreate a ComponentPublish a ComponentLimitationsComponent galleryopen_in_newConfiguration and themingaddApp testingaddAPI referenceaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Develop/Concepts/Custom componentsCustom Components Components are third-party Python modules that extend what's possible with Streamlit. How to use a Component Components are super easy to use: Start by finding the Component you'd like to use. Two great resources for this are: The Component gallery This thread, by Fanilo A. from our forums. Install the Component using your favorite Python package manager. This step and all following steps are described in your component's instructions. For example, to use the fantastic AgGrid Component, you first install it with: pip install streamlit-aggrid In your Python code, import the Component as described in its instructions. For AgGrid, this step is: from st_aggrid import AgGrid ...now you're ready to use it! For AgGrid, that's: AgGrid(my_dataframe) Making your own Component If you're interested in making your own component, check out the following resources: Create a Component Publish a Component Components API Blog post for when we launched Components! Alternatively, if you prefer to learn using videos, our engineer Tim Conkling has put together some amazing tutorials: Video tutorial, part 1 Video tutorial, part 2 Previous: Connections and secretsNext: Intro to custom componentsforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy
https://docs.streamlit.io/deploy/tutorials/kubernetes#create-a-docker-container
DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsremoveDockerKubernetesschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Deploy/Other platforms/KubernetesDeploy Streamlit using Kubernetes Introduction So you have an amazing app and you want to start sharing it with other people, what do you do? You have a few options. First, where do you want to run your Streamlit app, and how do you want to access it? On your corporate network - Most corporate networks are closed to the outside world. You typically use a VPN to log onto your corporate network and access resources there. You could run your Streamlit app on a server in your corporate network for security reasons, to ensure that only folks internal to your company can access it. On the cloud - If you'd like to access your Streamlit app from outside of a corporate network, or share your app with folks outside of your home network or laptop, you might choose this option. In this case, it'll depend on your hosting provider. We have community-submitted guides from Heroku, AWS, and other providers. Wherever you decide to deploy your app, you will first need to containerize it. This guide walks you through using Kubernetes to deploy your app. If you prefer Docker see Deploy Streamlit using Docker. Prerequisites Install Docker Engine Install the gcloud CLI Install Docker Engine If you haven't already done so, install Docker on your server. Docker provides .deb and .rpm packages from many Linux distributions, including: Debian Ubuntu Verify that Docker Engine is installed correctly by running the hello-world Docker image: sudo docker run hello-world starTipFollow Docker's official post-installation steps for Linux to run Docker as a non-root user, so that you don't have to preface the docker command with sudo. Install the gcloud CLI In this guide, we will orchestrate Docker containers with Kubernetes and host docker images on the Google Container Registry (GCR). As GCR is a Google-supported Docker registry, we need to register gcloud as the Docker credential helper. Follow the official documentation to Install the gcloud CLI and initialize it. Create a Docker container We need to create a docker container which contains all the dependencies and the application code. Below you can see the entrypoint, i.e. the command run when the container starts, and the Dockerfile definition. Create an entrypoint script Create a run.sh script containing the following: #!/bin/bash APP_PID= stopRunningProcess() { # Based on https://linuxconfig.org/how-to-propagate-a-signal-to-child-processes-from-a-bash-script if test ! "${APP_PID}" = '' && ps -p ${APP_PID} > /dev/null ; then > /proc/1/fd/1 echo "Stopping ${COMMAND_PATH} which is running with process ID ${APP_PID}" kill -TERM ${APP_PID} > /proc/1/fd/1 echo "Waiting for ${COMMAND_PATH} to process SIGTERM signal" wait ${APP_PID} > /proc/1/fd/1 echo "All processes have stopped running" else > /proc/1/fd/1 echo "${COMMAND_PATH} was not started when the signal was sent or it has already been stopped" fi } trap stopRunningProcess EXIT TERM source ${VIRTUAL_ENV}/bin/activate streamlit run ${HOME}/app/streamlit_app.py & APP_ID=${!} wait ${APP_ID} Create a Dockerfile Docker builds images by reading the instructions from a Dockerfile. A Dockerfile is a text document that contains all the commands a user could call on the command line to assemble an image. Learn more in the Dockerfile reference. The docker build command builds an image from a Dockerfile. The docker run command first creates a container over the specified image, and then starts it using the specified command. Here's an example Dockerfile that you can add to the root of your directory. FROM python:3.8-slim RUN groupadd --gid 1000 appuser \ && useradd --uid 1000 --gid 1000 -ms /bin/bash appuser RUN pip3 install --no-cache-dir --upgrade \ pip \ virtualenv RUN apt-get update && apt-get install -y \ build-essential \ software-properties-common \ git USER appuser WORKDIR /home/appuser RUN git clone https://github.com/streamlit/streamlit-example.git app ENV VIRTUAL_ENV=/home/appuser/venv RUN virtualenv ${VIRTUAL_ENV} RUN . ${VIRTUAL_ENV}/bin/activate && pip install -r app/requirements.txt EXPOSE 8501 COPY run.sh /home/appuser ENTRYPOINT ["./run.sh"] priority_highImportantAs mentioned in Development flow, for Streamlit version 1.10.0 and higher, Streamlit apps cannot be run from the root directory of Linux distributions. Your main script should live in a directory other than the root directory. If you try to run a Streamlit app from the root directory, Streamlit will throw a FileNotFoundError: [Errno 2] No such file or directory error. For more information, see GitHub issue #5239.If you are using Streamlit version 1.10.0 or higher, you must set the WORKDIR to a directory other than the root directory. For example, you can set the WORKDIR to /home/appuser as shown in the example Dockerfile above. Build a Docker image Put the above files (run.sh and Dockerfile) in the same folder and build the docker image: docker build --platform linux/amd64 -t gcr.io/$GCP_PROJECT_ID/k8s-streamlit:test . priority_highImportantReplace $GCP_PROJECT_ID in the above command with the name of your Google Cloud project. Upload the Docker image to a container registry The next step is to upload the Docker image to a container registry. In this example, we will use the Google Container Registry (GCR). Start by enabling the Container Registry API. Sign in to Google Cloud and navigate to your project’s Container Registry and click Enable. We can now build the Docker image from the previous step and push it to our project’s GCR. Be sure to replace $GCP_PROJECT_ID in the docker push command with the name of your project: gcloud auth configure-docker docker push gcr.io/$GCP_PROJECT_ID/k8s-streamlit:test Create a Kubernetes deployment For this step you will need a: Running Kubernetes service Custom domain for which you can generate a TLS certificate DNS service where you can configure your custom domain to point to the application IP As the image was uploaded to the container registry in the previous step, we can run it in Kubernetes using the below configurations. Install and run Kubernetes Make sure your Kubernetes client, kubectl, is installed and running on your machine. Configure a Google OAuth Client and oauth2-proxy For configuring the Google OAuth Client, please see Google Auth Provider. Configure oauth2-proxy to use the desired OAuth Provider Configuration and update the oath2-proxy config in the config map. The below configuration contains a ouath2-proxy sidecar container which handles the authentication with Google. You can learn more from the oauth2-proxy repository. Create a Kubernetes configuration file Create a YAML configuration file named k8s-streamlit.yaml: apiVersion: v1 kind: ConfigMap metadata: name: streamlit-configmap data: oauth2-proxy.cfg: |- http_address = "0.0.0.0:4180" upstreams = ["http://127.0.0.1:8501/"] email_domains = ["*"] client_id = "<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/utilities/st.experimental_user#examples
DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceremovePAGE ELEMENTSWrite and magicaddText elementsaddData elementsaddChart elementsaddInput widgetsaddMedia elementsaddLayouts and containersaddChat elementsaddStatus elementsaddThird-party componentsopen_in_newAPPLICATION LOGICNavigation and pagesaddExecution flowaddCaching and stateaddConnections and secretsaddCustom componentsaddUtilitiesremovest.experimental_userst.helpst.htmlConfigurationaddTOOLSApp testingaddCommand lineaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Develop/API reference/Utilities/st.experimental_userpriority_highImportantThis is an experimental feature. Experimental features and their APIs may change or be removed at any time. To learn more, click here. st.experimental_userStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeA read-only, dict-like object for accessing information about current user. st.experimental_user is dependant on the host platform running the Streamlit app. If the host platform has not configured the function, it will behave as it does in a locally running app. Properties can by accessed via key or attribute notation. For example, st.experimental_user["email"] or st.experimental_user.email. Class description[source] st.experimental_user() Methods to_dict() Get user info as a dictionary. Attributes email (str) If running locally, this property returns the string literal "test@example.com". If running on Streamlit Community Cloud, this property returns one of two values: None if the user is not logged in or not a member of the app's workspace. Such users appear under anonymous pseudonyms in the app's analytics. The user's email if the the user is logged in and a member of the app's workspace. Such users are identified by their email in the app's analytics. Examples The ability to personalize apps for the user viewing the app is a great way to make your app more engaging. It unlocks a plethora of use-cases for developers, some of which could include: showing additional controls for admins, visualizing a user's Streamlit history, a personalized stock ticker, a chatbot app, and much more. We're excited to see what you build with this feature! Here's a code snippet that shows extra buttons for admins: # Show extra buttons for admin users. ADMIN_USERS = { 'person1@email.com', 'person2@email.com', 'person3@email.com' } if st.experimental_user.email in ADMIN_USERS: display_the_extra_admin_buttons() display_the_interface_everyone_sees() Show different content to users based on their email address: # Show different content based on the user's email address. if st.experimental_user.email == 'jane@email.com': display_jane_content() elif st.experimental_user.email == 'adam@foocorp.io': display_adam_content() else: st.write("Please contact us to get access!") Greet users with their name that's stored in a database: # Greet the user by their name. if st.experimental_user.email: # Get the user's name from the database. name = get_name_from_db(st.experimental_user.email) st.write('Hello, %s!' % name) st.experimental_user.to_dictStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeGet user info as a dictionary. This method primarily exists for internal use and is not needed for most cases. st.experimental_user returns an object that inherits from dict by default. Function signature[source] st.experimental_user.to_dict() Returns(Dict[str,str]) A dictionary of the current user's information. Previous: UtilitiesNext: st.helpforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy
https://docs.streamlit.io/develop/api-reference/text#formatted-text
DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceremovePAGE ELEMENTSWrite and magicaddText elementsremoveHEADINGS & BODYst.titlest.headerst.subheaderst.markdownFORMATTED TEXTst.captionst.codest.dividerst.echost.latexst.textData elementsaddChart elementsaddInput widgetsaddMedia elementsaddLayouts and containersaddChat elementsaddStatus elementsaddThird-party componentsopen_in_newAPPLICATION LOGICNavigation and pagesaddExecution flowaddCaching and stateaddConnections and secretsaddCustom componentsaddUtilitiesaddConfigurationaddTOOLSApp testingaddCommand lineaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Develop/API reference/Text elementsText elements Streamlit apps usually start with a call to st.title to set the app's title. After that, there are 2 heading levels you can use: st.header and st.subheader. Pure text is entered with st.text, and Markdown with st.markdown. We also offer a "swiss-army knife" command called st.write, which accepts multiple arguments, and multiple data types. And as described above, you can also use magic commands in place of st.write. Headings and body text MarkdownDisplay string formatted as Markdown.st.markdown("Hello **world**!") TitleDisplay text in title formatting.st.title("The app title") HeaderDisplay text in header formatting.st.header("This is a header") SubheaderDisplay text in subheader formatting.st.subheader("This is a subheader") Formatted text CaptionDisplay text in small font.st.caption("This is written small caption text") Code blockDisplay a code block with optional syntax highlighting.st.code("a = 1234") EchoDisplay some code on the app, then execute it. Useful for tutorials.with st.echo(): st.write('This code will be printed') Preformatted textWrite fixed-width and preformatted text.st.text("Hello world") LaTeXDisplay mathematical expressions formatted as LaTeX.st.latex("\int a x^2 \,dx") DividerDisplay a horizontal rule.st.divider() Third-party componentsThese are featured components created by our lovely community. If you don't see what you're looking for, check out our Components Hub app and Streamlit Extras for more examples and inspiration! PreviousTagsAdd tags to your Streamlit apps. Created by @gagan3012.st_tags(label='# Enter Keywords:', text='Press enter to add more', value=['Zero', 'One', 'Two'], suggestions=['five', 'six', 'seven', 'eight', 'nine', 'three', 'eleven', 'ten', 'four'], maxtags = 4, key='1') NLUApply text mining on a dataframe. Created by @JohnSnowLabs.nlu.load('sentiment').predict('I love NLU! <3') Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.mention(label="An awesome Streamlit App", icon="streamlit", url="https://extras.streamlit.app",) Annotated textDisplay annotated text in Streamlit apps. Created by @tvst.annotated_text("This ", ("is", "verb"), " some ", ("annotated", "adj"), ("text", "noun"), " for those of ", ("you", "pronoun"), " who ", ("like", "verb"), " this sort of ", ("thing", "noun"), ".") Drawable CanvasProvides a sketching canvas using Fabric.js. Created by @andfanilo.st_canvas(fill_color="rgba(255, 165, 0, 0.3)", stroke_width=stroke_width, stroke_color=stroke_color, background_color=bg_color, background_image=Image.open(bg_image) if bg_image else None, update_streamlit=realtime_update, height=150, drawing_mode=drawing_mode, point_display_radius=point_display_radius if drawing_mode == 'point' else 0, key="canvas",) TagsAdd tags to your Streamlit apps. Created by @gagan3012.st_tags(label='# Enter Keywords:', text='Press enter to add more', value=['Zero', 'One', 'Two'], suggestions=['five', 'six', 'seven', 'eight', 'nine', 'three', 'eleven', 'ten', 'four'], maxtags = 4, key='1') NLUApply text mining on a dataframe. Created by @JohnSnowLabs.nlu.load('sentiment').predict('I love NLU! <3') Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.mention(label="An awesome Streamlit App", icon="streamlit", url="https://extras.streamlit.app",) Annotated textDisplay annotated text in Streamlit apps. Created by @tvst.annotated_text("This ", ("is", "verb"), " some ", ("annotated", "adj"), ("text", "noun"), " for those of ", ("you", "pronoun"), " who ", ("like", "verb"), " this sort of ", ("thing", "noun"), ".") Drawable CanvasProvides a sketching canvas using Fabric.js. Created by @andfanilo.st_canvas(fill_color="rgba(255, 165, 0, 0.3)", stroke_width=stroke_width, stroke_color=stroke_color, background_color=bg_color, background_image=Image.open(bg_image) if bg_image else None, update_streamlit=realtime_update, height=150, drawing_mode=drawing_mode, point_display_radius=point_display_radius if drawing_mode == 'point' else 0, key="canvas",) TagsAdd tags to your Streamlit apps. Created by @gagan3012.st_tags(label='# Enter Keywords:', text='Press enter to add more', value=['Zero', 'One', 'Two'], suggestions=['five', 'six', 'seven', 'eight', 'nine', 'three', 'eleven', 'ten', 'four'], maxtags = 4, key='1') NLUApply text mining on a dataframe. Created by @JohnSnowLabs.nlu.load('sentiment').predict('I love NLU! <3') Streamlit ExtrasA library with useful Streamlit extras. Created by @arnaudmiribel.mention(label="An awesome Streamlit App", icon="streamlit", url="https://extras.streamlit.app",) NextPrevious: Write and magicNext: st.titleforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy
https://docs.streamlit.io/develop/tutorials/execution-flow/create-a-multiple-container-fragment#create-a-fragment-across-multiple-containers
DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceaddTutorialsremoveExecution flowremoveFRAGMENTSRerun your app from a fragmentCreate a multiple-container fragmentStart and stop a streaming fragmentConnect to data sourcesaddMultipage appsaddWork with LLMsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Develop/Tutorials/Execution flow/Create a multiple container fragmentCreate a fragment across multiple containers Streamlit lets you turn functions into fragments, which can rerun independently from the full script. If your fragment doesn't write to outside containers, Streamlit will clear and redraw all the fragment elements with each fragment rerun. However, if your fragment does write elements to outside containers, Streamlit will not clear those elements during a fragment rerun. Instead, those elements accumulate with each fragment rerun until the next full-script rerun. If you want a fragment to update multiple containers in your app, use st.empty() containers to prevent accumulating elements. Applied concepts Use fragments to run two independent processes separately. Distribute a fragment across multiple containers. Prerequisites streamlit>=1.33.0 This tutorial uses fragments, which require Streamlit version 1.33.0 or later. This tutorial assumes you have a clean working directory called your-repository. You should have a basic understanding of fragments and st.empty(). Summary In this toy example, you'll build an app with six containers. Three containers will have orange cats. The other three containers will have black cats. You'll have three buttons in the sidebar: "Herd the black cats," "Herd the orange cats," and "Herd all the cats." Since herding cats is slow, you'll use fragments to help Streamlit run the associated processes efficiently. You'll create two fragments, one for the black cats and one for the orange cats. Since the buttons will be in the sidebar and the fragments will update containers in the main body, you'll use a trick with st.empty() to ensure you don't end up with too many cats in your app (if it's even possible to have too many cats). 😻 Here's a look at what you'll build: Complete codeexpand_moreimport streamlit as st import time st.title("Cats!") row1 = st.columns(3) row2 = st.columns(3) grid = [col.container(height=200) for col in row1 + row2] safe_grid = [card.empty() for card in grid] def black_cats(): time.sleep(1) st.title("🐈‍⬛ 🐈‍⬛") st.markdown("🐾 🐾 🐾 🐾") def orange_cats(): time.sleep(1) st.title("🐈 🐈") st.markdown("🐾 🐾 🐾 🐾") @st.experimental_fragment def herd_black_cats(card_a, card_b, card_c): st.button("Herd the black cats") container_a = card_a.container() container_b = card_b.container() container_c = card_c.container() with container_a: black_cats() with container_b: black_cats() with container_c: black_cats() @st.experimental_fragment def herd_orange_cats(card_a, card_b, card_c): st.button("Herd the orange cats") container_a = card_a.container() container_b = card_b.container() container_c = card_c.container() with container_a: orange_cats() with container_b: orange_cats() with container_c: orange_cats() with st.sidebar: herd_black_cats(grid[0].empty(), grid[2].empty(), grid[4].empty()) herd_orange_cats(grid[1].empty(), grid[3].empty(), grid[5].empty()) st.button("Herd all the cats") Built with Streamlit 🎈Fullscreen open_in_new Build the example Initialize your app In your_repository, create a file named app.py. In a terminal, change directories to your_repository and start your app. streamlit run app.py Your app will be blank since you still need to add code. In app.py, write the following: import streamlit as st import time You'll use time.sleep() to slow things down and see the fragments working. Save your app.py file and view your running app. Click "Always rerun" or hit your "A" key in your running app. Your running preview will automatically update as you save changes to app.py. Your preview will still be blank. Return to your code. Frame out your app's containers Add a title to your app and two rows of three containers. st.title("Cats!") row1 = st.columns(3) row2 = st.columns(3) grid = [col.container(height=200) for col in row1 + row2] Save your file to see your updated preview. Define a helper function to draw two black cats. def black_cats(): time.sleep(1) st.title("🐈‍⬛ 🐈‍⬛") st.markdown("🐾 🐾 🐾 🐾") This function represents "herding two cats" and uses time.sleep() to simulate a slower process. You will use this to draw two cats in one of your grid cards later on. Define another helper function to draw two orange cats. def orange_cats(): time.sleep(1) st.title("🐈 🐈") st.markdown("🐾 🐾 🐾 🐾") (Optional) Test out your functions by calling each one within a grid card. with grid[0]: black_cats() with grid[1]: orange_cats() Save your app.py file to see the preview. Delete these four lines when finished. Define your fragments Since each fragment will span across the sidebar and three additional containers, you'll use the sidebar to hold the main body of the fragment and pass the three containers as function arguments. Use an @st.experimental_fragment decorator and start your black-cat fragment definition. @st.experimental_fragment def herd_black_cats(card_a, card_b, card_c): Add a button for rerunning this fragment. st.button("Herd the black cats") Write to each container using your helper function. with card_a: black_cats() with card_b: black_cats() with card_c: black_cats() This code above will not behave as desired, but you'll explore and correct this in the following steps. Test out your code. Call your fragment function in the sidebar. with st.sidebar: herd_black_cats(grid[0], grid[2], grid[4]) Save your file and try using the button in the sidebar. More and more cats are appear in the cards with each fragment rerun! This is the expected behavior when fragments write to outside containers. To fix this, you will pass st.empty() containers to your fragment function. Delete the lines of code from the previous two steps. To prepare for using st.empty() containers, correct your cat-herding function as follows. After the button, define containers to place in the st.empty() cards you'll pass to your fragment. container_a = card_a.container() container_b = card_b.container() container_c = card_c.container() with container_a: black_cats() with container_b: black_cats() with container_c: black_cats() In this new version, card_a, card_b, and card_c will be st.empty() containers. You create container_a, container_b, and container_c to allow Streamlit to draw multiple elements on each grid card. Similarly define your orange-cat fragment function. @st.experimental_fragment def herd_orange_cats(card_a, card_b, card_c): st.button("Herd the orange cats") container_a = card_a.container() container_b = card_b.container() container_c = card_c.container() with container_a: orange_cats() with container_b: orange_cats() with container_c: orange_cats() Put the functions together together to create an app Call both of your fragments in the sidebar. with st.sidebar: herd_black_cats(grid[0].empty(), grid[2].empty(), grid[4].empty()) herd_orange_cats(grid[1].empty(), grid[3].empty(), grid[5].empty()) By creating st.empty() containers in each card and passing them to your fragments, you prevent elements from accumulating in the cards with each fragment rerun. If you create the st.empty() containers earlier in your app, full-script reruns will clear the orange-cat cards while (first) rendering the black-cat cards. Include a button outside of your fragments. When clicked, the button will trigger a full-script rerun since you're calling its widget function outside of any fragment. st.button("Herd all the cats") Save your file and try out the app! When you click "Herd the black cats" or "Herd the orange cats," Streamlit will only redraw the three related cards. When you click "Herd all the cats," Streamlit redraws all six cards. Previous: Rerun your app from a fragmentNext: Start and stop a streaming fragmentforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy
https://docs.streamlit.io/develop/api-reference/charts/st.altair_chart#step-2-annotate-the-chart
DocumentationsearchSearchrocket_launchGet startedInstallationaddFundamentalsaddFirst stepsaddcodeDevelopConceptsaddAPI referenceremovePAGE ELEMENTSWrite and magicaddText elementsaddData elementsaddChart elementsremoveSIMPLEst.area_chartst.bar_chartst.line_chartst.mapst.scatter_chartADVANCEDst.altair_chartst.bokeh_chartst.graphviz_chartst.plotly_chartst.pydeck_chartst.pyplotst.vega_lite_chartInput widgetsaddMedia elementsaddLayouts and containersaddChat elementsaddStatus elementsaddThird-party componentsopen_in_newAPPLICATION LOGICNavigation and pagesaddExecution flowaddCaching and stateaddConnections and secretsaddCustom componentsaddUtilitiesaddConfigurationaddTOOLSApp testingaddCommand lineaddTutorialsaddQuick referenceaddweb_assetDeployConceptsaddStreamlit Community CloudaddStreamlit in Snowflakeopen_in_newOther platformsaddschoolKnowledge baseFAQInstalling dependenciesDeployment issuesHome/Develop/API reference/Chart elements/st.altair_chartst.altair_chartStreamlit VersionVersion 1.34.0Version 1.33.0Version 1.32.0Version 1.31.0Version 1.30.0Version 1.29.0Version 1.28.0Version 1.27.0Version 1.26.0Version 1.25.0Version 1.24.0Version 1.23.0Version 1.22.0Version 1.21.0Version 1.20.0Version 1.19.0Version 1.18.0Version 1.17.0Version 1.16.0Version 1.15.0Version 1.14.0Version 1.13.0Streamlit in SnowflakeDisplay a chart using the Altair library. Function signature[source] st.altair_chart(altair_chart, use_container_width=False, theme="streamlit") Parameters altair_chart (altair.Chart) The Altair chart object to display. use_container_width (bool) If True, set the chart width to the column width. This takes precedence over Altair's native width value. theme ("streamlit" or None) The theme of the chart. Currently, we only support "streamlit" for the Streamlit defined design or None to fallback to the default behavior of the library. Example import streamlit as st import pandas as pd import numpy as np import altair as alt chart_data = pd.DataFrame(np.random.randn(20, 3), columns=["a", "b", "c"]) c = ( alt.Chart(chart_data) .mark_circle() .encode(x="a", y="b", size="c", color="c", tooltip=["a", "b", "c"]) ) st.altair_chart(c, use_container_width=True) Built with Streamlit 🎈Fullscreen open_in_new Examples of Altair charts can be found at https://altair-viz.github.io/gallery/. Theming Altair charts are displayed using the Streamlit theme by default. This theme is sleek, user-friendly, and incorporates Streamlit's color palette. The added benefit is that your charts better integrate with the rest of your app's design. The Streamlit theme is available from Streamlit 1.16.0 through the theme="streamlit" keyword argument. To disable it, and use Altair's native theme, use theme=None instead. Let's look at an example of charts with the Streamlit theme and the native Altair theme: import altair as alt from vega_datasets import data source = data.cars() chart = alt.Chart(source).mark_circle().encode( x='Horsepower', y='Miles_per_Gallon', color='Origin', ).interactive() tab1, tab2 = st.tabs(["Streamlit theme (default)", "Altair native theme"]) with tab1: # Use the Streamlit theme. # This is the default. So you can also omit the theme argument. st.altair_chart(chart, theme="streamlit", use_container_width=True) with tab2: # Use the native Altair theme. st.altair_chart(chart, theme=None, use_container_width=True) Click the tabs in the interactive app below to see the charts with the Streamlit theme enabled and disabled. Built with Streamlit 🎈Fullscreen open_in_new If you're wondering if your own customizations will still be taken into account, don't worry! You can still make changes to your chart configurations. In other words, although we now enable the Streamlit theme by default, you can overwrite it with custom colors or fonts. For example, if you want a chart line to be green instead of the default red, you can do it! Here's an example of an Altair chart where manual color passing is done and reflected: See the codeexpand_moreimport altair as alt import streamlit as st from vega_datasets import data source = data.seattle_weather() scale = alt.Scale( domain=["sun", "fog", "drizzle", "rain", "snow"], range=["#e7ba52", "#a7a7a7", "#aec7e8", "#1f77b4", "#9467bd"], ) color = alt.Color("weather:N", scale=scale) # We create two selections: # - a brush that is active on the top panel # - a multi-click that is active on the bottom panel brush = alt.selection_interval(encodings=["x"]) click = alt.selection_multi(encodings=["color"]) # Top panel is scatter plot of temperature vs time points = ( alt.Chart() .mark_point() .encode( alt.X("monthdate(date):T", title="Date"), alt.Y( "temp_max:Q", title="Maximum Daily Temperature (C)", scale=alt.Scale(domain=[-5, 40]), ), color=alt.condition(brush, color, alt.value("lightgray")), size=alt.Size("precipitation:Q", scale=alt.Scale(range=[5, 200])), ) .properties(width=550, height=300) .add_selection(brush) .transform_filter(click) ) # Bottom panel is a bar chart of weather type bars = ( alt.Chart() .mark_bar() .encode( x="count()", y="weather:N", color=alt.condition(click, color, alt.value("lightgray")), ) .transform_filter(brush) .properties( width=550, ) .add_selection(click) ) chart = alt.vconcat(points, bars, data=source, title="Seattle Weather: 2012-2015") tab1, tab2 = st.tabs(["Streamlit theme (default)", "Altair native theme"]) with tab1: st.altair_chart(chart, theme="streamlit", use_container_width=True) with tab2: st.altair_chart(chart, theme=None, use_container_width=True) Notice how the custom colors are still reflected in the chart, even when the Streamlit theme is enabled 👇 Built with Streamlit 🎈Fullscreen open_in_new For many more examples of Altair charts with and without the Streamlit theme, check out the altair.streamlit.app. Annotating charts Altair also allows you to annotate your charts with text, images, and emojis. You can do this by creating layered charts, which let you overlay two different charts on top of each other. The idea is to use the first chart to show the data, and the second chart to show the annotations. The second chart can then be overlaid on top of the first chart using the + operator to create a layered chart. Let's walk through an example of annotating a time-series chart with text and an emoji. Step 1: Create the base chart In this example, we create a time-series chart to track the evolution of stock prices. The chart is interactive and contains a multi-line tooltip. Click here to learn more about multi-line tooltips in Altair. First, we import the required libraries and load the example stocks dataset using the vega_datasets package: import altair as alt import pandas as pd import streamlit as st from vega_datasets import data # We use @st.cache_data to keep the dataset in cache @st.cache_data def get_data(): source = data.stocks() source = source[source.date.gt("2004-01-01")] return source source = get_data() Next, we define a function get_chart() to create the interactive time-series chart of the stock prices with a multi-line tooltip. The x-axis represents the date, and the y-axis represents the stock price. We then invoke get_chart() that takes the stock prices dataframe as an input and returns a chart object. This is going to be our base chart on which we will overlay the annotations in Step 2. # Define the base time-series chart. def get_chart(data): hover = alt.selection_single( fields=["date"], nearest=True, on="mouseover", empty="none", ) lines = ( alt.Chart(data, title="Evolution of stock prices") .mark_line() .encode( x="date", y="price", color="symbol", ) ) # Draw points on the line, and highlight based on selection points = lines.transform_filter(hover).mark_circle(size=65) # Draw a rule at the location of the selection tooltips = ( alt.Chart(data) .mark_rule() .encode( x="yearmonthdate(date)", y="price", opacity=alt.condition(hover, alt.value(0.3), alt.value(0)), tooltip=[ alt.Tooltip("date", title="Date"), alt.Tooltip("price", title="Price (USD)"), ], ) .add_selection(hover) ) return (lines + points + tooltips).interactive() chart = get_chart(source) Step 2: Annotate the chart Now that we have our first chart that shows the data, we can annotate it with text and an emoji. Let's overlay the ⬇ emoji on top of the time-series chart at specifc points of interest. We want users to hover over the ⬇ emoji to see the associated annotation text. For simplicity, let's annotate four specific dates and set the height of the annotations at constant value of 10. starTipYou can vary the horizontal and vertical postions of the annotations by replacing the hard-coded values with the output of Streamlit widgets! Click here to jump to a live example below, and develop an intuition for the ideal horizontal and vertical positions of the annotations by playing with Streamlit widgets. To do so, we create a dataframe annotations_df containing the dates, annotation text, and the height of the annotations: # Add annotations ANNOTATIONS = [ ("Mar 01, 2008", "Pretty good day for GOOG"), ("Dec 01, 2007", "Something's going wrong for GOOG & AAPL"), ("Nov 01, 2008", "Market starts again thanks to..."), ("Dec 01, 2009", "Small crash for GOOG after..."), ] annotations_df = pd.DataFrame(ANNOTATIONS, columns=["date", "event"]) annotations_df.date = pd.to_datetime(annotations_df.date) annotations_df["y"] = 10 Using this dataframe, we create a scatter plot with the x-axis representing the date, and the y-axis representing the height of the annotation. The data point at the specific date and height is represented by the ⬇ emoji, using Altair's mark_text() mark. The annotation text is displayed as a tooltip when users hover over the ⬇ emoji. This is achieved using Altair's encode() method to map the event column containing the annotation text to the visual attribute ⬇ of the plot. annotation_layer = ( alt.Chart(annotations_df) .mark_text(size=20, text="⬇", dx=-8, dy=-10, align="left") .encode( x="date:T", y=alt.Y("y:Q"), tooltip=["event"], ) .interactive() ) Finally, we overlay the annotations on top of the base chart using the + operator to create the final layered chart! 🎈 st.altair_chart( (chart + annotation_layer).interactive(), use_container_width=True ) To use images instead of emojis, replace the line containing .mark_text() with .mark_image(), and replace image_url below with the URL of the image: .mark_image( width=12, height=12, url="image_url", ) Interactive example Now that you've learned how to annotate charts, the sky's the limit! We've extended the above example to let you interactively paste your favorite emoji and set its position on the chart with Streamlit widgets. 👇 Built with Streamlit 🎈Fullscreen open_in_newPrevious: st.scatter_chartNext: st.bokeh_chartforumStill have questions?Our forums are full of helpful information and Streamlit experts.HomeContact UsCommunity© 2024 Snowflake Inc.Cookie policy