KeyError: 'st.session_state has no key in Streamlit

# Libraries
import io
import os
import numpy as np
import pandas as pd
import streamlit as st

def login():
    # interface codes for the login screen
    # (css,buttons,background,input area etc )
    path_input_0 = st.text_input(
        "File Path:",
        "Please enter the path to the folder containing the Abstract_Account_Web_App.py file",
        key="PATH_INPUT_LAST"
    )
    st.write(path_input_0)
    global proceed
    if st.button("Proceed"):
        st.session_state["page"] = "main"
        st.balloons()
        st.experimental_rerun()



def main():
   
    if 'PATH_INPUT_LAST' in st.session_state:
    
        file0 = st.session_state["PATH_INPUT_LAST"]+"/Bankomat Alışveriş Özeti.csv"
        st.write(file0)
        if(os.path.exists(file0) and os.path.isfile(file0)):
          os.remove(file0)
          print("file was deleted as preprocessing")
        else:
          print("file was not found to delete")
    
    # interface codes for the main screen
    # (css,input,buttons etc.)
    def set_texts(pdf_files:list):
        print("starting to text process")
        #This function reads pdf and gets "CRC-32" components as texts
        for pdf_file in pdf_files:
            with fitz.open(pdf_file) as doc:
                text = ""
                for page in doc:
                    new_text = page.get_text()
                    text += new_text
            
                    return text
  


 
    pathz = st.session_state["PATH_INPUT_LAST"] + "/Bankomat Alışveriş Özeti.pdf"
    st.write("path1:", pathz)
       
    file_names = r'%s' % pathz
        
    st.write(file_names)
    set_texts([file_names])
   
    if st.button('Show Info Analysis'):   
       st.write(file_names)


if __name__ == "__main__":
    if "page" not in st.session_state:
        st.session_state["page"] = "login"

    if st.session_state["page"] == "login":
        login()

    elif st.session_state["page"] == "main":
        st.balloons()
        main()

Hello friends, I’m entering the input area on the login screen: “folder path containing the Abstract_Account_Web_App.py file” and then I am pressing the Proceed button.

When it comes to the main screen, path1, and file_names are displayed correctly and properly. However, when I click the ‘Show Info Analysis’ button on the main screen, I get an error as below:

“KeyError: 'st.session_state has no key “PATH_INPUT_LAST”. Did you forget to initialize it? More info: https://docs.streamlit.io/library/advanced -features/session-state#initialization”

How can I solve this problem?

Traceback:

File "f:\anaconda\lib\site-packages\streamlit\runtime\scriptrunner\script_runner.py", line 556, in _run_script
    exec(code, module.__dict__)
File "C:\Users\Desktop\abstract_account\Abstract_Account_Web_App.py", line 85, in <module>
    main()
File "C:\Users\Desktop\abstract_account\Abstract_Account_Web_App.py", line 64, in main
    pathz = st.session_state["PATH_INPUT_LAST"] + "/Bankomat Alışveriş Özeti.pdf"
File "f:\anaconda\lib\site-packages\streamlit\runtime\state\session_state_proxy.py", line 93, in __getitem__
    return get_session_state()[key]
File "f:\anaconda\lib\site-packages\streamlit\runtime\state\safe_session_state.py", line 111, in __getitem__
    return self._state[key]
File "f:\anaconda\lib\site-packages\streamlit\runtime\state\session_state.py", line 440, in __getitem__
    raise KeyError(_missing_key_error_message(key))

You never initialize “PATH_INPUT_LAST” into the session state.

I guess you mean to do this in your login function?

If it provides a solution to my problem, it can be done there.

I haven’t tried, but I guess it is something like:


if st.button("Proceed"):
        st.session_state["page"] = "main"
        st.session_state["PATH_INPUT_LAST"] = path_input_0
        st.balloons()
        st.experimental_rerun()

But I’m not 100% sure.

1 Like

In addition to what you wrote, I also deleted the key and it worked (delete key here) :

def login():
# interface codes for the login screen
# (css,buttons,background,input area etc )
path_input_0 = st.text_input(
“File Path:”,
“Please enter the path to the folder containing the Abstract_Account_Web_App.py file”,

)

@LukeF What is the reason why it doesn’t give an error like this, compared to the previous code?

1 Like

Nice work!

I’m not 100% sure why deleting the key works, but my guess is that it didn’t like sharing the key name with the key in session state.
If I had time I would experiment.
Perhaps you could try adding the text input key back with a random name?