Streamlit
Streamlit is a powerful Python framework designed for building web applications. It enables developers to transform Python scripts into interactive web apps with ease. The framework is particularly known for its ability to create interactive widgets, manage session states, and automatically handle the layout of web elements.
Overview
Streamlit provides a seamless interface for building web applications using Python scripts. It simplifies the process of creating interactive widgets and managing session states, which are crucial for tracking user activities and storing data during a session. This allows the application to remember user inputs and selections without needing to refresh the page.
Widgets and Automatic Layout
One of the standout features of Streamlit is its automatic layout capability. This feature allows developers to focus on the functionality of their applications while Streamlit takes care of the layout of web elements such as buttons and text-input boxes. The framework comes with a variety of common web elements, or widgets, out of the box. These widgets are categorized into six types: Clickable (buttons), Single or Multiple Choice, Numeric Data, Textual Data, Multimedia, and Date and Time.
Figure 14.6 The available widgets in the streamlit framework. The six categories are Clickable (buttons), Single or Multiple Choice, Numeric Data, Textual Data, Multimedia, and Date and Time.
Organizing a Streamlit Project
Organizing a Streamlit project involves structuring the code into various components such as dependencies, global variables, and interface configuration functions. This organization enhances the readability and maintainability of the code, making it easier to manage and scale the application.
Example Implementations
Setting Up the Sidebar
The sidebar in a Streamlit app can be set up to include various interactive elements such as buttons and radio buttons. Below is an example of how to configure a sidebar:
def setup_sidebar():
sidebar.button("Show Tasks", on_click=update_session_tracking,
args=(menu_key, TaskierMenuOption.SHOW_TASKS.value))
sidebar.button("New Task", on_click=update_session_tracking,
args=(menu_key, TaskierMenuOption.NEW_TASK.value))
selected_db = sidebar.radio("Choose Database Option", [x.value for x
in TaskierDBOption])
set_db_option(selected_db)
sidebar.button("Load Data to Database", on_click=Task.load_seed_data)
sidebar.markdown("___")
if session[menu_key] == TaskierMenuOption.SHOW_TASKS.value:
setup_filters()
elif session[menu_key] == TaskierMenuOption.SHOW_TASK_DETAIL.value:
setup_deletion()
Showing Tasks
Streamlit allows for the display of tasks in a web app, with options to sort and view details:
def show_tasks():
filter_params = session[sorting_params_key]
if filter_params[TaskierFilterKey.SORTING_KEY.value] is not None:
reading_params = get_reading_params(filter_params)
tasks = Task.load_tasks(**reading_params)
sorting_key = sorting_keys[filter_params[
TaskierFilterKey.SORTING_KEY.value]]
should_reverse = filter_params[
TaskierFilterKey.SORTING_ORDER.value] == sorting_orders[1]
tasks.sort(key=lambda x: getattr(x, sorting_key),
reverse=should_reverse)
else:
tasks = Task.load_tasks()
for task in tasks:
col1, col2 = st.columns([3, 1])
col1.write(str(task))
col2.button("View Detail", key=task.task_id,
on_click=wants_task_detail, args=(task,))
st.write(f"Status: {task.status.name.title()}")
st.markdown("___")
Showing Task Details
To display detailed information about a specific task, Streamlit provides a form interface:
def show_task_detail():
task = session[working_task_key]
form = st.form("existing_task_form", clear_on_submit=False)
form.title("Task Detail")
task.title = form.text_input("The title", value=task.title,
key="existing_task_title")
task.desc = form.text_input("The description", value=task.desc,
key="existing_task_desc")
task.urgency = form.slider("The urgency level", min_value=1,
max_value=5, value=task.urgency)
status = form.selectbox("The status", index=task.status,
options=status_options, key="existing_task_status")
task.status = TaskStatus(status_options.index(status))
task.completion_note = form.text_input("The completion note",
value=task.completion_note, key="existing_task_note")
submitted = form.form_submit_button("Update Task")
if submitted:
try:
task.update_in_db()
except TaskierError:
form.error("Couldn't update the task as it's maybe
deleted already.")
else:
session[working_task_key] = task
form.success("Your Task Was Updated!")
Creating New Tasks
Streamlit also supports the creation of new tasks through a simple form interface:
def show_new_task_entry():
with st.form("new_task_form", clear_on_submit=True):
st.title("New Task")
title = st.text_input("The title", key="new_task_title")
desc = st.text_input("The description", key="new_task_desc")
urgency = st.slider("The urgency level", min_value=1, max_value=5)
submitted = st.form_submit_button("Save Task")
if submitted:
task = Task.task_from_form_entry(title, desc, urgency)
task.save_to_db()
st.success("Your Task Was Saved!")
Streamlit’s capabilities make it an excellent choice for developers looking to create interactive and dynamic web applications using Python. Its ease of use and powerful features allow for rapid development and deployment of web apps.
FAQ (Frequently asked questions)
What is Streamlit?
How does Streamlit help developers?
What types of widgets are available in Streamlit?
What does Streamlit provide for building web apps?
What is the purpose of session state in Streamlit?
How can you set up a sidebar in Streamlit?
How are tasks displayed in a Streamlit web app?
How can you show a task’s detail in Streamlit?
How do you create a new task in a Streamlit web app?