filename
stringlengths 24
54
| content
stringlengths 819
44.7k
|
---|---|
st.select_slider_-_Streamlit_Docs.txt | st.select_slider - Streamlit Docs Documentation search Search rocket_launch Get started Installation add Fundamentals add First steps add code Develop Concepts add API reference remove PAGE ELEMENTS Write and magic add Text elements add Data elements add Chart elements add Input widgets remove BUTTONS st.button st.download_button st.form_submit_button link st.link_button st.page_link SELECTIONS st.checkbox st.color_picker st.feedback st.multiselect st.pills st.radio st.segmented_control st.selectbox st.select_slider st.toggle NUMERIC st.number_input st.slider DATE & TIME st.date_input st.time_input TEXT st.chat_input link st.text_area st.text_input MEDIA & FILES st.audio_input st.camera_input st.data_editor link st.file_uploader Media elements add Layouts and containers add Chat elements add Status elements add Third-party components open_in_new APPLICATION LOGIC Navigation and pages add Execution flow add Caching and state add Connections and secrets add Custom components add Utilities add Configuration add TOOLS App testing add Command line add Tutorials add Quick reference add web_asset Deploy Concepts add Streamlit Community Cloud add Snowflake Other platforms add school Knowledge base FAQ Installing dependencies Deployment issues Home / Develop / API reference / Input widgets / st.select_slider st.select_slider Streamlit Version Version 1.41.0 Version 1.40.0 Version 1.39.0 Version 1.38.0 Version 1.37.0 Version 1.36.0 Version 1.35.0 Version 1.34.0 Version 1.33.0 Version 1.32.0 Version 1.31.0 Version 1.30.0 Version 1.29.0 Version 1.28.0 Version 1.27.0 Version 1.26.0 Version 1.25.0 Version 1.24.0 Version 1.23.0 Version 1.22.0 Version 1.21.0 Version 1.20.0 Streamlit in Snowflake Display a slider widget to select items from a list. This also allows you to render a range slider by passing a two-element tuple or list as the value . The difference between st.select_slider and st.slider is that select_slider accepts any datatype and takes an iterable set of options, while st.slider only accepts numerical or date/time data and takes a range as input. Function signature [source] st.select_slider(label, options=(), value=None, format_func=special_internal_function, key=None, help=None, on_change=None, args=None, kwargs=None, *, disabled=False, label_visibility="visible") Parameters label (str) A short label explaining to the user what this slider is for. The label can optionally contain GitHub-flavored Markdown of the following types: Bold, Italics, Strikethroughs, Inline Code, Links, and Images. Images display like icons, with a max height equal to the font height. Unsupported Markdown elements are unwrapped so only their children (text contents) render. Display unsupported elements as literal characters by backslash-escaping them. E.g., "1\. Not an ordered list" . See the body parameter of st.markdown for additional, supported Markdown directives. For accessibility reasons, you should never set an empty label, but you can hide it with label_visibility if needed. In the future, we may disallow empty labels by raising an exception. options (Iterable) Labels for the select options in an Iterable . This can be a list , set , or anything supported by st.dataframe . If options is dataframe-like, the first column will be used. Each label will be cast to str internally by default. value (a supported type or a tuple/list of supported types or None) The value of the slider when it first renders. If a tuple/list of two values is passed here, then a range slider with those lower and upper bounds is rendered. For example, if set to (1, 10) the slider will have a selectable range between 1 and 10. Defaults to first option. format_func (function) Function to modify the display of the labels from the options. argument. It receives the option as an argument and its output will be cast to str. key (str or int) An optional string or integer to use as the unique key for the widget. If this is omitted, a key will be generated for the widget based on its content. No two widgets may have the same key. help (str) An optional tooltip that gets displayed next to the widget label. Streamlit only displays the tooltip when label_visibility="visible" . on_change (callable) An optional callback invoked when this select_slider's value changes. args (tuple) An optional tuple of args to pass to the callback. kwargs (dict) An optional dict of kwargs to pass to the callback. disabled (bool) An optional boolean that disables the select slider if set to True . The default is False . label_visibility ("visible", "hidden", or "collapsed") The visibility of the label. The default is "visible" . If this is "hidden" , Streamlit displays an empty spacer instead of the label, which can help keep the widget alligned with other widgets. If this is "collapsed" , Streamlit displays no label or spacer. Returns (any value or tuple of any value) The current value of the slider widget. The return type will match the data type of the value parameter. Examples import streamlit as st color = st.select_slider( "Select a color of the rainbow", options=[ "red", "orange", "yellow", "green", "blue", "indigo", "violet", ], ) st.write("My favorite color is", color) And here's an example of a range select slider: import streamlit as st start_color, end_color = st.select_slider( "Select a range of color wavelength", options=[ "red", "orange", "yellow", "green", "blue", "indigo", "violet", ], value=("red", "blue"), ) st.write("You selected wavelengths between", start_color, "and", end_color) Built with Streamlit 🎈 Fullscreen open_in_new Featured videos Check out our video on how to use one of Streamlit's core functions, the select slider! 🎈 In the video below, we'll take it a step further and make a double-ended slider. Previous: st.selectbox Next: st.toggle forum Still have questions? Our forums are full of helpful information and Streamlit experts. Home Contact Us Community © 2025 Snowflake Inc. Cookie policy forum Ask AI |
st.connections.BaseConnection_-_Streamlit_Docs.txt | st.connections.BaseConnection - Streamlit Docs Documentation search Search rocket_launch Get started Installation add Fundamentals add First steps add code Develop Concepts add API reference remove PAGE ELEMENTS Write and magic add Text elements add Data elements add Chart elements add Input widgets add Media elements add Layouts and containers add Chat elements add Status elements add Third-party components open_in_new APPLICATION LOGIC Navigation and pages add Execution flow add Caching and state add Connections and secrets remove SECRETS st.secrets secrets.toml CONNECTIONS st.connection SnowflakeConnection SQLConnection BaseConnection SnowparkConnection delete Custom components add Utilities add Configuration add TOOLS App testing add Command line add Tutorials add Quick reference add web_asset Deploy Concepts add Streamlit Community Cloud add Snowflake Other platforms add school Knowledge base FAQ Installing dependencies Deployment issues Home / Develop / API reference / Connections and secrets / BaseConnection star Tip This page only contains information on the st.connections.BaseConnection class. For a deeper dive into creating and managing data connections within Streamlit apps, read Connecting to data . st.connections.BaseConnection Streamlit Version Version 1.41.0 Version 1.40.0 Version 1.39.0 Version 1.38.0 Version 1.37.0 Version 1.36.0 Version 1.35.0 Version 1.34.0 Version 1.33.0 Version 1.32.0 Version 1.31.0 Version 1.30.0 Version 1.29.0 Version 1.28.0 Version 1.27.0 Version 1.26.0 Version 1.25.0 Version 1.24.0 Version 1.23.0 Version 1.22.0 Version 1.21.0 Version 1.20.0 Streamlit in Snowflake 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.BaseConnection(connection_name, **kwargs) Methods reset () Reset this connection so that it gets reinitialized the next time it's used. BaseConnection.reset Streamlit Version Version 1.41.0 Version 1.40.0 Version 1.39.0 Version 1.38.0 Version 1.37.0 Version 1.36.0 Version 1.35.0 Version 1.34.0 Version 1.33.0 Version 1.32.0 Version 1.31.0 Version 1.30.0 Version 1.29.0 Version 1.28.0 Version 1.27.0 Version 1.26.0 Version 1.25.0 Version 1.24.0 Version 1.23.0 Version 1.22.0 Version 1.21.0 Version 1.20.0 Streamlit in Snowflake Reset this connection so that it gets reinitialized the next time it's used. This method can be useful when a connection has become stale, an auth token has expired, or in similar scenarios where a broken connection might be fixed by reinitializing it. Note that some connection methods may already use reset() in their error handling code. Function signature [source] BaseConnection.reset() Returns (None) No description Example import streamlit as st conn = st.connection("my_conn") # Reset the connection before using it if it isn't healthy # Note: is_healthy() isn't a real method and is just shown for example here. if not conn.is_healthy(): conn.reset() # Do stuff with conn... Previous: SQLConnection Next: st.experimental_connection forum Still have questions? Our forums are full of helpful information and Streamlit experts. Home Contact Us Community © 2025 Snowflake Inc. Cookie policy forum Ask AI |
Annotate_an_Altair_chart_-_Streamlit_Docs.txt | Annotate an Altair chart - Streamlit Docs Documentation search Search rocket_launch Get started Installation add Fundamentals add First steps add code Develop Concepts add API reference add Tutorials remove Elements remove CHARTS Annotate an Altair chart DATAFRAMES Get dataframe row-selections Execution flow add Connect to data sources add Multipage apps add Work with LLMs add Quick reference add web_asset Deploy Concepts add Streamlit Community Cloud add Snowflake Other platforms add school Knowledge base FAQ Installing dependencies Deployment issues Home / Develop / Tutorials / Elements / Annotate an Altair chart Annotate an Altair chart Altair allows you to annotate your charts with text, images, and emojis. You can do this by overlaying two charts to create a layered chart . Applied concepts Use layered charts in Altair to create annotations. Prerequisites This tutorial requires the following Python libraries: streamlit altair>=4.0.0 vega_datasets This tutorial assumes you have a clean working directory called your-repository . You should have a basic understanding of the Vega-Altair charting library. Summary In this example, you will create a time-series chart to track the evolution of stock prices. The chart will have two layers: a data layer and an annotation layer. Each layer is an altair.Chart object. You will combine the two charts with the + opterator to create a layered chart. Within the data layer, you'll add a multi-line tooltip to show information about datapoints. To learn more about multi-line tooltips, see this example in Vega-Altair's documentation. You'll add another tooltip to the annotation layer. Here's a look at what you'll build: Complete code expand_more import streamlit as st import altair as alt import pandas as pd from vega_datasets import data @st.cache_data def get_data(): source = data.stocks() source = source[source.date.gt("2004-01-01")] return source stock_data = get_data() hover = alt.selection_single( fields=["date"], nearest=True, on="mouseover", empty="none", ) lines = ( alt.Chart(stock_data, title="Evolution of stock prices") .mark_line() .encode( x="date", y="price", color="symbol", ) ) points = lines.transform_filter(hover).mark_circle(size=65) tooltips = ( alt.Chart(stock_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) ) data_layer = lines + points + tooltips ANNOTATIONS = [ ("Sep 01, 2007", 450, "🙂", "Something's going well for GOOG & AAPL."), ("Nov 01, 2008", 220, "🙂", "The market is recovering."), ("Dec 01, 2007", 750, "😱", "Something's going wrong for GOOG & AAPL."), ("Dec 01, 2009", 680, "😱", "A hiccup for GOOG."), ] annotations_df = pd.DataFrame( ANNOTATIONS, columns=["date", "price", "marker", "description"] ) annotations_df.date = pd.to_datetime(annotations_df.date) annotation_layer = ( alt.Chart(annotations_df) .mark_text(size=20, dx=-10, dy=0, align="left") .encode(x="date:T", y=alt.Y("price:Q"), text="marker", tooltip="description") ) combined_chart = data_layer + annotation_layer st.altair_chart(combined_chart, use_container_width=True) 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 altair as alt import pandas as pd from vega_datasets import data You'll be using these libraries as follows: You'll download a dataset using vega_datasets . You'll maniputate the data using pandas . You'll define a chart using altair . 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 the data layer You'll build an 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. Import data from vega_datasets . @st.cache_data def get_data(): source = data.stocks() source = source[source.date.gt("2004-01-01")] return source stock_data = get_data() The @st.cache_data decorator turns get_data() into a cahced function. Streamlit will only download the data once since the data will be saved in a cache. For more information about caching, see Caching overview . Define a mouseover selection event in Altair. hover = alt.selection_single( fields=["date"], nearest=True, on="mouseover", empty="none", ) This defines a mouseover selection for points. fields=["date"] allows Altair to identify other points with the same date. You will use this to create a vertical line highlight when a user hovers over a point. Define a basic line chart to graph the five series in your data set. lines = ( alt.Chart(stock_data, title="Evolution of stock prices") .mark_line() .encode( x="date", y="price", color="symbol", ) ) Draw points on the lines and highlight them based on the mouseover selection. points = lines.transform_filter(hover).mark_circle(size=65) Since the mouseover selection includes fields=["date"] , Altair will draw circles on each series at the same date. Draw a vertical rule at the location of the mouseover selection. tooltips = ( alt.Chart(stock_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) ) The opacity parameter ensures each vertical line is only visible when it's part of a mouseover selection. Each alt.Tooltip adds a line to your multi-line tooltip. Combine the lines, points, and tooltips into a single chart. data_layer = lines + points + tooltips Optional: Test out your code by rendering your data layer. st.altair_chart(data_layer, use_container_width=True) Save your file and examine the chart in your app. Use your mouse to hover over points. Observe the circle marks, vertical line, and tooltip as you hover over a point. Delete the line or keep it at the end of your app to be updated as you continue. Build the annotation layer Now that you have the first chart that shows the data, you can annotate it with text and an emoji. In this section, you'll add some emojis and tooltips to mark specifc points of interest. Create a list of annotations. ANNOTATIONS = [ ("Sep 01, 2007", 450, "🙂", "Something's going well for GOOG & AAPL."), ("Nov 01, 2008", 220, "🙂", "The market is recovering."), ("Dec 01, 2007", 750, "😱", "Something's going wrong for GOOG & AAPL."), ("Dec 01, 2009", 680, "😱", "A hiccup for GOOG."), ] annotations_df = pd.DataFrame( ANNOTATIONS, columns=["date", "price", "marker", "description"] ) annotations_df.date = pd.to_datetime(annotations_df.date) The first two columns ("date" and "price") determine where Altair will place the marker. The third column ("marker") determines what icon Altair will place. The last column ("description") will fill in the associated tooltip. Create a scatter plot with the x-axis representing the date and the y-axis representing the height ("price") of each annotation. annotation_layer = ( alt.Chart(annotations_df) .mark_text(size=20, dx=-10, dy=0, align="left") .encode(x="date:T", y=alt.Y("price:Q"), text="marker", tooltip="description") ) The dx=-10, dy=0 inside of .mark_text() offsets the icons so they are centered at the coordinate in your annotations dataframe. The four columns are passed to the chart through the .encode() method. If you want to use the same marker for all points, you can remove text="marker" from the .encode() method and add the marker to .mark_text() . For example, .mark_text(text="🥳") would make all the icons be "🥳". For more information about .mark_text() , see Altair's documentation . Combine the chart layers Define the combined chart. combined_chart = data_layer + annotation_layer Display the chart in Streamlit. st.altair_chart(combined_chart, use_container_width=True) Next steps Play around with your new app. If you want to use custom images instead of text or emojis to annotation your chart, you can replace the line containing .mark_text() with .mark_image() . For some URL string stored in a variable IMAGE_URL , you could do something like this: .mark_image( width=12, height=12, url=IMAGE_URL, ) If you want to enable panning and zooming for your chart, add .interactive() when you define your combined chart: combined_chart = (data_layer + annotation_layer).interactive() Previous: Elements Next: Get dataframe row-selections forum Still have questions? Our forums are full of helpful information and Streamlit experts. Home Contact Us Community © 2025 Snowflake Inc. Cookie policy forum Ask AI |
Build_LLM_apps_-_Streamlit_Docs.txt | Build LLM apps - Streamlit Docs Documentation search Search rocket_launch Get started Installation add Fundamentals add First steps add code Develop Concepts add API reference add Tutorials remove Elements add Execution flow add Connect to data sources add Multipage apps add Work with LLMs remove Build a basic LLM chat app Build an LLM app using LangChain Quick reference add web_asset Deploy Concepts add Streamlit Community Cloud add Snowflake Other platforms add school Knowledge base FAQ Installing dependencies Deployment issues Home / Develop / Tutorials / Work with LLMs Build LLM apps Build a basic chat app Build a simple OpenAI chat app to get started with Streamlit's chat elements. Build an LLM app using LangChain Build a chat app using the LangChain framework with OpenAI. Previous: Multipage apps Next: Build a basic LLM chat app forum Still have questions? Our forums are full of helpful information and Streamlit experts. Home Contact Us Community © 2025 Snowflake Inc. Cookie policy forum Ask AI |
Execution_flow_-_Streamlit_Docs.txt | Execution flow - Streamlit Docs Documentation search Search rocket_launch Get started Installation add Fundamentals add First steps add code Develop Concepts add API reference remove PAGE ELEMENTS Write and magic add Text elements add Data elements add Chart elements add Input widgets add Media elements add Layouts and containers add Chat elements add Status elements add Third-party components open_in_new APPLICATION LOGIC Navigation and pages add Execution flow remove st.dialog st.form st.form_submit_button st.fragment st.rerun st.stop Caching and state add Connections and secrets add Custom components add Utilities add Configuration add TOOLS App testing add Command line add Tutorials add Quick reference add web_asset Deploy Concepts add Streamlit Community Cloud add Snowflake Other platforms add school Knowledge base FAQ Installing dependencies Deployment issues Home / Develop / API reference / Execution flow Execution flow Change execution By default, Streamlit apps execute the script entirely, but we allow some functionality to handle control flow in your applications. Modal dialog Insert a modal dialog that can rerun independently from the rest of the script. @st.dialog("Sign up") def email_form(): name = st.text_input("Name") email = st.text_input("Email") Fragments Define a fragment to rerun independently from the rest of the script. @st.fragment(run_every="10s") def fragment(): df = get_data() st.line_chart(df) Rerun script Rerun the script immediately. st.rerun() Stop execution Stops 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! Forms Create 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 button Display 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 components These are featured components created by our lovely community. For more examples and inspiration, check out our Components Gallery and Streamlit Extras ! Autorefresh Force a refresh without tying up a script. Created by @kmcgrady . from streamlit_autorefresh import st_autorefresh st_autorefresh(interval=2000, limit=100, key="fizzbuzzcounter") Pydantic Auto-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 Pages An 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 pages Next: st.dialog forum Still have questions? Our forums are full of helpful information and Streamlit experts. Home Contact Us Community © 2025 Snowflake Inc. Cookie policy forum Ask AI |
Connect_Streamlit_to_Supabase_-_Streamlit_Docs.txt | Connect Streamlit to Supabase - Streamlit Docs Documentation search Search rocket_launch Get started Installation add Fundamentals add First steps add code Develop Concepts add API reference add Tutorials remove Elements add Execution flow add Connect to data sources remove AWS S3 BigQuery Firestore open_in_new Google Cloud Storage Microsoft SQL Server MongoDB MySQL Neon PostgreSQL Private Google Sheet Public Google Sheet Snowflake Supabase Tableau TiDB TigerGraph Multipage apps add Work with LLMs add Quick reference add web_asset Deploy Concepts add Streamlit Community Cloud add Snowflake Other platforms add school Knowledge base FAQ Installing dependencies Deployment issues Home / Develop / Tutorials / Connect to data sources / Supabase Connect 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_pin Note Community-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 GitHub Authorize Supabase Once you're signed in, you can create a project. Your Supabase account Create a new project Your screen should look like this once your project has been created: priority_high Important Make 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 editor Create 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 queries View 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_high Important 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 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 star Tip We'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: Snowflake Next: Tableau forum Still have questions? Our forums are full of helpful information and Streamlit experts. Home Contact Us Community © 2025 Snowflake Inc. Cookie policy forum Ask AI |
Enabling_camera_or_microphone_access_in_your_brows.txt | Enabling camera or microphone access in your browser - Streamlit Docs Documentation search Search rocket_launch Get started Installation add Fundamentals add First steps add code Develop Concepts add API reference add Tutorials add Quick reference add web_asset Deploy Concepts add Streamlit Community Cloud add Snowflake Other platforms add school Knowledge base FAQ Installing dependencies Deployment issues Home / Knowledge base / FAQ / Enabling camera access in your browser Enabling camera or microphone access in your browser Streamlit apps may include a widget to upload images from your camera or record sound with your microphone. To safeguard the users' privacy and security, browsers require users to explicitly allow access to their camera or microphone before those devices can be used. To learn how to enable camera access, please check the documentation for your browser: Chrome Safari Firefox Previous: How do I create an anchor link? Next: How to download a file in Streamlit? forum Still have questions? Our forums are full of helpful information and Streamlit experts. Home Contact Us Community © 2025 Snowflake Inc. Cookie policy forum Ask AI |
Magic_-_Streamlit_Docs.txt | Magic - Streamlit Docs Documentation search Search rocket_launch Get started Installation add Fundamentals add First steps add code Develop Concepts add API reference remove PAGE ELEMENTS Write and magic remove st.write st.write_stream magic Text elements add Data elements add Chart elements add Input widgets add Media elements add Layouts and containers add Chat elements add Status elements add Third-party components open_in_new APPLICATION LOGIC Navigation and pages add Execution flow add Caching and state add Connections and secrets add Custom components add Utilities add Configuration add TOOLS App testing add Command line add Tutorials add Quick reference add web_asset Deploy Concepts add Streamlit Community Cloud add Snowflake Other platforms add school Knowledge base FAQ Installing dependencies Deployment issues Home / Develop / API reference / Write and magic / magic Magic Magic commands are a feature in Streamlit that allows you to write almost anything (markdown, data, charts) without having to type an explicit command at all. Just put the thing you want to show on its own line of code, and it will appear in your app. Here's an example: # Draw a title and some text to the app: ''' # This is the document title This is some _markdown_. ''' import pandas as pd df = pd.DataFrame({'col1': [1,2,3]}) df # 👈 Draw the dataframe x = 10 'x', x # 👈 Draw the string 'x' and then the value of x # Also works with most supported chart types import matplotlib.pyplot as plt import numpy as np arr = np.random.normal(1, 1, size=100) fig, ax = plt.subplots() ax.hist(arr, bins=20) fig # 👈 Draw a Matplotlib chart How Magic works Any time Streamlit sees either a variable or literal value on its own line, it automatically writes that to your app using st.write (which you'll learn about later). Also, magic is smart enough to ignore docstrings. That is, it ignores the strings at the top of files and functions. If you prefer to call Streamlit commands more explicitly, you can always turn magic off in your ~/.streamlit/config.toml with the following setting: [runner] magicEnabled = false priority_high Important Right now, Magic only works in the main Python app file, not in imported files. See GitHub issue #288 for a discussion of the issues. Featured video Learn what the st.write and magic commands are and how to use them. Previous: st.write_stream Next: Text elements forum Still have questions? Our forums are full of helpful information and Streamlit experts. Home Contact Us Community © 2025 Snowflake Inc. Cookie policy forum Ask AI |
Button_behavior_and_examples_-_Streamlit_Docs.txt | Button behavior and examples - Streamlit Docs Documentation search Search rocket_launch Get started Installation add Fundamentals add First steps add code Develop Concepts remove CORE Architecture & execution add Multipage apps add App design remove Animate & update elements Button behavior and examples Dataframes Using custom classes Working with timezones ADDITIONAL Connections and secrets add Custom components add Configuration and theming add App testing add API reference add Tutorials add Quick reference add web_asset Deploy Concepts add Streamlit Community Cloud add Snowflake Other platforms add school Knowledge base FAQ Installing dependencies Deployment issues Home / Develop / Concepts / App design / Button behavior and examples Button 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_high Important Don'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 display_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 st.write(f'Option {option} processed with add {add}') result[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 elements Next: Dataframes forum Still have questions? Our forums are full of helpful information and Streamlit experts. Home Contact Us Community © 2025 Snowflake Inc. Cookie policy forum Ask AI |
st.column_config.NumberColumn_-_Streamlit_Docs.txt | st.column_config.NumberColumn - Streamlit Docs Documentation search Search rocket_launch Get started Installation add Fundamentals add First steps add code Develop Concepts add API reference remove PAGE ELEMENTS Write and magic add Text elements add Data elements remove st.dataframe st.data_editor st.column_config remove Column Text column Number column Checkbox column Selectbox column Datetime column Date column Time column List column Link column Image column Area chart column Line chart column Bar chart column Progress column st.table st.metric st.json Chart elements add Input widgets add Media elements add Layouts and containers add Chat elements add Status elements add Third-party components open_in_new APPLICATION LOGIC Navigation and pages add Execution flow add Caching and state add Connections and secrets add Custom components add Utilities add Configuration add TOOLS App testing add Command line add Tutorials add Quick reference add web_asset Deploy Concepts add Streamlit Community Cloud add Snowflake Other platforms add school Knowledge base FAQ Installing dependencies Deployment issues Home / Develop / API reference / Data elements / st.column_config / Number column st.column_config.NumberColumn Streamlit Version Version 1.41.0 Version 1.40.0 Version 1.39.0 Version 1.38.0 Version 1.37.0 Version 1.36.0 Version 1.35.0 Version 1.34.0 Version 1.33.0 Version 1.32.0 Version 1.31.0 Version 1.30.0 Version 1.29.0 Version 1.28.0 Version 1.27.0 Version 1.26.0 Version 1.25.0 Version 1.24.0 Version 1.23.0 Version 1.22.0 Version 1.21.0 Version 1.20.0 Streamlit in Snowflake Configure a number column in st.dataframe or st.data_editor . This is the default column type for integer and float values. This command needs to be used in the column_config parameter of st.dataframe or st.data_editor . When used with st.data_editor , editing will be enabled with a numeric input widget. Function signature [source] st.column_config.NumberColumn(label=None, *, width=None, help=None, disabled=None, required=None, pinned=None, default=None, format=None, min_value=None, max_value=None, step=None) Parameters label (str or None) The label shown at the top of the column. If this is None (default), the column name is used. width ("small", "medium", "large", or None) The display width of the column. If this is None (default), the column will be sized to fit the cell contents. Otherwise, this can be one of the following: "small" : 75px wide "medium" : 200px wide "large" : 400px wide help (str or None) An optional tooltip that gets displayed when hovering over the column label. If this is None (default), no tooltip is displayed. disabled (bool or None) Whether editing should be disabled for this column. If this is None (default), Streamlit will decide: indices are disabled and data columns are not. If a column has mixed types, it may become uneditable regardless of disabled . required (bool or None) Whether edited cells in the column need to have a value. If this is False (default), the user can submit empty values for this column. If this is True , an edited cell in this column can only be submitted if its value is not None , and a new row will only be submitted after the user fills in this column. pinned (bool or None) Whether the column is pinned. A pinned column will stay visible on the left side no matter where the user scrolls. If this is None (default), Streamlit will decide: index columns are pinned, and data columns are not pinned. default (int, float, or None) Specifies the default value in this column when a new row is added by the user. This defaults to None . format (str or None) A printf-style format string controlling how numbers are displayed. This does not impact the return value. The following formatters are valid: %d , %e , %f , %g , %i , %u . You can also add prefixes and suffixes, e.g. "$ %.2f" to show a dollar prefix. If this is None (default), the numbers are not formatted. Number formatting from column_config always takes precedence over number formatting from pandas.Styler . min_value (int, float, or None) The minimum value that can be entered. If this is None (default), there will be no minimum. max_value (int, float, or None) The maximum value that can be entered. If this is None (default), there will be no maximum. step (int, float, or None) The precision of numbers that can be entered. If this None (default), integer columns will have a step of 1 and float columns will have unrestricted precision. In this case, some floats may display like integers. Setting step for float columns will ensure a consistent number of digits after the decimal even without setting format . Examples import pandas as pd import streamlit as st data_df = pd.DataFrame( { "price": [20, 950, 250, 500], } ) st.data_editor( data_df, column_config={ "price": st.column_config.NumberColumn( "Price (in USD)", help="The price of the product in USD", min_value=0, max_value=1000, step=1, format="$%d", ) }, hide_index=True, ) Built with Streamlit 🎈 Fullscreen open_in_new Previous: Text column Next: Checkbox column forum Still have questions? Our forums are full of helpful information and Streamlit experts. Home Contact Us Community © 2025 Snowflake Inc. Cookie policy forum Ask AI |
How_to_install_a_package_not_on_PyPI_Conda_but_ava.txt | How to install a package not on PyPI/Conda but available on GitHub - Streamlit Docs Documentation search Search rocket_launch Get started Installation add Fundamentals add First steps add code Develop Concepts add API reference add Tutorials add Quick reference add web_asset Deploy Concepts add Streamlit Community Cloud add Snowflake Other platforms add school Knowledge base FAQ Installing dependencies Deployment issues Home / Knowledge base / Installing dependencies / How to install a package not on PyPI or Conda but available on GitHub How 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/[email protected]#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 dependencies Next: ImportError libGL.so.1 cannot open shared object file No such file or directory forum Still have questions? Our forums are full of helpful information and Streamlit experts. Home Contact Us Community © 2025 Snowflake Inc. Cookie policy forum Ask AI |
st.feedback_-_Streamlit_Docs.txt | st.feedback - Streamlit Docs Documentation search Search rocket_launch Get started Installation add Fundamentals add First steps add code Develop Concepts add API reference remove PAGE ELEMENTS Write and magic add Text elements add Data elements add Chart elements add Input widgets remove BUTTONS st.button st.download_button st.form_submit_button link st.link_button st.page_link SELECTIONS st.checkbox st.color_picker st.feedback st.multiselect st.pills st.radio st.segmented_control st.selectbox st.select_slider st.toggle NUMERIC st.number_input st.slider DATE & TIME st.date_input st.time_input TEXT st.chat_input link st.text_area st.text_input MEDIA & FILES st.audio_input st.camera_input st.data_editor link st.file_uploader Media elements add Layouts and containers add Chat elements add Status elements add Third-party components open_in_new APPLICATION LOGIC Navigation and pages add Execution flow add Caching and state add Connections and secrets add Custom components add Utilities add Configuration add TOOLS App testing add Command line add Tutorials add Quick reference add web_asset Deploy Concepts add Streamlit Community Cloud add Snowflake Other platforms add school Knowledge base FAQ Installing dependencies Deployment issues Home / Develop / API reference / Input widgets / st.feedback st.feedback Streamlit Version Version 1.41.0 Version 1.40.0 Version 1.39.0 Version 1.38.0 Version 1.37.0 Version 1.36.0 Version 1.35.0 Version 1.34.0 Version 1.33.0 Version 1.32.0 Version 1.31.0 Version 1.30.0 Version 1.29.0 Version 1.28.0 Version 1.27.0 Version 1.26.0 Version 1.25.0 Version 1.24.0 Version 1.23.0 Version 1.22.0 Version 1.21.0 Version 1.20.0 Streamlit in Snowflake Display a feedback widget. A feedback widget is an icon-based button group available in three styles, as described in options . It is commonly used in chat and AI apps to allow users to rate responses. Function signature [source] st.feedback(options="thumbs", *, key=None, disabled=False, on_change=None, args=None, kwargs=None) Parameters options ("thumbs", "faces", or "stars") The feedback options displayed to the user. options can be one of the following: "thumbs" (default): Streamlit displays a thumb-up and thumb-down button group. "faces" : Streamlit displays a row of five buttons with facial expressions depicting increasing satisfaction from left to right. "stars" : Streamlit displays a row of star icons, allowing the user to select a rating from one to five stars. key (str or int) An optional string or integer to use as the unique key for the widget. If this is omitted, a key will be generated for the widget based on its content. No two widgets may have the same key. disabled (bool) An optional boolean that disables the feedback widget if set to True . The default is False . on_change (callable) An optional callback invoked when this feedback widget's value changes. args (tuple) An optional tuple of args to pass to the callback. kwargs (dict) An optional dict of kwargs to pass to the callback. Returns (int or None) An integer indicating the user's selection, where 0 is the lowest feedback. Higher values indicate more positive feedback. If no option was selected, the widget returns None . For options="thumbs" , a return value of 0 indicates thumbs-down, and 1 indicates thumbs-up. For options="faces" and options="stars" , return values range from 0 (least satisfied) to 4 (most satisfied). Examples Display a feedback widget with stars, and show the selected sentiment: import streamlit as st sentiment_mapping = ["one", "two", "three", "four", "five"] selected = st.feedback("stars") if selected is not None: st.markdown(f"You selected {sentiment_mapping[selected]} star(s).") Built with Streamlit 🎈 Fullscreen open_in_new Display a feedback widget with thumbs, and show the selected sentiment: import streamlit as st sentiment_mapping = [":material/thumb_down:", ":material/thumb_up:"] selected = st.feedback("thumbs") if selected is not None: st.markdown(f"You selected: {sentiment_mapping[selected]}") Built with Streamlit 🎈 Fullscreen open_in_new Previous: st.color_picker Next: st.multiselect forum Still have questions? Our forums are full of helpful information and Streamlit experts. Home Contact Us Community © 2025 Snowflake Inc. Cookie policy forum Ask AI |
Start_and_stop_a_streaming_fragment___Streamlit_Do.txt | Start and stop a streaming fragment - Streamlit Docs Documentation search Search rocket_launch Get started Installation add Fundamentals add First steps add code Develop Concepts add API reference add Tutorials remove Elements add Execution flow remove FRAGMENTS Rerun your app from a fragment Create a multiple-container fragment Start and stop a streaming fragment Connect to data sources add Multipage apps add Work with LLMs add Quick reference add web_asset Deploy Concepts add Streamlit Community Cloud add Snowflake Other platforms add school Knowledge base FAQ Installing dependencies Deployment issues Home / Develop / Tutorials / Execution flow / Start and stop a streaming fragment Start 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 The following must be installed in your Python environment: streamlit>=1.37.0 You should 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 code expand_more import 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.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 data expand_more 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 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.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.fragment() decorator. Complete function to show and stream data expand_more @st.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.fragment decorator and start your function definition. @st.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 fragment Next: Connect to data sources forum Still have questions? Our forums are full of helpful information and Streamlit experts. Home Contact Us Community © 2025 Snowflake Inc. Cookie policy forum Ask AI |
Install_Streamlit_using_command_line___Streamlit_D.txt | Install Streamlit using command line - Streamlit Docs Documentation search Search rocket_launch Get started Installation remove Use command line Use Anaconda Distribution Use GitHub Codespaces Use Snowflake Fundamentals add First steps add code Develop Concepts add API reference add Tutorials add Quick reference add web_asset Deploy Concepts add Streamlit Community Cloud add Snowflake Other platforms add school Knowledge base FAQ Installing dependencies Deployment issues Home / Get started / Installation / Use command line Install 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.9 to 3.13 . 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: Installation Next: Use Anaconda Distribution forum Still have questions? Our forums are full of helpful information and Streamlit experts. Home Contact Us Community © 2025 Snowflake Inc. Cookie policy forum Ask AI |
Work_with_Streamlit_elements_-_Streamlit_Docs.txt | Work with Streamlit elements - Streamlit Docs Documentation search Search rocket_launch Get started Installation add Fundamentals add First steps add code Develop Concepts add API reference add Tutorials remove Elements remove CHARTS Annotate an Altair chart DATAFRAMES Get dataframe row-selections Execution flow add Connect to data sources add Multipage apps add Work with LLMs add Quick reference add web_asset Deploy Concepts add Streamlit Community Cloud add Snowflake Other platforms add school Knowledge base FAQ Installing dependencies Deployment issues Home / Develop / Tutorials / Elements Previous: Tutorials Next: Annotate an Altair chart forum Still have questions? Our forums are full of helpful information and Streamlit experts. Home Contact Us Community © 2025 Snowflake Inc. Cookie policy forum Ask AI |
st.vega_lite_chart_-_Streamlit_Docs.txt | st.vega_lite_chart - Streamlit Docs Documentation search Search rocket_launch Get started Installation add Fundamentals add First steps add code Develop Concepts add API reference remove PAGE ELEMENTS Write and magic add Text elements add Data elements add Chart elements remove SIMPLE st.area_chart st.bar_chart st.line_chart st.map st.scatter_chart ADVANCED st.altair_chart st.bokeh_chart st.graphviz_chart st.plotly_chart st.pydeck_chart st.pyplot st.vega_lite_chart Input widgets add Media elements add Layouts and containers add Chat elements add Status elements add Third-party components open_in_new APPLICATION LOGIC Navigation and pages add Execution flow add Caching and state add Connections and secrets add Custom components add Utilities add Configuration add TOOLS App testing add Command line add Tutorials add Quick reference add web_asset Deploy Concepts add Streamlit Community Cloud add Snowflake Other platforms add school Knowledge base FAQ Installing dependencies Deployment issues Home / Develop / API reference / Chart elements / st.vega_lite_chart st.vega_lite_chart Streamlit Version Version 1.41.0 Version 1.40.0 Version 1.39.0 Version 1.38.0 Version 1.37.0 Version 1.36.0 Version 1.35.0 Version 1.34.0 Version 1.33.0 Version 1.32.0 Version 1.31.0 Version 1.30.0 Version 1.29.0 Version 1.28.0 Version 1.27.0 Version 1.26.0 Version 1.25.0 Version 1.24.0 Version 1.23.0 Version 1.22.0 Version 1.21.0 Version 1.20.0 Streamlit in Snowflake Display a chart using the Vega-Lite library. Vega-Lite is a high-level grammar for defining interactive graphics. Function signature [source] st.vega_lite_chart(data=None, spec=None, *, use_container_width=False, theme="streamlit", key=None, on_select="ignore", selection_mode=None, **kwargs) Parameters data (Anything supported by st.dataframe) Either the data to be plotted or a Vega-Lite spec containing the data (which more closely follows the Vega-Lite API). spec (dict or None) The Vega-Lite spec for the chart. If spec is None (default), Streamlit uses the spec passed in data . You cannot pass a spec to both data and spec . See https://vega.github.io/vega-lite/docs/ for more info. use_container_width (bool) Whether to override the figure's native width with the width of the parent container. If use_container_width is False (default), Streamlit sets the width of the chart to fit its contents according to the plotting library, up to the width of the parent container. If use_container_width is True , Streamlit sets the width of the figure to match the width of the parent container. theme ("streamlit" or None) The theme of the chart. If theme is "streamlit" (default), Streamlit uses its own design default. If theme is None , Streamlit falls back to the default behavior of the library. key (str) An optional string to use for giving this element a stable identity. If key is None (default), this element's identity will be determined based on the values of the other parameters. Additionally, if selections are activated and key is provided, Streamlit will register the key in Session State to store the selection state. The selection state is read-only. on_select ("ignore", "rerun", or callable) How the figure should respond to user selection events. This controls whether or not the figure behaves like an input widget. on_select can be one of the following: "ignore" (default): Streamlit will not react to any selection events in the chart. The figure will not behave like an input widget. "rerun" : Streamlit will rerun the app when the user selects data in the chart. In this case, st.vega_lite_chart will return the selection data as a dictionary. A callable : Streamlit will rerun the app and execute the callable as a callback function before the rest of the app. In this case, st.vega_lite_chart will return the selection data as a dictionary. To use selection events, the Vega-Lite spec defined in data or spec must include selection parameters from the the charting library. To learn about defining interactions in Vega-Lite, see Dynamic Behaviors with Parameters in Vega-Lite's documentation. selection_mode (str or Iterable of str) The selection parameters Streamlit should use. If selection_mode is None (default), Streamlit will use all selection parameters defined in the chart's Vega-Lite spec. When Streamlit uses a selection parameter, selections from that parameter will trigger a rerun and be included in the selection state. When Streamlit does not use a selection parameter, selections from that parameter will not trigger a rerun and not be included in the selection state. Selection parameters are identified by their name property. **kwargs (any) The Vega-Lite spec for the chart as keywords. This is an alternative to spec . Returns (element or dict) If on_select is "ignore" (default), this command returns an internal placeholder for the chart element that can be used with the .add_rows() method. Otherwise, this command returns a dictionary-like object that supports both key and attribute notation. The attributes are described by the VegaLiteState dictionary schema. Example import streamlit as st import pandas as pd import numpy as np chart_data = pd.DataFrame(np.random.randn(200, 3), columns=["a", "b", "c"]) st.vega_lite_chart( chart_data, { "mark": {"type": "circle", "tooltip": True}, "encoding": { "x": {"field": "a", "type": "quantitative"}, "y": {"field": "b", "type": "quantitative"}, "size": {"field": "c", "type": "quantitative"}, "color": {"field": "c", "type": "quantitative"}, }, }, ) Built with Streamlit 🎈 Fullscreen open_in_new Examples of Vega-Lite usage without Streamlit can be found at https://vega.github.io/vega-lite/examples/ . Most of those can be easily translated to the syntax shown above. Chart selections VegaLiteState Streamlit Version Version 1.41.0 Version 1.40.0 Version 1.39.0 Version 1.38.0 Version 1.37.0 Version 1.36.0 Version 1.35.0 Version 1.34.0 Version 1.33.0 Version 1.32.0 Version 1.31.0 Version 1.30.0 Version 1.29.0 Version 1.28.0 Version 1.27.0 Version 1.26.0 Version 1.25.0 Version 1.24.0 Version 1.23.0 Version 1.22.0 Version 1.21.0 Version 1.20.0 Streamlit in Snowflake The schema for the Vega-Lite event state. The event state is stored in a dictionary-like object that supports both key and attribute notation. Event states cannot be programmatically changed or set through Session State. Only selection events are supported at this time. Attributes selection (dict) The state of the on_select event. This attribute returns a dictionary-like object that supports both key and attribute notation. The name of each Vega-Lite selection parameter becomes an attribute in the selection dictionary. The format of the data within each attribute is determined by the selection parameter definition within Vega-Lite. Examples The following two examples have equivalent definitions. Each one has a point and interval selection parameter include in the chart definition. The point selection parameter is named "point_selection" . The interval or box selection parameter is named "interval_selection" . The follow example uses st.altair_chart : import streamlit as st import pandas as pd import numpy as np import altair as alt if "data" not in st.session_state: st.session_state.data = pd.DataFrame( np.random.randn(20, 3), columns=["a", "b", "c"] ) df = st.session_state.data point_selector = alt.selection_point("point_selection") interval_selector = alt.selection_interval("interval_selection") chart = ( alt.Chart(df) .mark_circle() .encode( x="a", y="b", size="c", color="c", tooltip=["a", "b", "c"], fillOpacity=alt.condition(point_selector, alt.value(1), alt.value(0.3)), ) .add_params(point_selector, interval_selector) ) event = st.altair_chart(chart, key="alt_chart", on_select="rerun") event The following example uses st.vega_lite_chart : import streamlit as st import pandas as pd import numpy as np if "data" not in st.session_state: st.session_state.data = pd.DataFrame( np.random.randn(20, 3), columns=["a", "b", "c"] ) spec = { "mark": {"type": "circle", "tooltip": True}, "params": [ {"name": "interval_selection", "select": "interval"}, {"name": "point_selection", "select": "point"}, ], "encoding": { "x": {"field": "a", "type": "quantitative"}, "y": {"field": "b", "type": "quantitative"}, "size": {"field": "c", "type": "quantitative"}, "color": {"field": "c", "type": "quantitative"}, "fillOpacity": { "condition": {"param": "point_selection", "value": 1}, "value": 0.3, }, }, } event = st.vega_lite_chart( st.session_state.data, spec, key="vega_chart", on_select="rerun" ) event Try selecting points in this interactive example. When you click a point, the selection will appear under the attribute, "point_selection" , which is the name given to the point selection parameter. Similarly, when you make an interval selection, it will appear under the attribute "interval_selection" . You can give your selection parameters other names if desired. If you hold Shift while selecting points, existing point selections will be preserved. Interval selections are not preserved when making additional selections. Built with Streamlit 🎈 Fullscreen open_in_new element.add_rows Streamlit Version Version 1.41.0 Version 1.40.0 Version 1.39.0 Version 1.38.0 Version 1.37.0 Version 1.36.0 Version 1.35.0 Version 1.34.0 Version 1.33.0 Version 1.32.0 Version 1.31.0 Version 1.30.0 Version 1.29.0 Version 1.28.0 Version 1.27.0 Version 1.26.0 Version 1.25.0 Version 1.24.0 Version 1.23.0 Version 1.22.0 Version 1.21.0 Version 1.20.0 Streamlit in Snowflake Concatenate 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 Theming Vega-Lite 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 Vega-Lite's native theme, use theme=None instead. Let's look at an example of charts with the Streamlit theme and the native Vega-Lite theme: import streamlit as st from vega_datasets import data source = data.cars() chart = { "mark": "point", "encoding": { "x": { "field": "Horsepower", "type": "quantitative", }, "y": { "field": "Miles_per_Gallon", "type": "quantitative", }, "color": {"field": "Origin", "type": "nominal"}, "shape": {"field": "Origin", "type": "nominal"}, }, } tab1, tab2 = st.tabs(["Streamlit theme (default)", "Vega-Lite native theme"]) with tab1: # Use the Streamlit theme. # This is the default. So you can also omit the theme argument. st.vega_lite_chart( source, chart, theme="streamlit", use_container_width=True ) with tab2: st.vega_lite_chart( source, 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! Previous: st.pyplot Next: Input widgets forum Still have questions? Our forums are full of helpful information and Streamlit experts. Home Contact Us Community © 2025 Snowflake Inc. Cookie policy forum Ask AI |
Media_elements_-_Streamlit_Docs.txt | Media elements - Streamlit Docs Documentation search Search rocket_launch Get started Installation add Fundamentals add First steps add code Develop Concepts add API reference remove PAGE ELEMENTS Write and magic add Text elements add Data elements add Chart elements add Input widgets add Media elements remove st.audio st.image st.logo st.video Layouts and containers add Chat elements add Status elements add Third-party components open_in_new APPLICATION LOGIC Navigation and pages add Execution flow add Caching and state add Connections and secrets add Custom components add Utilities add Configuration add TOOLS App testing add Command line add Tutorials add Quick reference add web_asset Deploy Concepts add Streamlit Community Cloud add Snowflake Other platforms add school Knowledge base FAQ Installing dependencies Deployment issues Home / Develop / API reference / Media elements Media elements It's easy to embed images, videos, and audio files directly into your Streamlit apps. Image Display an image or list of images. st.image(numpy_array) st.image(image_bytes) st.image(file) st.image("https://example.com/myimage.jpg") Logo Display a logo in the upper-left corner of your app and its sidebar. st.logo("logo.jpg") Audio Display an audio player. st.audio(numpy_array) st.audio(audio_bytes) st.audio(file) st.audio("https://example.com/myaudio.mp3", format="audio/mp3") Video Display 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 components These are featured components created by our lovely community. For more examples and inspiration, check out our Components Gallery and Streamlit Extras ! Previous Streamlit Cropper A 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 Coordinates Get 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 Lottie Integrate Lottie animations inside 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 Webrtc Handling and transmitting real-time video/audio streams with Streamlit. Created by @whitphx . from streamlit_webrtc import webrtc_streamer webrtc_streamer(key="sample") Drawable Canvas Provides 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 Comparison Compare 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 Cropper A 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 Coordinates Get 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 Lottie Integrate Lottie animations inside 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 Webrtc Handling and transmitting real-time video/audio streams with Streamlit. Created by @whitphx . from streamlit_webrtc import webrtc_streamer webrtc_streamer(key="sample") Drawable Canvas Provides 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 Comparison Compare 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 Cropper A 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 Coordinates Get 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 Lottie Integrate Lottie animations inside 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 Previous: Input widgets Next: st.audio forum Still have questions? Our forums are full of helpful information and Streamlit experts. Home Contact Us Community © 2025 Snowflake Inc. Cookie policy forum Ask AI |
Quick_reference_-_Streamlit_Docs.txt | Quick reference - Streamlit Docs Documentation search Search rocket_launch Get started Installation add Fundamentals add First steps add code Develop Concepts add API reference add Tutorials add Quick reference remove Cheat sheet Release notes add Pre-release features Roadmap open_in_new web_asset Deploy Concepts add Streamlit Community Cloud add Snowflake Other platforms add school Knowledge base FAQ Installing dependencies Deployment issues Home / Develop / Quick reference Quick reference Cheatsheet A dense list of Streamlit commands with example syntax. Release notes See how Streamlit has changed with each new version. Pre-release features Understand how we introduce new features and how you can get your hands on them sooner! Roadmap Get a sneak peek at what we have scheduled for the next year. Previous: Tutorials Next: Cheat sheet forum Still have questions? Our forums are full of helpful information and Streamlit experts. Home Contact Us Community © 2025 Snowflake Inc. Cookie policy forum Ask AI |
Quickstart_-_Streamlit_Docs.txt | Quickstart - Streamlit Docs Documentation search Search rocket_launch Get started Installation add Fundamentals add First steps add code Develop Concepts add API reference add Tutorials add Quick reference add web_asset Deploy Concepts add Streamlit Community Cloud remove Get started remove Quickstart Create your account Connect your GitHub account Explore your workspace Deploy from a template Fork and edit a public app Trust and security Deploy your app add Manage your app add Share your app add Manage your account add Status and limitations Snowflake Other platforms add school Knowledge base FAQ Installing dependencies Deployment issues Home / Deploy / Streamlit Community Cloud / Get started / Quickstart Quickstart 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 sign in to your GitHub account during this process. Community Cloud will use the email from your GitHub account to create your Community Cloud account. For other sign-in options, see Create your account . Prerequisites You must have a GitHub account. Sign up for Streamlit Community Cloud Go to share.streamlit.io . Click " Continue to sign-in ." Click " Continue with GitHub ." Enter your GitHub credentials and follow GitHub's authentication prompts. Fill in your account information, and click " I accept " at the bottom. Add access to your public repositories In the upper-left corner, click " Workspaces warning ." From the drop down, click " Connect GitHub account ." Enter your GitHub credentials and follow GitHub's authentication prompts. Click " Authorize streamlit ." Optional: Add access to private repositories In the upper-left corner, click on your GitHub username. From the drop down, click " Settings ." On the left side of the dialog, select " Linked accounts ." Under "Source control," click " Connect here arrow_forward ." Click " Authorize streamlit ." Create a new app from a template In the upper-right corner, click " Create app ." When asked "Do you already have an app?" click " Nope, create one from a template ." From the list of templates on the left, select " Blank app ." At the bottom, select the option to " Open GitHub Codespaces... " At the bottom, click " Deploy ." Edit your app in GitHub Codespaces Wait for GitHub to set up your codespace. It can take several minutes to fully initialize your codespace. After the Visual Studio Code editor appears in your codespace, it can take several minutes to install Python and start the Streamlit server. When complete, a split screen view displays a code editor on the left and a running app on the right. The code editor opens two tabs by default: the repository's readme file and the app's entrypoint file. Go to the app's entrypoint file ( streamlit_app.py ) in the left pane, and change line 3 by adding "Streamlit" inside st.title . -st.title("🎈 My new app") +st.title("🎈 My new Streamlit app") Files are automatically saved in your codespace with each edit. A moment after typing a change, your app on the right side will display a rerun prompt. Click " Always rerun ." If the rerun prompt disappears before you click it, you can hover over the overflow menu icon ( more_vert ) to bring it back. Optional: Continue to make edits and observe the changes within seconds. Publish your changes In the left navigation bar, click the source control icon. In the source control sidebar on the left, enter a name for your commit. Click " check Commit ." To stage and commit all your changes, in the confirmation dialog, click " Yes ." Your changes are committed locally in your codespace. To push your commit to GitHub, in the source control sidebar on the left, click " cached 1 arrow_upward ." To push commits to "origin/main," in the confirmation dialog, click " OK ." Your changes are now saved to your GitHub repository. Community Cloud will immediately reflect the changes in your deployed app. Optional: To see your updated, published app, return to the " My apps " section of your workspace at share.streamlit.io , and click on your app. Stop or delete your codespace When you stop interacting with your codespace, GitHub will generally stop your codespace for you. However, the surest way to avoid undesired use of your capacity is to stop or delete your codespace when you are done. 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. If you want to return to your work later, click " Stop codespace ." Otherwise, click " Delete ." Congratulations! You just deployed an app to Streamlit Community Cloud. 🎉 Return to your workspace at share.streamlit.io/ and deploy another Streamlit app . Previous: Get started Next: Create your account forum Still have questions? Our forums are full of helpful information and Streamlit experts. Home Contact Us Community © 2025 Snowflake Inc. Cookie policy forum Ask AI |
secrets.toml_-_Streamlit_Docs.txt | secrets.toml - Streamlit Docs Documentation search Search rocket_launch Get started Installation add Fundamentals add First steps add code Develop Concepts add API reference remove PAGE ELEMENTS Write and magic add Text elements add Data elements add Chart elements add Input widgets add Media elements add Layouts and containers add Chat elements add Status elements add Third-party components open_in_new APPLICATION LOGIC Navigation and pages add Execution flow add Caching and state add Connections and secrets remove SECRETS st.secrets secrets.toml CONNECTIONS st.connection SnowflakeConnection SQLConnection BaseConnection SnowparkConnection delete Custom components add Utilities add Configuration add TOOLS App testing add Command line add Tutorials add Quick reference add web_asset Deploy Concepts add Streamlit Community Cloud add Snowflake Other platforms add school Knowledge base FAQ Installing dependencies Deployment issues Home / Develop / API reference / Connections and secrets / secrets.toml secrets.toml secrets.toml is an optional file you can define for your working directory or global development environment. When secrets.toml is defined both globally and in your working directory, Streamlit combines the secrets and gives precendence to the working-directory secrets. For more information, see Secrets management . File location To define your secrets locally or per-project, add .streamlit/secrets.toml to your working directory. Your working directory is wherever you call streamlit run . If you haven't previously created the .streamlit directory, you will need to add it. To define your configuration globally, you must first locate your global .streamlit directory. Streamlit adds this hidden directory to your OS user profile during installation. For MacOS/Linux, this will be ~/.streamlit/secrets.toml . For Windows, this will be %userprofile%/.streamlit/secrets.toml . Optionally, you can change where Streamlit searches for secrets through the configuration option, secrets.files . File format secrets.toml is a TOML file. 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: st.secrets Next: st.connection forum Still have questions? Our forums are full of helpful information and Streamlit experts. Home Contact Us Community © 2025 Snowflake Inc. Cookie policy forum Ask AI |
st.fragment_-_Streamlit_Docs.txt | st.fragment - Streamlit Docs Documentation search Search rocket_launch Get started Installation add Fundamentals add First steps add code Develop Concepts add API reference remove PAGE ELEMENTS Write and magic add Text elements add Data elements add Chart elements add Input widgets add Media elements add Layouts and containers add Chat elements add Status elements add Third-party components open_in_new APPLICATION LOGIC Navigation and pages add Execution flow remove st.dialog st.form st.form_submit_button st.fragment st.rerun st.stop Caching and state add Connections and secrets add Custom components add Utilities add Configuration add TOOLS App testing add Command line add Tutorials add Quick reference add web_asset Deploy Concepts add Streamlit Community Cloud add Snowflake Other platforms add school Knowledge base FAQ Installing dependencies Deployment issues Home / Develop / API reference / Execution flow / st.fragment st.fragment Streamlit Version Version 1.41.0 Version 1.40.0 Version 1.39.0 Version 1.38.0 Version 1.37.0 Version 1.36.0 Version 1.35.0 Version 1.34.0 Version 1.33.0 Version 1.32.0 Version 1.31.0 Version 1.30.0 Version 1.29.0 Version 1.28.0 Version 1.27.0 Version 1.26.0 Version 1.25.0 Version 1.24.0 Version 1.23.0 Version 1.22.0 Version 1.21.0 Version 1.20.0 Streamlit in Snowflake Decorator to turn a function into a fragment which can rerun independently of the full app. When a user interacts with an input widget created inside a fragment, Streamlit only reruns the fragment instead of the full app. If run_every is set, Streamlit will also rerun the fragment at the specified interval while the session is active, even if the user is not interacting with your app. To trigger an app rerun from inside a fragment, call st.rerun() directly. To trigger a fragment rerun from within itself, call st.rerun(scope="fragment") . Any values from the fragment that need to be accessed from the wider app should generally be stored in Session State. When Streamlit element commands are called directly in a fragment, the elements are cleared and redrawn on each fragment rerun, just like all elements are redrawn on each app rerun. The rest of the app is persisted during a fragment rerun. When a fragment renders elements into externally created containers, the elements will not be cleared with each fragment rerun. Instead, elements will accumulate in those containers with each fragment rerun, until the next app rerun. Calling st.sidebar in a fragment is not supported. To write elements to the sidebar with a fragment, call your fragment function inside a with st.sidebar context manager. Fragment code can interact with Session State, imported modules, and other Streamlit elements created outside the fragment. Note that these interactions are additive across multiple fragment reruns. You are responsible for handling any side effects of that behavior. Warning Fragments can only contain widgets in their main body. Fragments can't render widgets to externally created containers. Function signature [source] st.fragment(func=None, *, run_every=None) Parameters func (callable) The function to turn into a fragment. run_every (int, float, timedelta, str, or None) The time interval between automatic fragment reruns. This can be one of the following: None (default). An int or float specifying the interval in seconds. A string specifying the time in a format supported by Pandas' 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) . If run_every is None , the fragment will only rerun from user-triggered events. Examples The following example demonstrates basic usage of @st.fragment . As an analogy, "inflating balloons" is a slow process that happens outside of the fragment. "Releasing balloons" is a quick process that happens inside of the fragment. import streamlit as st import time @st.fragment def release_the_balloons(): st.button("Release the balloons", help="Fragment rerun") st.balloons() with st.spinner("Inflating balloons..."): time.sleep(5) release_the_balloons() st.button("Inflate more balloons", help="Full rerun") Built with Streamlit 🎈 Fullscreen open_in_new This next example demonstrates how elements both inside and outside of a fragement update with each app or fragment rerun. In this app, clicking "Rerun full app" will increment both counters and update all values displayed in the app. In contrast, clicking "Rerun fragment" will only increment the counter within the fragment. In this case, the st.write command inside the fragment will update the app's frontend, but the two st.write commands outside the fragment will not update the frontend. import streamlit as st if "app_runs" not in st.session_state: st.session_state.app_runs = 0 st.session_state.fragment_runs = 0 @st.fragment def my_fragment(): st.session_state.fragment_runs += 1 st.button("Rerun fragment") st.write(f"Fragment says it ran {st.session_state.fragment_runs} times.") st.session_state.app_runs += 1 my_fragment() st.button("Rerun full app") st.write(f"Full app says it ran {st.session_state.app_runs} times.") st.write(f"Full app sees that fragment ran {st.session_state.fragment_runs} times.") Built with Streamlit 🎈 Fullscreen open_in_new You can also trigger an app rerun from inside a fragment by calling st.rerun . import streamlit as st if "clicks" not in st.session_state: st.session_state.clicks = 0 @st.fragment def count_to_five(): if st.button("Plus one!"): st.session_state.clicks += 1 if st.session_state.clicks % 5 == 0: st.rerun() return count_to_five() st.header(f"Multiples of five clicks: {st.session_state.clicks // 5}") if st.button("Check click count"): st.toast(f"## Total clicks: {st.session_state.clicks}") Built with Streamlit 🎈 Fullscreen open_in_new Previous: st.form_submit_button Next: st.rerun forum Still have questions? Our forums are full of helpful information and Streamlit experts. Home Contact Us Community © 2025 Snowflake Inc. Cookie policy forum Ask AI |
st.column_config.TextColumn_-_Streamlit_Docs.txt | st.column_config.TextColumn - Streamlit Docs Documentation search Search rocket_launch Get started Installation add Fundamentals add First steps add code Develop Concepts add API reference remove PAGE ELEMENTS Write and magic add Text elements add Data elements remove st.dataframe st.data_editor st.column_config remove Column Text column Number column Checkbox column Selectbox column Datetime column Date column Time column List column Link column Image column Area chart column Line chart column Bar chart column Progress column st.table st.metric st.json Chart elements add Input widgets add Media elements add Layouts and containers add Chat elements add Status elements add Third-party components open_in_new APPLICATION LOGIC Navigation and pages add Execution flow add Caching and state add Connections and secrets add Custom components add Utilities add Configuration add TOOLS App testing add Command line add Tutorials add Quick reference add web_asset Deploy Concepts add Streamlit Community Cloud add Snowflake Other platforms add school Knowledge base FAQ Installing dependencies Deployment issues Home / Develop / API reference / Data elements / st.column_config / Text column st.column_config.TextColumn Streamlit Version Version 1.41.0 Version 1.40.0 Version 1.39.0 Version 1.38.0 Version 1.37.0 Version 1.36.0 Version 1.35.0 Version 1.34.0 Version 1.33.0 Version 1.32.0 Version 1.31.0 Version 1.30.0 Version 1.29.0 Version 1.28.0 Version 1.27.0 Version 1.26.0 Version 1.25.0 Version 1.24.0 Version 1.23.0 Version 1.22.0 Version 1.21.0 Version 1.20.0 Streamlit in Snowflake Configure a text column in st.dataframe or st.data_editor . This is the default column type for string values. This command needs to be used in the column_config parameter of st.dataframe or st.data_editor . When used with st.data_editor , editing will be enabled with a text input widget. Function signature [source] st.column_config.TextColumn(label=None, *, width=None, help=None, disabled=None, required=None, pinned=None, default=None, max_chars=None, validate=None) Parameters label (str or None) The label shown at the top of the column. If this is None (default), the column name is used. width ("small", "medium", "large", or None) The display width of the column. If this is None (default), the column will be sized to fit the cell contents. Otherwise, this can be one of the following: "small" : 75px wide "medium" : 200px wide "large" : 400px wide help (str or None) An optional tooltip that gets displayed when hovering over the column label. If this is None (default), no tooltip is displayed. disabled (bool or None) Whether editing should be disabled for this column. If this is None (default), Streamlit will decide: indices are disabled and data columns are not. If a column has mixed types, it may become uneditable regardless of disabled . required (bool or None) Whether edited cells in the column need to have a value. If this is False (default), the user can submit empty values for this column. If this is True , an edited cell in this column can only be submitted if its value is not None , and a new row will only be submitted after the user fills in this column. pinned (bool or None) Whether the column is pinned. A pinned column will stay visible on the left side no matter where the user scrolls. If this is None (default), Streamlit will decide: index columns are pinned, and data columns are not pinned. default (str or None) Specifies the default value in this column when a new row is added by the user. This defaults to None . max_chars (int or None) The maximum number of characters that can be entered. If this is None (default), there will be no maximum. validate (str or None) A JS-flavored regular expression (e.g. "^[a-z]+$" ) that edited values are validated against. If the user input is invalid, it will not be submitted. Examples import pandas as pd import streamlit as st data_df = pd.DataFrame( { "widgets": ["st.selectbox", "st.number_input", "st.text_area", "st.button"], } ) st.data_editor( data_df, column_config={ "widgets": st.column_config.TextColumn( "Widgets", help="Streamlit **widget** commands 🎈", default="st.", max_chars=50, validate=r"^st\.[a-z_]+$", ) }, hide_index=True, ) Built with Streamlit 🎈 Fullscreen open_in_new Previous: Column Next: Number column forum Still have questions? Our forums are full of helpful information and Streamlit experts. Home Contact Us Community © 2025 Snowflake Inc. Cookie policy forum Ask AI |
Favorite_your_app_-_Streamlit_Docs.txt | Favorite your app - Streamlit Docs Documentation search Search rocket_launch Get started Installation add Fundamentals add First steps add code Develop Concepts add API reference add Tutorials add Quick reference add web_asset Deploy Concepts add Streamlit Community Cloud remove Get started add Deploy your app add Manage your app remove App analytics App settings Delete your app Edit your app Favorite your app Reboot your app Rename your app in GitHub Upgrade Python Upgrade Streamlit Share your app add Manage your account add Status and limitations Snowflake Other platforms add school Knowledge base FAQ Installing dependencies Deployment issues Home / Deploy / Streamlit Community Cloud / Manage your app / Favorite your app Favorite your app Streamlit Community Cloud supports a "favorite" feature that lets you quickly access your apps from your workspace. Favorited apps appear at the top of their workspace with a yellow star ( star ) beside them. You can favorite and unfavorite apps in any workspace to which you have access as a developer or invited viewer. push_pin Note Favorites are specific to your account. Other members of your workspace cannot see which apps you have favorited. Favoriting and unfavoriting your app You can favorite your app: From your workspace . From your app ! Favorite your app from your workspace From your workspace at share.streamlit.io , hover over your app. If your app is not yet favorited, a star outline ( star_border ) will appear on hover. Click on the star ( star_border / star ) next to your app name to toggle its favorited status. Favorite your app from your app toolbar From your app at <your-custom-subdomain>.streamlit.app , click the star ( star_border / star ) in the upper-right corner to toggle your app's favorited status. Previous: Edit your app Next: Reboot your app forum Still have questions? Our forums are full of helpful information and Streamlit experts. Home Contact Us Community © 2025 Snowflake Inc. Cookie policy forum Ask AI |
st.secrets_-_Streamlit_Docs.txt | st.secrets - Streamlit Docs Documentation search Search rocket_launch Get started Installation add Fundamentals add First steps add code Develop Concepts add API reference remove PAGE ELEMENTS Write and magic add Text elements add Data elements add Chart elements add Input widgets add Media elements add Layouts and containers add Chat elements add Status elements add Third-party components open_in_new APPLICATION LOGIC Navigation and pages add Execution flow add Caching and state add Connections and secrets remove SECRETS st.secrets secrets.toml CONNECTIONS st.connection SnowflakeConnection SQLConnection BaseConnection SnowparkConnection delete Custom components add Utilities add Configuration add TOOLS App testing add Command line add Tutorials add Quick reference add web_asset Deploy Concepts add Streamlit Community Cloud add Snowflake Other platforms add school Knowledge base FAQ Installing dependencies Deployment issues Home / Develop / API reference / Connections and secrets / st.secrets st.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 By default, 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 . Configure secrets locations You can configure where Streamlit searches for secrets through the configuration option, secrets.files . With this option, you can list additional secrets locations and change the order of precedence. You can specify other TOML files or include Kubernetes style secret files. 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 secrets Next: secrets.toml forum Still have questions? Our forums are full of helpful information and Streamlit experts. Home Contact Us Community © 2025 Snowflake Inc. Cookie policy forum Ask AI |
st.error_-_Streamlit_Docs.txt | st.error - Streamlit Docs Documentation search Search rocket_launch Get started Installation add Fundamentals add First steps add code Develop Concepts add API reference remove PAGE ELEMENTS Write and magic add Text elements add Data elements add Chart elements add Input widgets add Media elements add Layouts and containers add Chat elements add Status elements remove CALLOUTS st.success st.info st.warning st.error st.exception OTHER st.progress st.spinner st.status st.toast st.balloons st.snow Third-party components open_in_new APPLICATION LOGIC Navigation and pages add Execution flow add Caching and state add Connections and secrets add Custom components add Utilities add Configuration add TOOLS App testing add Command line add Tutorials add Quick reference add web_asset Deploy Concepts add Streamlit Community Cloud add Snowflake Other platforms add school Knowledge base FAQ Installing dependencies Deployment issues Home / Develop / API reference / Status elements / st.error st.error Streamlit Version Version 1.41.0 Version 1.40.0 Version 1.39.0 Version 1.38.0 Version 1.37.0 Version 1.36.0 Version 1.35.0 Version 1.34.0 Version 1.33.0 Version 1.32.0 Version 1.31.0 Version 1.30.0 Version 1.29.0 Version 1.28.0 Version 1.27.0 Version 1.26.0 Version 1.25.0 Version 1.24.0 Version 1.23.0 Version 1.22.0 Version 1.21.0 Version 1.20.0 Streamlit in Snowflake Display error message. Function signature [source] st.error(body, *, icon=None) Parameters body (str) The error 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 (rounded 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.error('This is an error', icon="🚨") Previous: st.warning Next: st.exception forum Still have questions? Our forums are full of helpful information and Streamlit experts. Home Contact Us Community © 2025 Snowflake Inc. Cookie policy forum Ask AI |
Streamlit_documentation.txt | Streamlit documentation Documentation search Search rocket_launch Get started Installation add Fundamentals add First steps add code Develop Concepts add API reference add Tutorials add Quick reference add web_asset Deploy Concepts add Streamlit Community Cloud add Snowflake Other platforms add school Knowledge base FAQ Installing dependencies Deployment issues Streamlit documentation Streamlit is an open-source Python framework for data scientists and AI/ML engineers to deliver dynamic data apps with only a few lines of code. Build and deploy powerful data apps in minutes. Let's get started! install_desktop Setup and installation Get set up to start working with Streamlit. dvr API reference Learn about our APIs, with actionable explanations of specific functions and features. grid_view App gallery Try out awesome apps created by our users, and curated from our forums or Twitter. How to use our docs rocket_launch Get started with Streamlit! Set up your development environment and learn the fundamental concepts, and start coding! description Develop your Streamlit app! Our API reference explains each Streamlit function with examples. Dive deep into all of our features with conceptual guides. Try out our step-by-step tutorials. cloud Deploy your Streamlit app! Streamlit Community Cloud our free platform for deploying and sharing Streamlit apps. Streamlit in Snowflake is an enterprise-class solution where you can house your data and apps in one, unified, global system. Explore all your options! school Knowledge base is a self-serve library of tips, tricks, and articles that answer your questions about creating and deploying Streamlit apps. What's new view_column Add borders to columns and metrics st.columns and st.metric have a new border parameter to show an optional border. palette Primary color in Markdown Now you can use the color "primary" in Markdown to color or highlight text with your app's primary color. push_pin Pin or freeze dataframe columns Column configuration has a new pinned parameter to pin columns on the left as users scroll horizontally. ads_click Tertiary buttons Buttons have a new, "tertiary" type for a more subtle appearance. more_horiz Pills You can create a single- or multi-select group of pill-buttons. view_week Segmented control You can create a segmented button or button group. Latest blog posts View all updates Join the community Streamlit is more than just a way to make data apps, it's also a community of creators that share their apps and ideas and help each other make their work better. Please come join us on the community forum. We love to hear your questions, ideas, and help you work through your bugs — stop by today! View forum Other Media GitHub View the Streamlit source code and issue tracker. YouTube Watch screencasts made by the Streamlit team and the community. Twitter Follow @streamlit on Twitter to keep up with the latest news. LinkedIn Follow @streamlit on the world's largest professional network. Newsletter Sign up for communications from Streamlit. Next: Get started Home Contact Us Community © 2025 Snowflake Inc. Cookie policy forum Ask AI |
st.column_config.DateColumn_-_Streamlit_Docs.txt | st.column_config.DateColumn - Streamlit Docs Documentation search Search rocket_launch Get started Installation add Fundamentals add First steps add code Develop Concepts add API reference remove PAGE ELEMENTS Write and magic add Text elements add Data elements remove st.dataframe st.data_editor st.column_config remove Column Text column Number column Checkbox column Selectbox column Datetime column Date column Time column List column Link column Image column Area chart column Line chart column Bar chart column Progress column st.table st.metric st.json Chart elements add Input widgets add Media elements add Layouts and containers add Chat elements add Status elements add Third-party components open_in_new APPLICATION LOGIC Navigation and pages add Execution flow add Caching and state add Connections and secrets add Custom components add Utilities add Configuration add TOOLS App testing add Command line add Tutorials add Quick reference add web_asset Deploy Concepts add Streamlit Community Cloud add Snowflake Other platforms add school Knowledge base FAQ Installing dependencies Deployment issues Home / Develop / API reference / Data elements / st.column_config / Date column st.column_config.DateColumn Streamlit Version Version 1.41.0 Version 1.40.0 Version 1.39.0 Version 1.38.0 Version 1.37.0 Version 1.36.0 Version 1.35.0 Version 1.34.0 Version 1.33.0 Version 1.32.0 Version 1.31.0 Version 1.30.0 Version 1.29.0 Version 1.28.0 Version 1.27.0 Version 1.26.0 Version 1.25.0 Version 1.24.0 Version 1.23.0 Version 1.22.0 Version 1.21.0 Version 1.20.0 Streamlit in Snowflake Configure a date column in st.dataframe or st.data_editor . This is the default column type for date values. This command needs to be used in the column_config parameter of st.dataframe or st.data_editor . When used with st.data_editor , editing will be enabled with a date picker widget. Function signature [source] st.column_config.DateColumn(label=None, *, width=None, help=None, disabled=None, required=None, pinned=None, default=None, format=None, min_value=None, max_value=None, step=None) Parameters label (str or None) The label shown at the top of the column. If this is None (default), the column name is used. width ("small", "medium", "large", or None) The display width of the column. If this is None (default), the column will be sized to fit the cell contents. Otherwise, this can be one of the following: "small" : 75px wide "medium" : 200px wide "large" : 400px wide help (str or None) An optional tooltip that gets displayed when hovering over the column label. If this is None (default), no tooltip is displayed. disabled (bool or None) Whether editing should be disabled for this column. If this is None (default), Streamlit will decide: indices are disabled and data columns are not. If a column has mixed types, it may become uneditable regardless of disabled . required (bool or None) Whether edited cells in the column need to have a value. If this is False (default), the user can submit empty values for this column. If this is True , an edited cell in this column can only be submitted if its value is not None , and a new row will only be submitted after the user fills in this column. pinned (bool or None) Whether the column is pinned. A pinned column will stay visible on the left side no matter where the user scrolls. If this is None (default), Streamlit will decide: index columns are pinned, and data columns are not pinned. default (datetime.date or None) Specifies the default value in this column when a new row is added by the user. This defaults to None . format (str or None) A momentJS format string controlling how times are displayed. See momentJS docs for available formats. If this is None (default), the format is YYYY-MM-DD . Number formatting from column_config always takes precedence over number formatting from pandas.Styler . min_value (datetime.date or None) The minimum date that can be entered. If this is None (default), there will be no minimum. max_value (datetime.date or None) The maximum date that can be entered. If this is None (default), there will be no maximum. step (int or None) The stepping interval in days. If this is None (default), the step will be 1 day. Examples from datetime import date import pandas as pd import streamlit as st data_df = pd.DataFrame( { "birthday": [ date(1980, 1, 1), date(1990, 5, 3), date(1974, 5, 19), date(2001, 8, 17), ] } ) st.data_editor( data_df, column_config={ "birthday": st.column_config.DateColumn( "Birthday", min_value=date(1900, 1, 1), max_value=date(2005, 1, 1), format="DD.MM.YYYY", step=1, ), }, hide_index=True, ) Built with Streamlit 🎈 Fullscreen open_in_new Previous: Datetime column Next: Time column forum Still have questions? Our forums are full of helpful information and Streamlit experts. Home Contact Us Community © 2025 Snowflake Inc. Cookie policy forum Ask AI |
Widget_updating_for_every_second_input_when_using_.txt | Widget updating for every second input when using session state - Streamlit Docs Documentation search Search rocket_launch Get started Installation add Fundamentals add First steps add code Develop Concepts add API reference add Tutorials add Quick reference add web_asset Deploy Concepts add Streamlit Community Cloud add Snowflake Other platforms add school Knowledge base FAQ Installing dependencies Deployment issues Home / Knowledge base / FAQ / Widget updating for every second input when using session state Widget updating for every second input when using session state Overview You are using session state to store page interactions in your app. When users interact with a widget in your app (e.g., click a button), you expect your app to update its widget states and reflect the new values. However, you notice that it doesn't. Instead, users have to interact with the widget twice (e.g., click a button twice) for the app to show the correct values. What do you do now? 🤔 Let's walk through the solution in the section below. Solution When using session state to update widgets or values in your script, you need to use the unique key you assigned to the widget, not the variable that you assigned your widget to. In the example code block below, the unique key assigned to the slider widget is slider , and the variable the widget is assigned to is slide_val . Let's see this in an example. Say you want a user to click a button that resets a slider. To have the slider's value update on the button click, you need to use a callback function with the on_click parameter of st.button : # the callback function for the button will add 1 to the # slider value up to 10 def plus_one(): if st.session_state["slider"] < 10: st.session_state.slider += 1 else: pass return # when creating the button, assign the name of your callback # function to the on_click parameter add_one = st.button("Add one to the slider", on_click=plus_one, key="add_one") # create the slider slide_val = st.slider("Pick a number", 0, 10, key="slider") Relevant resources Caching Sqlite DB connection resulting in glitchy rendering of the page Select all checkbox that is linked to selectbox of options Previous: Where does st.file_uploader store uploaded files and when do they get deleted? Next: Why does Streamlit restrict nested st.columns? forum Still have questions? Our forums are full of helpful information and Streamlit experts. Home Contact Us Community © 2025 Snowflake Inc. Cookie policy forum Ask AI |
st.column_config.LinkColumn_-_Streamlit_Docs.txt | st.column_config.LinkColumn - Streamlit Docs Documentation search Search rocket_launch Get started Installation add Fundamentals add First steps add code Develop Concepts add API reference remove PAGE ELEMENTS Write and magic add Text elements add Data elements remove st.dataframe st.data_editor st.column_config remove Column Text column Number column Checkbox column Selectbox column Datetime column Date column Time column List column Link column Image column Area chart column Line chart column Bar chart column Progress column st.table st.metric st.json Chart elements add Input widgets add Media elements add Layouts and containers add Chat elements add Status elements add Third-party components open_in_new APPLICATION LOGIC Navigation and pages add Execution flow add Caching and state add Connections and secrets add Custom components add Utilities add Configuration add TOOLS App testing add Command line add Tutorials add Quick reference add web_asset Deploy Concepts add Streamlit Community Cloud add Snowflake Other platforms add school Knowledge base FAQ Installing dependencies Deployment issues Home / Develop / API reference / Data elements / st.column_config / Link column st.column_config.LinkColumn Streamlit Version Version 1.41.0 Version 1.40.0 Version 1.39.0 Version 1.38.0 Version 1.37.0 Version 1.36.0 Version 1.35.0 Version 1.34.0 Version 1.33.0 Version 1.32.0 Version 1.31.0 Version 1.30.0 Version 1.29.0 Version 1.28.0 Version 1.27.0 Version 1.26.0 Version 1.25.0 Version 1.24.0 Version 1.23.0 Version 1.22.0 Version 1.21.0 Version 1.20.0 Streamlit in Snowflake Configure a link column in st.dataframe or st.data_editor . The cell values need to be string and will be shown as clickable links. This command needs to be used in the column_config parameter of st.dataframe or st.data_editor . When used with st.data_editor , editing will be enabled with a text input widget. Function signature [source] st.column_config.LinkColumn(label=None, *, width=None, help=None, disabled=None, required=None, pinned=None, default=None, max_chars=None, validate=None, display_text=None) Parameters label (str or None) The label shown at the top of the column. If this is None (default), the column name is used. width ("small", "medium", "large", or None) The display width of the column. If this is None (default), the column will be sized to fit the cell contents. Otherwise, this can be one of the following: "small" : 75px wide "medium" : 200px wide "large" : 400px wide help (str or None) An optional tooltip that gets displayed when hovering over the column label. If this is None (default), no tooltip is displayed. disabled (bool or None) Whether editing should be disabled for this column. If this is None (default), Streamlit will decide: indices are disabled and data columns are not. If a column has mixed types, it may become uneditable regardless of disabled . required (bool or None) Whether edited cells in the column need to have a value. If this is False (default), the user can submit empty values for this column. If this is True , an edited cell in this column can only be submitted if its value is not None , and a new row will only be submitted after the user fills in this column. pinned (bool or None) Whether the column is pinned. A pinned column will stay visible on the left side no matter where the user scrolls. If this is None (default), Streamlit will decide: index columns are pinned, and data columns are not pinned. default (str or None) Specifies the default value in this column when a new row is added by the user. This defaults to None . max_chars (int or None) The maximum number of characters that can be entered. If this is None (default), there will be no maximum. validate (str or None) A JS-flavored regular expression (e.g. "^https://.+$" ) that edited values are validated against. If the user input is invalid, it will not be submitted. display_text (str or None) The text that is displayed in the cell. This can be one of the following: None (default) to display the URL itself. A string that is displayed in every cell, e.g. "Open link" . A JS-flavored regular expression (detected by usage of parentheses) to extract a part of the URL via a capture group. For example, use "https://(.*?)\.example\.com" to extract the display text "foo" from the URL "https://foo.example.com". For more complex cases, you may use Pandas Styler's format function on the underlying dataframe. Note that this makes the app slow, doesn't work with editable columns, and might be removed in the future. Text formatting from column_config always takes precedence over text formatting from pandas.Styler . Examples import pandas as pd import streamlit as st data_df = pd.DataFrame( { "apps": [ "https://roadmap.streamlit.app", "https://extras.streamlit.app", "https://issues.streamlit.app", "https://30days.streamlit.app", ], "creator": [ "https://github.com/streamlit", "https://github.com/arnaudmiribel", "https://github.com/streamlit", "https://github.com/streamlit", ], } ) st.data_editor( data_df, column_config={ "apps": st.column_config.LinkColumn( "Trending apps", help="The top trending Streamlit apps", validate=r"^https://[a-z]+\.streamlit\.app$", max_chars=100, display_text=r"https://(.*?)\.streamlit\.app" ), "creator": st.column_config.LinkColumn( "App Creator", display_text="Open profile" ), }, hide_index=True, ) Built with Streamlit 🎈 Fullscreen open_in_new Previous: List column Next: Image column forum Still have questions? Our forums are full of helpful information and Streamlit experts. Home Contact Us Community © 2025 Snowflake Inc. Cookie policy forum Ask AI |
st.pyplot_-_Streamlit_Docs.txt | st.pyplot - Streamlit Docs Documentation search Search rocket_launch Get started Installation add Fundamentals add First steps add code Develop Concepts add API reference remove PAGE ELEMENTS Write and magic add Text elements add Data elements add Chart elements remove SIMPLE st.area_chart st.bar_chart st.line_chart st.map st.scatter_chart ADVANCED st.altair_chart st.bokeh_chart st.graphviz_chart st.plotly_chart st.pydeck_chart st.pyplot st.vega_lite_chart Input widgets add Media elements add Layouts and containers add Chat elements add Status elements add Third-party components open_in_new APPLICATION LOGIC Navigation and pages add Execution flow add Caching and state add Connections and secrets add Custom components add Utilities add Configuration add TOOLS App testing add Command line add Tutorials add Quick reference add web_asset Deploy Concepts add Streamlit Community Cloud add Snowflake Other platforms add school Knowledge base FAQ Installing dependencies Deployment issues Home / Develop / API reference / Chart elements / st.pyplot st.pyplot Streamlit Version Version 1.41.0 Version 1.40.0 Version 1.39.0 Version 1.38.0 Version 1.37.0 Version 1.36.0 Version 1.35.0 Version 1.34.0 Version 1.33.0 Version 1.32.0 Version 1.31.0 Version 1.30.0 Version 1.29.0 Version 1.28.0 Version 1.27.0 Version 1.26.0 Version 1.25.0 Version 1.24.0 Version 1.23.0 Version 1.22.0 Version 1.21.0 Version 1.20.0 Streamlit in Snowflake Display a matplotlib.pyplot figure. Important You must install matplotlib to use this command. Function signature [source] st.pyplot(fig=None, clear_figure=None, use_container_width=True, **kwargs) Parameters fig (Matplotlib Figure) The Matplotlib Figure object to render. See https://matplotlib.org/stable/gallery/index.html for examples. Note When this argument isn't specified, this function will render the global Matplotlib figure object. However, this feature is deprecated and will be removed in a later version. clear_figure (bool) If True, the figure will be cleared after being rendered. If False, the figure will not be cleared after being rendered. If left unspecified, we pick a default based on the value of fig . If fig is set, defaults to False . If fig is not set, defaults to True . This simulates Jupyter's approach to matplotlib rendering. use_container_width (bool) Whether to override the figure's native width with the width of the parent container. If use_container_width is True (default), Streamlit sets the width of the figure to match the width of the parent container. If use_container_width is False , Streamlit sets the width of the chart to fit its contents according to the plotting library, up to the width of the parent container. **kwargs (any) Arguments to pass to Matplotlib's savefig function. Example import streamlit as st import matplotlib.pyplot as plt import numpy as np arr = np.random.normal(1, 1, size=100) fig, ax = plt.subplots() ax.hist(arr, bins=20) st.pyplot(fig) Built with Streamlit 🎈 Fullscreen open_in_new Matplotlib supports several types of "backends". If you're getting an error using Matplotlib with Streamlit, try setting your backend to "TkAgg": echo "backend: TkAgg" >> ~/.matplotlib/matplotlibrc For more information, see https://matplotlib.org/faq/usage_faq.html . priority_high Warning Matplotlib doesn't work well with threads . So if you're using Matplotlib you should wrap your code with locks as shown in the snippet below. This Matplotlib bug is more prominent when you deploy and share your app apps since you're more likely to get concurrent users then. from matplotlib.backends.backend_agg import RendererAgg _lock = RendererAgg.lock with _lock: fig.title('This is a figure)') fig.plot([1,20,3,40]) st.pyplot(fig) Previous: st.pydeck_chart Next: st.vega_lite_chart forum Still have questions? Our forums are full of helpful information and Streamlit experts. Home Contact Us Community © 2025 Snowflake Inc. Cookie policy forum Ask AI |
Create_an_app_-_Streamlit_Docs.txt | Create an app - Streamlit Docs Documentation search Search rocket_launch Get started Installation add Fundamentals add First steps remove Create an app Create a multipage app code Develop Concepts add API reference add Tutorials add Quick reference add web_asset Deploy Concepts add Streamlit Community Cloud add Snowflake Other platforms add school Knowledge base FAQ Installing dependencies Deployment issues Home / Get started / First steps / Create an app Create an app If you've made it this far, chances are you've installed Streamlit and run through the basics in Basic concepts and Advanced concepts . If not, now is a good time to take a look. The easiest way to learn how to use Streamlit is to try things out yourself. As you read through this guide, test each method. As long as your app is running, every time you add a new element to your script and save, Streamlit's UI will ask if you'd like to rerun the app and view the changes. This allows you to work in a fast interactive loop: you write some code, save it, review the output, write some more, and so on, until you're happy with the results. The goal is to use Streamlit to create an interactive app for your data or model and along the way to use Streamlit to review, debug, perfect, and share your code. In this guide, you're going to use Streamlit's core features to create an interactive app; exploring a public Uber dataset for pickups and drop-offs in New York City. When you're finished, you'll know how to fetch and cache data, draw charts, plot information on a map, and use interactive widgets, like a slider, to filter results. star Tip If you'd like to skip ahead and see everything at once, the complete script is available below . Create your first app Streamlit is more than just a way to make data apps, it’s also a community of creators that share their apps and ideas and help each other make their work better. Please come join us on the community forum. We love to hear your questions, ideas, and help you work through your bugs — stop by today! The first step is to create a new Python script. Let's call it uber_pickups.py . Open uber_pickups.py in your favorite IDE or text editor, then add these lines: import streamlit as st import pandas as pd import numpy as np Every good app has a title, so let's add one: st.title('Uber pickups in NYC') Now it's time to run Streamlit from the command line: streamlit run uber_pickups.py Running a Streamlit app is no different than any other Python script. Whenever you need to view the app, you can use this command. star Tip Did you know you can also pass a URL to streamlit run ? This is great when combined with GitHub Gists. For example: streamlit run https://raw.githubusercontent.com/streamlit/demo-uber-nyc-pickups/master/streamlit_app.py As usual, the app should automatically open in a new tab in your browser. Fetch some data Now that you have an app, the next thing you'll need to do is fetch the Uber dataset for pickups and drop-offs in New York City. Let's start by writing a function to load the data. Add this code to your script: DATE_COLUMN = 'date/time' DATA_URL = ('https://s3-us-west-2.amazonaws.com/' 'streamlit-demo-data/uber-raw-data-sep14.csv.gz') def load_data(nrows): data = pd.read_csv(DATA_URL, nrows=nrows) lowercase = lambda x: str(x).lower() data.rename(lowercase, axis='columns', inplace=True) data[DATE_COLUMN] = pd.to_datetime(data[DATE_COLUMN]) return data You'll notice that load_data is a plain old function that downloads some data, puts it in a Pandas dataframe, and converts the date column from text to datetime. The function accepts a single parameter ( nrows ), which specifies the number of rows that you want to load into the dataframe. Now let's test the function and review the output. Below your function, add these lines: # Create a text element and let the reader know the data is loading. data_load_state = st.text('Loading data...') # Load 10,000 rows of data into the dataframe. data = load_data(10000) # Notify the reader that the data was successfully loaded. data_load_state.text('Loading data...done!') You'll see a few buttons in the upper-right corner of your app asking if you'd like to rerun the app. Choose Always rerun , and you'll see your changes automatically each time you save. Ok, that's underwhelming... It turns out that it takes a long time to download data, and load 10,000 lines into a dataframe. Converting the date column into datetime isn’t a quick job either. You don’t want to reload the data each time the app is updated – luckily Streamlit allows you to cache the data. Effortless caching Try adding @st.cache_data before the load_data declaration: @st.cache_data def load_data(nrows): Then save the script, and Streamlit will automatically rerun your app. Since this is the first time you’re running the script with @st.cache_data , you won't see anything change. Let’s tweak your file a little bit more so that you can see the power of caching. Replace the line data_load_state.text('Loading data...done!') with this: data_load_state.text("Done! (using st.cache_data)") Now save. See how the line you added appeared immediately? If you take a step back for a second, this is actually quite amazing. Something magical is happening behind the scenes, and it only takes one line of code to activate it. How's it work? Let's take a few minutes to discuss how @st.cache_data actually works. When you mark a function with Streamlit’s cache annotation, it tells Streamlit that whenever the function is called that it should check two things: The input parameters you used for the function call. The code inside the function. If this is the first time Streamlit has seen both these items, with these exact values, and in this exact combination, it runs the function and stores the result in a local cache. The next time the function is called, if the two values haven't changed, then Streamlit knows it can skip executing the function altogether. Instead, it reads the output from the local cache and passes it on to the caller -- like magic. "But, wait a second," you’re saying to yourself, "this sounds too good to be true. What are the limitations of all this awesomesauce?" Well, there are a few: Streamlit will only check for changes within the current working directory. If you upgrade a Python library, Streamlit's cache will only notice this if that library is installed inside your working directory. If your function is not deterministic (that is, its output depends on random numbers), or if it pulls data from an external time-varying source (for example, a live stock market ticker service) the cached value will be none-the-wiser. Lastly, you should avoid mutating the output of a function cached with st.cache_data since cached values are stored by reference. While these limitations are important to keep in mind, they tend not to be an issue a surprising amount of the time. Those times, this cache is really transformational. star Tip Whenever you have a long-running computation in your code, consider refactoring it so you can use @st.cache_data , if possible. Please read Caching for more details. Now that you know how caching with Streamlit works, let’s get back to the Uber pickup data. Inspect the raw data It's always a good idea to take a look at the raw data you're working with before you start working with it. Let's add a subheader and a printout of the raw data to the app: st.subheader('Raw data') st.write(data) In the Basic concepts guide you learned that st.write will render almost anything you pass to it. In this case, you're passing in a dataframe and it's rendering as an interactive table. st.write tries to do the right thing based on the data type of the input. If it isn't doing what you expect you can use a specialized command like st.dataframe instead. For a full list, see API reference . Draw a histogram Now that you've had a chance to take a look at the dataset and observe what's available, let's take things a step further and draw a histogram to see what Uber's busiest hours are in New York City. To start, let's add a subheader just below the raw data section: st.subheader('Number of pickups by hour') Use NumPy to generate a histogram that breaks down pickup times binned by hour: hist_values = np.histogram( data[DATE_COLUMN].dt.hour, bins=24, range=(0,24))[0] Now, let's use Streamlit's st.bar_chart() method to draw this histogram. st.bar_chart(hist_values) Save your script. This histogram should show up in your app right away. After a quick review, it looks like the busiest time is 17:00 (5 P.M.). To draw this diagram we used Streamlit's native bar_chart() method, but it's important to know that Streamlit supports more complex charting libraries like Altair, Bokeh, Plotly, Matplotlib and more. For a full list, see supported charting libraries . Plot data on a map Using a histogram with Uber's dataset helped us determine what the busiest times are for pickups, but what if we wanted to figure out where pickups were concentrated throughout the city. While you could use a bar chart to show this data, it wouldn't be easy to interpret unless you were intimately familiar with latitudinal and longitudinal coordinates in the city. To show pickup concentration, let's use Streamlit st.map() function to overlay the data on a map of New York City. Add a subheader for the section: st.subheader('Map of all pickups') Use the st.map() function to plot the data: st.map(data) Save your script. The map is fully interactive. Give it a try by panning or zooming in a bit. After drawing your histogram, you determined that the busiest hour for Uber pickups was 17:00. Let's redraw the map to show the concentration of pickups at 17:00. Locate the following code snippet: st.subheader('Map of all pickups') st.map(data) Replace it with: hour_to_filter = 17 filtered_data = data[data[DATE_COLUMN].dt.hour == hour_to_filter] st.subheader(f'Map of all pickups at {hour_to_filter}:00') st.map(filtered_data) You should see the data update instantly. To draw this map we used the st.map function that's built into Streamlit, but if you'd like to visualize complex map data, we encourage you to take a look at the st.pydeck_chart . Filter results with a slider In the last section, when you drew the map, the time used to filter results was hardcoded into the script, but what if we wanted to let a reader dynamically filter the data in real time? Using Streamlit's widgets you can. Let's add a slider to the app with the st.slider() method. Locate hour_to_filter and replace it with this code snippet: hour_to_filter = st.slider('hour', 0, 23, 17) # min: 0h, max: 23h, default: 17h Use the slider and watch the map update in real time. Use a button to toggle data Sliders are just one way to dynamically change the composition of your app. Let's use the st.checkbox function to add a checkbox to your app. We'll use this checkbox to show/hide the raw data table at the top of your app. Locate these lines: st.subheader('Raw data') st.write(data) Replace these lines with the following code: if st.checkbox('Show raw data'): st.subheader('Raw data') st.write(data) We're sure you've got your own ideas. When you're done with this tutorial, check out all the widgets that Streamlit exposes in our API Reference . Let's put it all together That's it, you've made it to the end. Here's the complete script for our interactive app. star Tip If you've skipped ahead, after you've created your script, the command to run Streamlit is streamlit run [app name] . import streamlit as st import pandas as pd import numpy as np st.title('Uber pickups in NYC') DATE_COLUMN = 'date/time' DATA_URL = ('https://s3-us-west-2.amazonaws.com/' 'streamlit-demo-data/uber-raw-data-sep14.csv.gz') @st.cache_data def load_data(nrows): data = pd.read_csv(DATA_URL, nrows=nrows) lowercase = lambda x: str(x).lower() data.rename(lowercase, axis='columns', inplace=True) data[DATE_COLUMN] = pd.to_datetime(data[DATE_COLUMN]) return data data_load_state = st.text('Loading data...') data = load_data(10000) data_load_state.text("Done! (using st.cache_data)") if st.checkbox('Show raw data'): st.subheader('Raw data') st.write(data) st.subheader('Number of pickups by hour') hist_values = np.histogram(data[DATE_COLUMN].dt.hour, bins=24, range=(0,24))[0] st.bar_chart(hist_values) # Some number in the range 0-23 hour_to_filter = st.slider('hour', 0, 23, 17) filtered_data = data[data[DATE_COLUMN].dt.hour == hour_to_filter] st.subheader('Map of all pickups at %s:00' % hour_to_filter) st.map(filtered_data) Share your app After you’ve built a Streamlit app, it's time to share it! To show it off to the world you can use Streamlit Community Cloud to deploy, manage, and share your app for free. It works in 3 simple steps: Put your app in a public GitHub repo (and make sure it has a requirements.txt!) Sign into share.streamlit.io Click 'Deploy an app' and then paste in your GitHub URL That's it! 🎈 You now have a publicly deployed app that you can share with the world. Click to learn more about how to use Streamlit Community Cloud . Get help That's it for getting started, now you can go and build your own apps! If you run into difficulties here are a few things you can do. Check out our community forum and post a question Quick help from command line with streamlit help Go through our Knowledge Base for tips, step-by-step tutorials, and articles that answer your questions about creating and deploying Streamlit apps. Read more documentation! Check out: Concepts for things like caching, theming, and adding statefulness to apps. API reference for examples of every Streamlit command. Previous: First steps Next: Create a multipage app forum Still have questions? Our forums are full of helpful information and Streamlit experts. Home Contact Us Community © 2025 Snowflake Inc. Cookie policy forum Ask AI |
Navigation_and_pages_-_Streamlit_Docs.txt | Navigation and pages - Streamlit Docs Documentation search Search rocket_launch Get started Installation add Fundamentals add First steps add code Develop Concepts add API reference remove PAGE ELEMENTS Write and magic add Text elements add Data elements add Chart elements add Input widgets add Media elements add Layouts and containers add Chat elements add Status elements add Third-party components open_in_new APPLICATION LOGIC Navigation and pages remove st.navigation st.Page st.page_link link st.switch_page Execution flow add Caching and state add Connections and secrets add Custom components add Utilities add Configuration add TOOLS App testing add Command line add Tutorials add Quick reference add web_asset Deploy Concepts add Streamlit Community Cloud add Snowflake Other platforms add school Knowledge base FAQ Installing dependencies Deployment issues Home / Develop / API reference / Navigation and pages Navigation and pages Navigation Configure the available pages in a multipage app. st.navigation({ "Your account" : [log_out, settings], "Reports" : [overview, usage], "Tools" : [search] }) Page Define a page in a multipage app. home = st.Page( "home.py", title="Home", icon=":material/home:" ) Page link Display 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 page Programmatically navigates to a specified page. st.switch_page("pages/my_page.py") Previous: Third-party components Next: st.navigation forum Still have questions? Our forums are full of helpful information and Streamlit experts. Home Contact Us Community © 2025 Snowflake Inc. Cookie policy forum Ask AI |
st.column_config.Column_-_Streamlit_Docs.txt | st.column_config.Column - Streamlit Docs Documentation search Search rocket_launch Get started Installation add Fundamentals add First steps add code Develop Concepts add API reference remove PAGE ELEMENTS Write and magic add Text elements add Data elements remove st.dataframe st.data_editor st.column_config remove Column Text column Number column Checkbox column Selectbox column Datetime column Date column Time column List column Link column Image column Area chart column Line chart column Bar chart column Progress column st.table st.metric st.json Chart elements add Input widgets add Media elements add Layouts and containers add Chat elements add Status elements add Third-party components open_in_new APPLICATION LOGIC Navigation and pages add Execution flow add Caching and state add Connections and secrets add Custom components add Utilities add Configuration add TOOLS App testing add Command line add Tutorials add Quick reference add web_asset Deploy Concepts add Streamlit Community Cloud add Snowflake Other platforms add school Knowledge base FAQ Installing dependencies Deployment issues Home / Develop / API reference / Data elements / st.column_config / Column st.column_config.Column Streamlit Version Version 1.41.0 Version 1.40.0 Version 1.39.0 Version 1.38.0 Version 1.37.0 Version 1.36.0 Version 1.35.0 Version 1.34.0 Version 1.33.0 Version 1.32.0 Version 1.31.0 Version 1.30.0 Version 1.29.0 Version 1.28.0 Version 1.27.0 Version 1.26.0 Version 1.25.0 Version 1.24.0 Version 1.23.0 Version 1.22.0 Version 1.21.0 Version 1.20.0 Streamlit in Snowflake Configure a generic column in st.dataframe or st.data_editor . The type of the column will be automatically inferred from the data type. This command needs to be used in the column_config parameter of st.dataframe or st.data_editor . To change the type of the column and enable type-specific configuration options, use one of the column types in the st.column_config namespace, e.g. st.column_config.NumberColumn . Function signature [source] st.column_config.Column(label=None, *, width=None, help=None, disabled=None, required=None, pinned=None) Parameters label (str or None) The label shown at the top of the column. If this is None (default), the column name is used. width ("small", "medium", "large", or None) The display width of the column. If this is None (default), the column will be sized to fit the cell contents. Otherwise, this can be one of the following: "small" : 75px wide "medium" : 200px wide "large" : 400px wide help (str or None) An optional tooltip that gets displayed when hovering over the column label. If this is None (default), no tooltip is displayed. disabled (bool or None) Whether editing should be disabled for this column. If this is None (default), Streamlit will decide: indices are disabled and data columns are not. If a column has mixed types, it may become uneditable regardless of disabled . required (bool or None) Whether edited cells in the column need to have a value. If this is False (default), the user can submit empty values for this column. If this is True , an edited cell in this column can only be submitted if its value is not None , and a new row will only be submitted after the user fills in this column. pinned (bool or None) Whether the column is pinned. A pinned column will stay visible on the left side no matter where the user scrolls. If this is None (default), Streamlit will decide: index columns are pinned, and data columns are not pinned. Examples import pandas as pd import streamlit as st data_df = pd.DataFrame( { "widgets": ["st.selectbox", "st.number_input", "st.text_area", "st.button"], } ) st.data_editor( data_df, column_config={ "widgets": st.column_config.Column( "Streamlit Widgets", help="Streamlit **widget** commands 🎈", width="medium", required=True, ) }, hide_index=True, num_rows="dynamic", ) Built with Streamlit 🎈 Fullscreen open_in_new Previous: st.column_config Next: Text column forum Still have questions? Our forums are full of helpful information and Streamlit experts. Home Contact Us Community © 2025 Snowflake Inc. Cookie policy forum Ask AI |
Upgrade_your_app_s_Python_version_on_Community_Clo.txt | Upgrade your app's Python version on Community Cloud - Streamlit Docs Documentation search Search rocket_launch Get started Installation add Fundamentals add First steps add code Develop Concepts add API reference add Tutorials add Quick reference add web_asset Deploy Concepts add Streamlit Community Cloud remove Get started add Deploy your app add Manage your app remove App analytics App settings Delete your app Edit your app Favorite your app Reboot your app Rename your app in GitHub Upgrade Python Upgrade Streamlit Share your app add Manage your account add Status and limitations Snowflake Other platforms add school Knowledge base FAQ Installing dependencies Deployment issues Home / Deploy / Streamlit Community Cloud / Manage your app / Upgrade Python Upgrade your app's Python version on Community Cloud Dependencies within Python can be upgraded in place by simply changing your environment configuration file (typically requirements.txt ). However, Python itself can't be changed after deployment. When you deploy an app, you can select the version of Python through the " Advanced settings " dialog. After you have deployed an app, you must delete it and redeploy it to change the version of Python it uses. Take note of your app's settings: Current, custom subdomain. GitHub coordinates (repository, branch, and entrypoint file path). Secrets. When you delete an app, its custom subdomain is immediately available for reuse. Delete your app . Deploy your app . On the deployment page, select your app's GitHub coordinates. Set your custom domain to match your deleted instance. Click " Advanced settings ." Choose your desired version of Python. Optional: If your app had secrets, re-enter them. Click " Save ." Click " Deploy ." In a few minutes, Community Cloud will redirect you to your redployed app. Previous: Rename your app in GitHub Next: Upgrade Streamlit forum Still have questions? Our forums are full of helpful information and Streamlit experts. Home Contact Us Community © 2025 Snowflake Inc. Cookie policy forum Ask AI |
Connect_Streamlit_to_Google_BigQuery___Streamlit_D.txt | Connect Streamlit to Google BigQuery - Streamlit Docs Documentation search Search rocket_launch Get started Installation add Fundamentals add First steps add code Develop Concepts add API reference add Tutorials remove Elements add Execution flow add Connect to data sources remove AWS S3 BigQuery Firestore open_in_new Google Cloud Storage Microsoft SQL Server MongoDB MySQL Neon PostgreSQL Private Google Sheet Public Google Sheet Snowflake Supabase Tableau TiDB TigerGraph Multipage apps add Work with LLMs add Quick reference add web_asset Deploy Concepts add Streamlit Community Cloud add Snowflake Other platforms add school Knowledge base FAQ Installing dependencies Deployment issues Home / Develop / Tutorials / Connect to data sources / BigQuery Connect 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_pin Note If 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_pin Note If 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_high Important 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 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 S3 Next: Firestore forum Still have questions? Our forums are full of helpful information and Streamlit experts. Home Contact Us Community © 2025 Snowflake Inc. Cookie policy forum Ask AI |
Get_started_with_Streamlit_Community_Cloud___Strea.txt | Get started with Streamlit Community Cloud - Streamlit Docs Documentation search Search rocket_launch Get started Installation add Fundamentals add First steps add code Develop Concepts add API reference add Tutorials add Quick reference add web_asset Deploy Concepts add Streamlit Community Cloud remove Get started remove Quickstart Create your account Connect your GitHub account Explore your workspace Deploy from a template Fork and edit a public app Trust and security Deploy your app add Manage your app add Share your app add Manage your account add Status and limitations Snowflake Other platforms add school Knowledge base FAQ Installing dependencies Deployment issues Home / Deploy / Streamlit Community Cloud / Get started Get started with Streamlit Community Cloud Welcome to Streamlit Community Cloud, where you can share your Streamlit apps with the world! Whether you've already created your first Streamlit app or you're just getting started, you're in the right place. First things first, you need to create your Streamlit Community Cloud account to start deploying apps. rocket_launch Quickstart Create your account and deploy an example app as fast as possible. Jump right into coding with GitHub Codespaces. security Trust and Security Security first! If you want to read up on how we handle your data before you get started, we've got you covered. If you're looking for help to build your first Streamlit app, read our Get started docs for the Streamlit library. If you want to fork an app and start with an example, check out our App gallery . Either way, it only takes a few minutes to create your first app. If you're looking for more detailed instructions than the quickstart, try the following: person Create your account. See all the options and get complete explanations as you create your Streamlit Community Cloud account. code Connect your GitHub account. After your create your Community Cloud account, connect GitHub for source control. computer Explore your workspace. Take a quick tour of your Community Cloud workspace. See where all the magic happens. auto_fix_high Deploy an app from a template. Use a template to get your own app up and running in minutes. fork_right Fork and edit a public app. Start with a bang! Fork a public app and jump right into the code. Previous: Streamlit Community Cloud Next: Quickstart forum Still have questions? Our forums are full of helpful information and Streamlit experts. Home Contact Us Community © 2025 Snowflake Inc. Cookie policy forum Ask AI |
Widget_behavior_-_Streamlit_Docs.txt | Widget behavior - Streamlit Docs Documentation search Search rocket_launch Get started Installation add Fundamentals add First steps add code Develop Concepts remove CORE Architecture & execution remove Running your app Streamlit's architecture The app chrome Caching Session State Forms Fragments Widget behavior Multipage apps add App design add ADDITIONAL Connections and secrets add Custom components add Configuration and theming add App testing add API reference add Tutorials add Quick reference add web_asset Deploy Concepts add Streamlit Community Cloud add Snowflake Other platforms add school Knowledge base FAQ Installing dependencies Deployment issues Home / Develop / Concepts / Architecture & execution / Widget behavior Understanding widget behavior Widgets (like st.button , st.selectbox , and st.text_input ) are at the heart of Streamlit apps. They are the interactive elements of Streamlit that pass information from your users into your Python code. Widgets are magical and often work how you want, but they can have surprising behavior in some situations. Understanding the different parts of a widget and the precise order in which events occur helps you achieve your desired results. This guide covers advanced concepts about widgets. Generally, it begins with simpler concepts and increases in complexity. For most beginning users, these details won't be important to know right away. When you want to dynamically change widgets or preserve widget information between pages, these concepts will be important to understand. We recommend having a basic understanding of Session State before reading this guide. 🎈 TL;DR expand_more The actions of one user do not affect the widgets of any other user. A widget function call returns the widget's current value, which is a simple Python type. (e.g. st.button returns a boolean value.) Widgets return their default values on their first call before a user interacts with them. A widget's identity depends on the arguments passed to the widget function. Changing a widget's label, min or max value, default value, placeholder text, help text, or key will cause it to reset. If you don't call a widget function in a script run, Streamlit will delete the widget's information— including its key-value pair in Session State . If you call the same widget function later, Streamlit treats it as a new widget. The last two points (widget identity and widget deletion) are the most relevant when dynamically changing widgets or working with multi-page applications. This is covered in detail later in this guide: Statefulness of widgets and Widget life cycle . Anatomy of a widget There are four parts to keep in mind when using widgets: The frontend component as seen by the user. The backend value or value as seen through st.session_state . The key of the widget used to access its value via st.session_state . The return value given by the widget's function. Widgets are session dependent Widget states are dependent on a particular session (browser connection). The actions of one user do not affect the widgets of any other user. Furthermore, if a user opens up multiple tabs to access an app, each tab will be a unique session. Changing a widget in one tab will not affect the same widget in another tab. Widgets return simple Python data types The value of a widget as seen through st.session_state and returned by the widget function are of simple Python types. For example, st.button returns a boolean value and will have the same boolean value saved in st.session_state if using a key. The first time a widget function is called (before a user interacts with it), it will return its default value. (e.g. st.selectbox returns the first option by default.) Default values are configurable for all widgets with a few special exceptions like st.button and st.file_uploader . Keys help distinguish widgets and access their values Widget keys serve two purposes: Distinguishing two otherwise identical widgets. Creating a means to access and manipulate the widget's value through st.session_state . Whenever possible, Streamlit updates widgets incrementally on the frontend instead of rebuilding them with each rerun. This means Streamlit assigns an ID to each widget from the arguments passed to the widget function. A widget's ID is based on parameters such as label, min or max value, default value, placeholder text, help text, and key. The page where the widget appears also factors into a widget's ID. If you have two widgets of the same type with the same arguments on the same page, you will get a DuplicateWidgetID error. In this case, assign unique keys to the two widgets. Streamlit can't understand two identical widgets on the same page # This will cause a DuplicateWidgetID error. st.button("OK") st.button("OK") Use keys to distinguish otherwise identical widgets st.button("OK", key="privacy") st.button("OK", key="terms") Order of operations When a user interacts with a widget, the order of logic is: Its value in st.session_state is updated. The callback function (if any) is executed. The page reruns with the widget function returning its new value. If the callback function writes anything to the screen, that content will appear above the rest of the page. A callback function runs as a prefix to the script rerunning. Consequently, that means anything written via a callback function will disappear as soon as the user performs their next action. Other widgets should generally not be created within a callback function. push_pin Note If a callback function is passed any args or kwargs, those arguments will be established when the widget is rendered. In particular, if you want to use a widget's new value in its own callback function, you cannot pass that value to the callback function via the args parameter; you will have to assign a key to the widget and look up its new value using a call to st.session_state within the callback function . Using callback functions with forms Using a callback function with a form requires consideration of this order of operations. import streamlit as st if "attendance" not in st.session_state: st.session_state.attendance = set() def take_attendance(): if st.session_state.name in st.session_state.attendance: st.info(f"{st.session_state.name} has already been counted.") else: st.session_state.attendance.add(st.session_state.name) with st.form(key="my_form"): st.text_input("Name", key="name") st.form_submit_button("I'm here!", on_click=take_attendance) Built with Streamlit 🎈 Fullscreen open_in_new Statefulness of widgets As long as the defining parameters of a widget remain the same and that widget is continuously rendered on the frontend, then it will be stateful and remember user input. Changing parameters of a widget will reset it If any of the defining parameters of a widget change, Streamlit will see it as a new widget and it will reset. The use of manually assigned keys and default values is particularly important in this case. Note that callback functions, callback args and kwargs, label visibility, and disabling a widget do not affect a widget's identity. In this example, we have a slider whose min and max values are changed. Try interacting with each slider to change its value then change the min or max setting to see what happens. import streamlit as st cols = st.columns([2, 1, 2]) minimum = cols[0].number_input("Minimum", 1, 5) maximum = cols[2].number_input("Maximum", 6, 10, 10) st.slider("No default, no key", minimum, maximum) st.slider("No default, with key", minimum, maximum, key="a") st.slider("With default, no key", minimum, maximum, value=5) st.slider("With default, with key", minimum, maximum, value=5, key="b") Built with Streamlit 🎈 Fullscreen open_in_new Updating a slider with no default value For the first two sliders above, as soon as the min or max value is changed, the sliders reset to the min value. The changing of the min or max value makes them "new" widgets from Streamlit's perspective and so they are recreated from scratch when the app reruns with the changed parameters. Since no default value is defined, each widget will reset to its min value. This is the same with or without a key since it's seen as a new widget either way. There is a subtle point to understand about pre-existing keys connecting to widgets. This will be explained further down in Widget life cycle . Updating a slider with a default value For the last two sliders above, a change to the min or max value will result in the widgets being seen as "new" and thus recreated like before. Since a default value of 5 is defined, each widget will reset to 5 whenever the min or max is changed. This is again the same (with or without a key). A solution to Retain statefulness when changing a widget's parameters is provided further on. Widgets do not persist when not continually rendered If a widget's function is not called during a script run, then none of its parts will be retained, including its value in st.session_state . If a widget has a key and you navigate away from that widget, its key and associated value in st.session_state will be deleted. Even temporarily hiding a widget will cause it to reset when it reappears; Streamlit will treat it like a new widget. You can either interrupt the Widget clean-up process (described at the end of this page) or save the value to another key. Save widget values in Session State to preserve them between pages If you want to navigate away from a widget and return to it while keeping its value, use a separate key in st.session_state to save the information independently from the widget. In this example, a temporary key is used with a widget. The temporary key uses an underscore prefix. Hence, "_my_key" is used as the widget key, but the data is copied to "my_key" to preserve it between pages. import streamlit as st def store_value(): # Copy the value to the permanent key st.session_state["my_key"] = st.session_state["_my_key"] # Copy the saved value to the temporary key st.session_state["_my_key"] = st.session_state["my_key"] st.number_input("Number of filters", key="_my_key", on_change=store_value) If this is functionalized to work with multiple widgets, it could look something like this: import streamlit as st def store_value(key): st.session_state[key] = st.session_state["_"+key] def load_value(key): st.session_state["_"+key] = st.session_state[key] load_value("my_key") st.number_input("Number of filters", key="_my_key", on_change=store_value, args=["my_key"]) Widget life cycle When a widget function is called, Streamlit will check if it already has a widget with the same parameters. Streamlit will reconnect if it thinks the widget already exists. Otherwise, it will make a new one. As mentioned earlier, Streamlit determines a widget's ID based on parameters such as label, min or max value, default value, placeholder text, help text, and key. The page name also factors into a widget's ID. On the other hand, callback functions, callback args and kwargs, label visibility, and disabling a widget do not affect a widget's identity. Calling a widget function when the widget doesn't already exist If your script rerun calls a widget function with changed parameters or calls a widget function that wasn't used on the last script run: Streamlit will build the frontend and backend parts of the widget, using its default value. If the widget has been assigned a key, Streamlit will check if that key already exists in Session State. a. If it exists and is not currently associated with another widget, Streamlit will assign that key's value to the widget. b. Otherwise, it will assign the default value to the key in st.session_state (creating a new key-value pair or overwriting an existing one). If there are args or kwargs for a callback function, they are computed and saved at this point in time. The widget value is then returned by the function. Step 2 can be tricky. If you have a widget: st.number_input("Alpha",key="A") and you change it on a page rerun to: st.number_input("Beta",key="A") Streamlit will see that as a new widget because of the label change. The key "A" will be considered part of the widget labeled "Alpha" and will not be attached as-is to the new widget labeled "Beta" . Streamlit will destroy st.session_state.A and recreate it with the default value. If a widget attaches to a pre-existing key when created and is also manually assigned a default value, you will get a warning if there is a disparity. If you want to control a widget's value through st.session_state , initialize the widget's value through st.session_state and avoid the default value argument to prevent conflict. Calling a widget function when the widget already exists When rerunning a script without changing a widget's parameters: Streamlit will connect to the existing frontend and backend parts. If the widget has a key that was deleted from st.session_state , then Streamlit will recreate the key using the current frontend value. (e.g Deleting a key will not revert the widget to a default value.) It will return the current value of the widget. Widget clean-up process When Streamlit gets to the end of a script run, it will delete the data for any widgets it has in memory that were not rendered on the screen. Most importantly, that means Streamlit will delete all key-value pairs in st.session_state associated with a widget not currently on screen. Additional examples As promised, let's address how to retain the statefulness of widgets when changing pages or modifying their parameters. There are two ways to do this. Use dummy keys to duplicate widget values in st.session_state and protect the data from being deleted along with the widget. Interrupt the widget clean-up process. The first method was shown above in Save widget values in Session State to preserve them between pages Interrupting the widget clean-up process To retain information for a widget with key="my_key" , just add this to the top of every page: st.session_state.my_key = st.session_state.my_key When you manually save data to a key in st.session_state , it will become detached from any widget as far as the clean-up process is concerned. If you navigate away from a widget with some key "my_key" and save data to st.session_state.my_key on the new page, you will interrupt the widget clean-up process and prevent the key-value pair from being deleted or overwritten if another widget with the same key exists. Retain statefulness when changing a widget's parameters Here is a solution to our earlier example of changing a slider's min and max values. This solution interrupts the clean-up process as described above. import streamlit as st # Set default value if "a" not in st.session_state: st.session_state.a = 5 cols = st.columns(2) minimum = cols[0].number_input("Min", 1, 5, key="min") maximum = cols[1].number_input("Max", 6, 10, 10, key="max") def update_value(): # Helper function to ensure consistency between widget parameters and value st.session_state.a = min(st.session_state.a, maximum) st.session_state.a = max(st.session_state.a, minimum) # Validate the slider value before rendering update_value() st.slider("A", minimum, maximum, key="a") Built with Streamlit 🎈 Fullscreen open_in_new The update_value() helper function is actually doing two things. On the surface, it's making sure there are no inconsistent changes to the parameters values as described. Importantly, it's also interrupting the widget clean-up process. When the min or max value of the widget changes, Streamlit sees it as a new widget on rerun. Without saving a value to st.session_state.a , the value would be thrown out and replaced by the "new" widget's default value. Previous: Fragments Next: Multipage apps forum Still have questions? Our forums are full of helpful information and Streamlit experts. Home Contact Us Community © 2025 Snowflake Inc. Cookie policy forum Ask AI |
App_is_not_loading_when_running_remotely___Streaml.txt | App is not loading when running remotely - Streamlit Docs Documentation search Search rocket_launch Get started Installation add Fundamentals add First steps add code Develop Concepts add API reference add Tutorials add Quick reference add web_asset Deploy Concepts add Streamlit Community Cloud add Snowflake Other platforms add school Knowledge base FAQ Installing dependencies Deployment issues Home / Knowledge base / Deployment issues / App is not loading when running remotely App is not loading when running remotely Below are a few common errors that occur when users spin up their own solution to host a Streamlit app remotely. To learn about a deceptively simple way to host Streamlit apps that avoids all the issues below, check out Streamlit Community Cloud . Symptom #1: The app never loads When you enter the app's URL in a browser and all you see is a blank page, a "Page not found" error, a "Connection refused" error , or anything like that, first check that Streamlit is actually running on the remote server. On a Linux server you can SSH into it and then run: ps -Al | grep streamlit If you see Streamlit running, the most likely culprit is the Streamlit port not being exposed. The fix depends on your exact setup. Below are three example fixes: Try port 80: Some hosts expose port 80 by default. To set Streamlit to use that port, start Streamlit with the --server.port option: streamlit run my_app.py --server.port=80 AWS EC2 server : First, click on your instance in the AWS Console . Then scroll down and click on Security Groups → Inbound → Edit . Next, add a Custom TCP rule that allows the Port Range 8501 with Source 0.0.0.0/0 . Other types of server : Check the firewall settings. If that still doesn't solve the problem, try running a simple HTTP server instead of Streamlit, and seeing if that works correctly. If it does, then you know the problem lies somewhere in your Streamlit app or configuration (in which case you should ask for help in our forums !) If not, then it's definitely unrelated to Streamlit. How to start a simple HTTP server: python -m http.server [port] Symptom #2: The app says "Please wait..." or shows skeleton elements forever This symptom appears differently starting from version 1.29.0. For earlier versions of Streamlit, a loading app shows a blue box in the center of the page with a "Please wait..." message. Starting from version 1.29.0, a loading app shows skeleton elements. If this loading screen does not go away, the underlying cause is likely one of the following: Using port 3000 which is reserved for internal development. Misconfigured CORS protection. Server is stripping headers from the Websocket connection, thereby breaking compression. To diagnose the issue, first make sure you are not using port 3000. If in doubt, try port 80 as described above. Next, try temporarily disabling CORS protection by running Streamlit with the --server.enableCORS flag set to false : streamlit run my_app.py --server.enableCORS=false If this fixes your issue, you should re-enable CORS protection and then set browser.serverAddress to the URL of your Streamlit app. If the issue persists, try disabling websocket compression by running Streamlit with the --server.enableWebsocketCompression flag set to false streamlit run my_app.py --server.enableWebsocketCompression=false If this fixes your issue, your server setup is likely stripping the Sec-WebSocket-Extensions HTTP header that is used to negotiate Websocket compression. Compression is not required for Streamlit to work, but it's strongly recommended as it improves performance. If you'd like to turn it back on, you'll need to find which part of your infrastructure is stripping the Sec-WebSocket-Extensions HTTP header and change that behavior. Symptom #3: Unable to upload files when running in multiple replicas If the file uploader widget returns an error with status code 403, this is probably due to a misconfiguration in your app's XSRF protection logic. To diagnose the issue, try temporarily disabling XSRF protection by running Streamlit with the --server.enableXsrfProtection flag set to false : streamlit run my_app.py --server.enableXsrfProtection=false If this fixes your issue, you should re-enable XSRF protection and try one or both of the following: Set browser.serverAddress and browser.serverPort to the URL and port of your Streamlit app. Configure your app to use the same secret across every replica by setting the server.cookieSecret config option to the same hard-to-guess string everywhere. Previous: Invoking a Python subprocess in a deployed Streamlit app Next: Argh. This app has gone over its resource limits forum Still have questions? Our forums are full of helpful information and Streamlit experts. Home Contact Us Community © 2025 Snowflake Inc. Cookie policy forum Ask AI |
st.balloons_-_Streamlit_Docs.txt | st.balloons - Streamlit Docs Documentation search Search rocket_launch Get started Installation add Fundamentals add First steps add code Develop Concepts add API reference remove PAGE ELEMENTS Write and magic add Text elements add Data elements add Chart elements add Input widgets add Media elements add Layouts and containers add Chat elements add Status elements remove CALLOUTS st.success st.info st.warning st.error st.exception OTHER st.progress st.spinner st.status st.toast st.balloons st.snow Third-party components open_in_new APPLICATION LOGIC Navigation and pages add Execution flow add Caching and state add Connections and secrets add Custom components add Utilities add Configuration add TOOLS App testing add Command line add Tutorials add Quick reference add web_asset Deploy Concepts add Streamlit Community Cloud add Snowflake Other platforms add school Knowledge base FAQ Installing dependencies Deployment issues Home / Develop / API reference / Status elements / st.balloons st.balloons Streamlit Version Version 1.41.0 Version 1.40.0 Version 1.39.0 Version 1.38.0 Version 1.37.0 Version 1.36.0 Version 1.35.0 Version 1.34.0 Version 1.33.0 Version 1.32.0 Version 1.31.0 Version 1.30.0 Version 1.29.0 Version 1.28.0 Version 1.27.0 Version 1.26.0 Version 1.25.0 Version 1.24.0 Version 1.23.0 Version 1.22.0 Version 1.21.0 Version 1.20.0 Streamlit in Snowflake Draw celebratory balloons. Function signature [source] st.balloons() Example import streamlit as st st.balloons() ...then watch your app and get ready for a celebration! Previous: st.toast Next: st.snow forum Still have questions? Our forums are full of helpful information and Streamlit experts. Home Contact Us Community © 2025 Snowflake Inc. Cookie policy forum Ask AI |
Connect_Streamlit_to_MongoDB_-_Streamlit_Docs.txt | Connect Streamlit to MongoDB - Streamlit Docs Documentation search Search rocket_launch Get started Installation add Fundamentals add First steps add code Develop Concepts add API reference add Tutorials remove Elements add Execution flow add Connect to data sources remove AWS S3 BigQuery Firestore open_in_new Google Cloud Storage Microsoft SQL Server MongoDB MySQL Neon PostgreSQL Private Google Sheet Public Google Sheet Snowflake Supabase Tableau TiDB TigerGraph Multipage apps add Work with LLMs add Quick reference add web_asset Deploy Concepts add Streamlit Community Cloud add Snowflake Other platforms add school Knowledge base FAQ Installing dependencies Deployment issues Home / Develop / Tutorials / Connect to data sources / MongoDB Connect Streamlit to MongoDB Introduction This guide explains how to securely access a remote MongoDB database from Streamlit Community Cloud. It uses the PyMongo library and Streamlit's Secrets management . Create a MongoDB Database push_pin Note If you already have a database that you want to use, feel free to skip to the next step . First, follow the official tutorials to install MongoDB , set up authentication (note down the username and password!), and connect to the MongoDB instance . Once you are connected, open the mongo shell and enter the following two commands to create a collection with some example values: use mydb db.mycollection.insertMany([{"name" : "Mary", "pet": "dog"}, {"name" : "John", "pet": "cat"}, {"name" : "Robert", "pet": "bird"}]) Add username and password to your local app secrets Your local Streamlit app will read secrets from a file .streamlit/secrets.toml in your app's root directory. Create this file if it doesn't exist yet and add the database information as shown below: # .streamlit/secrets.toml [mongo] host = "localhost" port = 27017 username = "xxx" password = "xxx" priority_high Important When copying your app secrets to Streamlit Community Cloud, be sure to replace the values of host , port , username , and password with those of your remote MongoDB database! Add this file to .gitignore and don't commit it to your GitHub repo! Copy your app secrets to the cloud As the secrets.toml file above is not committed to GitHub, you need to pass its content to your deployed app (on Streamlit Community Cloud) separately. Go to the app dashboard and in the app's dropdown menu, click on Edit Secrets . Copy the content of secrets.toml into the text area. More information is available at Secrets management . Add PyMongo to your requirements file Add the PyMongo package to your requirements.txt file, preferably pinning its version (replace x.x.x with the version you want installed): # requirements.txt pymongo==x.x.x Write your Streamlit app Copy the code below to your Streamlit app and run it. Make sure to adapt the name of your database and collection. # streamlit_app.py import streamlit as st import pymongo # Initialize connection. # Uses st.cache_resource to only run once. @st.cache_resource def init_connection(): return pymongo.MongoClient(**st.secrets["mongo"]) client = init_connection() # Pull data from the collection. # Uses st.cache_data to only rerun when the query changes or after 10 min. @st.cache_data(ttl=600) def get_data(): db = client.mydb items = db.mycollection.find() items = list(items) # make hashable for st.cache_data return items items = get_data() # Print results. for item in items: st.write(f"{item['name']} has a :{item['pet']}:") See st.cache_data above? Without it, Streamlit would run the query every time the app reruns (e.g. on a widget interaction). With st.cache_data , it only runs when the query changes or after 10 minutes (that's what ttl is for). Watch out: If your database updates more frequently, you should adapt ttl or remove caching so viewers always see the latest data. Learn more in Caching . If everything worked out (and you used the example data we created above), your app should look like this: Previous: Microsoft SQL Server Next: MySQL forum Still have questions? Our forums are full of helpful information and Streamlit experts. Home Contact Us Community © 2025 Snowflake Inc. Cookie policy forum Ask AI |
Run_your_Streamlit_app_-_Streamlit_Docs.txt | Run your Streamlit app - Streamlit Docs Documentation search Search rocket_launch Get started Installation add Fundamentals add First steps add code Develop Concepts remove CORE Architecture & execution remove Running your app Streamlit's architecture The app chrome Caching Session State Forms Fragments Widget behavior Multipage apps add App design add ADDITIONAL Connections and secrets add Custom components add Configuration and theming add App testing add API reference add Tutorials add Quick reference add web_asset Deploy Concepts add Streamlit Community Cloud add Snowflake Other platforms add school Knowledge base FAQ Installing dependencies Deployment issues Home / Develop / Concepts / Architecture & execution / Running your app Run your Streamlit app Working with Streamlit is simple. First you sprinkle a few Streamlit commands into a normal Python script, and then you run it. We list few ways to run your script, depending on your use case. Use streamlit run Once you've created your script, say your_script.py , the easiest way to run it is with streamlit run : streamlit run your_script.py 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. Pass arguments to your script When passing your script some custom arguments, they must be passed after two dashes. Otherwise the arguments get interpreted as arguments to Streamlit itself: streamlit run your_script.py [-- script args] Pass a URL to streamlit run You can also pass a URL to streamlit run ! This is great when your script is hosted remotely, such as a GitHub Gist. For example: streamlit run https://raw.githubusercontent.com/streamlit/demo-uber-nyc-pickups/master/streamlit_app.py Run Streamlit as a Python module Another way of running Streamlit is to run it as a Python module. This is 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 Previous: Architecture & execution Next: Streamlit's architecture forum Still have questions? Our forums are full of helpful information and Streamlit experts. Home Contact Us Community © 2025 Snowflake Inc. Cookie policy forum Ask AI |
Connect_Streamlit_to_Snowflake___Streamlit_Docs_e9.txt | Connect Streamlit to Snowflake - Streamlit Docs Documentation search Search rocket_launch Get started Installation add Fundamentals add First steps add code Develop Concepts add API reference add Tutorials remove Elements add Execution flow add Connect to data sources remove AWS S3 BigQuery Firestore open_in_new Google Cloud Storage Microsoft SQL Server MongoDB MySQL Neon PostgreSQL Private Google Sheet Public Google Sheet Snowflake Supabase Tableau TiDB TigerGraph Multipage apps add Work with LLMs add Quick reference add web_asset Deploy Concepts add Streamlit Community Cloud add Snowflake Other platforms add school Knowledge base FAQ Installing dependencies Deployment issues Home / Develop / Tutorials / Connect to data sources / Snowflake Connect Streamlit to Snowflake Introduction This guide explains how to securely access a Snowflake database from Streamlit. It uses st.connection , the Snowpark library , and Streamlit's Secrets management . Prerequisites The following packages must be installed in your Python environment: streamlit>=1.28 snowflake-snowpark-python>=0.9.0 snowflake-connector-python>=2.8.0 push_pin Note Use the correct version of Python required by snowflake-snowpark-python . For example, if you use snowflake-snowpark-python==1.23.0 , you must use Python version >=3.8, <3.12. You must have a Snowflake account. To create a trial account, see the tutorial in Get started . You should have a basic understanding of st.connection and Secrets management . Create a Snowflake database If you already have a database that you want to use, you can skip to the next step . Sign in to your Snowflake account at https://app.snowflake.com . In the left navigation, select " Projects ," and then select " Worksheets ." To create a new worksheet, in the upper-right corner, click the plus icon ( add ). You can use a worksheet to quickly and conveniently execute SQL statements. This is a great way to learn about and experiment with SQL in a trial account. Optional: To rename your worksheet, in the upper-left corner, hover over the tab with your worksheet name, and then click the overflow menu icon ( more_vert ). Select " Rename ", enter a new worksheet name (e.g. "Scratchwork"), and then press " Enter ". To create a new database with a table, in your worksheet's SQL editor, type and execute the following SQL statements: CREATE DATABASE PETS; CREATE TABLE MYTABLE (NAME varchar(80), PET varchar(80)); INSERT INTO MYTABLE VALUES ('Mary', 'dog'), ('John', 'cat'), ('Robert', 'bird'); SELECT * FROM MYTABLE; To execute the statements in a worksheet, select all the lines you want to execute by highlighting them with your mouse. Then, in the upper-right corner, click the play button ( play_arrow ). Alternatively, if you want to execute everything in a worksheet, click the down arrow ( expand_more ) next to the play button, and select " Run All ". priority_high Important If no lines are highlighted and you click the play button, only the line with your cursor will be executed. Optional: To view your new database, above the left navigation, select " Databases ." Click the down arrows ( expand_more ) to expand "PETS" → "PUBLIC" → "Tables" → "MYTABLE." For your use in later steps, note down your role, warehouse, database, and schema. In the preceding screenshot, these are the following: role = "ACCOUNTADMIN" warehouse = "COMPUTE_WH" database = "PETS" schema = "PUBLIC" Because the SQL statements did not specify a schema, they defaulted to the "PUBLIC" schema within the new "PETS" database. The role and warehouse are trial-account defaults. You can see the role and warehouse used by your worksheet in the upper-right corner, to the left of the " Share " and play ( play_arrow ) buttons. In Snowflake, databases provide storage, and warehouses provide compute. When you configure your connection, you aren't explicitly required to declare role, warehouse, database, and schema; if these are not specified, the connection will use your account defaults. If you want to use multiple roles, warehouses, or databases, you can also change these settings within an active connection. However, declaring these defaults avoids unintentional selections. To conveniently copy your account identifier, in the lower-left corner, click your profile image, and hover over your account. A popover dialog expands to the right with your organization and account. In the popover, hover over your account, and click the copy icon ( content_copy ). The account identifier in your clipboard is period-separated, which is the format used for SQL statements. However, the Snowflake Connector for Python requires a hyphen-separated format. Paste your account identifier into your notes, and change the period to a hyphen. account = "xxxxxxx-xxxxxxx" For more information, see Account identifiers in the Snowflake docs. Add connection parameters to your local app secrets There are three places Streamlit looks for your connection parameters: keyword arguments in st.connection , .streamlit/secrets.toml , and .snowflake/configuration.toml . For more information, especially if you want to manage multiple connections, see the examples in the API reference for SnowflakeConnnection . To configure your connection, you must specify the following: Your account identifier ( account ) Your username ( user ) Some form of authentication parameter (like password or private_key_file ) If you don't have MFA on your account, you can just specify your password . Alternatively, you can set up key-pair authentication on your account and point to your private_key_file . If you are just looking for a quick, local connection, you can set authenticator to prompt you for credentials in an external browser. In addition to the three required parameters to authenticate your connection, it is common to specify the default role , warehouse , database , and schema for convenience. For more information about required and optional parameters, see the Snowflake Connector for Python documentation. Option 1: Use .streamlit/secrets.toml If you don't already have a .streamlit/secrets.toml file in your app's working directory, create an empty secrets file. To learn more, see Secrets Management . priority_high Important Add this file to .gitignore and don't commit it to your GitHub repo! If you want to use this connection in multiple repositories, you can create a global secrets.toml file instead. For more information, see secrets.toml file location . Add your connection parameters to .streamlit/secrets.toml : [connections.snowflake] account = "xxxxxxx-xxxxxxx" user = "xxx" private_key_file = "../xxx/xxx.p8" role = "xxx" warehouse = "xxx" database = "xxx" schema = "xxx" priority_high Important Your account identifier must be hyphen-separated: <my_organization>-<my_account> . This is the general-purpose identifier format and not the period-separated format used within SQL statements. In the example above, the connection uses key-pair authentication. Therefore, private_key_file is defined instead of password . private_key_file can be an absolute or relative path. If you use a relative path, it should be relative to your app's working directory (where you execute streamlit run ). Option 2: Use .snowflake/connections.toml If you already have your connection configured using Snowflake's connections file , you can use it as-is. If you are using a default connection, no change is needed in later steps of this tutorial. If you are using a named connection, you will need to include the name in st.connection . This is noted in a later step. For information about using named connections, see the examples in the API reference for SnowflakeConnnection . If you don't already have a .snowflake/configuration.toml file in your user directory, create an empty connections file. Add your connection parameters to .snowflake/connection.toml : [default] account = "xxxxxxx-xxxxxxx" user = "xxx" private_key_file = "../xxx/xxx.p8" role = "xxx" warehouse = "xxx" database = "xxx" schema = "xxx" This example uses key-pair authentication as described in the previous option. Write your Streamlit app Copy the following code to your Streamlit app and save it. If you are not using the example database and table from the first section of this tutorial, replace the SQL query and results handling as appropriate. # streamlit_app.py import streamlit as st conn = st.connection("snowflake") df = conn.query("SELECT * FROM mytable;", ttl="10m") for row in df.itertuples(): st.write(f"{row.NAME} has a :{row.PET}:") The st.connection command creates a SnowflakeConnection object and handles secrets retrieval. The .query() method handles query caching and retries. By default, query results are cached without expiring. Setting ttl="10m" ensures that the query result is cached for no longer than 10 minutes. To disable caching, you can set ttl=0 instead. Learn more in Caching . push_pin Note If you configured your connection using a named connection in .snowflake/connections.toml instead of [default] (Option 2 above), you must include your connection name in st.connection . If you have [my_connection] in your connections file, replace the line with st.connection as follows: conn = st.connection("my_connection", type="snowflake") In your working directory, open a terminal, and run your Streamlit app. streamlit run streamlit_app.py If everything worked out (and you used the example table from the first section), your app should look like this: Use a Snowpark session The SnowflakeConnection used above also provides access to Snowpark sessions for dataframe-style operations that run natively inside Snowflake. Using this approach, you can rewrite the app above as follows: # streamlit_app.py import streamlit as st conn = st.connection("snowflake") @st.cache_data def load_table(): session = conn.session() return session.table("mytable").to_pandas() df = load_table() for row in df.itertuples(): st.write(f"{row.NAME} has a :{row.PET}:") Because this example uses .session() instead of .query() , caching is added manually for better performance and efficiency. If everything worked out (and you used the example table from the first section), your app should look the same as the preceding screenshot. Connecting to Snowflake from Community Cloud This tutorial assumes a local Streamlit app, however you can also connect to Snowflake from apps hosted in Community Cloud. The main additional steps are: Include information about dependencies using a requirements.txt file with snowflake-snowpark-python and any other dependencies. Add your secrets to your Community Cloud app. You must use the .streamlit/secrets.toml format described in Option 1 above. Previous: Public Google Sheet Next: Supabase forum Still have questions? Our forums are full of helpful information and Streamlit experts. Home Contact Us Community © 2025 Snowflake Inc. Cookie policy forum Ask AI |
Deploy_Streamlit_using_Docker_-_Streamlit_Docs.txt | Deploy Streamlit using Docker - Streamlit Docs Documentation search Search rocket_launch Get started Installation add Fundamentals add First steps add code Develop Concepts add API reference add Tutorials add Quick reference add web_asset Deploy Concepts add Streamlit Community Cloud add Snowflake Other platforms remove Docker Kubernetes school Knowledge base FAQ Installing dependencies Deployment issues Home / Deploy / Other platforms / Docker Deploy Streamlit using Docker 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 Docker to deploy your app. If you prefer Kubernetes see Deploy Streamlit using Kubernetes . Prerequisites Install Docker Engine Check network port accessibility 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 star Tip Follow 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 . Check network port accessibility As you and your users are behind your corporate VPN, you need to make sure all of you can access a certain network port. Let's say port 8501 , as it is the default port used by Streamlit. Contact your IT team and request access to port 8501 for you and your users. 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. i.e. in /app/ # app/Dockerfile FROM python:3.9-slim WORKDIR /app RUN apt-get update && apt-get install -y \ build-essential \ curl \ software-properties-common \ git \ && rm -rf /var/lib/apt/lists/* RUN git clone https://github.com/streamlit/streamlit-example.git . RUN pip3 install -r requirements.txt EXPOSE 8501 HEALTHCHECK CMD curl --fail http://localhost:8501/_stcore/health ENTRYPOINT ["streamlit", "run", "streamlit_app.py", "--server.port=8501", "--server.address=0.0.0.0"] Dockerfile walkthrough Let’s walk through each line of the Dockerfile : A Dockerfile must start with a FROM instruction. It sets the Base Image (think OS) for the container: FROM python:3.9-slim Docker has a number of official Docker base images based on various Linux distributions. They also have base images that come with language-specific modules such as Python . The python images come in many flavors, each designed for a specific use case. Here, we use the python:3.9-slim image which is a lightweight image that comes with the latest version of Python 3.9. star Tip You can also use your own base image, provided the image you use contains a supported version of Python for Streamlit. There is no one-size-fits-all approach to using any specific base image, nor is there an official Streamlit-specific base image. The WORKDIR instruction sets the working directory for any RUN , CMD , ENTRYPOINT , COPY and ADD instructions that follow it in the Dockerfile . Let’s set it to app/ : WORKDIR /app priority_high Important As 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 /app as shown in the example Dockerfile above. Install git so that we can clone the app code from a remote repo: RUN apt-get update && apt-get install -y \ build-essential \ curl \ software-properties-common \ git \ && rm -rf /var/lib/apt/lists/* Clone your code that lives in a remote repo to WORKDIR : a. If your code is in a public repo: RUN git clone https://github.com/streamlit/streamlit-example.git . Once cloned, the directory of WORKDIR will look like the following: app/ - requirements.txt - streamlit_app.py where requirements.txt file contains all your Python dependencies . E.g altair pandas streamlit and streamlit_app.py is your main script. E.g. from collections import namedtuple import altair as alt import math import pandas as pd import streamlit as st """ # Welcome to Streamlit! Edit `/streamlit_app.py` to customize this app to your heart's desire :heart: If you have any questions, checkout our [documentation](https://docs.streamlit.io) and [community forums](https://discuss.streamlit.io). In the meantime, below is an example of what you can do with just a few lines of code: """ with st.echo(code_location='below'): total_points = st.slider("Number of points in spiral", 1, 5000, 2000) num_turns = st.slider("Number of turns in spiral", 1, 100, 9) Point = namedtuple('Point', 'x y') data = [] points_per_turn = total_points / num_turns for curr_point_num in range(total_points): curr_turn, i = divmod(curr_point_num, points_per_turn) angle = (curr_turn + 1) * 2 * math.pi * i / points_per_turn radius = curr_point_num / total_points x = radius * math.cos(angle) y = radius * math.sin(angle) data.append(Point(x, y)) st.altair_chart(alt.Chart(pd.DataFrame(data), height=500, width=500) .mark_circle(color='#0068c9', opacity=0.5) .encode(x='x:Q', y='y:Q')) b. If your code is in a private repo, please read Using SSH to access private data in builds and modify the Dockerfile accordingly -- to install an SSH client, download the public key for github.com , and clone your private repo. If you use an alternative VCS such as GitLab or Bitbucket, please consult the documentation for that VCS on how to copy your code to the WORKDIR of the Dockerfile. c. If your code lives in the same directory as the Dockerfile, copy all your app files from your server into the container, including streamlit_app.py , requirements.txt , etc, by replacing the git clone line with: COPY . . More generally, the idea is copy your app code from wherever it may live on your server into the container. If the code is not in the same directory as the Dockerfile, modify the above command to include the path to the code. Install your app’s Python dependencies from the cloned requirements.txt in the container: RUN pip3 install -r requirements.txt The EXPOSE instruction informs Docker that the container listens on the specified network ports at runtime. Your container needs to listen to Streamlit’s (default) port 8501: EXPOSE 8501 The HEALTHCHECK instruction tells Docker how to test a container to check that it is still working. Your container needs to listen to Streamlit’s (default) port 8501: HEALTHCHECK CMD curl --fail http://localhost:8501/_stcore/health An ENTRYPOINT allows you to configure a container that will run as an executable. Here, it also contains the entire streamlit run command for your app, so you don’t have to call it from the command line: ENTRYPOINT ["streamlit", "run", "streamlit_app.py", "--server.port=8501", "--server.address=0.0.0.0"] Build a Docker image The docker build command builds an image from a Dockerfile . Run the following command from the app/ directory on your server to build the image: docker build -t streamlit . The -t flag is used to tag the image. Here, we have tagged the image streamlit . If you run: docker images You should see a streamlit image under the REPOSITORY column. For example: REPOSITORY TAG IMAGE ID CREATED SIZE streamlit latest 70b0759a094d About a minute ago 1.02GB Run the Docker container Now that you have built the image, you can run the container by executing: docker run -p 8501:8501 streamlit The -p flag publishes the container’s port 8501 to your server’s 8501 port. If all went well, you should see an output similar to the following: docker run -p 8501:8501 streamlit You can now view your Streamlit app in your browser. URL: http://0.0.0.0:8501 To view your app, users can browse to http://0.0.0.0:8501 or http://localhost:8501 push_pin Note Based on your server's network configuration, you could map to port 80/443 so that users can view your app using the server IP or hostname. For example: http://your-server-ip:80 or http://your-hostname:443 . Previous: Other platforms Next: Kubernetes forum Still have questions? Our forums are full of helpful information and Streamlit experts. Home Contact Us Community © 2025 Snowflake Inc. Cookie policy forum Ask AI |
Streamlit_Trust_and_Security_-_Streamlit_Docs.txt | Streamlit Trust and Security - Streamlit Docs Documentation search Search rocket_launch Get started Installation add Fundamentals add First steps add code Develop Concepts add API reference add Tutorials add Quick reference add web_asset Deploy Concepts add Streamlit Community Cloud remove Get started remove Quickstart Create your account Connect your GitHub account Explore your workspace Deploy from a template Fork and edit a public app Trust and security Deploy your app add Manage your app add Share your app add Manage your account add Status and limitations Snowflake Other platforms add school Knowledge base FAQ Installing dependencies Deployment issues Home / Deploy / Streamlit Community Cloud / Get started / Trust and security Streamlit 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 app Next: Deploy your app forum Still have questions? Our forums are full of helpful information and Streamlit experts. Home Contact Us Community © 2025 Snowflake Inc. Cookie policy forum Ask AI |
st.video_-_Streamlit_Docs.txt | st.video - Streamlit Docs Documentation search Search rocket_launch Get started Installation add Fundamentals add First steps add code Develop Concepts add API reference remove PAGE ELEMENTS Write and magic add Text elements add Data elements add Chart elements add Input widgets add Media elements remove st.audio st.image st.logo st.video Layouts and containers add Chat elements add Status elements add Third-party components open_in_new APPLICATION LOGIC Navigation and pages add Execution flow add Caching and state add Connections and secrets add Custom components add Utilities add Configuration add TOOLS App testing add Command line add Tutorials add Quick reference add web_asset Deploy Concepts add Streamlit Community Cloud add Snowflake Other platforms add school Knowledge base FAQ Installing dependencies Deployment issues Home / Develop / API reference / Media elements / st.video st.video Streamlit Version Version 1.41.0 Version 1.40.0 Version 1.39.0 Version 1.38.0 Version 1.37.0 Version 1.36.0 Version 1.35.0 Version 1.34.0 Version 1.33.0 Version 1.32.0 Version 1.31.0 Version 1.30.0 Version 1.29.0 Version 1.28.0 Version 1.27.0 Version 1.26.0 Version 1.25.0 Version 1.24.0 Version 1.23.0 Version 1.22.0 Version 1.21.0 Version 1.20.0 Streamlit in Snowflake Display a video player. Function signature [source] st.video(data, format="video/mp4", start_time=0, *, subtitles=None, end_time=None, loop=False, autoplay=False, muted=False) Parameters data (str, Path, bytes, io.BytesIO, numpy.ndarray, or file) The video to play. This can be one of the following: A URL (string) for a hosted video file, including YouTube URLs. A path to a local video file. The path can be a str or Path object. Paths can be absolute or relative to the working directory (where you execute streamlit run ). Raw video data. Raw data formats must include all necessary file headers to match the file format specified via format . format (str) The MIME type for the video file. This defaults to "video/mp4" . For more information, see https://tools.ietf.org/html/rfc4281 . start_time (int, float, timedelta, str, or None) The time from which the element should start playing. This can be one of the following: None (default): The element plays from the beginning. An int or float specifying the time in seconds. float values are rounded down to whole seconds. A string specifying the time in a format supported by Pandas' Timedelta constructor , e.g. "2 minute" , "20s" , or "1m14s" . A timedelta object from Python's built-in datetime library , e.g. timedelta(seconds=70) . subtitles (str, bytes, Path, io.BytesIO, or dict) Optional subtitle data for the video, supporting several input types: None (default): No subtitles. A string, bytes, or Path: File path to a subtitle file in .vtt or .srt formats, or the raw content of subtitles conforming to these formats. Paths can be absolute or relative to the working directory (where you execute streamlit run ). If providing raw content, the string must adhere to the WebVTT or SRT format specifications. io.BytesIO: A BytesIO stream that contains valid .vtt or .srt formatted subtitle data. A dictionary: Pairs of labels and file paths or raw subtitle content in .vtt or .srt formats to enable multiple subtitle tracks. The label will be shown in the video player. Example: {"English": "path/to/english.vtt", "French": "path/to/french.srt"} When provided, subtitles are displayed by default. For multiple tracks, the first one is displayed by default. If you don't want any subtitles displayed by default, use an empty string for the value in a dictrionary's first pair: {"None": "", "English": "path/to/english.vtt"} Not supported for YouTube videos. end_time (int, float, timedelta, str, or None) The time at which the element should stop playing. This can be one of the following: None (default): The element plays through to the end. An int or float specifying the time in seconds. float values are rounded down to whole seconds. A string specifying the time in a format supported by Pandas' Timedelta constructor , e.g. "2 minute" , "20s" , or "1m14s" . A timedelta object from Python's built-in datetime library , e.g. timedelta(seconds=70) . loop (bool) Whether the video should loop playback. autoplay (bool) Whether the video should start playing automatically. This is False by default. Browsers will not autoplay unmuted videos if the user has not interacted with the page by clicking somewhere. To enable autoplay without user interaction, you must also set muted=True . muted (bool) Whether the video should play with the audio silenced. This is False by default. Use this in conjunction with autoplay=True to enable autoplay without user interaction. Example import streamlit as st video_file = open("myvideo.mp4", "rb") video_bytes = video_file.read() st.video(video_bytes) Built with Streamlit 🎈 Fullscreen open_in_new When you include subtitles, they will be turned on by default. A viewer can turn off the subtitles (or captions) from the browser's default video control menu, usually located in the lower-right corner of the video. Here is a simple VTT file ( subtitles.vtt ): WEBVTT 0:00:01.000 --> 0:00:02.000 Look! 0:00:03.000 --> 0:00:05.000 Look at the pretty stars! If the above VTT file lives in the same directory as your app, you can add subtitles like so: import streamlit as st VIDEO_URL = "https://example.com/not-youtube.mp4" st.video(VIDEO_URL, subtitles="subtitles.vtt") Built with Streamlit 🎈 Fullscreen open_in_new See additional examples of supported subtitle input types in our video subtitles feature demo . Note Some videos may not display if they are encoded using MP4V (which is an export option in OpenCV), as this codec is not widely supported by browsers. Converting your video to H.264 will allow the video to be displayed in Streamlit. See this StackOverflow post or this Streamlit forum post for more information. Previous: st.logo Next: Layouts and containers forum Still have questions? Our forums are full of helpful information and Streamlit experts. Home Contact Us Community © 2025 Snowflake Inc. Cookie policy forum Ask AI |
config.toml_-_Streamlit_Docs.txt | config.toml - Streamlit Docs Documentation search Search rocket_launch Get started Installation add Fundamentals add First steps add code Develop Concepts add API reference remove PAGE ELEMENTS Write and magic add Text elements add Data elements add Chart elements add Input widgets add Media elements add Layouts and containers add Chat elements add Status elements add Third-party components open_in_new APPLICATION LOGIC Navigation and pages add Execution flow add Caching and state add Connections and secrets add Custom components add Utilities add Configuration remove config.toml st.get_option st.set_option st.set_page_config TOOLS App testing add Command line add Tutorials add Quick reference add web_asset Deploy Concepts add Streamlit Community Cloud add Snowflake Other platforms add school Knowledge base FAQ Installing dependencies Deployment issues Home / Develop / API reference / Configuration / config.toml config.toml config.toml is an optional file you can define for your working directory or global development environment. When config.toml is defined both globally and in your working directory, Streamlit combines the configuration options and gives precedence to the working-directory configuration. Additionally, you can use environment variables and command-line options to override additional configuration options. For more information, see Configuration options . File location To define your configuration locally or per-project, add .streamlit/config.toml to your working directory. Your working directory is wherever you call streamlit run . If you haven't previously created the .streamlit directory, you will need to add it. To define your configuration globally, you must first locate your global .streamlit directory. Streamlit adds this hidden directory to your OS user profile during installation. For MacOS/Linux, this will be ~/.streamlit/config.toml . For Windows, this will be %userprofile%/.streamlit/config.toml . File format config.toml is a TOML file. Example [client] showErrorDetails = "none" [theme] primaryColor = "#F63366" backgroundColor = "black" Available configuration options Below are all the sections and options you can have in your .streamlit/config.toml file. To see all configurations, use the following command in your terminal or CLI: streamlit config show Global [global] # By default, Streamlit displays a warning when a user sets both a widget # default value in the function defining the widget and a widget value via # the widget's key in `st.session_state`. # If you'd like to turn off this warning, set this to True. # Default: false disableWidgetStateDuplicationWarning = false # If True, will show a warning when you run a Streamlit-enabled script # via "python my_script.py". # Default: true showWarningOnDirectExecution = true Logger [logger] # Level of logging for Streamlit's internal logger: "error", "warning", # "info", or "debug". # Default: "info" level = "info" # String format for logging messages. If logger.datetimeFormat is set, # logger messages will default to `%(asctime)s.%(msecs)03d %(message)s`. See # Python's documentation for available attributes: # https://docs.python.org/3/library/logging.html#formatter-objects # Default: "%(asctime)s %(message)s" messageFormat = "%(asctime)s %(message)s" Client [client] # Controls whether uncaught app exceptions and deprecation warnings # are displayed in the browser. This can be one of the following: # - "full" : In the browser, Streamlit displays app deprecation # warnings and exceptions, including exception types, # exception messages, and associated tracebacks. # - "stacktrace" : In the browser, Streamlit displays exceptions, # including exception types, generic exception messages, # and associated tracebacks. Deprecation warnings and # full exception messages will only print to the # console. # - "type" : In the browser, Streamlit displays exception types and # generic exception messages. Deprecation warnings, full # exception messages, and associated tracebacks only # print to the console. # - "none" : In the browser, Streamlit displays generic exception # messages. Deprecation warnings, full exception # messages, associated tracebacks, and exception types # will only print to the console. # - True : This is deprecated. Streamlit displays "full" # error details. # - False : This is deprecated. Streamlit displays "stacktrace" # error details. # Default: "full" showErrorDetails = "full" # Change the visibility of items in the toolbar, options menu, # and settings dialog (top right of the app). # Allowed values: # - "auto" : Show the developer options if the app is accessed through # localhost or through Streamlit Community Cloud as a developer. # Hide them otherwise. # - "developer" : Show the developer options. # - "viewer" : Hide the developer options. # - "minimal" : Show only options set externally (e.g. through # Streamlit Community Cloud) or through st.set_page_config. # If there are no options left, hide the menu. # Default: "auto" toolbarMode = "auto" # Controls whether to display the default sidebar page navigation in a # multi-page app. This only applies when app's pages are defined by the # `pages/` directory. # Default: true showSidebarNavigation = true Runner [runner] # Allows you to type a variable or string by itself in a single line of # Python code to write it to the app. # Default: true magicEnabled = true # Handle script rerun requests immediately, rather than waiting for script # execution to reach a yield point. This makes Streamlit much more # responsive to user interaction, but it can lead to race conditions in # apps that mutate session_state data outside of explicit session_state # assignment statements. # Default: true fastReruns = true # Raise an exception after adding unserializable data to Session State. # Some execution environments may require serializing all data in Session # State, so it may be useful to detect incompatibility during development, # or when the execution environment will stop supporting it in the future. # Default: false enforceSerializableSessionState = false # Adjust how certain 'options' widgets like radio, selectbox, and # multiselect coerce Enum members when the Enum class gets re-defined # during a script re-run. For more information, check out the docs: # https://docs.streamlit.io/develop/concepts/design/custom-classes#enums # Allowed values: # - "off" : Disables Enum coercion. # - "nameOnly" : Enum classes can be coerced if their member names match. # - "nameAndValue" : Enum classes can be coerced if their member names AND # member values match. # Default: "nameOnly" enumCoercion = "nameOnly" Server [server] # List of folders that should not be watched for changes. # Relative paths will be taken as relative to the current working directory. # Example: ['/home/user1/env', 'relative/path/to/folder'] # Default: [] folderWatchBlacklist = [] # Change the type of file watcher used by Streamlit, or turn it off # completely. # Allowed values: # - "auto" : Streamlit will attempt to use the watchdog module, and # falls back to polling if watchdog is not available. # - "watchdog" : Force Streamlit to use the watchdog module. # - "poll" : Force Streamlit to always use polling. # - "none" : Streamlit will not watch files. # Default: "auto" fileWatcherType = "auto" # Symmetric key used to produce signed cookies. If deploying on multiple # replicas, this should be set to the same value across all replicas to ensure # they all share the same secret. # Default: randomly generated secret key. cookieSecret = "a-random-key-appears-here" # If false, will attempt to open a browser window on start. # Default: false unless (1) we are on a Linux box where DISPLAY is unset, or # (2) we are running in the Streamlit Atom plugin. headless = false # Automatically rerun script when the file is modified on disk. # Default: false runOnSave = false # The address where the server will listen for client and browser # connections. Use this if you want to bind the server to a specific address. # If set, the server will only be accessible from this address, and not from # any aliases (like localhost). # Default: (unset) address = # The port where the server will listen for browser connections. # Don't use port 3000 which is reserved for internal development. # Default: 8501 port = 8501 # The base path for the URL where Streamlit should be served from. # Default: "" baseUrlPath = "" # Enables support for Cross-Origin Resource Sharing (CORS) protection, # for added security. # If XSRF protection is enabled and CORS protection is disabled at the # same time, Streamlit will enable them both instead. # Default: true enableCORS = true # Enables support for Cross-Site Request Forgery (XSRF) protection, for # added security. # If XSRF protection is enabled and CORS protection is disabled at the # same time, Streamlit will enable them both instead. # Default: true enableXsrfProtection = true # Max size, in megabytes, for files uploaded with the file_uploader. # Default: 200 maxUploadSize = 200 # Max size, in megabytes, of messages that can be sent via the WebSocket # connection. # Default: 200 maxMessageSize = 200 # Enables support for websocket compression. # Default: false enableWebsocketCompression = false # Enable serving files from a `static` directory in the running app's # directory. # Default: false enableStaticServing = false # TTL in seconds for sessions whose websockets have been disconnected. The server # may choose to clean up session state, uploaded files, etc for a given session # with no active websocket connection at any point after this time has passed. # Default: 120 disconnectedSessionTTL = 120 # Server certificate file for connecting via HTTPS. # Must be set at the same time as "server.sslKeyFile". # ['DO NOT USE THIS OPTION IN A PRODUCTION ENVIRONMENT. It has not gone through # security audits or performance tests. For the production environment, we # recommend performing SSL termination by the load balancer or the reverse # proxy.'] sslCertFile = # Cryptographic key file for connecting via HTTPS. # Must be set at the same time as "server.sslCertFile". # ['DO NOT USE THIS OPTION IN A PRODUCTION ENVIRONMENT. It has not gone through # security audits or performance tests. For the production environment, we # recommend performing SSL termination by the load balancer or the reverse # proxy.'] sslKeyFile = Browser [browser] # Internet address where users should point their browsers in order to # connect to the app. Can be IP address or DNS name and path. # This is used to: # - Set the correct URL for CORS and XSRF protection purposes. # - Show the URL on the terminal # - Open the browser # Default: "localhost" serverAddress = "localhost" # Whether to send usage statistics to Streamlit. # Default: true gatherUsageStats = true # Port where users should point their browsers in order to connect to the # app. # This is used to: # - Set the correct URL for XSRF protection purposes. # - Show the URL on the terminal (part of `streamlit run`). # - Open the browser automatically (part of `streamlit run`). # This option is for advanced use cases. To change the port of your app, use # `server.Port` instead. Don't use port 3000 which is reserved for internal # development. # Default: whatever value is set in server.port. serverPort = 8501 Mapbox [mapbox] # Configure Streamlit to use a custom Mapbox # token for elements like st.pydeck_chart and st.map. # To get a token for yourself, create an account at # https://mapbox.com. It's free (for moderate usage levels)! # Default: "" token = "" Theme [theme] # The preset Streamlit theme that your custom theme inherits from. # One of "light" or "dark". base = # Primary accent color for interactive elements. primaryColor = # Background color for the main content area. backgroundColor = # Background color used for the sidebar and most interactive widgets. secondaryBackgroundColor = # Color used for almost all text. textColor = # Font family for all text in the app, except code blocks. One of "sans serif", # "serif", or "monospace". font = Secrets [secrets] # List of locations where secrets are searched. An entry can be a path to a # TOML file or directory path where Kubernetes style secrets are saved. # Order is important, import is first to last, so secrets in later files # will take precedence over earlier ones. # Default: [ <path to local environment's secrets.toml file>, <path to project's secrets.toml file>,] files = [ "~/.streamlit/secrets.toml", "~/project directory/.streamlit/secrets.toml",] Previous: Configuration Next: st.get_option forum Still have questions? Our forums are full of helpful information and Streamlit experts. Home Contact Us Community © 2025 Snowflake Inc. Cookie policy forum Ask AI |
Trigger_a_full_script_rerun_from_inside_a_fragment.txt | Trigger a full-script rerun from inside a fragment - Streamlit Docs Documentation search Search rocket_launch Get started Installation add Fundamentals add First steps add code Develop Concepts add API reference add Tutorials remove Elements add Execution flow remove FRAGMENTS Rerun your app from a fragment Create a multiple-container fragment Start and stop a streaming fragment Connect to data sources add Multipage apps add Work with LLMs add Quick reference add web_asset Deploy Concepts add Streamlit Community Cloud add Snowflake Other platforms add school Knowledge base FAQ Installing dependencies Deployment issues Home / Develop / Tutorials / Execution flow / Rerun your app from a fragment Trigger a full-script rerun from inside a fragment Streamlit lets you turn functions into fragments , which can rerun independently from the full script. When a user interacts with a widget inside a fragment, only the fragment reruns. Sometimes, you may want to trigger a full-script rerun from inside a fragment. To do this, call st.rerun inside the fragment. Applied concepts Use a fragment to rerun part or all of your app, depending on user input. Prerequisites The following must be installed in your Python environment: streamlit>=1.37.0 You should have a clean working directory called your-repository . You should have a basic understanding of fragments and st.rerun . Summary In this example, you'll build an app to display sales data. The app has two sets of elements that depend on a date selection. One set of elements displays information for the selected day. The other set of elements displays information for the associated month. If the user changes days within a month, Streamlit only needs to update the first set of elements. If the user selects a day in a different month, Streamlit needs to update all the elements. You'll collect the day-specific elements into a fragment to avoid rerunning the full app when a user changes days within the same month. If you want to jump ahead to the fragment function definition, see Build a function to show daily sales data . Here's a look at what you'll build: Complete code expand_more import streamlit as st import pandas as pd import numpy as np from datetime import date, timedelta import string import time @st.cache_data def get_data(): """Generate random sales data for Widget A through Widget Z""" product_names = ["Widget " + letter for letter in string.ascii_uppercase] average_daily_sales = np.random.normal(1_000, 300, len(product_names)) products = dict(zip(product_names, average_daily_sales)) data = pd.DataFrame({}) sales_dates = np.arange(date(2023, 1, 1), date(2024, 1, 1), timedelta(days=1)) for product, sales in products.items(): data[product] = np.random.normal(sales, 300, len(sales_dates)).round(2) data.index = sales_dates data.index = data.index.date return data @st.fragment def show_daily_sales(data): time.sleep(1) with st.container(height=100): selected_date = st.date_input( "Pick a day ", value=date(2023, 1, 1), min_value=date(2023, 1, 1), max_value=date(2023, 12, 31), key="selected_date", ) if "previous_date" not in st.session_state: st.session_state.previous_date = selected_date previous_date = st.session_state.previous_date st.session_state.previous_date = selected_date is_new_month = selected_date.replace(day=1) != previous_date.replace(day=1) if is_new_month: st.rerun() with st.container(height=510): st.header(f"Best sellers, {selected_date:%m/%d/%y}") top_ten = data.loc[selected_date].sort_values(ascending=False)[0:10] cols = st.columns([1, 4]) cols[0].dataframe(top_ten) cols[1].bar_chart(top_ten) with st.container(height=510): st.header(f"Worst sellers, {selected_date:%m/%d/%y}") bottom_ten = data.loc[selected_date].sort_values()[0:10] cols = st.columns([1, 4]) cols[0].dataframe(bottom_ten) cols[1].bar_chart(bottom_ten) def show_monthly_sales(data): time.sleep(1) selected_date = st.session_state.selected_date this_month = selected_date.replace(day=1) next_month = (selected_date.replace(day=28) + timedelta(days=4)).replace(day=1) st.container(height=100, border=False) with st.container(height=510): st.header(f"Daily sales for all products, {this_month:%B %Y}") monthly_sales = data[(data.index < next_month) & (data.index >= this_month)] st.write(monthly_sales) with st.container(height=510): st.header(f"Total sales for all products, {this_month:%B %Y}") st.bar_chart(monthly_sales.sum()) st.set_page_config(layout="wide") st.title("Daily vs monthly sales, by product") st.markdown("This app shows the 2023 daily sales for Widget A through Widget Z.") data = get_data() daily, monthly = st.columns(2) with daily: show_daily_sales(data) with monthly: show_monthly_sales(data) Click here to see the example live on Community Cloud. 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 date, timedelta import string import time You'll be using these libraries as follows: You'll work with sales data in a pandas.DataFrame . You'll generate random sales numbers with numpy . The data will have datetime.date index values. The products sold will be "Widget A" through "Widget Z," so you'll use string for easy access to an alphabetical string. Optional: To help add emphasis at the end, you'll use time.sleep() to slow things down and see the fragment 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. Build a function to create random sales data To begin with, you'll define a function to randomly generate some sales data. It's okay to skip this section if you just want to copy the function. Complete function to randomly generate sales data expand_more @st.cache_data def get_data(): """Generate random sales data for Widget A through Widget Z""" product_names = ["Widget " + letter for letter in string.ascii_uppercase] average_daily_sales = np.random.normal(1_000, 300, len(product_names)) products = dict(zip(product_names, average_daily_sales)) data = pd.DataFrame({}) sales_dates = np.arange(date(2023, 1, 1), date(2024, 1, 1), timedelta(days=1)) for product, sales in products.items(): data[product] = np.random.normal(sales, 300, len(sales_dates)).round(2) data.index = sales_dates data.index = data.index.date return data Use an @st.cache_data decorator and start your function definition. @st.cache_data def get_data(): """Generate random sales data for Widget A through Widget Z""" You don't need to keep re-randomizing the data, so the caching decorator will randomly generate the data once and save it in Streamlit's cache. As your app reruns, it will use the cached value instead of recomputing new data. Define the list of product names and assign an average daily sales value to each. product_names = ["Widget " + letter for letter in string.ascii_uppercase] average_daily_sales = np.random.normal(1_000, 300, len(product_names)) products = dict(zip(product_names, average_daily_sales)) For each product, use its average daily sales to randomly generate daily sales values for an entire year. data = pd.DataFrame({}) sales_dates = np.arange(date(2023, 1, 1), date(2024, 1, 1), timedelta(days=1)) for product, sales in products.items(): data[product] = np.random.normal(sales, 300, len(sales_dates)).round(2) data.index = sales_dates data.index = data.index.date In the last line, data.index.date strips away the timestamp, so the index will show clean dates. Return the random sales data. return data Optional: Test out your function by calling it and displaying the data. data = get_data() data Save your app.py file to see the preview. Delete these two lines or keep them at the end of your app to be updated as you continue. Build a function to show daily sales data Since the daily sales data updates with every new date selection, you'll turn this function into a fragment. As a fragment, it can rerun independently from the rest of your app. You'll include an st.date_input widget inside this fragment and watch for a date selection that changes the month. When the fragment detects a change in the selected month, it will trigger a full app rerun so everything can update. Complete function to display daily sales data expand_more @st.fragment def show_daily_sales(data): time.sleep(1) selected_date = st.date_input( "Pick a day ", value=date(2023, 1, 1), min_value=date(2023, 1, 1), max_value=date(2023, 12, 31), key="selected_date", ) if "previous_date" not in st.session_state: st.session_state.previous_date = selected_date previous_date = st.session_state.previous_date st.session_state.previous_date = selected_date is_new_month = selected_date.replace(day=1) != previous_date.replace(day=1) if is_new_month: st.rerun() st.header(f"Best sellers, {selected_date:%m/%d/%y}") top_ten = data.loc[selected_date].sort_values(ascending=False)[0:10] cols = st.columns([1, 4]) cols[0].dataframe(top_ten) cols[1].bar_chart(top_ten) st.header(f"Worst sellers, {selected_date:%m/%d/%y}") bottom_ten = data.loc[selected_date].sort_values()[0:10] cols = st.columns([1, 4]) cols[0].dataframe(bottom_ten) cols[1].bar_chart(bottom_ten) Use an @st.fragment decorator and start your function definition. @st.fragment def show_daily_sales(data): Since your data will not change during a fragment rerun, you can pass the data into the fragment as an argument. Optional: Add time.sleep(1) to slow down the function and show off how the fragment works. time.sleep(1) Add an st.date_input widget. selected_date = st.date_input( "Pick a day ", value=date(2023, 1, 1), min_value=date(2023, 1, 1), max_value=date(2023, 12, 31), key="selected_date", ) Your random data is for 2023, so set the minimun and maximum dates to match. Use a key for the widget because elements outside the fragment will need this date value. When working with a fragment, it's best to use Session State to pass information in and out of the fragment. Initialize "previous_date" in Session State to compare each date selection. if "previous_date" not in st.session_state: st.session_state.previous_date = selected_date Save the previous date selection into a new variable and update "previous_date" in Session State. previous_date = st.session_state.previous_date st.session_state.previous_date = selected_date Call st.rerun() if the month changed. is_new_month = selected_date.replace(day=1) != previous_date.replace(day=1) if is_new_month: st.rerun() Show the best sellers from the selected date. st.header(f"Best sellers, {selected_date:%m/%d/%y}") top_ten = data.loc[selected_date].sort_values(ascending=False)[0:10] cols = st.columns([1, 4]) cols[0].dataframe(top_ten) cols[1].bar_chart(top_ten) Show the worst sellers from the selected date. st.header(f"Worst sellers, {selected_date:%m/%d/%y}") bottom_ten = data.loc[selected_date].sort_values()[0:10] cols = st.columns([1, 4]) cols[0].dataframe(bottom_ten) cols[1].bar_chart(bottom_ten) Optional: Test out your function by calling it and displaying the data. data = get_data() show_daily_sales(data) Save your app.py file to see the preview. Delete these two lines or keep them at the end of your app to be updated as you continue. Build a function to show monthly sales data Finally, let's build a function to display monthly sales data. It will be similar to your show_daily_sales function but doesn't need to be fragment. You only need to rerun this function when the whole app is rerunning. Complete function to display daily sales data expand_more def show_monthly_sales(data): time.sleep(1) selected_date = st.session_state.selected_date this_month = selected_date.replace(day=1) next_month = (selected_date.replace(day=28) + timedelta(days=4)).replace(day=1) st.header(f"Daily sales for all products, {this_month:%B %Y}") monthly_sales = data[(data.index < next_month) & (data.index >= this_month)] st.write(monthly_sales) st.header(f"Total sales for all products, {this_month:%B %Y}") st.bar_chart(monthly_sales.sum()) Start your function definition. def show_monthly_sales(data): Optional: Add time.sleep(1) to slow down the function and show off how the fragment works. time.sleep(1) Get the selected date from Session State and compute the first days of this and next month. selected_date = st.session_state.selected_date this_month = selected_date.replace(day=1) next_month = (selected_date.replace(day=28) + timedelta(days=4)).replace(day=1) Show the daily sales values for all products within the selected month. st.header(f"Daily sales for all products, {this_month:%B %Y}") monthly_sales = data[(data.index < next_month) & (data.index >= this_month)] st.write(monthly_sales) Show the total sales of each product within the selected month. st.header(f"Total sales for all products, {this_month:%B %Y}") st.bar_chart(monthly_sales.sum()) Optional: Test out your function by calling it and displaying the data. data = get_data() show_daily_sales(data) show_monthly_sales(data) Save your app.py file to see the preview. Delete these three lines when finished. Put the functions together together to create an app Let's show these elements side-by-side. You'll display the daily data on the left and the monthly data on the right. If you added optional lines at the end of your code to test your functions, clear them out now. Give your app a wide layout. st.set_page_config(layout="wide") Get your data. data = get_data() Add a title and description for your app. st.title("Daily vs monthly sales, by product") st.markdown("This app shows the 2023 daily sales for Widget A through Widget Z.") Create columns and call the functions to display data. daily, monthly = st.columns(2) with daily: show_daily_sales(data) with monthly: show_monthly_sales(data) Make it pretty Now, you have a functioning app that uses a fragment to prevent unnecessarily redrawing the monthly data. However, things aren't aligned on the page, so you can insert a few containers to make it pretty. Add three containers into each of the display functions. Add three containers to fix the height of elements in the show_daily_sales function. @st.fragment def show_daily_sales(data): time.sleep(1) with st.container(height=100): ### ADD CONTAINER ### selected_date = st.date_input( "Pick a day ", value=date(2023, 1, 1), min_value=date(2023, 1, 1), max_value=date(2023, 12, 31), key="selected_date", ) if "previous_date" not in st.session_state: st.session_state.previous_date = selected_date previous_date = st.session_state.previous_date previous_date = st.session_state.previous_date st.session_state.previous_date = selected_date is_new_month = selected_date.replace(day=1) != previous_date.replace(day=1) if is_new_month: st.rerun() with st.container(height=510): ### ADD CONTAINER ### st.header(f"Best sellers, {selected_date:%m/%d/%y}") top_ten = data.loc[selected_date].sort_values(ascending=False)[0:10] cols = st.columns([1, 4]) cols[0].dataframe(top_ten) cols[1].bar_chart(top_ten) with st.container(height=510): ### ADD CONTAINER ### st.header(f"Worst sellers, {selected_date:%m/%d/%y}") bottom_ten = data.loc[selected_date].sort_values()[0:10] cols = st.columns([1, 4]) cols[0].dataframe(bottom_ten) cols[1].bar_chart(bottom_ten) Add three containers to fix the height of elements in the show_monthly_sales function. def show_monthly_sales(data): time.sleep(1) selected_date = st.session_state.selected_date this_month = selected_date.replace(day=1) next_month = (selected_date.replace(day=28) + timedelta(days=4)).replace(day=1) st.container(height=100, border=False) ### ADD CONTAINER ### with st.container(height=510): ### ADD CONTAINER ### st.header(f"Daily sales for all products, {this_month:%B %Y}") monthly_sales = data[(data.index < next_month) & (data.index >= this_month)] st.write(monthly_sales) with st.container(height=510): ### ADD CONTAINER ### st.header(f"Total sales for all products, {this_month:%B %Y}") st.bar_chart(monthly_sales.sum()) The first container creates space to coordinate with the input widget in the show_daily_sales function. Next steps Continue beautifying the example. Try using st.plotly_chart or st.altair_chart to add labels to your charts and adjust their height. Previous: Execution flow Next: Create a multiple-container fragment forum Still have questions? Our forums are full of helpful information and Streamlit experts. Home Contact Us Community © 2025 Snowflake Inc. Cookie policy forum Ask AI |
st.context_-_Streamlit_Docs.txt | st.context - Streamlit Docs Documentation search Search rocket_launch Get started Installation add Fundamentals add First steps add code Develop Concepts add API reference remove PAGE ELEMENTS Write and magic add Text elements add Data elements add Chart elements add Input widgets add Media elements add Layouts and containers add Chat elements add Status elements add Third-party components open_in_new APPLICATION LOGIC Navigation and pages add Execution flow add Caching and state add Connections and secrets add Custom components add Utilities remove st.context st.experimental_user st.help st.html Configuration add TOOLS App testing add Command line add Tutorials add Quick reference add web_asset Deploy Concepts add Streamlit Community Cloud add Snowflake Other platforms add school Knowledge base FAQ Installing dependencies Deployment issues Home / Develop / API reference / Utilities / st.context st.context Streamlit Version Version 1.41.0 Version 1.40.0 Version 1.39.0 Version 1.38.0 Version 1.37.0 Version 1.36.0 Version 1.35.0 Version 1.34.0 Version 1.33.0 Version 1.32.0 Version 1.31.0 Version 1.30.0 Version 1.29.0 Version 1.28.0 Version 1.27.0 Version 1.26.0 Version 1.25.0 Version 1.24.0 Version 1.23.0 Version 1.22.0 Version 1.21.0 Version 1.20.0 Streamlit in Snowflake An interface to access user session context. st.context provides a read-only interface to access headers and cookies for the current user session. Each property ( st.context.headers and st.context.cookies ) returns a dictionary of named values. Class description [source] st.context() Attributes cookies A read-only, dict-like object containing cookies sent in the initial request. headers A read-only, dict-like object containing headers sent in the initial request. context.cookies Streamlit Version Version 1.41.0 Version 1.40.0 Version 1.39.0 Version 1.38.0 Version 1.37.0 Version 1.36.0 Version 1.35.0 Version 1.34.0 Version 1.33.0 Version 1.32.0 Version 1.31.0 Version 1.30.0 Version 1.29.0 Version 1.28.0 Version 1.27.0 Version 1.26.0 Version 1.25.0 Version 1.24.0 Version 1.23.0 Version 1.22.0 Version 1.21.0 Version 1.20.0 Streamlit in Snowflake A read-only, dict-like object containing cookies sent in the initial request. Function signature [source] context.cookies Examples Show a dictionary of cookies: import streamlit as st st.context.cookies Show the value of a specific cookie: import streamlit as st st.context.cookies["_ga"] context.headers Streamlit Version Version 1.41.0 Version 1.40.0 Version 1.39.0 Version 1.38.0 Version 1.37.0 Version 1.36.0 Version 1.35.0 Version 1.34.0 Version 1.33.0 Version 1.32.0 Version 1.31.0 Version 1.30.0 Version 1.29.0 Version 1.28.0 Version 1.27.0 Version 1.26.0 Version 1.25.0 Version 1.24.0 Version 1.23.0 Version 1.22.0 Version 1.21.0 Version 1.20.0 Streamlit in Snowflake A read-only, dict-like object containing headers sent in the initial request. Keys are case-insensitive and may be repeated. When keys are repeated, dict-like methods will only return the last instance of each key. Use .get_all(key="your_repeated_key") to see all values if the same header is set multiple times. Function signature [source] context.headers Examples Show a dictionary of headers (with only the last instance of any repeated key): import streamlit as st st.context.headers Show the value of a specific header (or the last instance if it's repeated): import streamlit as st st.context.headers["host"] Show of list of all headers for a given key: import streamlit as st st.context.headers.get_all("pragma") Previous: Utilities Next: st.experimental_user forum Still have questions? Our forums are full of helpful information and Streamlit experts. Home Contact Us Community © 2025 Snowflake Inc. Cookie policy forum Ask AI |
Connect_Streamlit_to_Google_Cloud_Storage___Stream.txt | Connect Streamlit to Google Cloud Storage - Streamlit Docs Documentation search Search rocket_launch Get started Installation add Fundamentals add First steps add code Develop Concepts add API reference add Tutorials remove Elements add Execution flow add Connect to data sources remove AWS S3 BigQuery Firestore open_in_new Google Cloud Storage Microsoft SQL Server MongoDB MySQL Neon PostgreSQL Private Google Sheet Public Google Sheet Snowflake Supabase Tableau TiDB TigerGraph Multipage apps add Work with LLMs add Quick reference add web_asset Deploy Concepts add Streamlit Community Cloud add Snowflake Other platforms add school Knowledge base FAQ Installing dependencies Deployment issues Home / Develop / Tutorials / Connect to data sources / Google Cloud Storage Connect 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_pin Note If 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_pin Note If 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_high Important 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 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: Firestore Next: Microsoft SQL Server forum Still have questions? Our forums are full of helpful information and Streamlit experts. Home Contact Us Community © 2025 Snowflake Inc. Cookie policy forum Ask AI |
Connections_and_databases_-_Streamlit_Docs.txt | Connections and databases - Streamlit Docs Documentation search Search rocket_launch Get started Installation add Fundamentals add First steps add code Develop Concepts add API reference remove PAGE ELEMENTS Write and magic add Text elements add Data elements add Chart elements add Input widgets add Media elements add Layouts and containers add Chat elements add Status elements add Third-party components open_in_new APPLICATION LOGIC Navigation and pages add Execution flow add Caching and state add Connections and secrets remove SECRETS st.secrets secrets.toml CONNECTIONS st.connection SnowflakeConnection SQLConnection BaseConnection SnowparkConnection delete Custom components add Utilities add Configuration add TOOLS App testing add Command line add Tutorials add Quick reference add web_asset Deploy Concepts add Streamlit Community Cloud add Snowflake Other platforms add school Knowledge base FAQ Installing dependencies Deployment issues Home / Develop / API reference / Connections and secrets Connections and databases Setup your connection Create a connection Connect to a data source or API conn = st.connection('pets_db', type='sql') pet_owners = conn.query('select * from pet_owners') st.dataframe(pet_owners) Built-in connections SnowflakeConnection A connection to Snowflake. conn = st.connection('snowflake') SQLConnection A connection to a SQL database using SQLAlchemy. conn = st.connection('sql') Third-party connections Connection base class Build 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 Secrets singleton Access secrets from a local TOML file. key = st.secrets["OpenAI_key"] Secrets file Save your secrets in a per-project or per-profile TOML file. OpenAI_key = "<YOUR_SECRET_KEY>" Deprecated classes delete SnowparkConnection A connection to Snowflake. conn = st.connection("snowpark") Previous: Caching and state Next: st.secrets forum Still have questions? Our forums are full of helpful information and Streamlit experts. Home Contact Us Community © 2025 Snowflake Inc. Cookie policy forum Ask AI |
st.time_input_-_Streamlit_Docs.txt | st.time_input - Streamlit Docs Documentation search Search rocket_launch Get started Installation add Fundamentals add First steps add code Develop Concepts add API reference remove PAGE ELEMENTS Write and magic add Text elements add Data elements add Chart elements add Input widgets remove BUTTONS st.button st.download_button st.form_submit_button link st.link_button st.page_link SELECTIONS st.checkbox st.color_picker st.feedback st.multiselect st.pills st.radio st.segmented_control st.selectbox st.select_slider st.toggle NUMERIC st.number_input st.slider DATE & TIME st.date_input st.time_input TEXT st.chat_input link st.text_area st.text_input MEDIA & FILES st.audio_input st.camera_input st.data_editor link st.file_uploader Media elements add Layouts and containers add Chat elements add Status elements add Third-party components open_in_new APPLICATION LOGIC Navigation and pages add Execution flow add Caching and state add Connections and secrets add Custom components add Utilities add Configuration add TOOLS App testing add Command line add Tutorials add Quick reference add web_asset Deploy Concepts add Streamlit Community Cloud add Snowflake Other platforms add school Knowledge base FAQ Installing dependencies Deployment issues Home / Develop / API reference / Input widgets / st.time_input st.time_input Streamlit Version Version 1.41.0 Version 1.40.0 Version 1.39.0 Version 1.38.0 Version 1.37.0 Version 1.36.0 Version 1.35.0 Version 1.34.0 Version 1.33.0 Version 1.32.0 Version 1.31.0 Version 1.30.0 Version 1.29.0 Version 1.28.0 Version 1.27.0 Version 1.26.0 Version 1.25.0 Version 1.24.0 Version 1.23.0 Version 1.22.0 Version 1.21.0 Version 1.20.0 Streamlit in Snowflake Display a time input widget. Function signature [source] st.time_input(label, value="now", key=None, help=None, on_change=None, args=None, kwargs=None, *, disabled=False, label_visibility="visible", step=0:15:00) Parameters label (str) A short label explaining to the user what this time input is for. The label can optionally contain GitHub-flavored Markdown of the following types: Bold, Italics, Strikethroughs, Inline Code, Links, and Images. Images display like icons, with a max height equal to the font height. Unsupported Markdown elements are unwrapped so only their children (text contents) render. Display unsupported elements as literal characters by backslash-escaping them. E.g., "1\. Not an ordered list" . See the body parameter of st.markdown for additional, supported Markdown directives. For accessibility reasons, you should never set an empty label, but you can hide it with label_visibility if needed. In the future, we may disallow empty labels by raising an exception. value ("now", datetime.time, datetime.datetime, str, or None) The value of this widget when it first renders. This can be one of the following: "now" (default): The widget initializes with the current time. A datetime.time or datetime.datetime object: The widget initializes with the given time, ignoring any date if included. An ISO-formatted time ("hh:mm", "hh:mm:ss", or "hh:mm:ss.sss") or datetime ("YYYY-MM-DD hh:mm:ss") string: The widget initializes with the given time, ignoring any date if included. None : The widget initializes with no time and returns None until the user selects a time. key (str or int) An optional string or integer to use as the unique key for the widget. If this is omitted, a key will be generated for the widget based on its content. No two widgets may have the same key. help (str) An optional tooltip that gets displayed next to the widget label. Streamlit only displays the tooltip when label_visibility="visible" . on_change (callable) An optional callback invoked when this time_input's value changes. args (tuple) An optional tuple of args to pass to the callback. kwargs (dict) An optional dict of kwargs to pass to the callback. disabled (bool) An optional boolean that disables the time input if set to True . The default is False . label_visibility ("visible", "hidden", or "collapsed") The visibility of the label. The default is "visible" . If this is "hidden" , Streamlit displays an empty spacer instead of the label, which can help keep the widget alligned with other widgets. If this is "collapsed" , Streamlit displays no label or spacer. step (int or timedelta) The stepping interval in seconds. Defaults to 900, i.e. 15 minutes. You can also pass a datetime.timedelta object. Returns (datetime.time or None) The current value of the time input widget or None if no time has been selected. Example import datetime import streamlit as st t = st.time_input("Set an alarm for", datetime.time(8, 45)) st.write("Alarm is set for", t) Built with Streamlit 🎈 Fullscreen open_in_new To initialize an empty time input, use None as the value: import datetime import streamlit as st t = st.time_input("Set an alarm for", value=None) st.write("Alarm is set for", t) Built with Streamlit 🎈 Fullscreen open_in_new Previous: st.date_input Next: st.chat_input forum Still have questions? Our forums are full of helpful information and Streamlit experts. Home Contact Us Community © 2025 Snowflake Inc. Cookie policy forum Ask AI |
Connect_Streamlit_to_PostgreSQL___Streamlit_Docs_1.txt | Connect Streamlit to PostgreSQL - Streamlit Docs Documentation search Search rocket_launch Get started Installation add Fundamentals add First steps add code Develop Concepts add API reference add Tutorials remove Elements add Execution flow add Connect to data sources remove AWS S3 BigQuery Firestore open_in_new Google Cloud Storage Microsoft SQL Server MongoDB MySQL Neon PostgreSQL Private Google Sheet Public Google Sheet Snowflake Supabase Tableau TiDB TigerGraph Multipage apps add Work with LLMs add Quick reference add web_asset Deploy Concepts add Streamlit Community Cloud add Snowflake Other platforms add school Knowledge base FAQ Installing dependencies Deployment issues Home / Develop / Tutorials / Connect to data sources / PostgreSQL Connect Streamlit to PostgreSQL Introduction This guide explains how to securely access a remote PostgreSQL database from Streamlit Community Cloud. It uses st.connection and Streamlit's Secrets management . The below example code will only work on Streamlit version >= 1.28 , when st.connection was added. Create a PostgreSQL database push_pin Note If you already have a database that you want to use, feel free to skip to the next step . First, follow this tutorial to install PostgreSQL and create a database (note down the database name, username, and password!). Open the SQL Shell ( psql ) and enter the following two commands to create a table with some example values: CREATE TABLE mytable ( name varchar(80), pet varchar(80) ); INSERT INTO mytable VALUES ('Mary', 'dog'), ('John', 'cat'), ('Robert', 'bird'); Add username and password to your local app secrets Your local Streamlit app will read secrets from a file .streamlit/secrets.toml in your app's root directory. Create this file if it doesn't exist yet and add the name, user, and password of your database as shown below: # .streamlit/secrets.toml [connections.postgresql] dialect = "postgresql" host = "localhost" port = "5432" database = "xxx" username = "xxx" password = "xxx" priority_high Important When copying your app secrets to Streamlit Community Cloud, be sure to replace the values of host , port , database , username , and password with those of your remote PostgreSQL database! Add this file to .gitignore and don't commit it to your GitHub repo! Copy your app secrets to the cloud As the secrets.toml file above is not committed to GitHub, you need to pass its content to your deployed app (on Streamlit Community Cloud) separately. Go to the app dashboard and in the app's dropdown menu, click on Edit Secrets . Copy the content of secrets.toml into the text area. More information is available at Secrets management . Add dependencies to your requirements file Add the psycopg2-binary and SQLAlchemy packages to your requirements.txt file, preferably pinning its version (replace x.x.x with the version you want installed): # requirements.txt psycopg2-binary==x.x.x sqlalchemy==x.x.x Write your Streamlit app Copy the code below to your Streamlit app and run it. Make sure to adapt query to use the name of your table. # streamlit_app.py import streamlit as st # Initialize connection. conn = st.connection("postgresql", type="sql") # Perform query. df = conn.query('SELECT * FROM mytable;', ttl="10m") # Print results. for row in df.itertuples(): st.write(f"{row.name} has a :{row.pet}:") See st.connection above? This handles secrets retrieval, setup, query caching and retries. By default, query() results are cached without expiring. In this case, we set ttl="10m" to ensure the query result is cached for no longer than 10 minutes. You can also set ttl=0 to disable caching. Learn more in Caching . If everything worked out (and you used the example table we created above), your app should look like this: Previous: Neon Next: Private Google Sheet forum Still have questions? Our forums are full of helpful information and Streamlit experts. Home Contact Us Community © 2025 Snowflake Inc. Cookie policy forum Ask AI |
st.success_-_Streamlit_Docs.txt | st.success - Streamlit Docs Documentation search Search rocket_launch Get started Installation add Fundamentals add First steps add code Develop Concepts add API reference remove PAGE ELEMENTS Write and magic add Text elements add Data elements add Chart elements add Input widgets add Media elements add Layouts and containers add Chat elements add Status elements remove CALLOUTS st.success st.info st.warning st.error st.exception OTHER st.progress st.spinner st.status st.toast st.balloons st.snow Third-party components open_in_new APPLICATION LOGIC Navigation and pages add Execution flow add Caching and state add Connections and secrets add Custom components add Utilities add Configuration add TOOLS App testing add Command line add Tutorials add Quick reference add web_asset Deploy Concepts add Streamlit Community Cloud add Snowflake Other platforms add school Knowledge base FAQ Installing dependencies Deployment issues Home / Develop / API reference / Status elements / st.success st.success Streamlit Version Version 1.41.0 Version 1.40.0 Version 1.39.0 Version 1.38.0 Version 1.37.0 Version 1.36.0 Version 1.35.0 Version 1.34.0 Version 1.33.0 Version 1.32.0 Version 1.31.0 Version 1.30.0 Version 1.29.0 Version 1.28.0 Version 1.27.0 Version 1.26.0 Version 1.25.0 Version 1.24.0 Version 1.23.0 Version 1.22.0 Version 1.21.0 Version 1.20.0 Streamlit in Snowflake Display a success message. Function signature [source] st.success(body, *, icon=None) Parameters body (str) The success 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 (rounded 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.success('This is a success message!', icon="✅") Previous: Status elements Next: st.info forum Still have questions? Our forums are full of helpful information and Streamlit experts. Home Contact Us Community © 2025 Snowflake Inc. Cookie policy forum Ask AI |
st.toast_-_Streamlit_Docs.txt | st.toast - Streamlit Docs Documentation search Search rocket_launch Get started Installation add Fundamentals add First steps add code Develop Concepts add API reference remove PAGE ELEMENTS Write and magic add Text elements add Data elements add Chart elements add Input widgets add Media elements add Layouts and containers add Chat elements add Status elements remove CALLOUTS st.success st.info st.warning st.error st.exception OTHER st.progress st.spinner st.status st.toast st.balloons st.snow Third-party components open_in_new APPLICATION LOGIC Navigation and pages add Execution flow add Caching and state add Connections and secrets add Custom components add Utilities add Configuration add TOOLS App testing add Command line add Tutorials add Quick reference add web_asset Deploy Concepts add Streamlit Community Cloud add Snowflake Other platforms add school Knowledge base FAQ Installing dependencies Deployment issues Home / Develop / API reference / Status elements / st.toast st.toast Streamlit Version Version 1.41.0 Version 1.40.0 Version 1.39.0 Version 1.38.0 Version 1.37.0 Version 1.36.0 Version 1.35.0 Version 1.34.0 Version 1.33.0 Version 1.32.0 Version 1.31.0 Version 1.30.0 Version 1.29.0 Version 1.28.0 Version 1.27.0 Version 1.26.0 Version 1.25.0 Version 1.24.0 Version 1.23.0 Version 1.22.0 Version 1.21.0 Version 1.20.0 Streamlit in Snowflake Display a short message, known as a notification "toast". The toast appears in the app's bottom-right corner and disappears after four seconds. Warning st.toast is not compatible with Streamlit's caching and cannot be called within a cached function. Function signature [source] st.toast(body, *, icon=None) Parameters body (str) The string to display as GitHub-flavored Markdown. Syntax information can be found at: https://github.github.com/gfm . See the body parameter of st.markdown for additional, supported Markdown directives. 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 (rounded 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.toast('Your edited image was saved!', icon='😍') When multiple toasts are generated, they will stack. Hovering over a toast will stop it from disappearing. When hovering ends, the toast will disappear after four more seconds. import streamlit as st import time if st.button('Three cheers'): st.toast('Hip!') time.sleep(.5) st.toast('Hip!') time.sleep(.5) st.toast('Hooray!', icon='🎉') Built with Streamlit 🎈 Fullscreen open_in_new Toast messages can also be updated. Assign st.toast(my_message) to a variable and use the .toast() method to update it. Note: if a toast has already disappeared or been dismissed, the update will not be seen. import streamlit as st import time def cook_breakfast(): msg = st.toast('Gathering ingredients...') time.sleep(1) msg.toast('Cooking...') time.sleep(1) msg.toast('Ready!', icon = "🥞") if st.button('Cook breakfast'): cook_breakfast() Built with Streamlit 🎈 Fullscreen open_in_new Previous: st.status Next: st.balloons forum Still have questions? Our forums are full of helpful information and Streamlit experts. Home Contact Us Community © 2025 Snowflake Inc. Cookie policy forum Ask AI |
Additional_Streamlit_features_-_Streamlit_Docs.txt | Additional Streamlit features - Streamlit Docs Documentation search Search rocket_launch Get started Installation add Fundamentals remove Basic concepts Advanced concepts Additional features Summary First steps add code Develop Concepts add API reference add Tutorials add Quick reference add web_asset Deploy Concepts add Streamlit Community Cloud add Snowflake Other platforms add school Knowledge base FAQ Installing dependencies Deployment issues Home / Get started / Fundamentals / Additional features Additional 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_pin Note The 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. star Tip Another 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.py import streamlit as st st.markdown("# Main page 🎈") st.sidebar.markdown("# Main page 🎈") pages/page_2.py import streamlit as st st.markdown("# Page 2 ❄️") st.sidebar.markdown("# Page 2 ❄️") pages/page_3.py import 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 hygiene 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 concepts Next: Summary forum Still have questions? Our forums are full of helpful information and Streamlit experts. Home Contact Us Community © 2025 Snowflake Inc. Cookie policy forum Ask AI |
Managing_secrets_when_deploying_your_app___Streaml.txt | Managing secrets when deploying your app - Streamlit Docs Documentation search Search rocket_launch Get started Installation add Fundamentals add First steps add code Develop Concepts add API reference add Tutorials add Quick reference add web_asset Deploy Concepts remove Dependencies Secrets Streamlit Community Cloud add Snowflake Other platforms add school Knowledge base FAQ Installing dependencies Deployment issues Home / Deploy / Concepts / Secrets Managing 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: Dependencies Next: Streamlit Community Cloud forum Still have questions? Our forums are full of helpful information and Streamlit experts. Home Contact Us Community © 2025 Snowflake Inc. Cookie policy forum Ask AI |
st.markdown_-_Streamlit_Docs.txt | st.markdown - Streamlit Docs Documentation search Search rocket_launch Get started Installation add Fundamentals add First steps add code Develop Concepts add API reference remove PAGE ELEMENTS Write and magic add Text elements remove HEADINGS & BODY st.title st.header st.subheader st.markdown FORMATTED TEXT st.caption st.code st.divider st.echo st.latex st.text UTILITIES st.html link Data elements add Chart elements add Input widgets add Media elements add Layouts and containers add Chat elements add Status elements add Third-party components open_in_new APPLICATION LOGIC Navigation and pages add Execution flow add Caching and state add Connections and secrets add Custom components add Utilities add Configuration add TOOLS App testing add Command line add Tutorials add Quick reference add web_asset Deploy Concepts add Streamlit Community Cloud add Snowflake Other platforms add school Knowledge base FAQ Installing dependencies Deployment issues Home / Develop / API reference / Text elements / st.markdown st.markdown Streamlit Version Version 1.41.0 Version 1.40.0 Version 1.39.0 Version 1.38.0 Version 1.37.0 Version 1.36.0 Version 1.35.0 Version 1.34.0 Version 1.33.0 Version 1.32.0 Version 1.31.0 Version 1.30.0 Version 1.29.0 Version 1.28.0 Version 1.27.0 Version 1.26.0 Version 1.25.0 Version 1.24.0 Version 1.23.0 Version 1.22.0 Version 1.21.0 Version 1.20.0 Streamlit in Snowflake Display string formatted as Markdown. Function signature [source] st.markdown(body, unsafe_allow_html=False, *, help=None) Parameters body (any) The text to display as GitHub-flavored Markdown. Syntax information can be found at: https://github.github.com/gfm . If anything other than a string is passed, it will be converted into a string behind the scenes using str(body) . 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 . Streamlit logo shortcode. Use :streamlit: to add a little Streamlit flair to your text. A limited set of typographical symbols. "<- -> <-> -- >= <= ~=" becomes "← → ↔ — ≥ ≤ ≈" when parsed as Markdown. Google Material Symbols (rounded style), using the syntax :material/icon_name: , where "icon_name" is the name of the icon in snake case. For a complete list of icons, see Google's Material Symbols font library. 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, or primary. For example, you can use :orange[your text here] or :blue-background[your text here] . If you use "primary" for color, Streamlit will use the default primary accent color unless you set the theme.primaryColor configuration option. unsafe_allow_html (bool) Whether to render HTML within body . If this is False (default), any HTML tags found in body will be escaped and therefore treated as raw text. If this is True , any HTML expressions within body will be rendered. Adding custom HTML to your app impacts safety, styling, and maintainability. Note If you only want to insert HTML or CSS without Markdown text, we recommend using st.html instead. help (str) An optional tooltip that gets displayed next to the Markdown. Examples import streamlit as st st.markdown("*Streamlit* is **really** ***cool***.") st.markdown(''' :red[Streamlit] :orange[can] :green[write] :blue[text] :violet[in] :gray[pretty] :rainbow[colors] and :blue-background[highlight] text.''') st.markdown("Here's a bouquet —\ :tulip::cherry_blossom::rose::hibiscus::sunflower::blossom:") multi = '''If you end a line with two spaces, a soft return is used for the next line. Two (or more) newline characters in a row will result in a hard return. ''' st.markdown(multi) Built with Streamlit 🎈 Fullscreen open_in_new import streamlit as st md = st.text_area('Type in your markdown string (without outer quotes)', "Happy Streamlit-ing! :balloon:") st.code(f""" import streamlit as st st.markdown('''{md}''') """) st.markdown(md) Built with Streamlit 🎈 Fullscreen open_in_new Previous: st.subheader Next: st.caption forum Still have questions? Our forums are full of helpful information and Streamlit experts. Home Contact Us Community © 2025 Snowflake Inc. Cookie policy forum Ask AI |
App_design_concepts_and_considerations___Streamlit.txt | App design concepts and considerations - Streamlit Docs Documentation search Search rocket_launch Get started Installation add Fundamentals add First steps add code Develop Concepts remove CORE Architecture & execution add Multipage apps add App design remove Animate & update elements Button behavior and examples Dataframes Using custom classes Working with timezones ADDITIONAL Connections and secrets add Custom components add Configuration and theming add App testing add API reference add Tutorials add Quick reference add web_asset Deploy Concepts add Streamlit Community Cloud add Snowflake Other platforms add school Knowledge base FAQ Installing dependencies Deployment issues Home / Develop / Concepts / App design App design concepts and considerations Animate and update elements Understand how to create dynamic, animated content or update elements without rerunning your app. Button behavior and examples Understand how buttons work with explanations and examples to avoid common mistakes. Dataframes Dataframes are a great way to display and edit data in a tabular format. Understand the UI and options available in Streamlit. Using custom Python classes in your Streamlit app Understand the impact of defining your own Python classes within Streamlit's rerun model. Working with timezones Understand how to localize time to your users. Previous: Multipage apps Next: Animate & update elements forum Still have questions? Our forums are full of helpful information and Streamlit experts. Home Contact Us Community © 2025 Snowflake Inc. Cookie policy forum Ask AI |
Display_progress_and_status_-_Streamlit_Docs.txt | Display progress and status - Streamlit Docs Documentation search Search rocket_launch Get started Installation add Fundamentals add First steps add code Develop Concepts add API reference remove PAGE ELEMENTS Write and magic add Text elements add Data elements add Chart elements add Input widgets add Media elements add Layouts and containers add Chat elements add Status elements remove CALLOUTS st.success st.info st.warning st.error st.exception OTHER st.progress st.spinner st.status st.toast st.balloons st.snow Third-party components open_in_new APPLICATION LOGIC Navigation and pages add Execution flow add Caching and state add Connections and secrets add Custom components add Utilities add Configuration add TOOLS App testing add Command line add Tutorials add Quick reference add web_asset Deploy Concepts add Streamlit Community Cloud add Snowflake Other platforms add school Knowledge base FAQ Installing dependencies Deployment issues Home / Develop / API reference / Status elements Display progress and status Streamlit provides a few methods that allow you to add animation to your apps. These animations include progress bars, status messages (like warnings), and celebratory balloons. Animated status elements Progress bar Display a progress bar. for i in range(101): st.progress(i) do_something_slow() Spinner Temporarily displays a message while executing a block of code. with st.spinner("Please wait..."): do_something_slow() Status container Display output of long-running tasks in a container. with st.status('Running'): do_something_slow() Toast Briefly displays a toast message in the bottom-right corner. st.toast('Butter!', icon='🧈') Balloons Display celebratory balloons! st.balloons() Snowflakes Display celebratory snowflakes! st.snow() Simple callout messages Success box Display a success message. st.success("Match found!") Info box Display an informational message. st.info("Dataset is updated every day at midnight.") Warning box Display warning message. st.warning("Unable to fetch image. Skipping...") Error box Display error message. st.error("We encountered an error") Exception output Display an exception. e = RuntimeError("This is an exception of type RuntimeError") st.exception(e) Third-party components These are featured components created by our lovely community. For more examples and inspiration, check out our Components Gallery and Streamlit Extras ! Stqdm The 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 box A 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 Extras A 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",) Previous: Chat elements Next: st.success forum Still have questions? Our forums are full of helpful information and Streamlit experts. Home Contact Us Community © 2025 Snowflake Inc. Cookie policy forum Ask AI |
Build_multipage_apps_-_Streamlit_Docs.txt | Build multipage apps - Streamlit Docs Documentation search Search rocket_launch Get started Installation add Fundamentals add First steps add code Develop Concepts add API reference add Tutorials remove Elements add Execution flow add Connect to data sources add Multipage apps remove Dynamic navigation Work with LLMs add Quick reference add web_asset Deploy Concepts add Streamlit Community Cloud add Snowflake Other platforms add school Knowledge base FAQ Installing dependencies Deployment issues Home / Develop / Tutorials / Multipage apps Build multipage apps Create a dynamic navigation menu Create a dynamic, user-dependant navigation menu with st.navigation . Previous: Connect to data sources Next: Dynamic navigation forum Still have questions? Our forums are full of helpful information and Streamlit experts. Home Contact Us Community © 2025 Snowflake Inc. Cookie policy forum Ask AI |
st.html_-_Streamlit_Docs.txt | st.html - Streamlit Docs Documentation search Search rocket_launch Get started Installation add Fundamentals add First steps add code Develop Concepts add API reference remove PAGE ELEMENTS Write and magic add Text elements add Data elements add Chart elements add Input widgets add Media elements add Layouts and containers add Chat elements add Status elements add Third-party components open_in_new APPLICATION LOGIC Navigation and pages add Execution flow add Caching and state add Connections and secrets add Custom components add Utilities remove st.context st.experimental_user st.help st.html Configuration add TOOLS App testing add Command line add Tutorials add Quick reference add web_asset Deploy Concepts add Streamlit Community Cloud add Snowflake Other platforms add school Knowledge base FAQ Installing dependencies Deployment issues Home / Develop / API reference / Utilities / st.html st.html Streamlit Version Version 1.41.0 Version 1.40.0 Version 1.39.0 Version 1.38.0 Version 1.37.0 Version 1.36.0 Version 1.35.0 Version 1.34.0 Version 1.33.0 Version 1.32.0 Version 1.31.0 Version 1.30.0 Version 1.29.0 Version 1.28.0 Version 1.27.0 Version 1.26.0 Version 1.25.0 Version 1.24.0 Version 1.23.0 Version 1.22.0 Version 1.21.0 Version 1.20.0 Streamlit in Snowflake Insert HTML into your app. Adding custom HTML to your app impacts safety, styling, and maintainability. We sanitize HTML with DOMPurify , but inserting HTML remains a developer risk. Passing untrusted code to st.html or dynamically loading external code can increase the risk of vulnerabilities in your app. st.html content is not iframed. Executing JavaScript is not supported at this time. Function signature [source] st.html(body) Parameters body (any) The HTML code to insert. This can be one of the following: A string of HTML code. A path to a local file with HTML code. The path can be a str or Path object. Paths can be absolute or relative to the working directory (where you execute streamlit run ). Any object. If body is not a string or path, Streamlit will convert the object to a string. body._repr_html_() takes precedence over str(body) when available. Example import streamlit as st st.html( "<p><span style='text-decoration: line-through double red;'>Oops</span>!</p>" ) Built with Streamlit 🎈 Fullscreen open_in_new Previous: st.help Next: Configuration forum Still have questions? Our forums are full of helpful information and Streamlit experts. Home Contact Us Community © 2025 Snowflake Inc. Cookie policy forum Ask AI |
Caching_overview_-_Streamlit_Docs.txt | Caching overview - Streamlit Docs Documentation search Search rocket_launch Get started Installation add Fundamentals add First steps add code Develop Concepts remove CORE Architecture & execution remove Running your app Streamlit's architecture The app chrome Caching Session State Forms Fragments Widget behavior Multipage apps add App design add ADDITIONAL Connections and secrets add Custom components add Configuration and theming add App testing add API reference add Tutorials add Quick reference add web_asset Deploy Concepts add Streamlit Community Cloud add Snowflake Other platforms add school Knowledge base FAQ Installing dependencies Deployment issues Home / Develop / Concepts / Architecture & execution / Caching push_pin Note Documentation for the deprecated @st.cache decorator can be found in Optimize performance with st.cache . Caching overview Streamlit runs your script from top to bottom at every user interaction or code change. This execution model makes development super easy. But it comes with two major challenges: Long-running functions run again and again, which slows down your app. Objects get recreated again and again, which makes it hard to persist them across reruns or sessions. But don't worry! Streamlit lets you tackle both issues with its built-in caching mechanism. Caching stores the results of slow function calls, so they only need to run once. This makes your app much faster and helps with persisting objects across reruns. Cached values are available to all users of your app. If you need to save results that should only be accessible within a session, use Session State instead. Table of contents expand_more Minimal example Basic usage Advanced usage Migrating from st.cache Minimal example To cache a function in Streamlit, you must decorate it with one of two decorators ( st.cache_data or st.cache_resource ): @st.cache_data def long_running_function(param1, param2): return … In this example, decorating long_running_function with @st.cache_data tells Streamlit that whenever the function is called, it checks two things: The values of the input parameters (in this case, param1 and param2 ). The code inside the function. If this is the first time Streamlit sees these parameter values and function code, it runs the function and stores the return value in a cache. The next time the function is called with the same parameters and code (e.g., when a user interacts with the app), Streamlit will skip executing the function altogether and return the cached value instead. During development, the cache updates automatically as the function code changes, ensuring that the latest changes are reflected in the cache. As mentioned, there are two caching decorators: st.cache_data is the recommended way to cache computations that return data: loading a DataFrame from CSV, transforming a NumPy array, querying an API, or any other function that returns a serializable data object (str, int, float, DataFrame, array, list, …). It creates a new copy of the data at each function call, making it safe against mutations and race conditions . The behavior of st.cache_data is what you want in most cases – so if you're unsure, start with st.cache_data and see if it works! st.cache_resource is the recommended way to cache global resources like ML models or database connections – unserializable objects that you don't want to load multiple times. Using it, you can share these resources across all reruns and sessions of an app without copying or duplication. Note that any mutations to the cached return value directly mutate the object in the cache (more details below). Streamlit's two caching decorators and their use cases. Basic usage st.cache_data st.cache_data is your go-to command for all functions that return data – whether DataFrames, NumPy arrays, str, int, float, or other serializable types. It's the right command for almost all use cases! Within each user session, an @st.cache_data -decorated function returns a copy of the cached return value (if the value is already cached). Usage Let's look at an example of using st.cache_data . Suppose your app loads the Uber ride-sharing dataset – a CSV file of 50 MB – from the internet into a DataFrame: def load_data(url): df = pd.read_csv(url) # 👈 Download the data return df df = load_data("https://github.com/plotly/datasets/raw/master/uber-rides-data1.csv") st.dataframe(df) st.button("Rerun") Running the load_data function takes 2 to 30 seconds, depending on your internet connection. (Tip: if you are on a slow connection, use this 5 MB dataset instead ). Without caching, the download is rerun each time the app is loaded or with user interaction. Try it yourself by clicking the button we added! Not a great experience… 😕 Now let's add the @st.cache_data decorator on load_data : @st.cache_data # 👈 Add the caching decorator def load_data(url): df = pd.read_csv(url) return df df = load_data("https://github.com/plotly/datasets/raw/master/uber-rides-data1.csv") st.dataframe(df) st.button("Rerun") Run the app again. You'll notice that the slow download only happens on the first run. Every subsequent rerun should be almost instant! 💨 Behavior How does this work? Let's go through the behavior of st.cache_data step by step: On the first run, Streamlit recognizes that it has never called the load_data function with the specified parameter value (the URL of the CSV file) So it runs the function and downloads the data. Now our caching mechanism becomes active: the returned DataFrame is serialized (converted to bytes) via pickle and stored in the cache (together with the value of the url parameter). On the next run, Streamlit checks the cache for an entry of load_data with the specific url . There is one! So it retrieves the cached object, deserializes it to a DataFrame, and returns it instead of re-running the function and downloading the data again. This process of serializing and deserializing the cached object creates a copy of our original DataFrame. While this copying behavior may seem unnecessary, it's what we want when caching data objects since it effectively prevents mutation and concurrency issues. Read the section “ Mutation and concurrency issues " below to understand this in more detail. priority_high Warning st.cache_data implicitly uses the pickle module, which is known to be insecure. Anything your cached function returns is pickled and stored, then unpickled on retrieval. Ensure your cached functions return trusted values because it is possible to construct malicious pickle data that will execute arbitrary code during unpickling. Never load data that could have come from an untrusted source in an unsafe mode or that could have been tampered with. Only load data you trust . Examples DataFrame transformations In the example above, we already showed how to cache loading a DataFrame. It can also be useful to cache DataFrame transformations such as df.filter , df.apply , or df.sort_values . Especially with large DataFrames, these operations can be slow. @st.cache_data def transform(df): df = df.filter(items=['one', 'three']) df = df.apply(np.sum, axis=0) return df Array computations Similarly, it can make sense to cache computations on NumPy arrays: @st.cache_data def add(arr1, arr2): return arr1 + arr2 Database queries You usually make SQL queries to load data into your app when working with databases. Repeatedly running these queries can be slow, cost money, and degrade the performance of your database. We strongly recommend caching any database queries in your app. See also our guides on connecting Streamlit to different databases for in-depth examples. connection = database.connect() @st.cache_data def query(): return pd.read_sql_query("SELECT * from table", connection) star Tip You should set a ttl (time to live) to get new results from your database. If you set st.cache_data(ttl=3600) , Streamlit invalidates any cached values after 1 hour (3600 seconds) and runs the cached function again. See details in Controlling cache size and duration . API calls Similarly, it makes sense to cache API calls. Doing so also avoids rate limits. @st.cache_data def api_call(): response = requests.get('https://jsonplaceholder.typicode.com/posts/1') return response.json() Running ML models (inference) Running complex machine learning models can use significant time and memory. To avoid rerunning the same computations over and over, use caching. @st.cache_data def run_model(inputs): return model(inputs) st.cache_resource st.cache_resource is the right command to cache “resources" that should be available globally across all users, sessions, and reruns. It has more limited use cases than st.cache_data , especially for caching database connections and ML models. Within each user session, an @st.cache_resource -decorated function returns the cached instance of the return value (if the value is already cached). Therefore, objects cached by st.cache_resource act like singletons and can mutate. Usage As an example for st.cache_resource , let's look at a typical machine learning app. As a first step, we need to load an ML model. We do this with Hugging Face's transformers library : from transformers import pipeline model = pipeline("sentiment-analysis") # 👈 Load the model If we put this code into a Streamlit app directly, the app will load the model at each rerun or user interaction. Repeatedly loading the model poses two problems: Loading the model takes time and slows down the app. Each session loads the model from scratch, which takes up a huge amount of memory. Instead, it would make much more sense to load the model once and use that same object across all users and sessions. That's exactly the use case for st.cache_resource ! Let's add it to our app and process some text the user entered: from transformers import pipeline @st.cache_resource # 👈 Add the caching decorator def load_model(): return pipeline("sentiment-analysis") model = load_model() query = st.text_input("Your query", value="I love Streamlit! 🎈") if query: result = model(query)[0] # 👈 Classify the query text st.write(result) If you run this app, you'll see that the app calls load_model only once – right when the app starts. Subsequent runs will reuse that same model stored in the cache, saving time and memory! Behavior Using st.cache_resource is very similar to using st.cache_data . But there are a few important differences in behavior: st.cache_resource does not create a copy of the cached return value but instead stores the object itself in the cache. All mutations on the function's return value directly affect the object in the cache, so you must ensure that mutations from multiple sessions do not cause problems. In short, the return value must be thread-safe. priority_high Warning Using st.cache_resource on objects that are not thread-safe might lead to crashes or corrupted data. Learn more below under Mutation and concurrency issues . Not creating a copy means there's just one global instance of the cached return object, which saves memory, e.g. when using a large ML model. In computer science terms, we create a singleton . Return values of functions do not need to be serializable. This behavior is great for types not serializable by nature, e.g., database connections, file handles, or threads. Caching these objects with st.cache_data is not possible. Examples Database connections st.cache_resource is useful for connecting to databases. Usually, you're creating a connection object that you want to reuse globally for every query. Creating a new connection object at each run would be inefficient and might lead to connection errors. That's exactly what st.cache_resource can do, e.g., for a Postgres database: @st.cache_resource def init_connection(): host = "hh-pgsql-public.ebi.ac.uk" database = "pfmegrnargs" user = "reader" password = "NWDMCE5xdipIjRrp" return psycopg2.connect(host=host, database=database, user=user, password=password) conn = init_connection() Of course, you can do the same for any other database. Have a look at our guides on how to connect Streamlit to databases for in-depth examples. Loading ML models Your app should always cache ML models, so they are not loaded into memory again for every new session. See the example above for how this works with 🤗 Hugging Face models. You can do the same thing for PyTorch, TensorFlow, etc. Here's an example for PyTorch: @st.cache_resource def load_model(): model = torchvision.models.resnet50(weights=ResNet50_Weights.DEFAULT) model.eval() return model model = load_model() Deciding which caching decorator to use The sections above showed many common examples for each caching decorator. But there are edge cases for which it's less trivial to decide which caching decorator to use. Eventually, it all comes down to the difference between “data" and “resource": Data are serializable objects (objects that can be converted to bytes via pickle ) that you could easily save to disk. Imagine all the types you would usually store in a database or on a file system – basic types like str, int, and float, but also arrays, DataFrames, images, or combinations of these types (lists, tuples, dicts, and so on). Resources are unserializable objects that you usually would not save to disk or a database. They are often more complex, non-permanent objects like database connections, ML models, file handles, threads, etc. From the types listed above, it should be obvious that most objects in Python are “data." That's also why st.cache_data is the correct command for almost all use cases. st.cache_resource is a more exotic command that you should only use in specific situations. Or if you're lazy and don't want to think too much, look up your use case or return type in the table below 😉: Use case Typical return types Caching decorator Reading a CSV file with pd.read_csv pandas.DataFrame st.cache_data Reading a text file str, list of str st.cache_data Transforming pandas dataframes pandas.DataFrame, pandas.Series st.cache_data Computing with numpy arrays numpy.ndarray st.cache_data Simple computations with basic types str, int, float, … st.cache_data Querying a database pandas.DataFrame st.cache_data Querying an API pandas.DataFrame, str, dict st.cache_data Running an ML model (inference) pandas.DataFrame, str, int, dict, list st.cache_data Creating or processing images PIL.Image.Image, numpy.ndarray st.cache_data Creating charts matplotlib.figure.Figure, plotly.graph_objects.Figure, altair.Chart st.cache_data (but some libraries require st.cache_resource, since the chart object is not serializable – make sure not to mutate the chart after creation!) Lazy computations polars.LazyFrame st.cache_resource (but may be better to use st.cache_data on the collected results) Loading ML models transformers.Pipeline, torch.nn.Module, tensorflow.keras.Model st.cache_resource Initializing database connections pyodbc.Connection, sqlalchemy.engine.base.Engine, psycopg2.connection, mysql.connector.MySQLConnection, sqlite3.Connection st.cache_resource Opening persistent file handles _io.TextIOWrapper st.cache_resource Opening persistent threads threading.thread st.cache_resource Advanced usage Controlling cache size and duration If your app runs for a long time and constantly caches functions, you might run into two problems: The app runs out of memory because the cache is too large. Objects in the cache become stale, e.g. because you cached old data from a database. You can combat these problems with the ttl and max_entries parameters, which are available for both caching decorators. The ttl (time-to-live) parameter ttl sets a time to live on a cached function. If that time is up and you call the function again, the app will discard any old, cached values, and the function will be rerun. The newly computed value will then be stored in the cache. This behavior is useful for preventing stale data (problem 2) and the cache from growing too large (problem 1). Especially when pulling data from a database or API, you should always set a ttl so you are not using old data. Here's an example: @st.cache_data(ttl=3600) # 👈 Cache data for 1 hour (=3600 seconds) def get_api_data(): data = api.get(...) return data star Tip You can also set ttl values using timedelta , e.g., ttl=datetime.timedelta(hours=1) . The max_entries parameter max_entries sets the maximum number of entries in the cache. An upper bound on the number of cache entries is useful for limiting memory (problem 1), especially when caching large objects. The oldest entry will be removed when a new entry is added to a full cache. Here's an example: @st.cache_data(max_entries=1000) # 👈 Maximum 1000 entries in the cache def get_large_array(seed): np.random.seed(seed) arr = np.random.rand(100000) return arr Customizing the spinner By default, Streamlit shows a small loading spinner in the app when a cached function is running. You can modify it easily with the show_spinner parameter, which is available for both caching decorators: @st.cache_data(show_spinner=False) # 👈 Disable the spinner def get_api_data(): data = api.get(...) return data @st.cache_data(show_spinner="Fetching data from API...") # 👈 Use custom text for spinner def get_api_data(): data = api.get(...) return data Excluding input parameters In a cached function, all input parameters must be hashable. Let's quickly explain why and what it means. When the function is called, Streamlit looks at its parameter values to determine if it was cached before. Therefore, it needs a reliable way to compare the parameter values across function calls. Trivial for a string or int – but complex for arbitrary objects! Streamlit uses hashing to solve that. It converts the parameter to a stable key and stores that key. At the next function call, it hashes the parameter again and compares it with the stored hash key. Unfortunately, not all parameters are hashable! E.g., you might pass an unhashable database connection or ML model to your cached function. In this case, you can exclude input parameters from caching. Simply prepend the parameter name with an underscore (e.g., _param1 ), and it will not be used for caching. Even if it changes, Streamlit will return a cached result if all the other parameters match up. Here's an example: @st.cache_data def fetch_data(_db_connection, num_rows): # 👈 Don't hash _db_connection data = _db_connection.fetch(num_rows) return data connection = init_connection() fetch_data(connection, 10) But what if you want to cache a function that takes an unhashable parameter? For example, you might want to cache a function that takes an ML model as input and returns the layer names of that model. Since the model is the only input parameter, you cannot exclude it from caching. In this case you can use the hash_funcs parameter to specify a custom hashing function for the model. The hash_funcs parameter As described above, Streamlit's caching decorators hash the input parameters and cached function's signature to determine whether the function has been run before and has a return value stored ("cache hit") or needs to be run ("cache miss"). Input parameters that are not hashable by Streamlit's hashing implementation can be ignored by prepending an underscore to their name. But there two rare cases where this is undesirable. i.e. where you want to hash the parameter that Streamlit is unable to hash: When Streamlit's hashing mechanism fails to hash a parameter, resulting in a UnhashableParamError being raised. When you want to override Streamlit's default hashing mechanism for a parameter. Let's discuss each of these cases in turn with examples. Example 1: Hashing a custom class Streamlit does not know how to hash custom classes. If you pass a custom class to a cached function, Streamlit will raise a UnhashableParamError . For example, let's define a custom class MyCustomClass that accepts an initial integer score. Let's also define a cached function multiply_score that multiplies the score by a multiplier: import streamlit as st class MyCustomClass: def __init__(self, initial_score: int): self.my_score = initial_score @st.cache_data def multiply_score(obj: MyCustomClass, multiplier: int) -> int: return obj.my_score * multiplier initial_score = st.number_input("Enter initial score", value=15) score = MyCustomClass(initial_score) multiplier = 2 st.write(multiply_score(score, multiplier)) If you run this app, you'll see that Streamlit raises a UnhashableParamError since it does not know how to hash MyCustomClass : UnhashableParamError: Cannot hash argument 'obj' (of type __main__.MyCustomClass) in 'multiply_score'. To fix this, we can use the hash_funcs parameter to tell Streamlit how to hash MyCustomClass . We do this by passing a dictionary to hash_funcs that maps the name of the parameter to a hash function. The choice of hash function is up to the developer. In this case, let's define a custom hash function hash_func that takes the custom class as input and returns the score. We want the score to be the unique identifier of the object, so we can use it to deterministically hash the object: import streamlit as st class MyCustomClass: def __init__(self, initial_score: int): self.my_score = initial_score def hash_func(obj: MyCustomClass) -> int: return obj.my_score # or any other value that uniquely identifies the object @st.cache_data(hash_funcs={MyCustomClass: hash_func}) def multiply_score(obj: MyCustomClass, multiplier: int) -> int: return obj.my_score * multiplier initial_score = st.number_input("Enter initial score", value=15) score = MyCustomClass(initial_score) multiplier = 2 st.write(multiply_score(score, multiplier)) Now if you run the app, you'll see that Streamlit no longer raises a UnhashableParamError and the app runs as expected. Let's now consider the case where multiply_score is an attribute of MyCustomClass and we want to hash the entire object: import streamlit as st class MyCustomClass: def __init__(self, initial_score: int): self.my_score = initial_score @st.cache_data def multiply_score(self, multiplier: int) -> int: return self.my_score * multiplier initial_score = st.number_input("Enter initial score", value=15) score = MyCustomClass(initial_score) multiplier = 2 st.write(score.multiply_score(multiplier)) If you run this app, you'll see that Streamlit raises a UnhashableParamError since it cannot hash the argument 'self' (of type __main__.MyCustomClass) in 'multiply_score' . A simple fix here could be to use Python's hash() function to hash the object: import streamlit as st class MyCustomClass: def __init__(self, initial_score: int): self.my_score = initial_score @st.cache_data(hash_funcs={"__main__.MyCustomClass": lambda x: hash(x.my_score)}) def multiply_score(self, multiplier: int) -> int: return self.my_score * multiplier initial_score = st.number_input("Enter initial score", value=15) score = MyCustomClass(initial_score) multiplier = 2 st.write(score.multiply_score(multiplier)) Above, the hash function is defined as lambda x: hash(x.my_score) . This creates a hash based on the my_score attribute of the MyCustomClass instance. As long as my_score remains the same, the hash remains the same. Thus, the result of multiply_score can be retrieved from the cache without recomputation. As an astute Pythonista, you may have been tempted to use Python's id() function to hash the object like so: import streamlit as st class MyCustomClass: def __init__(self, initial_score: int): self.my_score = initial_score @st.cache_data(hash_funcs={"__main__.MyCustomClass": id}) def multiply_score(self, multiplier: int) -> int: return self.my_score * multiplier initial_score = st.number_input("Enter initial score", value=15) score = MyCustomClass(initial_score) multiplier = 2 st.write(score.multiply_score(multiplier)) If you run the app, you'll notice that Streamlit recomputes multiply_score each time even if my_score hasn't changed! Puzzled? In Python, id() returns the identity of an object, which is unique and constant for the object during its lifetime. This means that even if the my_score value is the same between two instances of MyCustomClass , id() will return different values for these two instances, leading to different hash values. As a result, Streamlit considers these two different instances as needing separate cached values, thus it recomputes the multiply_score each time even if my_score hasn't changed. This is why we discourage using it as hash func, and instead encourage functions that return deterministic, true hash values. That said, if you know what you're doing, you can use id() as a hash function. Just be aware of the consequences. For example, id is often the correct hash func when you're passing the result of an @st.cache_resource function as the input param to another cached function. There's a whole class of object types that aren’t otherwise hashable. Example 2: Hashing a Pydantic model Let's consider another example where we want to hash a Pydantic model: import streamlit as st from pydantic import BaseModel class Person(BaseModel): name: str @st.cache_data def identity(person: Person): return person person = identity(Person(name="Lee")) st.write(f"The person is {person.name}") Above, we define a custom class Person using Pydantic's BaseModel with a single attribute name. We also define an identity function which accepts an instance of Person as an arg and returns it without modification. This function is intended to cache the result, therefore, if called multiple times with the same Person instance, it won't recompute but return the cached instance. If you run the app, however, you'll run into a UnhashableParamError: Cannot hash argument 'person' (of type __main__.Person) in 'identity'. error. This is because Streamlit does not know how to hash the Person class. To fix this, we can use the hash_funcs kwarg to tell Streamlit how to hash Person . In the version below, we define a custom hash function hash_func that takes the Person instance as input and returns the name attribute. We want the name to be the unique identifier of the object, so we can use it to deterministically hash the object: import streamlit as st from pydantic import BaseModel class Person(BaseModel): name: str @st.cache_data(hash_funcs={Person: lambda p: p.name}) def identity(person: Person): return person person = identity(Person(name="Lee")) st.write(f"The person is {person.name}") Example 3: Hashing a ML model There may be cases where you want to pass your favorite machine learning model to a cached function. For example, let's say you want to pass a TensorFlow model to a cached function, based on what model the user selects in the app. You might try something like this: import streamlit as st import tensorflow as tf @st.cache_resource def load_base_model(option): if option == 1: return tf.keras.applications.ResNet50(include_top=False, weights="imagenet") else: return tf.keras.applications.MobileNetV2(include_top=False, weights="imagenet") @st.cache_resource def load_layers(base_model): return [layer.name for layer in base_model.layers] option = st.radio("Model 1 or 2", [1, 2]) base_model = load_base_model(option) layers = load_layers(base_model) st.write(layers) In the above app, the user can select one of two models. Based on the selection, the app loads the corresponding model and passes it to load_layers . This function then returns the names of the layers in the model. If you run the app, you'll see that Streamlit raises a UnhashableParamError since it cannot hash the argument 'base_model' (of type keras.engine.functional.Functional) in 'load_layers' . If you disable hashing for base_model by prepending an underscore to its name, you'll observe that regardless of which base model is chosen, the layers displayed are same. This subtle bug is due to the fact that the load_layers function is not re-run when the base model changes. This is because Streamlit does not hash the base_model argument, so it does not know that the function needs to be re-run when the base model changes. To fix this, we can use the hash_funcs kwarg to tell Streamlit how to hash the base_model argument. In the version below, we define a custom hash function hash_func : Functional: lambda x: x.name . Our choice of hash func is informed by our knowledge that the name attribute of a Functional object or model uniquely identifies it. As long as the name attribute remains the same, the hash remains the same. Thus, the result of load_layers can be retrieved from the cache without recomputation. import streamlit as st import tensorflow as tf from keras.engine.functional import Functional @st.cache_resource def load_base_model(option): if option == 1: return tf.keras.applications.ResNet50(include_top=False, weights="imagenet") else: return tf.keras.applications.MobileNetV2(include_top=False, weights="imagenet") @st.cache_resource(hash_funcs={Functional: lambda x: x.name}) def load_layers(base_model): return [layer.name for layer in base_model.layers] option = st.radio("Model 1 or 2", [1, 2]) base_model = load_base_model(option) layers = load_layers(base_model) st.write(layers) In the above case, we could also have used hash_funcs={Functional: id} as the hash function. This is because id is often the correct hash func when you're passing the result of an @st.cache_resource function as the input param to another cached function. Example 4: Overriding Streamlit's default hashing mechanism Let's consider another example where we want to override Streamlit's default hashing mechanism for a pytz-localized datetime object: from datetime import datetime import pytz import streamlit as st tz = pytz.timezone("Europe/Berlin") @st.cache_data def load_data(dt): return dt now = datetime.now() st.text(load_data(dt=now)) now_tz = tz.localize(datetime.now()) st.text(load_data(dt=now_tz)) It may be surprising to see that although now and now_tz are of the same <class 'datetime.datetime'> type, Streamlit does not how to hash now_tz and raises a UnhashableParamError . In this case, we can override Streamlit's default hashing mechanism for datetime objects by passing a custom hash function to the hash_funcs kwarg: from datetime import datetime import pytz import streamlit as st tz = pytz.timezone("Europe/Berlin") @st.cache_data(hash_funcs={datetime: lambda x: x.strftime("%a %d %b %Y, %I:%M%p")}) def load_data(dt): return dt now = datetime.now() st.text(load_data(dt=now)) now_tz = tz.localize(datetime.now()) st.text(load_data(dt=now_tz)) Let's now consider a case where we want to override Streamlit's default hashing mechanism for NumPy arrays. While Streamlit natively hashes Pandas and NumPy objects, there may be cases where you want to override Streamlit's default hashing mechanism for these objects. For example, let's say we create a cache-decorated show_data function that accepts a NumPy array and returns it without modification. In the bellow app, data = df["str"].unique() (which is a NumPy array) is passed to the show_data function. import time import numpy as np import pandas as pd import streamlit as st @st.cache_data def get_data(): df = pd.DataFrame({"num": [112, 112, 2, 3], "str": ["be", "a", "be", "c"]}) return df @st.cache_data def show_data(data): time.sleep(2) # This makes the function take 2s to run return data df = get_data() data = df["str"].unique() st.dataframe(show_data(data)) st.button("Re-run") Since data is always the same, we expect the show_data function to return the cached value. However, if you run the app, and click the Re-run button, you'll notice that the show_data function is re-run each time. We can assume this behavior is a consequence of Streamlit's default hashing mechanism for NumPy arrays. To work around this, let's define a custom hash function hash_func that takes a NumPy array as input and returns a string representation of the array: import time import numpy as np import pandas as pd import streamlit as st @st.cache_data def get_data(): df = pd.DataFrame({"num": [112, 112, 2, 3], "str": ["be", "a", "be", "c"]}) return df @st.cache_data(hash_funcs={np.ndarray: str}) def show_data(data): time.sleep(2) # This makes the function take 2s to run return data df = get_data() data = df["str"].unique() st.dataframe(show_data(data)) st.button("Re-run") Now if you run the app, and click the Re-run button, you'll notice that the show_data function is no longer re-run each time. It's important to note here that our choice of hash function was very naive and not necessarily the best choice. For example, if the NumPy array is large, converting it to a string representation may be expensive. In such cases, it is up to you as the developer to define what a good hash function is for your use case. Static elements Since version 1.16.0, cached functions can contain Streamlit commands! For example, you can do this: @st.cache_data def get_api_data(): data = api.get(...) st.success("Fetched data from API!") # 👈 Show a success message return data As we know, Streamlit only runs this function if it hasn't been cached before. On this first run, the st.success message will appear in the app. But what happens on subsequent runs? It still shows up! Streamlit realizes that there is an st. command inside the cached function, saves it during the first run, and replays it on subsequent runs. Replaying static elements works for both caching decorators. You can also use this functionality to cache entire parts of your UI: @st.cache_data def show_data(): st.header("Data analysis") data = api.get(...) st.success("Fetched data from API!") st.write("Here is a plot of the data:") st.line_chart(data) st.write("And here is the raw data:") st.dataframe(data) Input widgets You can also use interactive input widgets like st.slider or st.text_input in cached functions. Widget replay is an experimental feature at the moment. To enable it, you need to set the experimental_allow_widgets parameter: @st.cache_data(experimental_allow_widgets=True) # 👈 Set the parameter def get_data(): num_rows = st.slider("Number of rows to get") # 👈 Add a slider data = api.get(..., num_rows) return data Streamlit treats the slider like an additional input parameter to the cached function. If you change the slider position, Streamlit will see if it has already cached the function for this slider value. If yes, it will return the cached value. If not, it will rerun the function using the new slider value. Using widgets in cached functions is extremely powerful because it lets you cache entire parts of your app. But it can be dangerous! Since Streamlit treats the widget value as an additional input parameter, it can easily lead to excessive memory usage. Imagine your cached function has five sliders and returns a 100 MB DataFrame. Then we'll add 100 MB to the cache for every permutation of these five slider values – even if the sliders do not influence the returned data! These additions can make your cache explode very quickly. Please be aware of this limitation if you use widgets in cached functions. We recommend using this feature only for isolated parts of your UI where the widgets directly influence the cached return value. priority_high Warning Support for widgets in cached functions is experimental. We may change or remove it anytime without warning. Please use it with care! push_pin Note Two widgets are currently not supported in cached functions: st.file_uploader and st.camera_input . We may support them in the future. Feel free to open a GitHub issue if you need them! Dealing with large data As we explained, you should cache data objects with st.cache_data . But this can be slow for extremely large data, e.g., DataFrames or arrays with >100 million rows. That's because of the copying behavior of st.cache_data : on the first run, it serializes the return value to bytes and deserializes it on subsequent runs. Both operations take time. If you're dealing with extremely large data, it can make sense to use st.cache_resource instead. It does not create a copy of the return value via serialization/deserialization and is almost instant. But watch out: any mutation to the function's return value (such as dropping a column from a DataFrame or setting a value in an array) directly manipulates the object in the cache. You must ensure this doesn't corrupt your data or lead to crashes. See the section on Mutation and concurrency issues below. When benchmarking st.cache_data on pandas DataFrames with four columns, we found that it becomes slow when going beyond 100 million rows. The table shows runtimes for both caching decorators at different numbers of rows (all with four columns): 10M rows 50M rows 100M rows 200M rows st.cache_data First run* 0.4 s 3 s 14 s 28 s Subsequent runs 0.2 s 1 s 2 s 7 s st.cache_resource First run* 0.01 s 0.1 s 0.2 s 1 s Subsequent runs 0 s 0 s 0 s 0 s *For the first run, the table only shows the overhead time of using the caching decorator. It does not include the runtime of the cached function itself. Mutation and concurrency issues In the sections above, we talked a lot about issues when mutating return objects of cached functions. This topic is complicated! But it's central to understanding the behavior differences between st.cache_data and st.cache_resource . So let's dive in a bit deeper. First, we should clearly define what we mean by mutations and concurrency: By mutations , we mean any changes made to a cached function's return value after that function has been called. I.e. something like this: @st.cache_data def create_list(): l = [1, 2, 3] l = create_list() # 👈 Call the function l[0] = 2 # 👈 Mutate its return value By concurrency , we mean that multiple sessions can cause these mutations at the same time. Streamlit is a web framework that needs to handle many users and sessions connecting to an app. If two people view an app at the same time, they will both cause the Python script to rerun, which may manipulate cached return objects at the same time – concurrently. Mutating cached return objects can be dangerous. It can lead to exceptions in your app and even corrupt your data (which can be worse than a crashed app!). Below, we'll first explain the copying behavior of st.cache_data and show how it can avoid mutation issues. Then, we'll show how concurrent mutations can lead to data corruption and how to prevent it. Copying behavior st.cache_data creates a copy of the cached return value each time the function is called. This avoids most mutations and concurrency issues. To understand it in detail, let's go back to the Uber ridesharing example from the section on st.cache_data above. We are making two modifications to it: We are using st.cache_resource instead of st.cache_data . st.cache_resource does not create a copy of the cached object, so we can see what happens without the copying behavior. After loading the data, we manipulate the returned DataFrame (in place!) by dropping the column "Lat" . Here's the code: @st.cache_resource # 👈 Turn off copying behavior def load_data(url): df = pd.read_csv(url) return df df = load_data("https://raw.githubusercontent.com/plotly/datasets/master/uber-rides-data1.csv") st.dataframe(df) df.drop(columns=['Lat'], inplace=True) # 👈 Mutate the dataframe inplace st.button("Rerun") Let's run it and see what happens! The first run should work fine. But in the second run, you see an exception: KeyError: "['Lat'] not found in axis" . Why is that happening? Let's go step by step: On the first run, Streamlit runs load_data and stores the resulting DataFrame in the cache. Since we're using st.cache_resource , it does not create a copy but stores the original DataFrame. Then we drop the column "Lat" from the DataFrame. Note that this is dropping the column from the original DataFrame stored in the cache. We are manipulating it! On the second run, Streamlit returns that exact same manipulated DataFrame from the cache. It does not have the column "Lat" anymore! So our call to df.drop results in an exception. Pandas cannot drop a column that doesn't exist. The copying behavior of st.cache_data prevents this kind of mutation error. Mutations can only affect a specific copy and not the underlying object in the cache. The next rerun will get its own, unmutated copy of the DataFrame. You can try it yourself, just replace st.cache_resource with st.cache_data above, and you'll see that everything works. Because of this copying behavior, st.cache_data is the recommended way to cache data transforms and computations – anything that returns a serializable object. Concurrency issues Now let's look at what can happen when multiple users concurrently mutate an object in the cache. Let's say you have a function that returns a list. Again, we are using st.cache_resource to cache it so that we are not creating a copy: @st.cache_resource def create_list(): l = [1, 2, 3] return l l = create_list() first_list_value = l[0] l[0] = first_list_value + 1 st.write("l[0] is:", l[0]) Let's say user A runs the app. They will see the following output: l[0] is: 2 Let's say another user, B, visits the app right after. In contrast to user A, they will see the following output: l[0] is: 3 Now, user A reruns the app immediately after user B. They will see the following output: l[0] is: 4 What is happening here? Why are all outputs different? When user A visits the app, create_list() is called, and the list [1, 2, 3] is stored in the cache. This list is then returned to user A. The first value of the list, 1 , is assigned to first_list_value , and l[0] is changed to 2 . When user B visits the app, create_list() returns the mutated list from the cache: [2, 2, 3] . The first value of the list, 2 , is assigned to first_list_value and l[0] is changed to 3 . When user A reruns the app, create_list() returns the mutated list again: [3, 2, 3] . The first value of the list, 3 , is assigned to first_list_value, and l[0] is changed to 4. If you think about it, this makes sense. Users A and B use the same list object (the one stored in the cache). And since the list object is mutated, user A's change to the list object is also reflected in user B's app. This is why you must be careful about mutating objects cached with st.cache_resource , especially when multiple users access the app concurrently. If we had used st.cache_data instead of st.cache_resource , the app would have copied the list object for each user, and the above example would have worked as expected – users A and B would have both seen: l[0] is: 2 push_pin Note This toy example might seem benign. But data corruption can be extremely dangerous! Imagine we had worked with the financial records of a large bank here. You surely don't want to wake up with less money on your account just because someone used the wrong caching decorator 😉 Migrating from st.cache We introduced the caching commands described above in Streamlit 1.18.0. Before that, we had one catch-all command st.cache . Using it was often confusing, resulted in weird exceptions, and was slow. That's why we replaced st.cache with the new commands in 1.18.0 (read more in this blog post ). The new commands provide a more intuitive and efficient way to cache your data and resources and are intended to replace st.cache in all new development. If your app is still using st.cache , don't despair! Here are a few notes on migrating: Streamlit will show a deprecation warning if your app uses st.cache . We will not remove st.cache soon, so you don't need to worry about your 2-year-old app breaking. But we encourage you to try the new commands going forward – they will be way less annoying! Switching code to the new commands should be easy in most cases. To decide whether to use st.cache_data or st.cache_resource , read Deciding which caching decorator to use . Streamlit will also recognize common use cases and show hints right in the deprecation warnings. Most parameters from st.cache are also present in the new commands, with a few exceptions: allow_output_mutation does not exist anymore. You can safely delete it. Just make sure you use the right caching command for your use case. suppress_st_warning does not exist anymore. You can safely delete it. Cached functions can now contain Streamlit commands and will replay them. If you want to use widgets inside cached functions, set experimental_allow_widgets=True . See Input widgets for an example. If you have any questions or issues during the migration process, please contact us on the forum , and we will be happy to assist you. 🎈 Previous: The app chrome Next: Session State forum Still have questions? Our forums are full of helpful information and Streamlit experts. Home Contact Us Community © 2025 Snowflake Inc. Cookie policy forum Ask AI |
st.spinner_-_Streamlit_Docs.txt | st.spinner - Streamlit Docs Documentation search Search rocket_launch Get started Installation add Fundamentals add First steps add code Develop Concepts add API reference remove PAGE ELEMENTS Write and magic add Text elements add Data elements add Chart elements add Input widgets add Media elements add Layouts and containers add Chat elements add Status elements remove CALLOUTS st.success st.info st.warning st.error st.exception OTHER st.progress st.spinner st.status st.toast st.balloons st.snow Third-party components open_in_new APPLICATION LOGIC Navigation and pages add Execution flow add Caching and state add Connections and secrets add Custom components add Utilities add Configuration add TOOLS App testing add Command line add Tutorials add Quick reference add web_asset Deploy Concepts add Streamlit Community Cloud add Snowflake Other platforms add school Knowledge base FAQ Installing dependencies Deployment issues Home / Develop / API reference / Status elements / st.spinner st.spinner Streamlit Version Version 1.41.0 Version 1.40.0 Version 1.39.0 Version 1.38.0 Version 1.37.0 Version 1.36.0 Version 1.35.0 Version 1.34.0 Version 1.33.0 Version 1.32.0 Version 1.31.0 Version 1.30.0 Version 1.29.0 Version 1.28.0 Version 1.27.0 Version 1.26.0 Version 1.25.0 Version 1.24.0 Version 1.23.0 Version 1.22.0 Version 1.21.0 Version 1.20.0 Streamlit in Snowflake Temporarily displays a message while executing a block of code. Function signature [source] st.spinner(text="In progress...") Parameters text (str) A message to display while executing that block Example import time import streamlit as st with st.spinner('Wait for it...'): time.sleep(5) st.success("Done!") Previous: st.progress Next: st.status forum Still have questions? Our forums are full of helpful information and Streamlit experts. Home Contact Us Community © 2025 Snowflake Inc. Cookie policy forum Ask AI |
st.components.v1.html_-_Streamlit_Docs.txt | st.components.v1.html - Streamlit Docs Documentation search Search rocket_launch Get started Installation add Fundamentals add First steps add code Develop Concepts add API reference remove PAGE ELEMENTS Write and magic add Text elements add Data elements add Chart elements add Input widgets add Media elements add Layouts and containers add Chat elements add Status elements add Third-party components open_in_new APPLICATION LOGIC Navigation and pages add Execution flow add Caching and state add Connections and secrets add Custom components remove st.components.v1.declare_component st.components.v1.html st.components.v1.iframe Utilities add Configuration add TOOLS App testing add Command line add Tutorials add Quick reference add web_asset Deploy Concepts add Streamlit Community Cloud add Snowflake Other platforms add school Knowledge base FAQ Installing dependencies Deployment issues Home / Develop / API reference / Custom components / st.components.v1.html st.components.v1.html Streamlit Version Version 1.41.0 Version 1.40.0 Version 1.39.0 Version 1.38.0 Version 1.37.0 Version 1.36.0 Version 1.35.0 Version 1.34.0 Version 1.33.0 Version 1.32.0 Version 1.31.0 Version 1.30.0 Version 1.29.0 Version 1.28.0 Version 1.27.0 Version 1.26.0 Version 1.25.0 Version 1.24.0 Version 1.23.0 Version 1.22.0 Version 1.21.0 Version 1.20.0 Streamlit in Snowflake Display an HTML string in an iframe. To use this function, import it from the streamlit.components.v1 module. If you want to insert HTML text into your app without an iframe, try st.html instead. Warning Using st.components.v1.html directly (instead of importing its module) is deprecated and will be disallowed in a later version. 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 iframe in CSS pixels. By default, this is the app's default element width. height (int) The height of the frame in CSS pixels. By default, this is 150 . scrolling (bool) Whether to allow scrolling in the iframe. If this False (default), Streamlit crops any content larger than the iframe and does not show a scrollbar. If this is True , Streamlit shows a scrollbar when the content is larger than the iframe. Example import streamlit.components.v1 as components components.html( "<p><span style='text-decoration: line-through double red;'>Oops</span>!</p>" ) Previous: st.components.v1.declare_component Next: st.components.v1.iframe forum Still have questions? Our forums are full of helpful information and Streamlit experts. Home Contact Us Community © 2025 Snowflake Inc. Cookie policy forum Ask AI |
st.connections.SQLConnection_-_Streamlit_Docs.txt | st.connections.SQLConnection - Streamlit Docs Documentation search Search rocket_launch Get started Installation add Fundamentals add First steps add code Develop Concepts add API reference remove PAGE ELEMENTS Write and magic add Text elements add Data elements add Chart elements add Input widgets add Media elements add Layouts and containers add Chat elements add Status elements add Third-party components open_in_new APPLICATION LOGIC Navigation and pages add Execution flow add Caching and state add Connections and secrets remove SECRETS st.secrets secrets.toml CONNECTIONS st.connection SnowflakeConnection SQLConnection BaseConnection SnowparkConnection delete Custom components add Utilities add Configuration add TOOLS App testing add Command line add Tutorials add Quick reference add web_asset Deploy Concepts add Streamlit Community Cloud add Snowflake Other platforms add school Knowledge base FAQ Installing dependencies Deployment issues Home / Develop / API reference / Connections and secrets / SQLConnection star Tip This 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.SQLConnection Streamlit Version Version 1.41.0 Version 1.40.0 Version 1.39.0 Version 1.38.0 Version 1.37.0 Version 1.36.0 Version 1.35.0 Version 1.34.0 Version 1.33.0 Version 1.32.0 Version 1.31.0 Version 1.30.0 Version 1.29.0 Version 1.28.0 Version 1.27.0 Version 1.26.0 Version 1.25.0 Version 1.24.0 Version 1.23.0 Version 1.22.0 Version 1.21.0 Version 1.20.0 Streamlit in Snowflake A connection to a SQL database using a SQLAlchemy Engine. Initialize this connection object using st.connection("sql") or st.connection("<name>", type="sql") . Connection parameters for a SQLConnection can be specified using secrets.toml and/or **kwargs . Possible connection parameters include: url or keyword arguments for sqlalchemy.engine.URL.create() , except drivername . Use dialect and driver instead of drivername . Keyword arguments for sqlalchemy.create_engine() , including custom connect() arguments used by your specific dialect or driver . autocommit . If this is False (default), the connection operates in manual commit (transactional) mode. If this is True , the connection operates in autocommit (non-transactional) mode. If url exists as a connection parameter, Streamlit will pass it to sqlalchemy.engine.make_url() . Otherwise, Streamlit requires (at a minimum) dialect , username , and host . Streamlit will use dialect and driver (if defined) to derive drivername , then pass the relevant connection parameters to sqlalchemy.engine.URL.create() . In addition to the default keyword arguments for sqlalchemy.create_engine() , your dialect may accept additional keyword arguments. For example, if you use dialect="snowflake" with Snowflake SQLAlchemy , you can pass a value for private_key to use key-pair authentication. If you use dialect="bigquery" with Google BigQuery , you can pass a value for location . 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 database interactions can be performed by using the .session property to receive a regular SQLAlchemy Session. Important SQLAlchemy must be installed in your environment to use this connection. You must also install your driver, such as pyodbc or psycopg2 . Class description [source] st.connections.SQLConnection(connection_name, **kwargs) Methods connect () Call .connect() on the underlying SQLAlchemy Engine, returning a new 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. Examples Example 1: Configuration with URL You can configure your SQL connection using Streamlit's Secrets management . The following example specifies a SQL connection URL. .streamlit/secrets.toml : [connections.sql] url = "xxx+xxx://xxx:xxx@xxx:xxx/xxx" Your app code: import streamlit as st conn = st.connection("sql") df = conn.query("SELECT * FROM pet_owners") st.dataframe(df) Example 2: Configuration with dialect, host, and username If you do not specify url , you must at least specify dialect , host , and username instead. The following example also includes password . .streamlit/secrets.toml : [connections.sql] dialect = "xxx" host = "xxx" username = "xxx" password = "xxx" Your app code: import streamlit as st conn = st.connection("sql") df = conn.query("SELECT * FROM pet_owners") st.dataframe(df) Example 3: Configuration with keyword arguments You can configure your SQL connection with keyword arguments (with or without secrets.toml ). For example, if you use Microsoft Entra ID with a Microsoft Azure SQL server, you can quickly set up a local connection for development using interactive authentication . This example requires the Microsoft ODBC Driver for SQL Server for Windows in addition to the sqlalchemy and pyodbc packages for Python. import streamlit as st conn = st.connection( "sql", dialect="mssql", driver="pyodbc", host="xxx.database.windows.net", database="xxx", username="xxx", query={ "driver": "ODBC Driver 18 for SQL Server", "authentication": "ActiveDirectoryInteractive", "encrypt": "yes", }, ) df = conn.query("SELECT * FROM pet_owners") st.dataframe(df) SQLConnection.connect Streamlit Version Version 1.41.0 Version 1.40.0 Version 1.39.0 Version 1.38.0 Version 1.37.0 Version 1.36.0 Version 1.35.0 Version 1.34.0 Version 1.33.0 Version 1.32.0 Version 1.31.0 Version 1.30.0 Version 1.29.0 Version 1.28.0 Version 1.27.0 Version 1.26.0 Version 1.25.0 Version 1.24.0 Version 1.23.0 Version 1.22.0 Version 1.21.0 Version 1.20.0 Streamlit in Snowflake Call .connect() on the underlying SQLAlchemy Engine, returning a new 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() Returns (sqlalchemy.engine.Connection) A new SQLAlchemy connection object. SQLConnection.query Streamlit Version Version 1.41.0 Version 1.40.0 Version 1.39.0 Version 1.38.0 Version 1.37.0 Version 1.36.0 Version 1.35.0 Version 1.34.0 Version 1.33.0 Version 1.32.0 Version 1.31.0 Version 1.30.0 Version 1.29.0 Version 1.28.0 Version 1.27.0 Version 1.26.0 Version 1.25.0 Version 1.24.0 Version 1.23.0 Version 1.22.0 Version 1.21.0 Version 1.20.0 Streamlit in Snowflake Run a read-only query. This method implements query result caching and simple error handling/retries. The caching behavior is identical to that of using @st.cache_data . Note Queries that are run without a specified ttl are cached indefinitely. All keyword arguments passed to this function are passed down to pandas.read_sql , except ttl . 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.reset Streamlit Version Version 1.41.0 Version 1.40.0 Version 1.39.0 Version 1.38.0 Version 1.37.0 Version 1.36.0 Version 1.35.0 Version 1.34.0 Version 1.33.0 Version 1.32.0 Version 1.31.0 Version 1.30.0 Version 1.29.0 Version 1.28.0 Version 1.27.0 Version 1.26.0 Version 1.25.0 Version 1.24.0 Version 1.23.0 Version 1.22.0 Version 1.21.0 Version 1.20.0 Streamlit in Snowflake Reset 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() Returns (None) No description 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.driver Streamlit Version Version 1.41.0 Version 1.40.0 Version 1.39.0 Version 1.38.0 Version 1.37.0 Version 1.36.0 Version 1.35.0 Version 1.34.0 Version 1.33.0 Version 1.32.0 Version 1.31.0 Version 1.30.0 Version 1.29.0 Version 1.28.0 Version 1.27.0 Version 1.26.0 Version 1.25.0 Version 1.24.0 Version 1.23.0 Version 1.22.0 Version 1.21.0 Version 1.20.0 Streamlit in Snowflake The name of the driver used by the underlying SQLAlchemy Engine. This is equivalent to accessing self._instance.driver . Function signature [source] SQLConnection.driver Returns (str) The name of the driver. For example, "pyodbc" or "psycopg2" . SQLConnection.engine Streamlit Version Version 1.41.0 Version 1.40.0 Version 1.39.0 Version 1.38.0 Version 1.37.0 Version 1.36.0 Version 1.35.0 Version 1.34.0 Version 1.33.0 Version 1.32.0 Version 1.31.0 Version 1.30.0 Version 1.29.0 Version 1.28.0 Version 1.27.0 Version 1.26.0 Version 1.25.0 Version 1.24.0 Version 1.23.0 Version 1.22.0 Version 1.21.0 Version 1.20.0 Streamlit in Snowflake The underlying SQLAlchemy Engine. This is equivalent to accessing self._instance . Function signature [source] SQLConnection.engine Returns (sqlalchemy.engine.base.Engine) The underlying SQLAlchemy Engine. SQLConnection.session Streamlit Version Version 1.41.0 Version 1.40.0 Version 1.39.0 Version 1.38.0 Version 1.37.0 Version 1.36.0 Version 1.35.0 Version 1.34.0 Version 1.33.0 Version 1.32.0 Version 1.31.0 Version 1.30.0 Version 1.29.0 Version 1.28.0 Version 1.27.0 Version 1.26.0 Version 1.25.0 Version 1.24.0 Version 1.23.0 Version 1.22.0 Version 1.21.0 Version 1.20.0 Streamlit in Snowflake Return 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 Returns (sqlalchemy.orm.Session) A SQLAlchemy 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: SnowflakeConnection Next: BaseConnection forum Still have questions? Our forums are full of helpful information and Streamlit experts. Home Contact Us Community © 2025 Snowflake Inc. Cookie policy forum Ask AI |
Login_attempt_to_Streamlit_Community_Cloud_fails_w.txt | Login attempt to Streamlit Community Cloud fails with error 403 - Streamlit Docs Documentation search Search rocket_launch Get started Installation add Fundamentals add First steps add code Develop Concepts add API reference add Tutorials add Quick reference add web_asset Deploy Concepts add Streamlit Community Cloud add Snowflake Other platforms add school Knowledge base FAQ Installing dependencies Deployment issues Home / Knowledge base / Deployment issues / Login attempt to Streamlit Community Cloud fails with error 403 Login attempt to Streamlit Community Cloud fails with error 403 Problem Streamlit Community Cloud has monitoring jobs to detect malicious users using the platform for crypto mining. These jobs sometimes result in false positives and a normal user starts getting error 403 against a login attempt. Solution Please contact Support by providing your GitHub username for help referring to this article. Previous: Huh. This is isn't supposed to happen message after trying to log in Next: How to submit a support case for Streamlit Community Cloud forum Still have questions? Our forums are full of helpful information and Streamlit experts. Home Contact Us Community © 2025 Snowflake Inc. Cookie policy forum Ask AI |
Overview_of_multipage_apps_-_Streamlit_Docs.txt | Overview of multipage apps - Streamlit Docs Documentation search Search rocket_launch Get started Installation add Fundamentals add First steps add code Develop Concepts remove CORE Architecture & execution add Multipage apps remove Overview Page and navigation Pages directory Working with widgets App design add ADDITIONAL Connections and secrets add Custom components add Configuration and theming add App testing add API reference add Tutorials add Quick reference add web_asset Deploy Concepts add Streamlit Community Cloud add Snowflake Other platforms add school Knowledge base FAQ Installing dependencies Deployment issues Home / Develop / Concepts / Multipage apps / Overview Overview of multipage apps Streamlit provides two built-in mechanisms for creating multipage apps. The simplest method is to use a pages/ directory. However, the preferred and more customizable method is to use st.navigation . st.Page and st.navigation If you want maximum flexibility in defining your multipage app, we recommend using st.Page and st.navigation . With st.Page you can declare any Python file or Callable as a page in your app. Furthermore, you can define common elements for your pages in your entrypoint file (the file you pass to streamlit run ). With these methods, your entrypoint file becomes like a picture frame shared by all your pages. You must include st.navigation in your entrypoint file to configure your app's navigation menu. This is also how your entrypoint file serves as the router between your pages. pages/ directory If you're looking for a quick and simple solution, just place a pages/ directory next to your entrypoint file. For every Python file in your pages/ directory, Streamlit will create an additional page for your app. Streamlit determines the page labels and URLs from the file name and automatically populates a navigation menu at the top of your app's sidebar. your_working_directory/ ├── pages/ │ ├── a_page.py │ └── another_page.py └── your_homepage.py Streamlit determines the page order in navigation from the filenames. You can use numerical prefixes in the filenames to adjust page order. For more information, see How pages are sorted in the sidebar . If you want to customize your navigation menu with this option, you can deactivate the default navigation through configuration ( client.showSidebarNavigation = false ). Then, you can use st.page_link to manually contruct a custom navigation menu. With st.page_link , you can change the page label and icon in your navigation menu, but you can't change the URLs of your pages. Page terminology A page has four identifying pieces as follows: Page source : This is a Python file or callable function with the page's source code. Page label : This is how the page is identified within the navigation menu. See looks_one . Page title : This is the content of the HTML <title> element and how the page is identified within a browser tab. See looks_two . Page URL pathname : This is the relative path of the page from the root URL of the app. See looks_3 . Additionly, a page can have two icons as follows: Page favicon : This is the icon next to your page title within a browser tab. See looks_4 . Page icon : This is the icon next to your page label in the navigation menu. See looks_5 . Typically, the page icon and favicon are the same, but it's possible make them different. 1. Page label, 2.Page titles, 3. Page URL pathname, 4.Page favicon, 5. Page icon Automatic page labels and URLs If you use st.Page without declaring the page title or URL pathname, Streamlit falls back on automatically determining the page label, title, and URL pathname in the same manner as when you use a pages/ directory with the default navigation menu. This section describes this naming convention which is shared between the two approaches to multipage apps. Parts of filenames and callables Filenames are composed of four different parts as follows (in order): number : A non-negative integer. separator : Any combination of underscore ( "_" ), dash ( "-" ), and space ( " " ). identifier : Everything up to, but not including, ".py" . ".py" For callables, the function name is the identifier , including any leading or trailing underscores. How Streamlit converts filenames into labels and titles Within the navigation menu, Streamlit displays page labels and titles as follows: If your page has an identifier , Streamlit displays the identifier . Any underscores within the page's identifier are treated as spaces. Therefore, leading and trailing underscores are not shown. Sequential underscores appear as a single space. Otherwise, if your page has a number but does not have an identifier , Streamlit displays the number , unmodified. Leading zeros are included, if present. Otherwise, if your page only has a separator with no number and no identifier , Streamlit will not display the page in the sidebar navigation. The following filenames and callables would all display as "Awesome page" in the sidebar navigation. "Awesome page.py" "Awesome_page.py" "02Awesome_page.py" "--Awesome_page.py" "1_Awesome_page.py" "33 - Awesome page.py" Awesome_page() _Awesome_page() __Awesome_page__() How Streamlit converts filenames into URL pathnames Your app's homepage is associated to the root URL of app. For all other pages, their identifier or number becomes their URL pathname as follows: If your page has an identifier that came from a filename, Streamlit uses the identifier with one modification. Streamlit condenses each consecutive grouping of spaces ( " " ) and underscores ( "_" ) to a single underscore. Otherwise, if your page has an identifier that came from the name of a callable, Streamlit uses the identifier unmodified. Otherwise, if your page has a number but does not have an identifier , Streamlit uses the number . Leading zeros are included, if present. For each filename in the list above, the URL pathname would be "Awesome_page" relative to the root URL of the app. For example, if your app was running on localhost port 8501 , the full URL would be localhost:8501/awesome_page . For the last two callables, however, the pathname would include the leading and trailing underscores to match the callable name exactly. Navigating between pages The primary way users navigate between pages is through the navigation widget. Both methods for defining multipage apps include a default navigation menu that appears in the sidebar. When a user clicks this navigation widget, the app reruns and loads the selected page. 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 as noted above. When multiple files have the same URL pathname, Streamlit picks the first one (based on the ordering in the navigation menu. Users can view a specific page by visiting the page's URL. priority_high Important Navigating between pages by URL creates a new browser session. In particular, clicking markdown links to other pages resets st.session_state . In order to retain values in st.session_state , handle page switching through Streamlit navigation commands and widgets, like st.navigation , st.switch_page , st.page_link , and the built-in navigation menu. 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 "Page not found." Previous: Multipage apps Next: Page and navigation forum Still have questions? Our forums are full of helpful information and Streamlit experts. Home Contact Us Community © 2025 Snowflake Inc. Cookie policy forum Ask AI |
st_column_config_AreaChartColumn___Streamlit_Docs_.txt | st.column_config.AreaChartColumn - Streamlit Docs Documentation search Search rocket_launch Get started Installation add Fundamentals add First steps add code Develop Concepts add API reference remove PAGE ELEMENTS Write and magic add Text elements add Data elements remove st.dataframe st.data_editor st.column_config remove Column Text column Number column Checkbox column Selectbox column Datetime column Date column Time column List column Link column Image column Area chart column Line chart column Bar chart column Progress column st.table st.metric st.json Chart elements add Input widgets add Media elements add Layouts and containers add Chat elements add Status elements add Third-party components open_in_new APPLICATION LOGIC Navigation and pages add Execution flow add Caching and state add Connections and secrets add Custom components add Utilities add Configuration add TOOLS App testing add Command line add Tutorials add Quick reference add web_asset Deploy Concepts add Streamlit Community Cloud add Snowflake Other platforms add school Knowledge base FAQ Installing dependencies Deployment issues Home / Develop / API reference / Data elements / st.column_config / Area chart column st.column_config.AreaChartColumn Streamlit Version Version 1.41.0 Version 1.40.0 Version 1.39.0 Version 1.38.0 Version 1.37.0 Version 1.36.0 Version 1.35.0 Version 1.34.0 Version 1.33.0 Version 1.32.0 Version 1.31.0 Version 1.30.0 Version 1.29.0 Version 1.28.0 Version 1.27.0 Version 1.26.0 Version 1.25.0 Version 1.24.0 Version 1.23.0 Version 1.22.0 Version 1.21.0 Version 1.20.0 Streamlit in Snowflake Configure an area chart column in st.dataframe or st.data_editor . Cells need to contain a list of numbers. Chart columns are not editable at the moment. This command needs to be used in the column_config parameter of st.dataframe or st.data_editor . Function signature [source] st.column_config.AreaChartColumn(label=None, *, width=None, help=None, pinned=None, y_min=None, y_max=None) Parameters label (str or None) The label shown at the top of the column. If this is None (default), the column name is used. width ("small", "medium", "large", or None) The display width of the column. If this is None (default), the column will be sized to fit the cell contents. Otherwise, this can be one of the following: "small" : 75px wide "medium" : 200px wide "large" : 400px wide help (str or None) An optional tooltip that gets displayed when hovering over the column label. If this is None (default), no tooltip is displayed. pinned (bool or None) Whether the column is pinned. A pinned column will stay visible on the left side no matter where the user scrolls. If this is None (default), Streamlit will decide: index columns are pinned, and data columns are not pinned. y_min (int, float, or None) The minimum value on the y-axis for all cells in the column. If this is None (default), every cell will use the minimum of its data. y_max (int, float, or None) The maximum value on the y-axis for all cells in the column. If this is None (default), every cell will use the maximum of its data. Examples import pandas as pd import streamlit as st data_df = pd.DataFrame( { "sales": [ [0, 4, 26, 80, 100, 40], [80, 20, 80, 35, 40, 100], [10, 20, 80, 80, 70, 0], [10, 100, 20, 100, 30, 100], ], } ) st.data_editor( data_df, column_config={ "sales": st.column_config.AreaChartColumn( "Sales (last 6 months)", width="medium", help="The sales volume in the last 6 months", y_min=0, y_max=100, ), }, hide_index=True, ) Built with Streamlit 🎈 Fullscreen open_in_new Previous: Image column Next: Line chart column forum Still have questions? Our forums are full of helpful information and Streamlit experts. Home Contact Us Community © 2025 Snowflake Inc. Cookie policy forum Ask AI |
st.cache_resource_-_Streamlit_Docs.txt | st.cache_resource - Streamlit Docs Documentation search Search rocket_launch Get started Installation add Fundamentals add First steps add code Develop Concepts add API reference remove PAGE ELEMENTS Write and magic add Text elements add Data elements add Chart elements add Input widgets add Media elements add Layouts and containers add Chat elements add Status elements add Third-party components open_in_new APPLICATION LOGIC Navigation and pages add Execution flow add Caching and state remove st.cache_data st.cache_resource st.session_state st.query_params st.experimental_get_query_params delete st.experimental_set_query_params delete Connections and secrets add Custom components add Utilities add Configuration add TOOLS App testing add Command line add Tutorials add Quick reference add web_asset Deploy Concepts add Streamlit Community Cloud add Snowflake Other platforms add school Knowledge base FAQ Installing dependencies Deployment issues Home / Develop / API reference / Caching and state / st.cache_resource star Tip This page only contains information on the st.cache_resource API. For a deeper dive into caching and how to use it, check out Caching . st.cache_resource Streamlit Version Version 1.41.0 Version 1.40.0 Version 1.39.0 Version 1.38.0 Version 1.37.0 Version 1.36.0 Version 1.35.0 Version 1.34.0 Version 1.33.0 Version 1.32.0 Version 1.31.0 Version 1.30.0 Version 1.29.0 Version 1.28.0 Version 1.27.0 Version 1.26.0 Version 1.25.0 Version 1.24.0 Version 1.23.0 Version 1.22.0 Version 1.21.0 Version 1.20.0 Streamlit in Snowflake 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() . A function's arguments must be hashable to cache it. If you have an unhashable argument (like a database connection) or an argument you want to exclude from caching, use an underscore prefix in the argument name. In this case, Streamlit will return a cached value when all other arguments match a previous function call. Alternatively, you can declare custom hashing functions with hash_funcs . To cache data, use st.cache_data instead. Learn more about caching at https://docs.streamlit.io/develop/concepts/architecture/caching . Function signature [source] st.cache_resource(func, *, ttl, max_entries, show_spinner, validate, experimental_allow_widgets, hash_funcs=None) Parameters func (callable) The function that creates the cached resource. Streamlit hashes the function's source code. ttl (float, timedelta, str, or None) The maximum time to keep an entry in the cache. Can be one of: None if cache entries should never expire (default). A number specifying the time in seconds. A string specifying the time in a format supported by Pandas's Timedelta constructor , e.g. "1d" , "1.5 days" , or "1h23s" . A timedelta object from Python's built-in datetime library , e.g. timedelta(days=1) . max_entries (int or None) The maximum number of entries to keep in the cache, or None for an unbounded cache. When a new entry is added to a full cache, the oldest cached entry will be removed. Defaults to None. show_spinner (bool or str) Enable the spinner. Default is True to show a spinner when there is a "cache miss" and the cached resource is being created. If string, value of show_spinner param will be used for spinner text. validate (callable or None) An optional validation function for cached data. validate is called each time the cached value is accessed. It receives the cached value as its only parameter and it must return a boolean. If validate returns False, the current cached value is discarded, and the decorated function is called to compute a new value. This is useful e.g. to check the health of database connections. experimental_allow_widgets (bool) delete The cached widget replay functionality was removed in 1.38. Please remove the experimental_allow_widgets parameter from your caching decorators. This parameter will be removed in a future version. Allow widgets to be used in the cached function. Defaults to False. hash_funcs (dict or None) Mapping of types or fully qualified names to hash functions. This is used to override the behavior of the hasher inside Streamlit's caching mechanism: when the hasher encounters an object, it will first check to see if its type matches a key in this dict and, if so, will use the provided function to generate a hash for it. See below for an example of how this can be used. Example import streamlit as st @st.cache_resource def get_database_session(url): # Create a database session object that points to the URL. return session s1 = get_database_session(SESSION_URL_1) # Actually executes the function, since this is the first time it was # encountered. s2 = get_database_session(SESSION_URL_1) # Does not execute the function. Instead, returns its previously computed # value. This means that now the connection object in s1 is the same as in s2. s3 = get_database_session(SESSION_URL_2) # This is a different URL, so the function executes. By default, all parameters to a cache_resource function must be hashable. Any parameter whose name begins with _ will not be hashed. You can use this as an "escape hatch" for parameters that are not hashable: import streamlit as st @st.cache_resource def get_database_session(_sessionmaker, url): # Create a database connection object that points to the URL. return connection s1 = get_database_session(create_sessionmaker(), DATA_URL_1) # Actually executes the function, since this is the first time it was # encountered. s2 = get_database_session(create_sessionmaker(), DATA_URL_1) # Does not execute the function. Instead, returns its previously computed # value - even though the _sessionmaker parameter was different # in both calls. A cache_resource function's cache can be procedurally cleared: import streamlit as st @st.cache_resource def get_database_session(_sessionmaker, url): # Create a database connection object that points to the URL. return connection fetch_and_clean_data.clear(_sessionmaker, "https://streamlit.io/") # Clear the cached entry for the arguments provided. get_database_session.clear() # Clear all cached entries for this function. To override the default hashing behavior, pass a custom hash function. You can do that by mapping a type (e.g. Person ) to a hash function ( str ) like this: import streamlit as st from pydantic import BaseModel class Person(BaseModel): name: str @st.cache_resource(hash_funcs={Person: str}) def get_person_name(person: Person): return person.name Alternatively, you can map the type's fully-qualified name (e.g. "__main__.Person" ) to the hash function instead: import streamlit as st from pydantic import BaseModel class Person(BaseModel): name: str @st.cache_resource(hash_funcs={"__main__.Person": str}) def get_person_name(person: Person): return person.name st.cache_resource.clear Streamlit Version Version 1.41.0 Version 1.40.0 Version 1.39.0 Version 1.38.0 Version 1.37.0 Version 1.36.0 Version 1.35.0 Version 1.34.0 Version 1.33.0 Version 1.32.0 Version 1.31.0 Version 1.30.0 Version 1.29.0 Version 1.28.0 Version 1.27.0 Version 1.26.0 Version 1.25.0 Version 1.24.0 Version 1.23.0 Version 1.22.0 Version 1.21.0 Version 1.20.0 Streamlit in Snowflake Clear all cache_resource caches. Function signature [source] st.cache_resource.clear() Example In the example below, pressing the "Clear All" button will clear all cache_resource caches. i.e. Clears cached global resources from all functions decorated with @st.cache_resource . import streamlit as st from transformers import BertModel @st.cache_resource def get_database_session(url): # Create a database session object that points to the URL. return session @st.cache_resource def get_model(model_type): # Create a model of the specified type. return BertModel.from_pretrained(model_type) if st.button("Clear All"): # Clears all st.cache_resource caches: st.cache_resource.clear() CachedFunc.clear Streamlit Version Version 1.41.0 Version 1.40.0 Version 1.39.0 Version 1.38.0 Version 1.37.0 Version 1.36.0 Version 1.35.0 Version 1.34.0 Version 1.33.0 Version 1.32.0 Version 1.31.0 Version 1.30.0 Version 1.29.0 Version 1.28.0 Version 1.27.0 Version 1.26.0 Version 1.25.0 Version 1.24.0 Version 1.23.0 Version 1.22.0 Version 1.21.0 Version 1.20.0 Streamlit in Snowflake Clear the cached function's associated cache. If no arguments are passed, Streamlit will clear all values cached for the function. If arguments are passed, Streamlit will clear the cached value for these arguments only. Function signature [source] CachedFunc.clear(*args, **kwargs) Parameters *args (Any) Arguments of the cached functions. **kwargs (Any) Keyword arguments of the cached function. Example import streamlit as st import time @st.cache_data def foo(bar): time.sleep(2) st.write(f"Executed foo({bar}).") return bar if st.button("Clear all cached values for `foo`", on_click=foo.clear): foo.clear() if st.button("Clear the cached value of `foo(1)`"): foo.clear(1) foo(1) foo(2) Using Streamlit commands in cached functions Static elements Since version 1.16.0, cached functions can contain Streamlit commands! For example, you can do this: from transformers import pipeline @st.cache_resource def load_model(): model = pipeline("sentiment-analysis") st.success("Loaded NLP model from Hugging Face!") # 👈 Show a success message return model As we know, Streamlit only runs this function if it hasn’t been cached before. On this first run, the st.success message will appear in the app. But what happens on subsequent runs? It still shows up! Streamlit realizes that there is an st. command inside the cached function, saves it during the first run, and replays it on subsequent runs. Replaying static elements works for both caching decorators. You can also use this functionality to cache entire parts of your UI: @st.cache_resource def load_model(): st.header("Data analysis") model = torchvision.models.resnet50(weights=ResNet50_Weights.DEFAULT) st.success("Loaded model!") st.write("Turning on evaluation mode...") model.eval() st.write("Here's the model:") return model Input widgets You can also use interactive input widgets like st.slider or st.text_input in cached functions. Widget replay is an experimental feature at the moment. To enable it, you need to set the experimental_allow_widgets parameter: @st.cache_resource(experimental_allow_widgets=True) # 👈 Set the parameter def load_model(): pretrained = st.checkbox("Use pre-trained model:") # 👈 Add a checkbox model = torchvision.models.resnet50(weights=ResNet50_Weights.DEFAULT, pretrained=pretrained) return model Streamlit treats the checkbox like an additional input parameter to the cached function. If you uncheck it, Streamlit will see if it has already cached the function for this checkbox state. If yes, it will return the cached value. If not, it will rerun the function using the new slider value. Using widgets in cached functions is extremely powerful because it lets you cache entire parts of your app. But it can be dangerous! Since Streamlit treats the widget value as an additional input parameter, it can easily lead to excessive memory usage. Imagine your cached function has five sliders and returns a 100 MB DataFrame. Then we’ll add 100 MB to the cache for every permutation of these five slider values – even if the sliders do not influence the returned data! These additions can make your cache explode very quickly. Please be aware of this limitation if you use widgets in cached functions. We recommend using this feature only for isolated parts of your UI where the widgets directly influence the cached return value. priority_high Warning Support for widgets in cached functions is currently experimental. We may change or remove it anytime without warning. Please use it with care! push_pin Note Two widgets are currently not supported in cached functions: st.file_uploader and st.camera_input . We may support them in the future. Feel free to open a GitHub issue if you need them! Previous: st.cache_data Next: st.experimental_memo forum Still have questions? Our forums are full of helpful information and Streamlit experts. Home Contact Us Community © 2025 Snowflake Inc. Cookie policy forum Ask AI |
Tutorials_-_Streamlit_Docs.txt | Tutorials - Streamlit Docs Documentation search Search rocket_launch Get started Installation add Fundamentals add First steps add code Develop Concepts add API reference add Tutorials remove Elements add Execution flow add Connect to data sources add Multipage apps add Work with LLMs add Quick reference add web_asset Deploy Concepts add Streamlit Community Cloud add Snowflake Other platforms add school Knowledge base FAQ Installing dependencies Deployment issues Home / Develop / Tutorials Tutorials Our tutorials include step-by-step examples of building different types of apps in Streamlit. Use core features to work with Streamlit's execution model Build simple apps and walk through examples to learn about Streamlit's core features and execution model. Connect to data sources Connect to popular datasources. Create multipage apps Create multipage apps, navigation, and flows. Chat apps and LLMs Work with LLMs and create chat apps. When you're done developing your app, see our deployment tutorials , too! Previous: API reference Next: Elements forum Still have questions? Our forums are full of helpful information and Streamlit experts. Home Contact Us Community © 2025 Snowflake Inc. Cookie policy forum Ask AI |
Managing_dependencies_when_deploying_your_app___St.txt | Managing dependencies when deploying your app - Streamlit Docs Documentation search Search rocket_launch Get started Installation add Fundamentals add First steps add code Develop Concepts add API reference add Tutorials add Quick reference add web_asset Deploy Concepts remove Dependencies Secrets Streamlit Community Cloud add Snowflake Other platforms add school Knowledge base FAQ Installing dependencies Deployment issues Home / Deploy / Concepts / Dependencies Managing dependencies when deploying your app Before you began developing your app, you set up and configured your development environment by installing Python and Streamlit. When you deploy your app, you need to set up and configure your deployment environment in the same way. When you deploy your app to a cloud service, your app's Python server will be running on a remote machine. This remote machine will not have access all the files and programs on your personal computer. All Streamlit apps have at least two dependencies: Python and Streamlit. Your app may have additional dependencies in the form of Python packages or software that must be installed to properly execute your script. If you are using a service like Streamlit Community Cloud which is designed for Streamlit apps, we'll take care of Python and Streamlit for you! Install Python and other software If you are using Streamlit Community Cloud, Python is already installed. You can just pick the version in the deployment dialog. If you need to install Python yourself or you have other non-Python software to install, follow your platform's instructions to install additional software. You will commonly use a package management tool to do this. For example, Streamlit Community Cloud uses Advanced Package Tool ( apt ) for Debian-based Linux systems. For more information about installing non-Python depencies on Streamlit Community Cloud, see apt-get dependencies . Install Python packages Once you have Python installed in your deployment environment, you'll need to install all the necessary Python packages, including Streamlit! With each import of an installed package, you add a Python dependency to your script. You need to install those dependencies in your deployment environment through a Python package manager. If you are using Streamlit Community Cloud, you'll have the latest version of Streamlit and all of its dependencies installed by default. So, if you're making a simple app and don't need additional dependencies, you won't have to do anything at all! pip and requirements.txt Since pip comes by default with Python, the most common way to configure your Python environment is with a requirements.txt file. Each line of a requirements.txt file is a package to pip install . You should not include built-in Python libraries like math , random , or distutils in your requirements.txt file. These are a part of Python and aren't installed separately. star Tip Since dependencies may rely on a specific version of Python, always be aware of the Python version used in your development environment, and select the same version for your deployment environment. If you have a script like the following, you would only need to install Streamlit. No extra dependencies would be needed since pandas and numpy are installed as direct dependencies of streamlit . Similarly, math and random are built into Python. import streamlit as st import pandas as pd import numpy as np import math import random st.write('Hi!') However, it's a best practice accurately record packages you use, so the recommended requirements.txt file would be: streamlit pandas numpy If you needed to specify certain versions, another valid example would be: streamlit==1.24.1 pandas>2.0 numpy<=1.25.1 A requirements.txt file is commonly saved in the root of your repository or file directory. If you are using Streamlit Community Cloud, see Add Python dependencies for more information. Otherwise, check your platform's documentation. Previous: Concepts Next: Secrets forum Still have questions? Our forums are full of helpful information and Streamlit experts. Home Contact Us Community © 2025 Snowflake Inc. Cookie policy forum Ask AI |
st.connection_-_Streamlit_Docs.txt | st.connection - Streamlit Docs Documentation search Search rocket_launch Get started Installation add Fundamentals add First steps add code Develop Concepts add API reference remove PAGE ELEMENTS Write and magic add Text elements add Data elements add Chart elements add Input widgets add Media elements add Layouts and containers add Chat elements add Status elements add Third-party components open_in_new APPLICATION LOGIC Navigation and pages add Execution flow add Caching and state add Connections and secrets remove SECRETS st.secrets secrets.toml CONNECTIONS st.connection SnowflakeConnection SQLConnection BaseConnection SnowparkConnection delete Custom components add Utilities add Configuration add TOOLS App testing add Command line add Tutorials add Quick reference add web_asset Deploy Concepts add Streamlit Community Cloud add Snowflake Other platforms add school Knowledge base FAQ Installing dependencies Deployment issues Home / Develop / API reference / Connections and secrets / st.connection star Tip This 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.connection Streamlit Version Version 1.41.0 Version 1.40.0 Version 1.39.0 Version 1.38.0 Version 1.37.0 Version 1.36.0 Version 1.35.0 Version 1.34.0 Version 1.33.0 Version 1.32.0 Version 1.31.0 Version 1.30.0 Version 1.29.0 Version 1.28.0 Version 1.27.0 Version 1.26.0 Version 1.25.0 Version 1.24.0 Version 1.23.0 Version 1.22.0 Version 1.21.0 Version 1.20.0 Streamlit in Snowflake Create a new connection to a data store or API, or return an existing one. Configuration options, credentials, and secrets for connections are combined from the following sources: The keyword arguments passed to this command. The app's secrets.toml files. Any connection-specific configuration files. The connection returned from st.connection is internally cached with st.cache_resource and is therefore shared between sessions. 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 secrets.toml . Streamlit uses secrets under [connections.<name>] for the connection. type will be inferred if name is one of the following: "snowflake" , "snowpark" , or "sql" . type (str, connection class, or None) The type of connection to create. This can be one of the following: None (default): Streamlit will infer the connection type from name . If the type is not inferrable from name , the type must be specified in secrets.toml instead. "snowflake" : Streamlit will initialize a connection with SnowflakeConnection . "snowpark" : Streamlit will initialize a connection with SnowparkConnection . This is deprecated. "sql" : Streamlit will initialize a connection with SQLConnection . A string path to an importable class: This must be a dot-separated module path ending in the importable class. Streamlit will import the class and initialize a connection with it. The class must extend st.connections.BaseConnection . An imported class reference: Streamlit will initialize a connection with the referenced class, which must extend st.connections.BaseConnection . max_entries (int or None) The maximum number of connections to keep in the cache. If this is None (default), the cache is unbounded. Otherwise, when a new entry is added to a full cache, the oldest cached entry is removed. ttl (float, timedelta, or None) The maximum number of seconds to keep results in the cache. If this is None (default), cached results do not expire with time. **kwargs (any) Connection-specific keyword arguments that are passed to the connection's ._connect() method. **kwargs are typically combined with (and take precendence over) key-value pairs in secrets.toml . To learn more, see the specific connection's documentation. Returns (Subclass of BaseConnection) An initialized connection object of the specified type . Examples Example 1: Inferred connection type 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. The following example creates a "sql" -type connection. .streamlit/secrets.toml : [connections.sql] dialect = "xxx" host = "xxx" username = "xxx" password = "xxx" Your app code: import streamlit as st conn = st.connection("sql") Example 2: Named connections Creating a connection with a custom name requires you to explicitly specify the type. If type is not passed as a keyword argument, it must be set in the appropriate section of secrets.toml . The following example creates two "sql" -type connections, each with their own custom name. The first defines type in the st.connection command; the second defines type in secrets.toml . .streamlit/secrets.toml : [connections.first_connection] dialect = "xxx" host = "xxx" username = "xxx" password = "xxx" [connections.second_connection] type = "sql" dialect = "yyy" host = "yyy" username = "yyy" password = "yyy" Your app code: import streamlit as st conn1 = st.connection("first_connection", type="sql") conn2 = st.connection("second_connection") Example 3: Using a path to the connection class Passing the full module path to the connection class can be useful, especially when working with a custom connection. Although this is not the typical way to create first party connections, the following example creates the same type of connection as one with type="sql" . Note that type is a string path. .streamlit/secrets.toml : [connections.my_sql_connection] url = "xxx+xxx://xxx:xxx@xxx:xxx/xxx" Your app code: import streamlit as st conn = st.connection( "my_sql_connection", type="streamlit.connections.SQLConnection" ) Example 4: Importing the connection class You can pass the connection class directly to the st.connection command. Doing so allows static type checking tools such as mypy to infer the exact return type of st.connection . The following example creates the same connection as in Example 3. .streamlit/secrets.toml : [connections.my_sql_connection] url = "xxx+xxx://xxx:xxx@xxx:xxx/xxx" Your app code: 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.toml Next: SnowflakeConnection forum Still have questions? Our forums are full of helpful information and Streamlit experts. Home Contact Us Community © 2025 Snowflake Inc. Cookie policy forum Ask AI |
Multipage_apps_-_Streamlit_Docs.txt | Multipage apps - Streamlit Docs Documentation search Search rocket_launch Get started Installation add Fundamentals add First steps add code Develop Concepts remove CORE Architecture & execution add Multipage apps remove Overview Page and navigation Pages directory Working with widgets App design add ADDITIONAL Connections and secrets add Custom components add Configuration and theming add App testing add API reference add Tutorials add Quick reference add web_asset Deploy Concepts add Streamlit Community Cloud add Snowflake Other platforms add school Knowledge base FAQ Installing dependencies Deployment issues Home / Develop / Concepts / Multipage apps Multipage apps Overview of multipage apps Streamlit provides multiple ways to define multipage apps. Understand the terminology and basic comparison between methods. Define multipage apps with st.Page and st.navigation Learn about the preferred method for defining multipage apps. st.Page and st.navigation give you flexibility to organize your project directory and label your pages as you please. Creating multipage apps using the pages/ directory Define your multipage apps through directory structure. Place additional Python files in a pages/ directory alongside your entrypoint file and pages are automatically shown in a navigation widget inside your app's sidebar. Working with widgets in multipage apps Understand how widget identity is tied to pages. Learn strategies to get the behavior you want out of widgets. Previous: Architecture & execution Next: Overview forum Still have questions? Our forums are full of helpful information and Streamlit experts. Home Contact Us Community © 2025 Snowflake Inc. Cookie policy forum Ask AI |
st.navigation_-_Streamlit_Docs.txt | st.navigation - Streamlit Docs Documentation search Search rocket_launch Get started Installation add Fundamentals add First steps add code Develop Concepts add API reference remove PAGE ELEMENTS Write and magic add Text elements add Data elements add Chart elements add Input widgets add Media elements add Layouts and containers add Chat elements add Status elements add Third-party components open_in_new APPLICATION LOGIC Navigation and pages remove st.navigation st.Page st.page_link link st.switch_page Execution flow add Caching and state add Connections and secrets add Custom components add Utilities add Configuration add TOOLS App testing add Command line add Tutorials add Quick reference add web_asset Deploy Concepts add Streamlit Community Cloud add Snowflake Other platforms add school Knowledge base FAQ Installing dependencies Deployment issues Home / Develop / API reference / Navigation and pages / st.navigation st.navigation Streamlit Version Version 1.41.0 Version 1.40.0 Version 1.39.0 Version 1.38.0 Version 1.37.0 Version 1.36.0 Version 1.35.0 Version 1.34.0 Version 1.33.0 Version 1.32.0 Version 1.31.0 Version 1.30.0 Version 1.29.0 Version 1.28.0 Version 1.27.0 Version 1.26.0 Version 1.25.0 Version 1.24.0 Version 1.23.0 Version 1.22.0 Version 1.21.0 Version 1.20.0 Streamlit in Snowflake Configure the available pages in a multipage app. Call st.navigation in your entrypoint file with one or more pages defined by st.Page . st.navigation returns the current page, which can be executed using .run() method. When using st.navigation , your entrypoint file (the file passed to streamlit run ) acts like a router or frame of common elements around each of your pages. Streamlit executes the entrypoint file with every app rerun. To execute the current page, you must call the .run() method on the StreamlitPage object returned by st.navigation . The set of available pages can be updated with each rerun for dynamic navigation. By default, st.navigation draws the available pages in the side navigation if there is more than one page. This behavior can be changed using the position keyword argument. As soon as any session of your app executes the st.navigation command, your app will ignore the pages/ directory (across all sessions). Function signature [source] st.navigation(pages, *, position="sidebar", expanded=False) Parameters pages (list[StreamlitPage] or dict[str, list[StreamlitPage]]) The available pages for the app. To create labeled sections or page groupings within the navigation menu, pages must be a dictionary. Each key is the label of a section and each value is the list of StreamlitPage objects for that section. To create a navigation menu with no sections or page groupings, pages must be a list of StreamlitPage objects. Use st.Page to create StreamlitPage objects. position ("sidebar" or "hidden") The position of the navigation menu. If position is "sidebar" (default), the navigation widget appears at the top of the sidebar. If position is "hidden" , the navigation widget is not displayed. If there is only one page in pages , the navigation will be hidden for any value of position . expanded (bool) Whether the navigation menu should be expanded. If this is False (default), the navigation menu will be collapsed and will include a button to view more options when there are too many pages to display. If this is True , the navigation menu will always be expanded; no button to collapse the menu will be displayed. If st.navigation changes from expanded=True to expanded=False on a rerun, the menu will stay expanded and a collapse button will be displayed. Returns (StreamlitPage) The current page selected by the user. Examples The following examples show possible entrypoint files, which is the file you pass to streamlit run . Your entrypoint file manages your app's navigation and serves as a router between pages. Example 1: Use a callable or Python file as a page You can declare pages from callables or file paths. page_1.py (in the same directory as your entrypoint file): import streamlit as st st.title("Page 1") Your entrypoint file: import streamlit as st def page_2(): st.title("Page 2") pg = st.navigation([st.Page("page_1.py"), st.Page(page_2)]) pg.run() Built with Streamlit 🎈 Fullscreen open_in_new Example 2: Group pages into sections You can use a dictionary to create sections within your navigation menu. In the following example, each page is similar to Page 1 in Example 1, and all pages are in the same directory. However, you can use Python files from anywhere in your repository. For more information, see st.Page . Directory structure: your_repository/ ├── create_account.py ├── learn.py ├── manage_account.py ├── streamlit_app.py └── trial.py streamlit_app.py : import streamlit as st pages = { "Your account": [ st.Page("create_account.py", title="Create your account"), st.Page("manage_account.py", title="Manage your account"), ], "Resources": [ st.Page("learn.py", title="Learn about us"), st.Page("trial.py", title="Try it out"), ], } pg = st.navigation(pages) pg.run() Built with Streamlit 🎈 Fullscreen open_in_new Example 3: Stateful widgets across multiple pages Call widget functions in your entrypoint file when you want a widget to be stateful across pages. Assign keys to your common widgets and access their values through Session State within your pages. import streamlit as st def page1(): st.write(st.session_state.foo) def page2(): st.write(st.session_state.bar) # Widgets shared by all the pages st.sidebar.selectbox("Foo", ["A", "B", "C"], key="foo") st.sidebar.checkbox("Bar", key="bar") pg = st.navigation([st.Page(page1), st.Page(page2)]) pg.run() Built with Streamlit 🎈 Fullscreen open_in_new Previous: Navigation and pages Next: st.Page forum Still have questions? Our forums are full of helpful information and Streamlit experts. Home Contact Us Community © 2025 Snowflake Inc. Cookie policy forum Ask AI |
Build_an_LLM_app_using_LangChain___Streamlit_Docs_.txt | Build an LLM app using LangChain - Streamlit Docs Documentation search Search rocket_launch Get started Installation add Fundamentals add First steps add code Develop Concepts add API reference add Tutorials remove Elements add Execution flow add Connect to data sources add Multipage apps add Work with LLMs remove Build a basic LLM chat app Build an LLM app using LangChain Quick reference add web_asset Deploy Concepts add Streamlit Community Cloud add Snowflake Other platforms add school Knowledge base FAQ Installing dependencies Deployment issues Home / Develop / Tutorials / Work with LLMs / Build an LLM app using LangChain Build an LLM app using LangChain OpenAI, LangChain, and Streamlit in 18 lines of code In this tutorial, you will build a Streamlit LLM app that can generate text from a user-provided prompt. This Python app will use the LangChain framework and Streamlit. Optionally, you can deploy your app to Streamlit Community Cloud when you're done. This tutorial is adapted from a blog post by Chanin Nantesanamat: LangChain tutorial #1: Build an LLM-powered app in 18 lines of code . Built with Streamlit 🎈 Fullscreen open_in_new Objectives Get an OpenAI key from the end user. Validate the user's OpenAI key. Get a text prompt from the user. Authenticate OpenAI with the user's key. Send the user's prompt to OpenAI's API. Get a response and display it. Bonus: Deploy the app on Streamlit Community Cloud! Prerequisites Python 3.9+ Streamlit LangChain OpenAI API key Setup coding environment In your IDE (integrated coding environment), open the terminal and install the following two Python libraries: pip install streamlit langchain-openai Create a requirements.txt file located in the root of your working directory and save these dependencies. This is necessary for deploying the app to the Streamlit Community Cloud later. streamlit openai langchain Building the app The app is only 18 lines of code: import streamlit as st from langchain_openai.chat_models import ChatOpenAI st.title("🦜🔗 Quickstart App") openai_api_key = st.sidebar.text_input("OpenAI API Key", type="password") def generate_response(input_text): model = ChatOpenAI(temperature=0.7, api_key=openai_api_key) st.info(model.invoke(input_text)) with st.form("my_form"): text = st.text_area( "Enter text:", "What are the three key pieces of advice for learning how to code?", ) submitted = st.form_submit_button("Submit") if not openai_api_key.startswith("sk-"): st.warning("Please enter your OpenAI API key!", icon="⚠") if submitted and openai_api_key.startswith("sk-"): generate_response(text) To start, create a new Python file and save it as streamlit_app.py in the root of your working directory. Import the necessary Python libraries. import streamlit as st from langchain_openai.chat_models import ChatOpenAI Create the app's title using st.title . st.title("🦜🔗 Quickstart App") Add a text input box for the user to enter their OpenAI API key. openai_api_key = st.sidebar.text_input("OpenAI API Key", type="password") Define a function to authenticate to OpenAI API with the user's key, send a prompt, and get an AI-generated response. This function accepts the user's prompt as an argument and displays the AI-generated response in a blue box using st.info . def generate_response(input_text): model = ChatOpenAI(temperature=0.7, api_key=openai_api_key) st.info(model.invoke(input_text)) Finally, use st.form() to create a text box ( st.text_area() ) for user input. When the user clicks Submit , the generate-response() function is called with the user's input as an argument. with st.form("my_form"): text = st.text_area( "Enter text:", "What are the three key pieces of advice for learning how to code?", ) submitted = st.form_submit_button("Submit") if not openai_api_key.startswith("sk-"): st.warning("Please enter your OpenAI API key!", icon="⚠") if submitted and openai_api_key.startswith("sk-"): generate_response(text) Remember to save your file! Return to your computer's terminal to run the app. streamlit run streamlit_app.py Deploying the app To deploy the app to the Streamlit Cloud, follow these steps: Create a GitHub repository for the app. Your repository should contain two files: your-repository/ ├── streamlit_app.py └── requirements.txt Go to Streamlit Community Cloud , click the New app button from your workspace, then specify the repository, branch, and main file path. Optionally, you can customize your app's URL by choosing a custom subdomain. Click the Deploy! button. Your app will now be deployed to Streamlit Community Cloud and can be accessed from around the world! 🌎 Conclusion Congratulations on building an LLM-powered Streamlit app in 18 lines of code! 🥳 You can use this app to generate text from any prompt that you provide. The app is limited by the capabilities of the OpenAI LLM, but it can still be used to generate some creative and interesting text. We hope you found this tutorial helpful! Check out more examples to see the power of Streamlit and LLM. 💖 Happy Streamlit-ing! 🎈 Previous: Build a basic LLM chat app Next: Quick reference forum Still have questions? Our forums are full of helpful information and Streamlit experts. Home Contact Us Community © 2025 Snowflake Inc. Cookie policy forum Ask AI |
App_testing_-_Streamlit_Docs.txt | App testing - Streamlit Docs Documentation search Search rocket_launch Get started Installation add Fundamentals add First steps add code Develop Concepts add API reference remove PAGE ELEMENTS Write and magic add Text elements add Data elements add Chart elements add Input widgets add Media elements add Layouts and containers add Chat elements add Status elements add Third-party components open_in_new APPLICATION LOGIC Navigation and pages add Execution flow add Caching and state add Connections and secrets add Custom components add Utilities add Configuration add TOOLS App testing remove st.testing.v1.AppTest Testing element classes Command line add Tutorials add Quick reference add web_asset Deploy Concepts add Streamlit Community Cloud add Snowflake Other platforms add school Knowledge base FAQ Installing dependencies Deployment issues Home / Develop / API reference / App testing App testing Streamlit app testing framework enables developers to build and run headless tests that execute their app code directly, simulate user input, and inspect rendered outputs for correctness. The provided class, AppTest, simulates a running app and 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. 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. The AppTest class st.testing.v1.AppTest st.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_file st.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.secrets["WORD"] = "Foobar" at.run() assert not at.exception AppTest.from_string st.testing.v1.AppTest.from_string initializes a simulated app from a string. from streamlit.testing.v1 import AppTest app_script = """ import streamlit as st word_of_the_day = st.text_input("What's the word of the day?", key="word") if word_of_the_day == st.secrets["WORD"]: st.success("That's right!") elif word_of_the_day and word_of_the_day != st.secrets["WORD"]: st.warn("Try again.") """ at = AppTest.from_string(app_script) at.secrets["WORD"] = "Foobar" at.run() assert not at.exception AppTest.from_function st.testing.v1.AppTest.from_function initializes a simulated app from a function. from streamlit.testing.v1 import AppTest def app_script (): import streamlit as st word_of_the_day = st.text_input("What's the word of the day?", key="word") if word_of_the_day == st.secrets["WORD"]: st.success("That's right!") elif word_of_the_day and word_of_the_day != st.secrets["WORD"]: st.warn("Try again.") at = AppTest.from_function(app_script) at.secrets["WORD"] = "Foobar" at.run() assert not at.exception Testing-element classes Block A 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 Element The 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" Button A representation of st.button and st.form_submit_button . at.button[0].click().run() ChatInput A representation of st.chat_input . at.chat_input[0].set_value("What is Streamlit?").run() Checkbox A representation of st.checkbox . at.checkbox[0].check().run() ColorPicker A representation of st.color_picker . at.color_picker[0].pick("#FF4B4B").run() DateInput A representation of st.date_input . release_date = datetime.date(2023, 10, 26) at.date_input[0].set_value(release_date).run() Multiselect A representation of st.multiselect . at.multiselect[0].select("New York").run() NumberInput A representation of st.number_input . at.number_input[0].increment().run() Radio A representation of st.radio . at.radio[0].set_value("New York").run() SelectSlider A representation of st.select_slider . at.select_slider[0].set_range("A","C").run() Selectbox A representation of st.selectbox . at.selectbox[0].select("New York").run() Slider A representation of st.slider . at.slider[0].set_range(2,5).run() TextArea A representation of st.text_area . at.text_area[0].input("Streamlit is awesome!").run() TextInput A representation of st.text_input . at.text_input[0].input("Streamlit").run() TimeInput A representation of st.time_input . at.time_input[0].increment().run() Toggle A representation of st.toggle . at.toggle[0].set_value("True").run() Previous: Configuration Next: st.testing.v1.AppTest forum Still have questions? Our forums are full of helpful information and Streamlit experts. Home Contact Us Community © 2025 Snowflake Inc. Cookie policy forum Ask AI |
Fork_and_edit_a_public_app_-_Streamlit_Docs.txt | Fork and edit a public app - Streamlit Docs Documentation search Search rocket_launch Get started Installation add Fundamentals add First steps add code Develop Concepts add API reference add Tutorials add Quick reference add web_asset Deploy Concepts add Streamlit Community Cloud remove Get started remove Quickstart Create your account Connect your GitHub account Explore your workspace Deploy from a template Fork and edit a public app Trust and security Deploy your app add Manage your app add Share your app add Manage your account add Status and limitations Snowflake Other platforms add school Knowledge base FAQ Installing dependencies Deployment issues Home / Deploy / Streamlit Community Cloud / Get started / Fork and edit a public app Fork and edit a public app Community Cloud is all about learning, sharing, and exploring the world of Streamlit. For apps with public repositories, you can quickly fork copies to your GitHub account, deploy your own version, and jump into a codespace on GitHub to start editing and exploring Streamlit code. From a forkable app, in the upper-right corner, click " Fork ." Optional: In the "App URL" field, choose a custom subdomain for your app. Every Community Cloud app is deployed to a subdomain on streamlit.app , but you can change your app's subdomain at any time. For more information, see App settings . Click " Fork! " The repository will be forked to your GitHub account. If you have already forked the repository, Community Cloud will use the existing fork. If your existing fork already has an associated codespace, the codespace will be reused. priority_high Warning Do not use this method in the following situations: You have an existing repository that matches the fork name (but isn't a fork of this app). You have an existing fork of this app, but you've changed the name of the repository. If you have an existing fork of this app and kept the original repository name, Community Cloud will use your existing fork. If you've previously deployed the app and opened a codespace, Community Cloud will open your existing codespace. Wait for GitHub to set up your codespace. It can take several minutes to fully initialize your codespace. After the Visual Studio Code editor appears in your codespace, it can take several minutes to install Python and start the Streamlit server. When complete, a split screen view displays a code editor on the left and a running app on the right. The code editor opens two tabs by default: the repository's readme file and the app's entrypoint file. priority_high Important The app displayed in your codespace is not the same instance you deployed on Community Cloud. Your codespace is a self-contained development environment. When you make edits inside a codespace, those edits don't leave the codespace until you commit them to your repository. When you commit your changes to your repository, Community Cloud detects the changes and updates your deployed app. To learn more, see Edit your app . Edit your newly forked app as desired. For more instructions on working with GitHub Codespaces, see Edit your app . Previous: Deploy from a template Next: Trust and security forum Still have questions? Our forums are full of helpful information and Streamlit experts. Home Contact Us Community © 2025 Snowflake Inc. Cookie policy forum Ask AI |
st.write_stream_-_Streamlit_Docs.txt | st.write_stream - Streamlit Docs Documentation search Search rocket_launch Get started Installation add Fundamentals add First steps add code Develop Concepts add API reference remove PAGE ELEMENTS Write and magic remove st.write st.write_stream magic Text elements add Data elements add Chart elements add Input widgets add Media elements add Layouts and containers add Chat elements add Status elements add Third-party components open_in_new APPLICATION LOGIC Navigation and pages add Execution flow add Caching and state add Connections and secrets add Custom components add Utilities add Configuration add TOOLS App testing add Command line add Tutorials add Quick reference add web_asset Deploy Concepts add Streamlit Community Cloud add Snowflake Other platforms add school Knowledge base FAQ Installing dependencies Deployment issues Home / Develop / API reference / Write and magic / st.write_stream st.write_stream Streamlit Version Version 1.41.0 Version 1.40.0 Version 1.39.0 Version 1.38.0 Version 1.37.0 Version 1.36.0 Version 1.35.0 Version 1.34.0 Version 1.33.0 Version 1.32.0 Version 1.31.0 Version 1.30.0 Version 1.29.0 Version 1.28.0 Version 1.27.0 Version 1.26.0 Version 1.25.0 Version 1.24.0 Version 1.23.0 Version 1.22.0 Version 1.21.0 Version 1.20.0 Streamlit in Snowflake Stream a generator, iterable, or stream-like sequence to the app. st.write_stream iterates through the given sequences and writes all chunks to the app. String chunks will be written using a typewriter effect. Other data types will be written using st.write . Function signature [source] st.write_stream(stream) Parameters stream (Callable, Generator, Iterable, OpenAI Stream, or LangChain Stream) The generator or iterable to stream. If you pass an async generator, Streamlit will internally convert it to a sync generator. Note To use additional LLM libraries, you can create a wrapper to manually define a generator function and include custom output parsing. Returns (str or list) The full response. If the streamed output only contains text, this is a string. Otherwise, this is a list of all the streamed objects. The return value is fully compatible as input for st.write . Example You can pass an OpenAI stream as shown in our tutorial, Build a basic LLM chat app . Alternatively, you can pass a generic generator function as input: import time import numpy as np import pandas as pd import streamlit as st _LOREM_IPSUM = """ Lorem ipsum dolor sit amet, **consectetur adipiscing** elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. """ def stream_data(): for word in _LOREM_IPSUM.split(" "): yield word + " " time.sleep(0.02) yield pd.DataFrame( np.random.randn(5, 10), columns=["a", "b", "c", "d", "e", "f", "g", "h", "i", "j"], ) for word in _LOREM_IPSUM.split(" "): yield word + " " time.sleep(0.02) if st.button("Stream data"): st.write_stream(stream_data) Built with Streamlit 🎈 Fullscreen open_in_new star Tip If your stream object is not compatible with st.write_stream , define a wrapper around your stream object to create a compatible generator function. for chunk in unsupported_stream: yield preprocess(chunk) For an example, see how we use Replicate with Snowflake Arctic in this code . Previous: st.write Next: magic forum Still have questions? Our forums are full of helpful information and Streamlit experts. Home Contact Us Community © 2025 Snowflake Inc. Cookie policy forum Ask AI |
Reboot_your_app_-_Streamlit_Docs.txt | Reboot your app - Streamlit Docs Documentation search Search rocket_launch Get started Installation add Fundamentals add First steps add code Develop Concepts add API reference add Tutorials add Quick reference add web_asset Deploy Concepts add Streamlit Community Cloud remove Get started add Deploy your app add Manage your app remove App analytics App settings Delete your app Edit your app Favorite your app Reboot your app Rename your app in GitHub Upgrade Python Upgrade Streamlit Share your app add Manage your account add Status and limitations Snowflake Other platforms add school Knowledge base FAQ Installing dependencies Deployment issues Home / Deploy / Streamlit Community Cloud / Manage your app / Reboot your app Reboot your app If you need to clear your app's memory or force a fresh build after modifying a file that Streamlit Community Cloud doesn't monitor, you may need to reboot your app. This will interrupt any user who may currently be using your app and may take a few minutes for your app to redeploy. Anyone visiting your app will see "Your app is in the oven" during a reboot. Rebooting your app on Community Cloud is easy! You can reboot your app: From your workspace . From your Cloud logs . Reboot your app from your workspace From your workspace at share.streamlit.io , click the overflow icon ( more_vert ) next to your app. Click " Reboot ." A confirmation will display. Click " Reboot ." Reboot your app from your Cloud logs From your app at <your-custom-subdomain>.streamlit.app , click " Manage app " in the lower-right corner. Click the overflow menu icon ( more_vert ) and click " Reboot app ." A confirmation will display. Click " Reboot ." Previous: Favorite your app Next: Rename your app in GitHub forum Still have questions? Our forums are full of helpful information and Streamlit experts. Home Contact Us Community © 2025 Snowflake Inc. Cookie policy forum Ask AI |
st.text_-_Streamlit_Docs.txt | st.text - Streamlit Docs Documentation search Search rocket_launch Get started Installation add Fundamentals add First steps add code Develop Concepts add API reference remove PAGE ELEMENTS Write and magic add Text elements remove HEADINGS & BODY st.title st.header st.subheader st.markdown FORMATTED TEXT st.caption st.code st.divider st.echo st.latex st.text UTILITIES st.html link Data elements add Chart elements add Input widgets add Media elements add Layouts and containers add Chat elements add Status elements add Third-party components open_in_new APPLICATION LOGIC Navigation and pages add Execution flow add Caching and state add Connections and secrets add Custom components add Utilities add Configuration add TOOLS App testing add Command line add Tutorials add Quick reference add web_asset Deploy Concepts add Streamlit Community Cloud add Snowflake Other platforms add school Knowledge base FAQ Installing dependencies Deployment issues Home / Develop / API reference / Text elements / st.text st.text Streamlit Version Version 1.41.0 Version 1.40.0 Version 1.39.0 Version 1.38.0 Version 1.37.0 Version 1.36.0 Version 1.35.0 Version 1.34.0 Version 1.33.0 Version 1.32.0 Version 1.31.0 Version 1.30.0 Version 1.29.0 Version 1.28.0 Version 1.27.0 Version 1.26.0 Version 1.25.0 Version 1.24.0 Version 1.23.0 Version 1.22.0 Version 1.21.0 Version 1.20.0 Streamlit in Snowflake Write text without Markdown or HTML parsing. For monospace text, use st.code . Function signature [source] st.text(body, *, help=None) Parameters body (str) The string to display. help (str) An optional tooltip that gets displayed next to the text. Example import streamlit as st st.text("This is text\n[and more text](that's not a Markdown link).") Built with Streamlit 🎈 Fullscreen open_in_new Previous: st.latex Next: st.html forum Still have questions? Our forums are full of helpful information and Streamlit experts. Home Contact Us Community © 2025 Snowflake Inc. Cookie policy forum Ask AI |
Delete_your_account_-_Streamlit_Docs.txt | Delete your account - Streamlit Docs Documentation search Search rocket_launch Get started Installation add Fundamentals add First steps add code Develop Concepts add API reference add Tutorials add Quick reference add web_asset Deploy Concepts add Streamlit Community Cloud remove Get started add Deploy your app add Manage your app add Share your app add Manage your account remove Sign in & sign out Workspace settings Manage your GitHub connection Update your email Delete your account Status and limitations Snowflake Other platforms add school Knowledge base FAQ Installing dependencies Deployment issues Home / Deploy / Streamlit Community Cloud / Manage your account / Delete your account Delete your account Deleting your Streamlit Community Cloud account is just as easy as creating it. When you delete your account, your information, account, and all your hosted apps are deleted as well. Read more about data deletion in Streamlit trust and security . priority_high Warning Deleting your account is permanent and cannot be undone. Make sure you really want to delete your account and all hosted apps before proceeding. Any app you've deployed will be deleted, regardless of the workspace it was deployed from. How to delete your account Follow these steps to delete your account: Sign in to Streamlit Community Cloud at share.streamlit.io and access your Workspace settings . From the " Linked accounts " section, click " Delete account ." In the confirmation dialog, follow the prompt and click " Delete account forever ." All your information and apps will be permanently deleted. It's that simple! If you have any questions or run into issues deleting your account, please reach out to us on our forum . We're happy to help! 🎈 Previous: Update your email Next: Status and limitations forum Still have questions? Our forums are full of helpful information and Streamlit experts. Home Contact Us Community © 2025 Snowflake Inc. Cookie policy forum Ask AI |
Get_started_with_app_testing_-_Streamlit_Docs.txt | Get started with app testing - Streamlit Docs Documentation search Search rocket_launch Get started Installation add Fundamentals add First steps add code Develop Concepts remove CORE Architecture & execution add Multipage apps add App design add ADDITIONAL Connections and secrets add Custom components add Configuration and theming add App testing remove Get started Beyond the basics Automate your tests Example Cheat sheet API reference add Tutorials add Quick reference add web_asset Deploy Concepts add Streamlit Community Cloud add Snowflake Other platforms add school Knowledge base FAQ Installing dependencies Deployment issues Home / Develop / Concepts / App testing / Get started Get 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 star Tip Note 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 testing Next: Beyond the basics forum Still have questions? Our forums are full of helpful information and Streamlit experts. Home Contact Us Community © 2025 Snowflake Inc. Cookie policy forum Ask AI |
Deploy_your_app_on_Community_Cloud___Streamlit_Doc.txt | Deploy your app on Community Cloud - Streamlit Docs Documentation search Search rocket_launch Get started Installation add Fundamentals add First steps add code Develop Concepts add API reference add Tutorials add Quick reference add web_asset Deploy Concepts add Streamlit Community Cloud remove Get started add Deploy your app remove File organization App dependencies Secrets management Deploy! Manage your app add Share your app add Manage your account add Status and limitations Snowflake Other platforms add school Knowledge base FAQ Installing dependencies Deployment issues Home / Deploy / Streamlit Community Cloud / Deploy your app / Deploy! Deploy your app on Community Cloud After you've organized your files and added your dependencies as described on the previous pages, you're ready to deploy your app to Community Cloud! Select your repository and entrypoint file From your workspace at share.streamlit.io , in the upper-right corner, click " Create app ." When asked "Do you already have an app?" click " Yup, I have an app ." Fill in your repository, branch, and file path. Alternatively, to paste a link directly to your_app.py on GitHub, click " Paste GitHub URL ." Optional: In the "App URL" field, choose a subdomain for your new app. Every Community Cloud app is deployed to a subdomain on streamlit.app , but you can change your app's subdomain at any time. For more information, see App settings . In the following example, Community Cloud will deploy an app to https://red-balloon.streamlit.app/ . Although Community Cloud attempts to suggest available repositories and files, these suggestions are not always complete. If the desired information is not listed for any field, enter it manually. Optional: Configure secrets and Python version push_pin Note Streamlit Community Cloud supports all released versions of Python that are still receiving security updates . Streamlit Community Cloud defaults to version 3.12. You can select a version of your choice from the "Python version" dropdown in the "Advanced settings" modal. If an app is running a version of Python that becomes unsupported, it will be forcibly upgraded to the oldest supported version of Python and may break. Click " Advanced settings ." Select your desired version of Python. To define environment variables and secrets, in the "Secrets" field, paste the contents of your secrets.toml file. For more information, see Community Cloud secrets management . Click " Save ." Watch your app launch Your app is now being deployed, and you can watch while it launches. Most apps are deployed within a few minutes, but if your app has a lot of dependencies, it may take longer. After the initial deployment, changes to your code should be reflected immediately in your app. Changes to your dependencies will be processed immediately, but may take a few minutes to install. push_pin Note The Streamlit Community Cloud logs on the right-hand side of your app are only viewable to users with write access to your repository. These logs help you debug any issues with the app. Learn more about Streamlit Community Cloud logs . View your app That's it—you're done! Your app now has a unique URL that you can share with others. Read more about how to Share your app with viewers. Unique subdomains If the " Custom subdomain (optional) " field is blank when you deploy your app, a URL is assigned following a structure based on your GitHub repo. The subdomain of the URL is a dash-separated list of the following: Repository owner (GitHub user or organization) Repository name Entrypoint file path Branch name, if other than main or master A random hash https://[GitHub username or organization]-[repo name]-[app path]-[branch name]-[short hash].streamlit.app For example, the following app is deployed from the streamlit organization. The repo is demo-self-driving and the app name is streamlit_app.py in the root directory. The branch name is master and therefore not included. https://streamlit-demo-self-driving-streamlit-app-8jya0g.streamlit.app Custom subdomains Setting a custom subdomain makes it much easier to share your app because you can choose something memorable. To learn how to change the subdomain of a deployed app, see View or change your app's URL . Previous: Secrets management Next: Manage your app forum Still have questions? Our forums are full of helpful information and Streamlit experts. Home Contact Us Community © 2025 Snowflake Inc. Cookie policy forum Ask AI |
Secrets_management_for_your_Community_Cloud_app___.txt | Secrets management for your Community Cloud app - Streamlit Docs Documentation search Search rocket_launch Get started Installation add Fundamentals add First steps add code Develop Concepts add API reference add Tutorials add Quick reference add web_asset Deploy Concepts add Streamlit Community Cloud remove Get started add Deploy your app remove File organization App dependencies Secrets management Deploy! Manage your app add Share your app add Manage your account add Status and limitations Snowflake Other platforms add school Knowledge base FAQ Installing dependencies Deployment issues Home / Deploy / Streamlit Community Cloud / Deploy your app / Secrets management Secrets management for your Community Cloud app Introduction If you are connecting to data sources , you will likely need to handle credentials or secrets. Storing unencrypted secrets in a git repository is a bad practice. If your application needs access to sensitive credentials, the recommended solution is to store those credentials in a file that is not committed to the repository and to pass them as environment variables. How to use secrets management Community Cloud lets you save your secrets within your app's settings. When developing locally, you can use st.secrets in your code to read secrets from a .streamlit/secrets.toml file. However, this secrets.toml file should never be committed to your repository. Instead, when you deploy your app, you can paste the contents of your secrets.toml file into the " Advanced settings " dialog. You can update your secrets at any time through your app's settings in your workspace. Prerequisites You should understand how to use st.secrets and secrets.toml . See Secrets management . Advanced settings While deploying your app, you can access " Advanced settings " to set your secrets. After your app is deployed, you can view or update your secrets through the app's settings. The deployment workflow is fully described on the next page, but the " Advanced settings " dialog looks like this: Simply copy and paste the contents of your local secrets.toml file into the "Secrets" field within the dialog. After you click " Save " to commit the changes, that's it! Edit your app's secrets If you need to add or edit your secrets for an app that is already deployed, you can access secrets through your App settings . See View or update your secrets . Previous: App dependencies Next: Deploy! forum Still have questions? Our forums are full of helpful information and Streamlit experts. Home Contact Us Community © 2025 Snowflake Inc. Cookie policy forum Ask AI |
st.file_uploader_-_Streamlit_Docs.txt | st.file_uploader - Streamlit Docs Documentation search Search rocket_launch Get started Installation add Fundamentals add First steps add code Develop Concepts add API reference remove PAGE ELEMENTS Write and magic add Text elements add Data elements add Chart elements add Input widgets remove BUTTONS st.button st.download_button st.form_submit_button link st.link_button st.page_link SELECTIONS st.checkbox st.color_picker st.feedback st.multiselect st.pills st.radio st.segmented_control st.selectbox st.select_slider st.toggle NUMERIC st.number_input st.slider DATE & TIME st.date_input st.time_input TEXT st.chat_input link st.text_area st.text_input MEDIA & FILES st.audio_input st.camera_input st.data_editor link st.file_uploader Media elements add Layouts and containers add Chat elements add Status elements add Third-party components open_in_new APPLICATION LOGIC Navigation and pages add Execution flow add Caching and state add Connections and secrets add Custom components add Utilities add Configuration add TOOLS App testing add Command line add Tutorials add Quick reference add web_asset Deploy Concepts add Streamlit Community Cloud add Snowflake Other platforms add school Knowledge base FAQ Installing dependencies Deployment issues Home / Develop / API reference / Input widgets / st.file_uploader st.file_uploader Streamlit Version Version 1.41.0 Version 1.40.0 Version 1.39.0 Version 1.38.0 Version 1.37.0 Version 1.36.0 Version 1.35.0 Version 1.34.0 Version 1.33.0 Version 1.32.0 Version 1.31.0 Version 1.30.0 Version 1.29.0 Version 1.28.0 Version 1.27.0 Version 1.26.0 Version 1.25.0 Version 1.24.0 Version 1.23.0 Version 1.22.0 Version 1.21.0 Version 1.20.0 Streamlit in Snowflake Display a file uploader widget. By default, uploaded files are limited to 200MB. You can configure this using the server.maxUploadSize config option. For more info on how to set config options, see https://docs.streamlit.io/develop/api-reference/configuration/config.toml Function signature [source] st.file_uploader(label, type=None, accept_multiple_files=False, key=None, help=None, on_change=None, args=None, kwargs=None, *, disabled=False, label_visibility="visible") Parameters label (str) A short label explaining to the user what this file uploader is for. The label can optionally contain GitHub-flavored Markdown of the following types: Bold, Italics, Strikethroughs, Inline Code, Links, and Images. Images display like icons, with a max height equal to the font height. Unsupported Markdown elements are unwrapped so only their children (text contents) render. Display unsupported elements as literal characters by backslash-escaping them. E.g., "1\. Not an ordered list" . See the body parameter of st.markdown for additional, supported Markdown directives. For accessibility reasons, you should never set an empty label, but you can hide it with label_visibility if needed. In the future, we may disallow empty labels by raising an exception. type (str or list of str or None) Array of allowed extensions. ['png', 'jpg'] The default is None, which means all extensions are allowed. accept_multiple_files (bool) If True, allows the user to upload multiple files at the same time, in which case the return value will be a list of files. Default: False key (str or int) An optional string or integer to use as the unique key for the widget. If this is omitted, a key will be generated for the widget based on its content. No two widgets may have the same key. help (str) An optional tooltip that gets displayed next to the widget label. Streamlit only displays the tooltip when label_visibility="visible" . on_change (callable) An optional callback invoked when this file_uploader's value changes. args (tuple) An optional tuple of args to pass to the callback. kwargs (dict) An optional dict of kwargs to pass to the callback. disabled (bool) An optional boolean that disables the file uploader if set to True . The default is False . label_visibility ("visible", "hidden", or "collapsed") The visibility of the label. The default is "visible" . If this is "hidden" , Streamlit displays an empty spacer instead of the label, which can help keep the widget alligned with other widgets. If this is "collapsed" , Streamlit displays no label or spacer. Returns (None or UploadedFile or list of UploadedFile) If accept_multiple_files is False, returns either None or an UploadedFile object. If accept_multiple_files is True, returns a list with the uploaded files as UploadedFile objects. If no files were uploaded, returns an empty list. The UploadedFile class is a subclass of BytesIO, and therefore is "file-like". This means you can pass an instance of it anywhere a file is expected. Examples Insert a file uploader that accepts a single file at a time: import streamlit as st import pandas as pd from io import StringIO uploaded_file = st.file_uploader("Choose a file") if uploaded_file is not None: # To read file as bytes: bytes_data = uploaded_file.getvalue() st.write(bytes_data) # To convert to a string based IO: stringio = StringIO(uploaded_file.getvalue().decode("utf-8")) st.write(stringio) # To read file as string: string_data = stringio.read() st.write(string_data) # Can be used wherever a "file-like" object is accepted: dataframe = pd.read_csv(uploaded_file) st.write(dataframe) Insert a file uploader that accepts multiple files at a time: import streamlit as st uploaded_files = st.file_uploader( "Choose a CSV file", accept_multiple_files=True ) for uploaded_file in uploaded_files: bytes_data = uploaded_file.read() st.write("filename:", uploaded_file.name) st.write(bytes_data) Built with Streamlit 🎈 Fullscreen open_in_new Previous: st.data_editor Next: Media elements forum Still have questions? Our forums are full of helpful information and Streamlit experts. Home Contact Us Community © 2025 Snowflake Inc. Cookie policy forum Ask AI |
st.button_-_Streamlit_Docs.txt | st.button - Streamlit Docs Documentation search Search rocket_launch Get started Installation add Fundamentals add First steps add code Develop Concepts add API reference remove PAGE ELEMENTS Write and magic add Text elements add Data elements add Chart elements add Input widgets remove BUTTONS st.button st.download_button st.form_submit_button link st.link_button st.page_link SELECTIONS st.checkbox st.color_picker st.feedback st.multiselect st.pills st.radio st.segmented_control st.selectbox st.select_slider st.toggle NUMERIC st.number_input st.slider DATE & TIME st.date_input st.time_input TEXT st.chat_input link st.text_area st.text_input MEDIA & FILES st.audio_input st.camera_input st.data_editor link st.file_uploader Media elements add Layouts and containers add Chat elements add Status elements add Third-party components open_in_new APPLICATION LOGIC Navigation and pages add Execution flow add Caching and state add Connections and secrets add Custom components add Utilities add Configuration add TOOLS App testing add Command line add Tutorials add Quick reference add web_asset Deploy Concepts add Streamlit Community Cloud add Snowflake Other platforms add school Knowledge base FAQ Installing dependencies Deployment issues Home / Develop / API reference / Input widgets / st.button st.button Streamlit Version Version 1.41.0 Version 1.40.0 Version 1.39.0 Version 1.38.0 Version 1.37.0 Version 1.36.0 Version 1.35.0 Version 1.34.0 Version 1.33.0 Version 1.32.0 Version 1.31.0 Version 1.30.0 Version 1.29.0 Version 1.28.0 Version 1.27.0 Version 1.26.0 Version 1.25.0 Version 1.24.0 Version 1.23.0 Version 1.22.0 Version 1.21.0 Version 1.20.0 Streamlit in Snowflake Display a button widget. Function signature [source] st.button(label, key=None, help=None, on_click=None, args=None, kwargs=None, *, type="secondary", icon=None, disabled=False, use_container_width=False) Parameters label (str) A short label explaining to the user what this button is for. The label can optionally contain GitHub-flavored Markdown of the following types: Bold, Italics, Strikethroughs, Inline Code, Links, and Images. Images display like icons, with a max height equal to the font height. Unsupported Markdown elements are unwrapped so only their children (text contents) render. Display unsupported elements as literal characters by backslash-escaping them. E.g., "1\. Not an ordered list" . See the body parameter of st.markdown for additional, supported Markdown directives. key (str or int) An optional string or integer to use as the unique key for the widget. If this is omitted, a key will be generated for the widget based on its content. No two widgets may have the same key. help (str) An optional tooltip that gets displayed when the button is hovered over. on_click (callable) An optional callback invoked when this button is clicked. args (tuple) An optional tuple of args to pass to the callback. kwargs (dict) An optional dict of kwargs to pass to the callback. type ("primary", "secondary", or "tertiary") An optional string that specifies the button type. This can be one of the following: "primary" : The button's background is the app's primary color for additional emphasis. "secondary" (default): The button's background coordinates with the app's background color for normal emphasis. "tertiary" : The button is plain text without a border or background for subtly. icon (str or None) An optional emoji or icon to display next to the button label. 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 (rounded 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. disabled (bool) An optional boolean that disables the button if set to True . The default is False . use_container_width (bool) Whether to expand the button's width to fill its parent container. If use_container_width is False (default), Streamlit sizes the button to fit its contents. If use_container_width is True , the width of the button matches its parent container. In both cases, if the contents of the button are wider than the parent container, the contents will line wrap. Returns (bool) True if the button was clicked on the last run of the app, False otherwise. Examples Example 1: Customize your button type import streamlit as st st.button("Reset", type="primary") if st.button("Say hello"): st.write("Why hello there") else: st.write("Goodbye") if st.button("Aloha", type="tertiary"): st.write("Ciao") Built with Streamlit 🎈 Fullscreen open_in_new Example 2: Add icons to your button Although you can add icons to your buttons through Markdown, the icon parameter is a convenient and consistent alternative. import streamlit as st left, middle, right = st.columns(3) if left.button("Plain button", use_container_width=True): left.markdown("You clicked the plain button.") if middle.button("Emoji button", icon="😃", use_container_width=True): middle.markdown("You clicked the emoji button.") if right.button("Material button", icon=":material/mood:", use_container_width=True): right.markdown("You clicked the Material button.") Built with Streamlit 🎈 Fullscreen open_in_new Advanced functionality Although a button is the simplest of input widgets, it's very common for buttons to be deeply tied to the use of st.session_state . Check out our advanced guide on Button behavior and examples . Featured videos Check out our video on how to use one of Streamlit's core functions, the button! In the video below, we'll take it a step further and learn how to combine a button , checkbox and radio button ! Previous: Input widgets Next: st.download_button forum Still have questions? Our forums are full of helpful information and Streamlit experts. Home Contact Us Community © 2025 Snowflake Inc. Cookie policy forum Ask AI |
Update_your_email_-_Streamlit_Docs.txt | Update your email - Streamlit Docs Documentation search Search rocket_launch Get started Installation add Fundamentals add First steps add code Develop Concepts add API reference add Tutorials add Quick reference add web_asset Deploy Concepts add Streamlit Community Cloud remove Get started add Deploy your app add Manage your app add Share your app add Manage your account remove Sign in & sign out Workspace settings Manage your GitHub connection Update your email Delete your account Status and limitations Snowflake Other platforms add school Knowledge base FAQ Installing dependencies Deployment issues Home / Deploy / Streamlit Community Cloud / Manage your account / Update your email Update your email To update your email on Streamlit Community Cloud, you have two options: You can create a new account and merge your existing account into it, or you can use your GitHub account to update your email. Option 1: Create a new account and merge it Two Community Cloud accounts can't have the same GitHub account for source control. When you connect a GitHub account to a new Community Cloud account for source control, Community Cloud will automatically merge any existing account with the same source control. Therefore, you can create a new account with the desired email and connect the same GitHub account to merge them together. Create a new account with your new email. Connect your GitHub account. Your old and new accounts are now merged, and you have effectively changed your email address. Option 2: Use your GitHub account Alternatively, you can change the email on your GitHub account and then sign in to Community Cloud with GitHub. Go to GitHub, and set your primary email address to your new email. If you are currently signed in to Community Cloud, sign out. Sign in to Community Cloud using GitHub . If you are redirected to your workspace and you see your existing apps, you're done! Your email has been changed. To confirm your current email and GitHub account, click on your workspace name in the upper-left corner, and look at the bottom of the drop-down menu. If you are redirected to an empty workspace and you see " Workspaces warning " in the upper-left corner, proceed to Connect your GitHub account . This can happen if you previously created an account with your new email but didn't connect a GitHub account to it. priority_high Important If you have multiple GitHub accounts, be careful. To avoid unexpected behavior, either use unique emails on each GitHub account or avoid signing in to Community Cloud using GitHub. Previous: Manage your GitHub connection Next: Delete your account forum Still have questions? Our forums are full of helpful information and Streamlit experts. Home Contact Us Community © 2025 Snowflake Inc. Cookie policy forum Ask AI |
Streamlit_Community_Cloud_-_Streamlit_Docs.txt | Streamlit Community Cloud - Streamlit Docs Documentation search Search rocket_launch Get started Installation add Fundamentals add First steps add code Develop Concepts add API reference add Tutorials add Quick reference add web_asset Deploy Concepts add Streamlit Community Cloud remove Get started add Deploy your app add Manage your app add Share your app add Manage your account add Status and limitations Snowflake Other platforms add school Knowledge base FAQ Installing dependencies Deployment issues Home / Deploy / Streamlit Community Cloud Welcome to Streamlit Community Cloud With Streamlit Community Cloud, you can create, deploy, and manage your Streamlit apps — all for free. Share your apps with the world and build a customized profile page to display your work. Your Community Cloud account connects directly to your GitHub repositories (public or private). Most apps will launch in only a few minutes. Community Cloud handles all of the containerization, so deploying is easy. Bring your own code, or start from one of our popular templates. Rapidly prototype, explore, and update apps by simply changing your code in GitHub. Most changes appear immediately! Want to avoid the work of setting up a local development environment? Community Cloud can help you quickly configure a codespace to develop in the cloud. Start coding or editing a Streamlit app with just a few clicks. See Edit your app . Go to our Community Cloud quickstart to speed-run through creating your account, deploying an example app, and editing it using GitHub Codespaces. If you haven't built your first Streamlit app yet, see Get started with Streamlit . arrow_forward Get started. Learn about Streamlit Community Cloud accounts and how to create one. flight_takeoff Deploy your app. A step-by-step guide on how to get your app deployed. settings Manage your app. Access logs, reboot apps, set favorites, and more. Jump into a GitHub codespace to edit your app in the cloud. share Share your app. Share or embed your app. manage_accounts Manage your account. Update your email, manage connections, or delete your account. Previous: Concepts Next: Get started forum Still have questions? Our forums are full of helpful information and Streamlit experts. Home Contact Us Community © 2025 Snowflake Inc. Cookie policy forum Ask AI |
st.components.v1.iframe_-_Streamlit_Docs.txt | st.components.v1.iframe - Streamlit Docs Documentation search Search rocket_launch Get started Installation add Fundamentals add First steps add code Develop Concepts add API reference remove PAGE ELEMENTS Write and magic add Text elements add Data elements add Chart elements add Input widgets add Media elements add Layouts and containers add Chat elements add Status elements add Third-party components open_in_new APPLICATION LOGIC Navigation and pages add Execution flow add Caching and state add Connections and secrets add Custom components remove st.components.v1.declare_component st.components.v1.html st.components.v1.iframe Utilities add Configuration add TOOLS App testing add Command line add Tutorials add Quick reference add web_asset Deploy Concepts add Streamlit Community Cloud add Snowflake Other platforms add school Knowledge base FAQ Installing dependencies Deployment issues Home / Develop / API reference / Custom components / st.components.v1.iframe st.components.v1.iframe Streamlit Version Version 1.41.0 Version 1.40.0 Version 1.39.0 Version 1.38.0 Version 1.37.0 Version 1.36.0 Version 1.35.0 Version 1.34.0 Version 1.33.0 Version 1.32.0 Version 1.31.0 Version 1.30.0 Version 1.29.0 Version 1.28.0 Version 1.27.0 Version 1.26.0 Version 1.25.0 Version 1.24.0 Version 1.23.0 Version 1.22.0 Version 1.21.0 Version 1.20.0 Streamlit in Snowflake Load a remote URL in an iframe. To use this function, import it from the streamlit.components.v1 module. Warning Using st.components.v1.iframe directly (instead of importing its module) is deprecated and will be disallowed in a later version. Function signature [source] st.components.v1.iframe(src, width=None, height=None, scrolling=False) Parameters src (str) The URL of the page to embed. width (int) The width of the iframe in CSS pixels. By default, this is the app's default element width. height (int) The height of the frame in CSS pixels. By default, this is 150 . scrolling (bool) Whether to allow scrolling in the iframe. If this False (default), Streamlit crops any content larger than the iframe and does not show a scrollbar. If this is True , Streamlit shows a scrollbar when the content is larger than the iframe. Example import streamlit.components.v1 as components components.iframe("https://example.com", height=500) Previous: st.components.v1.html Next: Utilities forum Still have questions? Our forums are full of helpful information and Streamlit experts. Home Contact Us Community © 2025 Snowflake Inc. Cookie policy forum Ask AI |
Sign_in_&_sign_out_-_Streamlit_Docs.txt | Sign in & sign out - Streamlit Docs Documentation search Search rocket_launch Get started Installation add Fundamentals add First steps add code Develop Concepts add API reference add Tutorials add Quick reference add web_asset Deploy Concepts add Streamlit Community Cloud remove Get started add Deploy your app add Manage your app add Share your app add Manage your account remove Sign in & sign out Workspace settings Manage your GitHub connection Update your email Delete your account Status and limitations Snowflake Other platforms add school Knowledge base FAQ Installing dependencies Deployment issues Home / Deploy / Streamlit Community Cloud / Manage your account / Sign in & sign out Sign in & sign out After you've created your account, you can sign in to share.streamlit.io as described by the following options. Sign in with Google Click " Continue to sign-in ." Click " Continue with Google ." Enter your Google account credentials and follow the prompts. If your account is already linked to GitHub, you may be immediately prompted to sign in with GitHub. Sign in with GitHub Click " Continue to sign-in ." Click " Continue with GitHub ." Enter your GitHub credentials and follow the prompts. priority_high Important When you sign in with GitHub, Community Cloud will look for an account that uses the same email you have on your GitHub account. If such an account doesn't exist, Community Cloud will look for an account that uses your GitHub account for source control. In this latter instance, Community Cloud will update the email on your Community Cloud account to match the email on your GitHub account. Sign in with Email Click " Continue to sign-in ." In the "Email" field, enter your email address. Click " Continue ." (If prompted, verify you are human.) Go to your email inbox, and copy your one-time, six-digit code. The code is valid for ten minutes. Return to the authentication page, and enter your code. (If prompted, verify you are human.) If your account is already linked to GitHub, you may be immediately prompted to sign in with GitHub. Sign out of your account From your workspace, click on your workspace name in the upper-left corner. Click " Sign out ." Previous: Manage your account Next: Workspace settings forum Still have questions? Our forums are full of helpful information and Streamlit experts. Home Contact Us Community © 2025 Snowflake Inc. Cookie policy forum Ask AI |
st_connections_SnowparkConnection___Streamlit_Docs.txt | st.connections.SnowparkConnection - Streamlit Docs Documentation search Search rocket_launch Get started Installation add Fundamentals add First steps add code Develop Concepts add API reference remove PAGE ELEMENTS Write and magic add Text elements add Data elements add Chart elements add Input widgets add Media elements add Layouts and containers add Chat elements add Status elements add Third-party components open_in_new APPLICATION LOGIC Navigation and pages add Execution flow add Caching and state add Connections and secrets remove SECRETS st.secrets secrets.toml CONNECTIONS st.connection SnowflakeConnection SQLConnection BaseConnection SnowparkConnection delete Custom components add Utilities add Configuration add TOOLS App testing add Command line add Tutorials add Quick reference add web_asset Deploy Concepts add Streamlit Community Cloud add Snowflake Other platforms add school Knowledge base FAQ Installing dependencies Deployment issues Home / Develop / API reference / Connections and secrets / SnowparkConnection star Tip This page only contains the st.connections.SnowparkConnection class. For a deeper dive into creating and managing data connections within Streamlit apps, read Connecting to data . st.connections.SnowparkConnection Streamlit Version Version 1.41.0 Version 1.40.0 Version 1.39.0 Version 1.38.0 Version 1.37.0 Version 1.36.0 Version 1.35.0 Version 1.34.0 Version 1.33.0 Version 1.32.0 Version 1.31.0 Version 1.30.0 Version 1.29.0 Version 1.28.0 Version 1.27.0 Version 1.26.0 Version 1.25.0 Version 1.24.0 Version 1.23.0 Version 1.22.0 Version 1.21.0 Version 1.20.0 Streamlit in Snowflake delete Deprecation notice st.connections.SnowParkConnection was deprecated in version 1.28.0. Use st.connections.SnowflakeConnection instead. A connection to Snowpark using snowflake.snowpark.session.Session. Initialize using st.connection("<name>", type="snowpark") . In addition to providing access to the Snowpark Session, SnowparkConnection supports direct SQL querying using query("...") and thread safe access using with conn.safe_session(): . See methods below for more information. SnowparkConnections should always be created using st.connection() , not initialized directly. Note We don't expect this iteration of SnowparkConnection to be able to scale well in apps with many concurrent users due to the lock contention that will occur over the single underlying Session object under high load. Class description [source] st.connections.SnowparkConnection(connection_name, **kwargs) Methods query (sql, ttl=None) Run a read-only SQL query. reset () Reset this connection so that it gets reinitialized the next time it's used. safe_session () Grab the underlying Snowpark session in a thread-safe manner. Attributes session Access the underlying Snowpark session. SnowparkConnection.query Streamlit Version Version 1.41.0 Version 1.40.0 Version 1.39.0 Version 1.38.0 Version 1.37.0 Version 1.36.0 Version 1.35.0 Version 1.34.0 Version 1.33.0 Version 1.32.0 Version 1.31.0 Version 1.30.0 Version 1.29.0 Version 1.28.0 Version 1.27.0 Version 1.26.0 Version 1.25.0 Version 1.24.0 Version 1.23.0 Version 1.22.0 Version 1.21.0 Version 1.20.0 Streamlit in Snowflake Run a read-only SQL query. This method implements both query result caching (with caching behavior identical to that of using @st.cache_data ) as well as simple error handling/retries. Note Queries that are run without a specified ttl are cached indefinitely. Function signature [source] SnowparkConnection.query(sql, ttl=None) Parameters sql (str) The read-only SQL query to execute. ttl (float, int, timedelta or None) The maximum number of seconds to keep results in the cache, or None if cached results should not expire. The default is None. Returns (pandas.DataFrame) The result of running the query, formatted as a pandas DataFrame. Example import streamlit as st conn = st.connection("snowpark") df = conn.query("SELECT * FROM pet_owners") st.dataframe(df) SnowparkConnection.reset Streamlit Version Version 1.41.0 Version 1.40.0 Version 1.39.0 Version 1.38.0 Version 1.37.0 Version 1.36.0 Version 1.35.0 Version 1.34.0 Version 1.33.0 Version 1.32.0 Version 1.31.0 Version 1.30.0 Version 1.29.0 Version 1.28.0 Version 1.27.0 Version 1.26.0 Version 1.25.0 Version 1.24.0 Version 1.23.0 Version 1.22.0 Version 1.21.0 Version 1.20.0 Streamlit in Snowflake Reset this connection so that it gets reinitialized the next time it's used. This method can be useful when a connection has become stale, an auth token has expired, or in similar scenarios where a broken connection might be fixed by reinitializing it. Note that some connection methods may already use reset() in their error handling code. Function signature [source] SnowparkConnection.reset() Returns (None) No description Example import streamlit as st conn = st.connection("my_conn") # Reset the connection before using it if it isn't healthy # Note: is_healthy() isn't a real method and is just shown for example here. if not conn.is_healthy(): conn.reset() # Do stuff with conn... SnowparkConnection.safe_session Streamlit Version Version 1.41.0 Version 1.40.0 Version 1.39.0 Version 1.38.0 Version 1.37.0 Version 1.36.0 Version 1.35.0 Version 1.34.0 Version 1.33.0 Version 1.32.0 Version 1.31.0 Version 1.30.0 Version 1.29.0 Version 1.28.0 Version 1.27.0 Version 1.26.0 Version 1.25.0 Version 1.24.0 Version 1.23.0 Version 1.22.0 Version 1.21.0 Version 1.20.0 Streamlit in Snowflake Grab the underlying Snowpark session in a thread-safe manner. As operations on a Snowpark session are not thread safe, we need to take care when using a session in the context of a Streamlit app where each script run occurs in its own thread. Using the contextmanager pattern to do this ensures that access on this connection's underlying Session is done in a thread-safe manner. Information on how to use Snowpark sessions can be found in the Snowpark documentation . Function signature [source] SnowparkConnection.safe_session() Example import streamlit as st conn = st.connection("snowpark") with conn.safe_session() as session: df = session.table("mytable").limit(10).to_pandas() st.dataframe(df) SnowparkConnection.session Streamlit Version Version 1.41.0 Version 1.40.0 Version 1.39.0 Version 1.38.0 Version 1.37.0 Version 1.36.0 Version 1.35.0 Version 1.34.0 Version 1.33.0 Version 1.32.0 Version 1.31.0 Version 1.30.0 Version 1.29.0 Version 1.28.0 Version 1.27.0 Version 1.26.0 Version 1.25.0 Version 1.24.0 Version 1.23.0 Version 1.22.0 Version 1.21.0 Version 1.20.0 Streamlit in Snowflake Access the underlying Snowpark session. Note Snowpark sessions are not thread safe. Users of this method are responsible for ensuring that access to the session returned by this method is done in a thread-safe manner. For most users, we recommend using the thread-safe safe_session() method and a with block. Information on how to use Snowpark sessions can be found in the Snowpark documentation . Function signature [source] SnowparkConnection.session Example import streamlit as st session = st.connection("snowpark").session df = session.table("mytable").limit(10).to_pandas() st.dataframe(df) Previous: st.experimental_connection Next: ExperimentalBaseConnection forum Still have questions? Our forums are full of helpful information and Streamlit experts. Home Contact Us Community © 2025 Snowflake Inc. Cookie policy forum Ask AI |
st_column_config_ProgressColumn___Streamlit_Docs_4.txt | st.column_config.ProgressColumn - Streamlit Docs Documentation search Search rocket_launch Get started Installation add Fundamentals add First steps add code Develop Concepts add API reference remove PAGE ELEMENTS Write and magic add Text elements add Data elements remove st.dataframe st.data_editor st.column_config remove Column Text column Number column Checkbox column Selectbox column Datetime column Date column Time column List column Link column Image column Area chart column Line chart column Bar chart column Progress column st.table st.metric st.json Chart elements add Input widgets add Media elements add Layouts and containers add Chat elements add Status elements add Third-party components open_in_new APPLICATION LOGIC Navigation and pages add Execution flow add Caching and state add Connections and secrets add Custom components add Utilities add Configuration add TOOLS App testing add Command line add Tutorials add Quick reference add web_asset Deploy Concepts add Streamlit Community Cloud add Snowflake Other platforms add school Knowledge base FAQ Installing dependencies Deployment issues Home / Develop / API reference / Data elements / st.column_config / Progress column st.column_config.ProgressColumn Streamlit Version Version 1.41.0 Version 1.40.0 Version 1.39.0 Version 1.38.0 Version 1.37.0 Version 1.36.0 Version 1.35.0 Version 1.34.0 Version 1.33.0 Version 1.32.0 Version 1.31.0 Version 1.30.0 Version 1.29.0 Version 1.28.0 Version 1.27.0 Version 1.26.0 Version 1.25.0 Version 1.24.0 Version 1.23.0 Version 1.22.0 Version 1.21.0 Version 1.20.0 Streamlit in Snowflake Configure a progress column in st.dataframe or st.data_editor . Cells need to contain a number. Progress columns are not editable at the moment. This command needs to be used in the column_config parameter of st.dataframe or st.data_editor . Function signature [source] st.column_config.ProgressColumn(label=None, *, width=None, help=None, pinned=None, format=None, min_value=None, max_value=None) Parameters label (str or None) The label shown at the top of the column. If this is None (default), the column name is used. width ("small", "medium", "large", or None) The display width of the column. If this is None (default), the column will be sized to fit the cell contents. Otherwise, this can be one of the following: "small" : 75px wide "medium" : 200px wide "large" : 400px wide help (str or None) An optional tooltip that gets displayed when hovering over the column label. If this is None (default), no tooltip is displayed. format (str or None) A printf-style format string controlling how numbers are displayed. This does not impact the return value. The following formatters are valid: %d , %e , %f , %g , %i , %u . You can also add prefixes and suffixes, e.g. "$ %.2f" to show a dollar prefix. If this is None (default), the numbers are not formatted. pinned (bool or None) Whether the column is pinned. A pinned column will stay visible on the left side no matter where the user scrolls. If this is None (default), Streamlit will decide: index columns are pinned, and data columns are not pinned. min_value (int, float, or None) The minimum value of the progress bar. If this is None (default), the minimum will be 0. max_value (int, float, or None) The maximum value of the progress bar. If this is None (default), the maximum will be 100 for integer values and 1.0 for float values. Examples import pandas as pd import streamlit as st data_df = pd.DataFrame( { "sales": [200, 550, 1000, 80], } ) st.data_editor( data_df, column_config={ "sales": st.column_config.ProgressColumn( "Sales volume", help="The sales volume in USD", format="$%f", min_value=0, max_value=1000, ), }, hide_index=True, ) Built with Streamlit 🎈 Fullscreen open_in_new Previous: Bar chart column Next: st.table forum Still have questions? Our forums are full of helpful information and Streamlit experts. Home Contact Us Community © 2025 Snowflake Inc. Cookie policy forum Ask AI |
Installing_dependencies_-_Streamlit_Docs.txt | Installing dependencies - Streamlit Docs Documentation search Search rocket_launch Get started Installation add Fundamentals add First steps add code Develop Concepts add API reference add Tutorials add Quick reference add web_asset Deploy Concepts add Streamlit Community Cloud add Snowflake Other platforms add school Knowledge base FAQ Installing dependencies Deployment issues Home / Knowledge base / Installing dependencies Installing dependencies ModuleNotFoundError: No module named ImportError: libGL.so.1: cannot open shared object file: No such file or directory ERROR: No matching distribution found for How to install a package not on PyPI/Conda but available on GitHub Previous: FAQ Next: How to install a package not on PyPI or Conda but available on GitHub forum Still have questions? Our forums are full of helpful information and Streamlit experts. Home Contact Us Community © 2025 Snowflake Inc. Cookie policy forum Ask AI |
Connect_your_GitHub_account_-_Streamlit_Docs.txt | Connect your GitHub account - Streamlit Docs Documentation search Search rocket_launch Get started Installation add Fundamentals add First steps add code Develop Concepts add API reference add Tutorials add Quick reference add web_asset Deploy Concepts add Streamlit Community Cloud remove Get started remove Quickstart Create your account Connect your GitHub account Explore your workspace Deploy from a template Fork and edit a public app Trust and security Deploy your app add Manage your app add Share your app add Manage your account add Status and limitations Snowflake Other platforms add school Knowledge base FAQ Installing dependencies Deployment issues Home / Deploy / Streamlit Community Cloud / Get started / Connect your GitHub account Connect your GitHub account Connecting GitHub to your Streamlit Community Cloud account allows you to deploy apps directly from the files you store in your repositories. It also lets the system check for updates to those files and automatically update your apps. When you first connect your GitHub account to your Community Cloud account, you'll be able to deploy apps from your public repositories to Community Cloud. If you want to deploy from private repositories, you can give Community Cloud additional permissions to do so. For more information about these permissions, see GitHub OAuth scope . priority_high Important In order to deploy an app, you must have admin permissions to its repository. If you don't have admin access, contact the repository's owner or fork the repository to create your own copy. For more help, see our community forum . If you are a member of a GitHub organization, that organization is displayed at the bottom of each GitHub OAuth prompt. In this case, we recommend reading about Organization access at the end of this page before performing the steps to connect your GitHub account. You must be an organization's owner in GitHub to grant access to that organization. Prerequisites You must have a Community Cloud account. See Create your account . You must have a GitHub account. Add access to public repositories In the upper-left corner, click " Workspaces warning ." From the drop down, click " Connect GitHub account ." Enter your GitHub credentials and follow GitHub's authentication prompts. Click " Authorize streamlit ." This adds the "Streamlit" OAuth application to your GitHub account. This allows Community Cloud to work with your public repositories and create codespaces for you. In the next section, you can allow Community Cloud to access your private repositories, too. For more information about using and reviewing the OAuth applications on your account, see Using OAuth apps in GitHub's docs. Optional: Add access to private repositories After your Community Cloud account has access to deploy from your public repositories, you can follow these additional steps to grant access to your private repositories. In the upper-left corner, click on your GitHub username. From the drop down, click " Settings ." On the left side of the dialog, select " Linked accounts ." Under "Source control," click " Connect here arrow_forward ." Click " Authorize streamlit ." Organization access To deploy apps from repositories owned by a GitHub organization, Community Cloud must have permission to access the organization's repositories. If you are a member of a GitHub organization when you connect your GitHub account, your OAuth prompts will include a section labeled "Organization access." If you have already connected your GitHub account and need to add access to an organization, follow the steps in Manage your GitHub connection to disconnect your GitHub account and start over. Alternatively, if you are not the owner of an organization, you can ask the owner to create a Community Cloud account for themselves and add permission directly. 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, the OAuth prompt will show the current status. Approved access If an organization has already granted Streamlit access, the OAuth prompt shows a green check ( check ). Pending access If a request has been previously sent but not yet approved, the OAuth prompt show "Access request pending." Follow up with the organization's owner to accept the request in GitHub. Denied access If a request has been previously sent and denied, the OAuth prompt shows a red X ( close ). 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 account Next: Explore your workspace forum Still have questions? Our forums are full of helpful information and Streamlit experts. Home Contact Us Community © 2025 Snowflake Inc. Cookie policy forum Ask AI |
2022_release_notes_-_Streamlit_Docs.txt | 2022 release notes - Streamlit Docs Documentation search Search rocket_launch Get started Installation add Fundamentals add First steps add code Develop Concepts add API reference add Tutorials add Quick reference remove Cheat sheet Release notes remove 2024 2023 2022 2021 2020 2019 Pre-release features Roadmap open_in_new web_asset Deploy Concepts add Streamlit Community Cloud add Snowflake Other platforms add school Knowledge base FAQ Installing dependencies Deployment issues Home / Develop / Quick reference / Release notes / 2022 2022 release notes This page contains release notes for Streamlit versions released in 2022. For the latest version of Streamlit, see Release notes . 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 ! Version 1.12.0 Release date: August 11, 2022 Highlights 📊 Built-in charts (e.g. st.line_chart ) get a brand-new look and parameters x and y ! Check out our blog post for more information. Notable Changes ⏯ Functions cached with st.experimental_memo or st.experimental_singleton can now contain static st commands. This allows caching text, charts, dataframes, and more! ↔️ The sidebar is now resizable via drag and drop. ☎️ st.info , st.success , st.error , and st.warning got a redesign and have a new keyword-only parameter: icon . Other Changes 🎚️ st.select_slider correctly handles all floats now ( #4973 , #4978 ). 🔢 st.multi_select can take values from enums ( #4987 ). 🍊 st.slider range values can now be set through st.session_state ( #5007 ). 🎨 st.progress got a redesign ( #5011 , #5086 ). 🔘 st.radio better deals with list-like dataframes ( #5021 ). 🧞♂️ st.cache properly handles JSON files now ( #5023 ). ⚓️ Headers render markdown now when the anchor parameter is set ( #5038 ). 🗻 st.image can now load SVGs from Inkscape ( #5040 ). 🗺️ st.map and st.pydeck_chart use light or dark style based on the app's theme ( #5074 , #5108 ). 🎈 Clicks on elements below st.balloons and st.snow don't get blocked anymore ( #5098 ). 🔝 Embedded apps have lower top padding ( #5111 ). 💅 Adjusted padding and alignment for widgets, charts, and dataframes ( #4995 , #5061 , #5081 ). ✍️ More type hints! ( #4926 , #4932 , #4933 ) Version 1.11.0 Release date: July 14, 2022 Highlights 🗂 Introducing st.tabs to have tab containers in your app. See our documentation on how to use this feature. Notable Changes ℹ️ st.metric supports tooltips with the help keyword parameter. 🚇 st.columns supports setting the gap size between columns with the gap keyword parameter. Other Changes 💅 Design tweaks to st.selectbox , st.expander , st.spinner ( #4801 ). 📱 The sidebar will close when users select a page from the navigation menu on mobile devices ( #4851 ). 🧠 st.memo supports dataclasses! ( #4850 ) 🏎 Bug fix for a race condition that destroyed widget state with rapid interaction ( #4882 ). 🏓 st.table presents overflowing content to be scrollable when placed inside columns and expanders ( #4934 ). 🐍 Types: More updated type annotations across Streamlit! ( #4808 , #4809 , #4856 ) Version 1.10.0 Release date: June 2, 2022 Highlights 📖 Introducing native support for multipage apps! Check out our blog post and try out our new streamlit hello . Notable Changes ✨ st.dataframe has been redesigned. 🔘 st.radio has a horizontal keyword-only parameter to display options horizontally. ⚠️ Streamlit Community Cloud will support richer exception formatting. 🏂 Get user information on private apps using st.experimental_user . Other Changes 📊 Upgraded Vega-Lite library to support even more interactive charting improvements. See their release notes to find out more. ( #4751 ). 📈 st.vega_lite_chart will respond to updates, particularly in response to input widgets ( #4736 ). 💬 st.markdown with long text will always wrap ( #4696 ). 📦 Support for PDM ( #4724 ). ✍️ Types: Updated type annotations across Streamlit! ( #4679 , #4680 , #4681 , #4682 , #4683 , #4684 , #4685 , #4686 , #4687 , #4688 , #4690 , #4703 , #4704 , #4705 , #4706 , #4707 , #4708 , #4710 , #4723 , #4733 ). Version 1.9.0 Release date: May 4, 2022 Notable Changes 🪗 st.json now supports a keyword-only argument, expanded on whether the JSON should be expanded by default (defaults to True ). 🏃♀️ More performance improvements from reducing redundant work each script run. Other Changes 🏇 Widgets when disabled is set/unset will maintain its value ( #4527 ). 🧪 Experimental feature to increase the speed of reruns using configuration runner.fastReruns . See #4628 for the known issues in enabling this feature. 🗺️ DataFrame timestamps support UTC offset (in addition to time zone notation) ( #4669 ). Version 1.8.0 Release date: March 24, 2022 Notable Changes 🏃♀️ Dataframes should see performance improvements ( #4463 ). Other Changes 🕰 st.slider handles timezones better by removing timezone conversions on the backend ( #4348 ). 👩🎨 Design improvements to our header ( #4496 ). Version 1.7.0 Release date: March 3, 2022 Highlights Introducing st.snow , celebrating our acquisition by Snowflake! See more information in our blog post . Version 1.6.0 Release date: Feb 24, 2022 Other Changes 🗜 WebSocket compression is now disabled by default, which will improve CPU and latency performance for large dataframes. You can use the server.enableWebsocketCompression configuration option to re-enable it if you find the increased network traffic more impactful. ☑️ 🔘 Radio and checkboxes improve focus on Keyboard navigation ( #4308 ). Version 1.5.0 Release date: Jan 27, 2022 Notable Changes 🌟 Favicon defaults to a PNG to allow for transparency ( #4272 ). 🚦 Select Slider Widget now has the disabled parameter that removes interactivity (completing all of our widgets) ( #4314 ). Other Changes 🔤 Improvements to our markdown library to provide better support for HTML (specifically nested HTML) ( #4221 ). 📖 Expanders maintain their expanded state better when multiple expanders are present ( #4290 ). 🗳 Improved file uploader and camera input to call its on_change handler only when necessary ( #4270 ). Version 1.4.0 Release date: Jan 13, 2022 Highlights 📸 Introducing st.camera_input for uploading images straight from your camera. Notable Changes 🚦 Widgets now have the disabled parameter that removes interactivity. 🚮 Clear st.experimental_memo and st.experimental_singleton programmatically by using the clear() method on a cached function. 📨 Developers can now configure the maximum size of a message to accommodate larger messages within the Streamlit application. See server.maxMessageSize . 🐍 We formally added support for Python 3.10. Other Changes 😵💫 Calling str or repr on threading.current_thread() does not cause a RecursionError ( #4172 ). 📹 Gracefully stop screencast recording when user removes permission to record ( #4180 ). 🌇 Better scale images by using a higher-quality image bilinear resampling algorithm ( #4159 ). Previous: 2023 Next: 2021 forum Still have questions? Our forums are full of helpful information and Streamlit experts. Home Contact Us Community © 2025 Snowflake Inc. Cookie policy forum Ask AI |
SEO_and_search_indexability_-_Streamlit_Docs.txt | SEO and search indexability - Streamlit Docs Documentation search Search rocket_launch Get started Installation add Fundamentals add First steps add code Develop Concepts add API reference add Tutorials add Quick reference add web_asset Deploy Concepts add Streamlit Community Cloud remove Get started add Deploy your app add Manage your app add Share your app remove Embed your app Search indexability Share previews Manage your account add Status and limitations Snowflake Other platforms add school Knowledge base FAQ Installing dependencies Deployment issues Home / Deploy / Streamlit Community Cloud / Share your app / Search indexability SEO and search indexability When you deploy a public app to Streamlit Community Cloud, it is automatically indexed by search engines like Google and Bing on a weekly basis. 🎈 This means that anyone can find your app by searching for its custom subdomain (e.g. "traingenerator.streamlit.app") or by searching for the app's title. Get the most out of app indexability Here are some tips to help you get the most out of app indexability: Make sure your app is public Choose a custom subdomain early Choose a descriptive app title Customize your app's meta description Make sure your app is public All public apps hosted on Community Cloud are indexed by search engines. If your app is private, it will not be indexed by search engines. To make your private app public, read Share your app . Choose a custom subdomain early Community Cloud automatically generates a subdomain for your app if you do not choose one. However, you can change your subdomain at any time! Custom subdomains modify your app URLs to reflect your app content, personal branding, or whatever you’d like. To learn how to change your app's subdomain, see View or change your app's URL . By choosing a custom subdomain, you can use it to help people find your app. For example, if you're deploying an app that generates training data, you might choose a subdomain like traingenerator.streamlit.app . This makes it easy for people to find your app by searching for "training generator" or "train generator streamlit app." We recommend choosing a custom subdomain when you deploy your app. This ensures that your app is indexed by search engines using your custom subdomain, rather than the automatically generated one. If you choose a custom subdomain later, your app may be indexed multiple times—once using the default subdomain and once using your custom subdomain. In this case, your old URL will result in a 404 error which can confuse users who are searching for your app. Choose a descriptive app title The meta title of your app is the text that appears in search engine results. It is also the text that appears in the browser tab when your app is open. By default, the meta title of your app is the same as the title of your app. However, you can customize the meta title of your app by setting the st.set_page_config parameter page_title to a custom string. For example: st.set_page_config(page_title="Traingenerator") This will change the meta title of your app to "Traingenerator." This makes it easier for people to find your app by searching for "Traingenerator" or "train generator streamlit app": Google search results for "train generator streamlit app" Customize your app's meta description Meta descriptions are the short descriptions that appear in search engine results. Search engines use the meta description to help users understand what your app is about. From our observations, search engines seem to favor the content in both st.header and st.text over st.title . If you put a description at the top of your app under st.header or st.text , there’s a good chance search engines will use this for the meta description. What does my indexed app look like? If you're curious about what your app looks like in search engine results, you can type the following into Google Search: site:<your-custom-subdomain>.streamlit.app Example: site:traingenerator.streamlit.app Google search results for "site:traingenerator.streamlit.app" What if I don't want my app to be indexed? If you don't want your app to be indexed by search engines, you can make it private. Read Share your app to learn more about making your app private. Note: each workspace can only have one private app. If you want to make your app private, you must first delete any other private app in your workspace or make it public. That said, Community Cloud is an open and free platform for the community to deploy, discover, and share Streamlit apps and code with each other. As such, we encourage you to make your app public so that it can be indexed by search engines and discovered by other Streamlit users and community members. Previous: Embed your app Next: Share previews forum Still have questions? Our forums are full of helpful information and Streamlit experts. Home Contact Us Community © 2025 Snowflake Inc. Cookie policy forum Ask AI |
App_analytics_-_Streamlit_Docs.txt | App analytics - Streamlit Docs Documentation search Search rocket_launch Get started Installation add Fundamentals add First steps add code Develop Concepts add API reference add Tutorials add Quick reference add web_asset Deploy Concepts add Streamlit Community Cloud remove Get started add Deploy your app add Manage your app remove App analytics App settings Delete your app Edit your app Favorite your app Reboot your app Rename your app in GitHub Upgrade Python Upgrade Streamlit Share your app add Manage your account add Status and limitations Snowflake Other platforms add school Knowledge base FAQ Installing dependencies Deployment issues Home / Deploy / Streamlit Community Cloud / Manage your app / App analytics App analytics Streamlit Community Cloud allows you to see the viewership of each of your apps. Specifically, you can see: The total viewers count of your app (counted from April 2022). The most recent unique viewers (capped at the last 20 viewers). A relative timestamp of each unique viewer's last visit. Access your app analytics You can get to your app's analytics: From your workspace . From your Cloud logs . Access app analytics from your workspace From your workspace at share.streamlit.io , click the overflow icon ( more_vert ) next to your app. Click " Analytics ." Access app analytics 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 " Analytics ." App viewers For public apps, we anonymize all viewers outside your workspace to protect their privacy and display anonymous viewers as random pseudonyms. You'll still be able to see the identities of fellow members in your workspace, including any viewers you've invited (once they've accepted). priority_high Important When you invite a viewer to an app, they gain access to analytics as well. Additionally, if someone is invited as a viewer to any app in your workspace, they can see analytics for all public apps in your workspace and invite additional viewers themselves. A viewer in your workspace may see the emails of developers and other viewers in your workspace through analytics. Meanwhile, for private apps where you control who has access, you will be able to see the specific users who recently viewed your apps. Additionally, you may occasionally see anonymous users in a private app. Rest assured, these anonymous users do have authorized view access granted by you or your workspace members. Common reasons why users show up anonymously are: The app was previously public. The given viewer viewed the app in April 2022, when the Streamlit team was honing user identification for this feature. See Streamlit's general Privacy Notice . Previous: Manage your app Next: App settings forum Still have questions? Our forums are full of helpful information and Streamlit experts. Home Contact Us Community © 2025 Snowflake Inc. Cookie policy forum Ask AI |
st.bar_chart_-_Streamlit_Docs.txt | st.bar_chart - Streamlit Docs Documentation search Search rocket_launch Get started Installation add Fundamentals add First steps add code Develop Concepts add API reference remove PAGE ELEMENTS Write and magic add Text elements add Data elements add Chart elements remove SIMPLE st.area_chart st.bar_chart st.line_chart st.map st.scatter_chart ADVANCED st.altair_chart st.bokeh_chart st.graphviz_chart st.plotly_chart st.pydeck_chart st.pyplot st.vega_lite_chart Input widgets add Media elements add Layouts and containers add Chat elements add Status elements add Third-party components open_in_new APPLICATION LOGIC Navigation and pages add Execution flow add Caching and state add Connections and secrets add Custom components add Utilities add Configuration add TOOLS App testing add Command line add Tutorials add Quick reference add web_asset Deploy Concepts add Streamlit Community Cloud add Snowflake Other platforms add school Knowledge base FAQ Installing dependencies Deployment issues Home / Develop / API reference / Chart elements / st.bar_chart st.bar_chart Streamlit Version Version 1.41.0 Version 1.40.0 Version 1.39.0 Version 1.38.0 Version 1.37.0 Version 1.36.0 Version 1.35.0 Version 1.34.0 Version 1.33.0 Version 1.32.0 Version 1.31.0 Version 1.30.0 Version 1.29.0 Version 1.28.0 Version 1.27.0 Version 1.26.0 Version 1.25.0 Version 1.24.0 Version 1.23.0 Version 1.22.0 Version 1.21.0 Version 1.20.0 Streamlit in Snowflake Display a bar chart. This is syntax-sugar around st.altair_chart . The main difference is this command uses the data's own column and indices to figure out the chart's Altair spec. As a result this is easier to use for many "just plot this" scenarios, while being less customizable. If st.bar_chart does not guess the data specification correctly, try specifying your desired chart using st.altair_chart . Function signature [source] st.bar_chart(data=None, *, x=None, y=None, x_label=None, y_label=None, color=None, horizontal=False, stack=None, width=None, height=None, use_container_width=True) Parameters data (Anything supported by st.dataframe) Data to be plotted. x (str or None) Column name or key associated to the x-axis data. If x is None (default), Streamlit uses the data index for the x-axis values. y (str, Sequence of str, or None) Column name(s) or key(s) associated to the y-axis data. If this is None (default), Streamlit draws the data of all remaining columns as data series. If this is a Sequence of strings, Streamlit draws several series on the same chart by melting your wide-format table into a long-format table behind the scenes. x_label (str or None) The label for the x-axis. If this is None (default), Streamlit will use the column name specified in x if available, or else no label will be displayed. y_label (str or None) The label for the y-axis. If this is None (default), Streamlit will use the column name(s) specified in y if available, or else no label will be displayed. color (str, tuple, Sequence of str, Sequence of tuple, or None) The color to use for different series in this chart. For a bar chart with just one series, this can be: None, to use the default color. A hex string like "#ffaa00" or "#ffaa0088". An RGB or RGBA tuple with the red, green, blue, and alpha components specified as ints from 0 to 255 or floats from 0.0 to 1.0. For a bar chart with multiple series, where the dataframe is in long format (that is, y is None or just one column), this can be: None, to use the default colors. The name of a column in the dataset. Data points will be grouped into series of the same color based on the value of this column. In addition, if the values in this column match one of the color formats above (hex string or color tuple), then that color will be used. For example: if the dataset has 1000 rows, but this column only contains the values "adult", "child", and "baby", then those 1000 datapoints will be grouped into three series whose colors will be automatically selected from the default palette. But, if for the same 1000-row dataset, this column contained the values "#ffaa00", "#f0f", "#0000ff", then then those 1000 datapoints would still be grouped into 3 series, but their colors would be "#ffaa00", "#f0f", "#0000ff" this time around. For a bar chart with multiple series, where the dataframe is in wide format (that is, y is a Sequence of columns), this can be: None, to use the default colors. A list of string colors or color tuples to be used for each of the series in the chart. This list should have the same length as the number of y values (e.g. color=["#fd0", "#f0f", "#04f"] for three lines). horizontal (bool) Whether to make the bars horizontal. If this is False (default), the bars display vertically. If this is True , Streamlit swaps the x-axis and y-axis and the bars display horizontally. stack (bool, "normalize", "center", "layered", or None) Whether to stack the bars. If this is None (default), Streamlit uses Vega's default. Other values can be as follows: True : The bars form a non-overlapping, additive stack within the chart. False : The bars display side by side. "layered" : The bars overlap each other without stacking. "normalize" : The bars are stacked and the total height is normalized to 100% of the height of the chart. "center" : The bars are stacked and shifted to center the total height around an axis. width (int or None) Desired width of the chart expressed in pixels. If width is None (default), Streamlit sets the width of the chart to fit its contents according to the plotting library, up to the width of the parent container. If width is greater than the width of the parent container, Streamlit sets the chart width to match the width of the parent container. To use width , you must set use_container_width=False . height (int or None) Desired height of the chart expressed in pixels. If height is None (default), Streamlit sets the height of the chart to fit its contents according to the plotting library. use_container_width (bool) Whether to override width with the width of the parent container. If use_container_width is True (default), Streamlit sets the width of the chart to match the width of the parent container. If use_container_width is False , Streamlit sets the chart's width according to width . Examples import streamlit as st import pandas as pd import numpy as np chart_data = pd.DataFrame(np.random.randn(20, 3), columns=["a", "b", "c"]) st.bar_chart(chart_data) Built with Streamlit 🎈 Fullscreen open_in_new You can also choose different columns to use for x and y, as well as set the color dynamically based on a 3rd column (assuming your dataframe is in long format): import streamlit as st import pandas as pd import numpy as np chart_data = pd.DataFrame( { "col1": list(range(20)) * 3, "col2": np.random.randn(60), "col3": ["A"] * 20 + ["B"] * 20 + ["C"] * 20, } ) st.bar_chart(chart_data, x="col1", y="col2", color="col3") Built with Streamlit 🎈 Fullscreen open_in_new If your dataframe is in wide format, you can group multiple columns under the y argument to show multiple series with different colors: import streamlit as st import pandas as pd import numpy as np chart_data = pd.DataFrame( { "col1": list(range(20)), "col2": np.random.randn(20), "col3": np.random.randn(20), } ) st.bar_chart( chart_data, x="col1", y=["col2", "col3"], color=["#FF0000", "#0000FF"], # Optional ) Built with Streamlit 🎈 Fullscreen open_in_new You can rotate your bar charts to display horizontally. import streamlit as st from vega_datasets import data source = data.barley() st.bar_chart(source, x="variety", y="yield", color="site", horizontal=True) Built with Streamlit 🎈 Fullscreen open_in_new You can unstack your bar charts. import streamlit as st from vega_datasets import data source = data.barley() st.bar_chart(source, x="year", y="yield", color="site", stack=False) Built with Streamlit 🎈 Fullscreen open_in_new element.add_rows Streamlit Version Version 1.41.0 Version 1.40.0 Version 1.39.0 Version 1.38.0 Version 1.37.0 Version 1.36.0 Version 1.35.0 Version 1.34.0 Version 1.33.0 Version 1.32.0 Version 1.31.0 Version 1.30.0 Version 1.29.0 Version 1.28.0 Version 1.27.0 Version 1.26.0 Version 1.25.0 Version 1.24.0 Version 1.23.0 Version 1.22.0 Version 1.21.0 Version 1.20.0 Streamlit in Snowflake Concatenate a dataframe to the bottom of the current one. Function signature [source] element.add_rows(data=None, **kwargs) Parameters data (pandas.DataFrame, pandas.Styler, pyarrow.Table, numpy.ndarray, pyspark.sql.DataFrame, snowflake.snowpark.dataframe.DataFrame, Iterable, dict, or None) Table to concat. Optional. **kwargs (pandas.DataFrame, numpy.ndarray, Iterable, dict, or None) The named dataset to concat. Optional. You can only pass in 1 dataset (including the one in the data parameter). Example import streamlit as st import pandas as pd import numpy as np df1 = pd.DataFrame( np.random.randn(50, 20), columns=("col %d" % i for i in range(20)) ) my_table = st.table(df1) df2 = pd.DataFrame( np.random.randn(50, 20), columns=("col %d" % i for i in range(20)) ) my_table.add_rows(df2) # Now the table shown in the Streamlit app contains the data for # df1 followed by the data for df2. You can do the same thing with plots. For example, if you want to add more data to a line chart: # Assuming df1 and df2 from the example above still exist... my_chart = st.line_chart(df1) my_chart.add_rows(df2) # Now the chart shown in the Streamlit app contains the data for # df1 followed by the data for df2. And for plots whose datasets are named, you can pass the data with a keyword argument where the key is the name: my_chart = st.vega_lite_chart( { "mark": "line", "encoding": {"x": "a", "y": "b"}, "datasets": { "some_fancy_name": df1, # <-- named dataset }, "data": {"name": "some_fancy_name"}, } ) my_chart.add_rows(some_fancy_name=df2) # <-- name used as keyword Previous: st.area_chart Next: st.line_chart forum Still have questions? Our forums are full of helpful information and Streamlit experts. Home Contact Us Community © 2025 Snowflake Inc. Cookie policy forum Ask AI |
st.help_-_Streamlit_Docs.txt | st.help - Streamlit Docs Documentation search Search rocket_launch Get started Installation add Fundamentals add First steps add code Develop Concepts add API reference remove PAGE ELEMENTS Write and magic add Text elements add Data elements add Chart elements add Input widgets add Media elements add Layouts and containers add Chat elements add Status elements add Third-party components open_in_new APPLICATION LOGIC Navigation and pages add Execution flow add Caching and state add Connections and secrets add Custom components add Utilities remove st.context st.experimental_user st.help st.html Configuration add TOOLS App testing add Command line add Tutorials add Quick reference add web_asset Deploy Concepts add Streamlit Community Cloud add Snowflake Other platforms add school Knowledge base FAQ Installing dependencies Deployment issues Home / Develop / API reference / Utilities / st.help st.help Streamlit Version Version 1.41.0 Version 1.40.0 Version 1.39.0 Version 1.38.0 Version 1.37.0 Version 1.36.0 Version 1.35.0 Version 1.34.0 Version 1.33.0 Version 1.32.0 Version 1.31.0 Version 1.30.0 Version 1.29.0 Version 1.28.0 Version 1.27.0 Version 1.26.0 Version 1.25.0 Version 1.24.0 Version 1.23.0 Version 1.22.0 Version 1.21.0 Version 1.20.0 Streamlit in Snowflake Display help and other information for a given object. Depending on the type of object that is passed in, this displays the object's name, type, value, signature, docstring, and member variables, methods — as well as the values/docstring of members and methods. Function signature [source] st.help(obj= ) Parameters obj (any) The object whose information should be displayed. If left unspecified, this call will display help for Streamlit itself. Example Don't remember how to initialize a dataframe? Try this: import streamlit as st import pandas st.help(pandas.DataFrame) Built with Streamlit 🎈 Fullscreen open_in_new Want to quickly check what data type is output by a certain function? Try: import streamlit as st x = my_poorly_documented_function() st.help(x) Want to quickly inspect an object? No sweat: class Dog: '''A typical dog.''' def __init__(self, breed, color): self.breed = breed self.color = color def bark(self): return 'Woof!' fido = Dog("poodle", "white") st.help(fido) Built with Streamlit 🎈 Fullscreen open_in_new And if you're using Magic, you can get help for functions, classes, and modules without even typing st.help : import streamlit as st import pandas # Get help for Pandas read_csv: pandas.read_csv # Get help for Streamlit itself: st Built with Streamlit 🎈 Fullscreen open_in_new Previous: st.experimental_user Next: st.html forum Still have questions? Our forums are full of helpful information and Streamlit experts. Home Contact Us Community © 2025 Snowflake Inc. Cookie policy forum Ask AI |
st.echo_-_Streamlit_Docs.txt | st.echo - Streamlit Docs Documentation search Search rocket_launch Get started Installation add Fundamentals add First steps add code Develop Concepts add API reference remove PAGE ELEMENTS Write and magic add Text elements remove HEADINGS & BODY st.title st.header st.subheader st.markdown FORMATTED TEXT st.caption st.code st.divider st.echo st.latex st.text UTILITIES st.html link Data elements add Chart elements add Input widgets add Media elements add Layouts and containers add Chat elements add Status elements add Third-party components open_in_new APPLICATION LOGIC Navigation and pages add Execution flow add Caching and state add Connections and secrets add Custom components add Utilities add Configuration add TOOLS App testing add Command line add Tutorials add Quick reference add web_asset Deploy Concepts add Streamlit Community Cloud add Snowflake Other platforms add school Knowledge base FAQ Installing dependencies Deployment issues Home / Develop / API reference / Text elements / st.echo st.echo Streamlit Version Version 1.41.0 Version 1.40.0 Version 1.39.0 Version 1.38.0 Version 1.37.0 Version 1.36.0 Version 1.35.0 Version 1.34.0 Version 1.33.0 Version 1.32.0 Version 1.31.0 Version 1.30.0 Version 1.29.0 Version 1.28.0 Version 1.27.0 Version 1.26.0 Version 1.25.0 Version 1.24.0 Version 1.23.0 Version 1.22.0 Version 1.21.0 Version 1.20.0 Streamlit in Snowflake Use in a with block to draw some code on the app, then execute it. Function signature [source] st.echo(code_location="above") Parameters code_location ("above" or "below") Whether to show the echoed code before or after the results of the executed code block. Example import streamlit as st with st.echo(): st.write('This code will be printed') Display code Sometimes you want your Streamlit app to contain both your usual Streamlit graphic elements and the code that generated those elements. That's where st.echo() comes in. Ok so let's say you have the following file, and you want to make its app a little bit more self-explanatory by making that middle section visible in the Streamlit app: import streamlit as st def get_user_name(): return 'John' # ------------------------------------------------ # Want people to see this part of the code... def get_punctuation(): return '!!!' greeting = "Hi there, " user_name = get_user_name() punctuation = get_punctuation() st.write(greeting, user_name, punctuation) # ...up to here # ------------------------------------------------ foo = 'bar' st.write('Done!') The file above creates a Streamlit app containing the words "Hi there, John ", and then "Done!". Now let's use st.echo() to make that middle section of the code visible in the app: import streamlit as st def get_user_name(): return 'John' with st.echo(): # Everything inside this block will be both printed to the screen # and executed. def get_punctuation(): return '!!!' greeting = "Hi there, " value = get_user_name() punctuation = get_punctuation() st.write(greeting, value, punctuation) # And now we're back to _not_ printing to the screen foo = 'bar' st.write('Done!') It's that simple! push_pin Note You can have multiple st.echo() blocks in the same file. Use it as often as you wish! Previous: st.divider Next: st.latex forum Still have questions? Our forums are full of helpful information and Streamlit experts. Home Contact Us Community © 2025 Snowflake Inc. Cookie policy forum Ask AI |
Subsets and Splits