liveBook · Manning

Session

As explained in Python How-To

Session state is per-session storage that preserves application data across reruns of a web application script.

How can a Streamlit app remember a user’s choices when the script reruns? Session state stores per-session data as key-value pairs, preserving activity while a browser tab remains active. It provides a practical workaround for Streamlit’s behavior of reloading the entire script after input changes. section 14.4.1 section 14.4.3

A task-management app can track:

  • The selected menu option, such as showing tasks, creating a task, or showing task details. section 14.4.3
  • Sorting and filtering choices in one sorting_params dictionary, including sort key, order, statuses, urgencies, and selected content. section 14.4.3

Initialize and route from session state

Use st.session_state through a short alias, initialize missing values once, and route the app according to the stored menu choice: session = st.session_state if menu_key not in session: session[menu_key] = TaskierMenuOption.SHOW_TASKS.value session[working_task_key] = None session[sorting_params_key] = {x.value: None for x in TaskierFilterKey} if session[menu_key] == TaskierMenuOption.SHOW_TASKS.value: show_tasks() elif session[menu_key] == TaskierMenuOption.NEW_TASK.value: show_new_task_entry() The membership check prevents initialization from overwriting choices on later reruns.

How Python How-To covers it

How deep it goes
Defines key-value storage and demonstrates initialization, updates, filtering state, and menu-based routing.
Examples
Uses a task-management app with menu selection, working-task storage, and sorting and filtering dictionaries.
What you can do after
Operate/configure Streamlit applications that retain menu, task, sorting, and filtering choices across input-triggered reruns.
How it connects
Connects Streamlit reruns, widgets, browser sessions, key-value pairs, enumerations, and application routing.

Also explained in

Compare how 5 books explain session →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Python How-To. The section links point to the parts of the book it draws on.