import streamlit as st
from src.utils.db import DataBaseManager
import base64
import random
import string
if 'edit_template_flag' not in st.session_state:
st.session_state['edit_template_flag'] = False
def main():
st.title("Email Templates 📝")
st.write("Create and manage your email templates.")
code
db_manager = DataBaseManager()
# Form to add a new template
st.subheader("Add a New Template")
with st.form("template_form", clear_on_submit=True):
title = st.text_input("Template Title")
subject = st.text_input("Subject")
body = st.text_area("Body")
submitted = st.form_submit_button("Add Template")
if submitted:
if not title or not subject or not body:
st.warning("Please fill in all fields.")
else:
template_data = {
'title': title,
'subject': subject,
'body': body
}
db_manager.add_template(template_data)
st.success(f"Template '{title}' added successfully!")
# st.rerun() # Rerun to update the list after addition
# Display existing templates
st.subheader("Existing Templates")
templates = db_manager.list_templates()
if templates:
# Search Functionality
search_query = st.text_input("Search Templates")
if search_query:
templates = [t for t in templates if search_query.lower() in t['title'].lower() or search_query.lower() in t['subject'].lower()]
if not templates:
st.info("No templates match your search.")
return
# Organize templates in columns
cols = st.columns(2) # Adjust the number of columns as needed
for idx, template in enumerate(templates):
col = cols[idx % 2]
with col:
display_template(db_manager, template)
else:
st.info("No templates have been added.")
Assistant
def display_template(db_manager, template):
st.markdown(f"### {template['title']}")
st.markdown(f"Subject: {template['subject']}")
st.markdown("Body:")
st.code(template['body'], language='markdown') # Display body in a code block
action_col1, action_col2, action_col3 = st.columns([1,1,2])
with action_col1:
if st.button('✏️ Edit', key=f"edit_{template['title']}"):
st.session_state.edit_template_flag = True
st.write(st.session_state.edit_template_flag)
if 'edit_template_flag' in st.session_state:
edit_template(db_manager, template)
st.write(st.session_state.edit_template_flag)
del st.session_state['edit_template_flag']
st.write('editted')
with action_col2:
if st.button('❌ Delete', key=f"delete_{template['title']}"):
db_manager.delete_template(template.doc_id)
st.success(f"Template '{template['title']}' deleted successfully!")
st.rerun()
with action_col3:
clipboard_button(template['body'], "📋 Copy Body")
def edit_template(db_manager, template):
st.subheader(f"Edit Template: {template['title']}")
st.write('template.doc_id', template.doc_id)
with st.form(f"edit_form_{template['title']}"):
title = st.text_input("Template Title", value=template['title'])
subject = st.text_input("Subject", value=template['subject'])
body = st.text_area("Body", value=template['body'])
submitted = st.form_submit_button("Save Changes")
code
if submitted:
# st.write('submitted')
if not title or not subject or not body:
st.warning("Please fill in all fields.")
else:
updated_template = {
'title': title,
'subject': subject,
'body': body
}
# st.write(updated_template)
db_manager.update_template(template.doc_id, updated_template)
# del st.session_state['edit_template_flag']
# st.write(db_manager.list_templates())
st.success(f"Template '{template['title']}' updated successfully!")
st.rerun()
but it is not working. it is not update template.
it seems where we put 'del st.session_state['edit_template_flag']' is so important, because when I modify to this:
import streamlit as st
from src.utils.db import DataBaseManager
import base64
import random
import string
if 'edit_template_flag' not in st.session_state:
st.session_state['edit_template_flag'] = False
def main():
st.title("Email Templates 📝")
st.write("Create and manage your email templates.")
code
db_manager = DataBaseManager()
# Form to add a new template
st.subheader("Add a New Template")
with st.form("template_form", clear_on_submit=True):
title = st.text_input("Template Title")
subject = st.text_input("Subject")
body = st.text_area("Body")
submitted = st.form_submit_button("Add Template")
if submitted:
if not title or not subject or not body:
st.warning("Please fill in all fields.")
else:
template_data = {
'title': title,
'subject': subject,
'body': body
}
db_manager.add_template(template_data)
st.success(f"Template '{title}' added successfully!")
# st.rerun() # Rerun to update the list after addition
# Display existing templates
st.subheader("Existing Templates")
templates = db_manager.list_templates()
if templates:
# Search Functionality
search_query = st.text_input("Search Templates")
if search_query:
templates = [t for t in templates if search_query.lower() in t['title'].lower() or search_query.lower() in t['subject'].lower()]
if not templates:
st.info("No templates match your search.")
return
# Organize templates in columns
cols = st.columns(2) # Adjust the number of columns as needed
for idx, template in enumerate(templates):
col = cols[idx % 2]
with col:
display_template(db_manager, template)
else:
st.info("No templates have been added.")
def display_template(db_manager, template):
st.markdown(f"### {template['title']}")
st.markdown(f"Subject: {template['subject']}")
st.markdown("Body:")
st.code(template['body'], language='markdown') # Display body in a code block
action_col1, action_col2, action_col3 = st.columns([1,1,2])
with action_col1:
if st.button('✏️ Edit', key=f"edit_{template['title']}"):
st.session_state.edit_template_flag = True
st.write(st.session_state.edit_template_flag)
if 'edit_template_flag' in st.session_state:
edit_template(db_manager, template)
st.write(st.session_state.edit_template_flag)
# del st.session_state['edit_template_flag']
st.write('editted')
with action_col2:
if st.button('❌ Delete', key=f"delete_{template['title']}"):
db_manager.delete_template(template.doc_id)
st.success(f"Template '{template['title']}' deleted successfully!")
st.rerun()
with action_col3:
clipboard_button(template['body'], "📋 Copy Body")
def edit_template(db_manager, template):
st.subheader(f"Edit Template: {template['title']}")
st.write('template.doc_id', template.doc_id)
with st.form(f"edit_form_{template['title']}"):
title = st.text_input("Template Title", value=template['title'])
subject = st.text_input("Subject", value=template['subject'])
body = st.text_area("Body", value=template['body'])
submitted = st.form_submit_button("Save Changes")
code
if submitted:
# st.write('submitted')
if not title or not subject or not body:
st.warning("Please fill in all fields.")
else:
updated_template = {
'title': title,
'subject': subject,
'body': body
}
# st.write(updated_template)
db_manager.update_template(template.doc_id, updated_template)
del st.session_state['edit_template_flag']
# st.write(db_manager.list_templates())
st.success(f"Template '{template['title']}' updated successfully!")
st.rerun()
I dont undrestand why first version dosnt work and why it is working when I move ' del st.session_state['edit_template_flag']' into edit_template function the problem solved.
please explain all I nedd to know about the place of set and rest or delet st.session_state
Certainly! Let's delve into your code and understand why moving del st.session_state['edit_template_flag'] resolves the issue, and explain the importance of setting and deleting session state variables at the appropriate times in Streamlit applications.
Understanding Streamlit's Execution Flow
First, it's crucial to understand how Streamlit apps execute:
Script Runs from Top to Bottom: Every interaction (like clicking a button) causes the entire script to rerun from the beginning.
Session State Persistence: The st.session_state is used to store variables that need to persist between runs. This allows you to manage the state of your app across reruns.
User Interactions: User inputs only take effect after the script has rerun. So, when you click a button, the script starts over, and the button's action can be processed.
Analyzing Your Code
Let's break down both versions of your display_template function and see how they differ.
First Version
python
def display_template(db_manager, template):
# ... display template ...
with action_col1:
if st.button('✏️ Edit', key=f"edit_{template['title']}"):
st.session_state.edit_template_flag = True
if 'edit_template_flag' in st.session_state:
edit_template(db_manager, template)
del st.session_state['edit_template_flag'] # Immediate deletion
Button Click: When the "Edit" button is clicked, st.session_state.edit_template_flag is set to True.
Immediate Deletion: Right after calling edit_template(), you delete edit_template_flag from st.session_state.
Second Version
python
def display_template(db_manager, template):
# ... display template ...
with action_col1:
if st.button('✏️ Edit', key=f"edit_{template['title']}"):
st.session_state.edit_template_flag = True
if 'edit_template_flag' in st.session_state:
edit_template(db_manager, template)
# del st.session_state['edit_template_flag'] # Deletion moved
def edit_template(db_manager, template):
# ... display edit form ...
if submitted:
# ... update template ...
del st.session_state['edit_template_flag'] # Deletion inside function
Button Click: Same as before.
Deletion After Submission: Now, edit_template_flag is only deleted after the user submits the edit form.
Why the First Version Doesn't Work
In the first version, del st.session_state['edit_template_flag'] is called immediately afteredit_template() is invoked. Here's why this causes the issue:
Script Rerun on Interaction: Clicking the "Edit" button triggers the script to rerun.
Setting the Flag: st.session_state.edit_template_flag is set to True.
Displaying the Form: The script checks for edit_template_flag and calls edit_template() to display the edit form.
Immediate Deletion: Right after displaying the form, you delete edit_template_flag.
Form Disappears: On the next script rerun (which happens when the user tries to interact with the form), edit_template_flag is no longer in st.session_state, so the form doesn't display.
User Can't Submit: The user never gets a chance to interact with the form because it vanishes before they can input data.
Key Point: The flag is deleted before the user can interact with the edit form.
Why the Second Version Works
In the second version, you only delete edit_template_flagafter the user has submitted the form:
Flag Persistence: After clicking "Edit," the flag remains in st.session_state.
Form Displayed: Each script rerun checks for the flag, and the form continues to be displayed.
User Interaction: The user can interact with the form and submit their changes.
Deleting the Flag at the Right Time: Once the form is submitted and the template is updated, edit_template_flag is deleted.
Form Hides After Submission: On the next rerun, since the flag is no longer present, the form doesn't display, which is the desired behavior.
Key Point: The flag remains set while the user interacts with the form and is only deleted after the interaction is complete.
Explanation of Session State Management
Setting Session State Variables
When to Set: When an event occurs that should change what is displayed or how the app behaves in subsequent runs.
Example: Clicking the "Edit" button sets st.session_state.edit_template_flag to True to indicate that the edit form should be displayed.
Deleting Session State Variables
When to Delete: After the purpose of the session state variable is fulfilled, typically after the user completes an action associated with that state.
Example: Deleting edit_template_flag after the user submits the edit form, so the form no longer displays.
Why Timing Matters
Premature Deletion: If you delete a session state variable before the user completes the associated action, the app won't behave as expected because on the next script rerun, the variable will be missing.
Persistent State: By maintaining the session state variable until after the user interaction, you ensure that the app's interface remains consistent and responsive to the user's actions.
Best Practices for Session State Variables
Initialize Variables: Ensure that all session state variables are initialized appropriately, often at the top of your script.
python
if 'edit_template_flag' not in st.session_state:
st.session_state['edit_template_flag'] = False
Set Variables in Response to Events: Update session state variables inside event handlers, such as button clicks.
python
if st.button('Edit'):
st.session_state['edit_template_flag'] = True
Use Variables to Control Workflow: Use the session state variables to conditionally display components or control the app's logic.
python
if st.session_state['edit_template_flag']:
edit_template()
Delete or Reset Variables Appropriately: Remove or reset session state variables after their purpose is served.
python
def edit_template():
if submitted:
# Process form submission
del st.session_state['edit_template_flag']
An Analogy
Think of st.session_state as a set of flags or indicators that guide your app's behavior:
Setting a Flag: You raise a flag when an event occurs (like the user wants to edit a template).
Reading the Flag: The app checks which flags are raised and displays content accordingly (shows the edit form if the edit flag is raised).
Lowering the Flag: Once the action is completed, you lower the flag to reset the app to its default state (hide the edit form after submission).
If you lower the flag before the action completes, the app won't display the expected components, leading to confusion for the user.
Conclusion
The key takeaway is the timing of when you set and delete session state variables in Streamlit:
Set session state variables when initiating an action that should persist across script reruns (e.g., displaying an edit form).
Delete session state variables after the user has completed the associated action and no longer needs that state to persist.
By placing del st.session_state['edit_template_flag'] inside the edit_template() function and only deleting it after the form is submitted, you ensure that the edit form remains displayed while the user interacts with it, and only hides after the user has completed the editing process.
Additional Tips
Avoid Global Flags: If you have multiple templates, consider using a more granular session state variable, such as st.session_state[f'edit_{template_id}'], to handle multiple edit forms independently.
Form Keys: Assign unique keys to forms and widgets, especially inside loops or when dealing with dynamic content, to prevent conflicts and ensure Streamlit can manage the widget states correctly.
Debugging: Use st.write() or st.session_state to print out the current session state during development, which can help you understand how your variables change over time.
I hope this explanation clarifies why the location of del st.session_state['edit_template_flag'] affects your app's behavior and how to manage session state variables effectively in Streamlit.