atexit registered function unable to access streamlit session state variable

56 Views Asked by At

I have registered an atexit function like this:

import streamlit as st
from azure.search.documents.indexes import SearchIndexClient 
from azure.core.credentials import AzureKeyCredential


@atexit.register
def delete_vector_index():
    admin_client = SearchIndexClient(endpoint=st.session_state.vector_store_address,
                      index_name=st.session_state.index_name,
                      credential=AzureKeyCredential(st.session_state.vector_store_password))
    admin_client.delete_index(st.session_state.index_name)

if "initialized" not in st.session_state:
    st.session_state.initialized = True
    st.session_state.vector_store_address: str = "<my endpoint>"
    st.session_state.vector_store_password: str = "<admin key>"
    st.session_state.index_name: str = "<index name>"

But everytime the interpreter finishes, this is the error message I get "AttributeError: st.session_state has no attribute "vector_store_address". Did you forget to initialize it? More info: https://docs.streamlit.io/library/advanced-features/session-state#initialization"

Why is the st.session_state variable inaccessible from the atexit function when it can be easily accessed from my other functions? Does anyone know what to do about this?

1

There are 1 best solutions below

0
Dasari Kamali On

The modified code below includes your code that accesses the Streamlit session state variable with the atexit function.

Code :

import atexit
import streamlit as st
from azure.search.documents.indexes import SearchIndexClient 
from azure.core.credentials import AzureKeyCredential

vector_store_address = None
vector_store_password = None
index_name = None

def delete_vector_index():
    if vector_store_address and vector_store_password and index_name:
        admin_client = SearchIndexClient(
            endpoint=vector_store_address,
            index_name=index_name,
            credential=AzureKeyCredential(vector_store_password)
        )
        admin_client.delete_index(index_name)

if "initialized" not in st.session_state:
    st.session_state.initialized = True
    vector_store_address = "https://<azure_search_name>.search.windows.net/"
    vector_store_password = "<azure_search_key>"
    index_name = "<index_name>"

atexit.register(delete_vector_index)

def main():
    st.title("Streamlit App")

if __name__ == "__main__":
    main()

Output :

It ran successfully as shown below:

enter image description here

I got the below output in the browser.

enter image description here

Next, the index was deleted while stopping Streamlit, as shown below.

enter image description here