Building Web Apps with Streamlit and Python

Introduction

In this article, we'll explore how to build a simple web app using Streamlit. Streamlit is a powerful Python library that allows developers to create interactive web applications quickly and easily. Streamlit is designed to make the process of creating web apps as painless as possible for Python developers. Below are some key advantages include:

  • Simple API
  • Fast prototyping
  • Easy deployment
  • Built-in widgets and components
  • Automatic reloading during development

Installation of Streamlit

pip install streamlit

Example

import streamlit as st
def main():
    st.title("Simple To-Do List App")
    # Initialize our to-do list
    if 'todos' not in st.session_state:
        st.session_state.todos = []
    # Input for new to-do item
    new_todo = st.text_input("Add a new to-do item:")
    if st.button("Add") and new_todo:
        st.session_state.todos.append(new_todo)
        st.success(f"Added: {new_todo}")
    # Display the to-do list
    st.subheader("Your To-Do List:")
    for i, todo in enumerate(st.session_state.todos, 1):
        st.write(f"{i}. {todo}")
    # Clear all to-dos
    if st.button("Clear All"):
        st.session_state.todos = []
        st.success("All items cleared!")
if __name__ == "__main__":
    main()

To run the above app use the below command and Streamlit will automatically run on the 8501 port.

streamlit run todo_app.py

Output

Output

Let's break down the above simple example.

  1. We import the Streamlit library.
  2. We define a main() function that contains our app logic.
  3. st. title() is used for setting the title of our web app.
  4. We use st.session_state to store our to-do list. This allows the list to persist between reruns of the app.
  5. st.text_input() creates a text field for entering new to-do items.
  6. st.button("Add") creates a button. When clicked, it adds the new item to the list.
  7. We use a for loop with st. write() to display each item in the to-do list.
  8. Another button is created to clear all items from the list.
  9. st. success() is used to display success messages when items are added or the list is cleared.

Summary

Streamlit automatically handles the web interface, making it easy to create interactive apps with just a few lines of Python code. This example shows how quickly you can create a functional web app without needing to worry about HTML, CSS, or JavaScript.


Similar Articles