Intro to Streamlit: Web-based Python data apps made easy

By Serdar Yegulalp

A common problem with Python applications is how to share them with other people. Developers frequently use a web interface to solve this issue, presenting the app's functionality by way of a UI. But that solution works best when the application UI is a natural fit for web components. Data exploration apps can work like this, for instance, but they also require front-end components written in JavaScript for ideal interactivity.

Streamlit is a Python library that aims to solve many of these issues at once. Using Streamlit, developers can create Python apps with web-based front ends, built from a rich library of interactive components.

The resulting application can be hosted anywhere a Python web app lives. Best of all, the developer doesn't need to know HTML, JavaScript, or CSS to get good results; they just need to write code in Python that uses Streamlit's methods and classes.

A simple Streamlit example

Streamlit programs are written in a declarative style. Objects show up on the web page in the order you declare them in your code. Any interaction with the components causes the program to re-run from the top down, reloading the web page to reflect the changes made.

Here's a simple example of a Streamlit app:

import streamlit as stst.title("Take input from the user")user_input = st.text_input("Say something:")if user_input: st.write("You said:", user_input)

Here's what happens if you run this code with Streamlit (using the streamlit run command):

These HTML widgets and all their behaviors are generated and managed by Streamlit automatically. This includes the app's state—in the user_input box, for instance, the if statement only fires when the user inputs something.

Many more HTML components are available in Streamlit than in the examples shown here. Components such as LaTeX-formatted text, Bokeh charts, camera input, and many more are natively available.

A more complex Streamlit example

For a more complex Streamlit application, take a look at this example in Streamlit's documentation. This app loads a common dataset of Uber pickups and dropoffs in Manhattan, grouped by hour. It then plots the times on a bar chart and the locations on an interactive map.

The entire program is only about 30 lines; it's short enough that you can copy and paste it into a file and run it yourself. It's also useful as a showcase for the way Streamlit does many things.

Data in Streamlit apps

Streamlit offers many native behaviors to make dealing with data sources easy. It uses dataframes as a primary format for loading and working with data.

You can also load data from any source you'd use in any other Python application, and Streamlit provides conveniences to aid the process. As an example, the data visualization app in the previous section uses Pandas to load a CSV file from a remote URL and translate it into a dataframe. While convenient, loading and formatting the data can be slow and time-intensive, especially if you're loading over a network connection. The program also reloads after each action taken by the user.

To defray this, Streamlit provides the @st.cache_data decorator, used to wrap the load_data() function. Additionally, @st.cache_data caches the data across multiple reloads of the application, so it is only loaded at first launch.

State management in Streamlit apps

Because Streamlit's design forces an application reload with each user interaction, keeping persistent state in a Streamlit app isn't always obvious. We've seen how data in a text box handles state between runs. But if we want to create and manage state apart from the state of individual controls, we need to use Streamlit's built-in session_state object.

streamlit.session_state is a key-value store—essentially a dictionary— that persists across runs. When a Streamlit program starts for the first time, that store is empty, so you need to test for the presence of keys before trying to access them.

import streamlit as st# create the key "sayings" if it doesn't existif 'sayings' not in st.session_state: st.session_state['sayings'] = []# for convenience, make a referencesayings = st.session_state['sayings']st.title("Take input from the user")user_input = st.text_input("Say something:")if sayings: # display "sayings" if it has inputs from previous runs st.write("You previously said:", sayings)if user_input: # add to "sayings" if we get an input sayings.append(user_input) st.write("You said:", user_input)

Note that any data stored in session_state only persists for the lifetime of the Streamlit server running the application. If the server stops, the data is lost. If you need data that persists more aggressively, you may need a solution like a database or an in-memory cache like Redis.

Data widgets for Streamlit apps

We've seen how elements on Streamlit pages can range from simple text labels or HTML controls to more elaborate elements like maps, charts, audio/video playback, or advanced interactions like chat boxes (e.g., for interacting with LLMs).

Streamlit controls for displaying or interacting with data are already pre-wired to handle rendering data for the most common use cases. For instance, Streamlit web widgets can use dataframes as a source, and automatically present dataframes with proper column labeling so you don't have to add that by hand.

A broad library of common data widgets is included with Streamlit by default. More such components, created and shared by the user community, are available by way of a simple pip install.

Deploying Streamlit apps

Because Streamlit applications are, at heart, Python web applications, they can be deployed much the same way as any networked Python app. The quick and dirty way is to just run the app on a given machine and provide access to it by way of the assigned port.

More advanced deployments also follow the same pattern as other Python web apps—using Docker, Kubernetes, or various common cloud services. Snowflake users in AWS and Microsoft Azure can also deploy Streamlit apps backed by Snowflake's data store. Finally, Streamlit provides its own Community Cloud hosting service, although that's a convenience and not mandatory for Streamlit apps.

© Info World