Session State not working the way I want

  1. Are you running your app locally or is it deployed?
    locally
  2. Share the full text of the error message (not a screenshot).
def main():
        if 'session_state' not in st.session_state or 'selected_data_source' not in st.session_state:
            st.session_state['selected_data_source']=dict('Local PC', 'Database')
            st.session_state.session_state = 'x_col'
                # create logout button
        authenticator.logout("Logout", "sidebar")
        data_a=None
        # Option to choose data source
        def handle_radio():
            if st.session_state.column_type:
                st.session_state.selected_data_source=st.session_state.column_type
                  
        st.sidebar.radio("Select Data Source", ["Local PC", "Database"], on_change=handle_radio, key='column_type')
                        
        if st.session_state.selected_data_source == "Local PC":
            # Allow users to upload a CSV file from their PC
            st.sidebar.header("Upload input files")
            uploaded_file = st.sidebar.file_uploader("", type=["csv", "xlsx"], accept_multiple_files=True)
            if uploaded_file is not None:
                for files in uploaded_file:
                    # Process the uploaded file here
                    file_name = files.name
                    file_extension = file_name.split('.')[-1].lower()
                        
                    #checking the extension of the file the user uploaded
                    if file_extension=='csv':
                        try:
                            data_ = pd.read_csv(files)
                            data_a=data_.copy()
                            st.sidebar.write("Loaded Data:")
                            st.write(data_)
                                            
                            # Hqandling exceptions error
                        except UnicodeDecodeError:
                            data_ = pd.read_csv(files, encoding='ISO-8859-1')  # or encoding='cp1252'
                            data_a=data_.copy()
                            st.sidebar.write("Loaded Data:")
                            st.write(data_)
                        except KeyError:
                            st.warning('please check the column headers to meet')
                        except pd.errors.ParserError as e:
                            # Handle the parsing error
                            st.warning(f"ParserError: {e}")
                        except Exception as e:
                            # This block can catch any other exceptions that were not specifically caught above
                            st.warning(f"An unexpected error occurred: {e}")
                    elif file_extension=='xlsx':
                        try:
                            data_ = pd.read_excel(files)
                            st.session_state.data_a=data_.copy()
                            st.sidebar.write("Loaded Data:")
                            st.dataframe(st.session_state.data_a)
                                # Continue processing the DataFrame
                        except UnicodeDecodeError:
                            data_ = pd.read_csv(files, encoding='ISO-8859-1')  # or encoding='cp1252'
                            st.session_state.data_a=data_.copy()
                            st.sidebar.write("Loaded Data:")
                            st.dataframe(st.session_state.data_a)
                        except KeyError:
                            st.warning('please check the column headers to meet')
                        except pd.errors.ParserError as e:
                                        # Handle the parsing error
                            st.warning(f"ParserError: {e}")
                        except Exception as e:
                            # This block can catch any other exceptions that were not specifically caught above
                            st.warning(f"An unexpected error occurred: {e}")
                    else:
                        st.warning(f"This file is unsupported: {file_extension}")
                                    
                            
        elif st.session_state.selected_data_source == "Database":
            # Database connection parameters (user inputs) 
            server = st.sidebar.text_input("Server", value="your_server_name")
            database = st.sidebar.text_input("Database", value="your_database_name")
            driver = st.sidebar.text_input("ODBC Driver", value="{ODBC Driver 17 for SQL Server}")
                            
            # User-specified SQL query
            user_query = st.sidebar.text_area("Enter your SQL query")
                            
            if st.sidebar.button("Load Data"):
                    # Connect to the database
                try:
                    conn = pyodbc.connect(f"DRIVER={driver};SERVER={server};DATABASE={database};Trusted_Connection=yes")
                    st.write('connection successful')
                    data_ = pd.read_sql(user_query, conn) 
                    st.session_state.data_a=data_.copy()
                    # Display the loaded data
                    st.sidebar.write("Loaded Data from SQL Server:")
                    st.dataframe(st.session_state.data_a)
                            
                except Exception as e:
                    st.error(f"An error occurred: {str(e)}")
                finally:
                    if conn is not None:
                        conn.close()
            if st.session_state.data_a is not None:
                column_=st.session_state.data_a.columns.tolist()
                
                x_col= st.sidebar.selectbox("Select X Column",column_)
                
                y_col= st.sidebar.selectbox("Select Y Column",column_)
              
                o =st.sidebar.selectbox("Select o Column", column_)
                
                l=st.sidebar.selectbox("Select L Column", column_)
                
            
    if __name__ == "__main__":
        main()

my session_state is not working properly. The data frame disappears when user selects any of the columns.
Also the column list is meant to populate in the selectbox only when user has been able to load data successfully either from local PC or Database but the app is behaving the opposite

@blackary please can you help with this. Thanks

There are a lot of things happening in this script – can you please simplify it down to the simplest version of the script that shows one or more of this issues you are having? This will probably be very helpful for your own debugging purposes, and will help others to provide feedback as well.

Some issues that stand out:

  1. st.session_state.selected_data_source = a dictionary by default, not a string – presumably you meant that to be a string, not a dict
  2. Session state is not necessary for at least some of the places you are using it
def handle_radio():
    if st.session_state.column_type:
        st.session_state.selected_data_source=st.session_state.column_type
          
st.sidebar.radio("Select Data Source", ["Local PC", "Database"], on_change=handle_radio, key='column_type')
                
if st.session_state.selected_data_source == "Local PC":

This could all be replaced with

selected_data_source = st.sidebar.radio("Select Data Source", ["Local PC", "Database"])       
if st.session_state.selected_data_source == "Local PC":
  1. If you use buttons to load data (e.g. if st.sidebar.button("Load Data"):, then the next time you interact with a widget, the state of that button will become False, and nothing inside the if will run.
    I would recommend reading through this:
    https://docs.streamlit.io/library/advanced-features/button-behavior-and-examples
    But, if you need some sort of selector, I you would probably be fine if you swapped out the st.button with st.checkbox.

Hi. Thanks.
used a check box and it fixed the issue

1 Like

This topic was automatically closed 2 days after the last reply. New replies are no longer allowed.