This is rather perplexing, I will need to find a way to recreate this error first, only then will I be able to debug it. Thank you for your patience.
My Python version is 3.10.10
Components:
extra-streamlit-components==0.1.56
streamlit==1.22.0
Try a fresh installation:
git clone https://github.com/vidz1979/Streamlit-Authenticator
cd Streamlit-Authenticator
python -m venv .venv
pip install -r requirements.txt
python apply-hash.py
streamlit run example.py
Do login, stop app, reload, stop again and reload it again. It should pop the error when app starts.
Error happens in Mac M1 and Ubuntu 20.04, didn’t tested it in Windows.
I had a clue of the error.
I’ve tried to use streamlit_cookies_manager and it uses @st.cache
, poping up a deprecation warning. When I modified streamlit_cookies_manager to use @st.cache_data
the same error happened!
Maybe the error has something to do with new cache_data
decorator.
I’ve been facing the same issue. However, I have built my own authentication module based on graph database. I am using cookie manager under extra_streamlit_components similar to streamlit_authentication and the problem is that.
I’ve been using @st.cache_data(experimental_allow_widgets=True) for cookie manager while getting this error.
After removing cache_data the error went away
did you ever find a solution here? I am still having the same problem.
I had the same error, not sure,but it seems I was able to solve it, every new variable before
if st.session_state.authentication_status:
in the app.py I changed with st.session.variable, for example
if "config" not in st.session_state:
with open('config.yaml') as file:
st.session_state.config = yaml.load(file, Loader=SafeLoader)
instead of
with open('config.yaml') as file:
config = yaml.load(file, Loader=SafeLoader)
Try this
Can you please go more in depth for your solution. I can’t get this to work and would love to get it solved! Thanks!
I too suddenly got the same error and main running 2 times. Does lowering the streamlit version make it ok?
I also have the error
Thanks! This worked for me when running the app locally.
For some reason, when I Dockerize the app, I receive a similar error issue when I pass the config parameters through stauth.Authenticate:
authenticator = stauth.Authenticate(
st.session_state.config['credentials'],
st.session_state.config['cookie']['name'],
st.session_state.config['cookie']['key'],
st.session_state.config['cookie']['expiry_days']
)
Try st.session_state.authenticator, instead of authenticator.
I got same issue. But after a long exploring I found the error did not come from authenticator but from other part of my code. In my case I set wrong API KEY for request, but received “widget brabra…”. I strongly recommend dig other part of your code rather than digging authenticator. gl.
Hello there. I tried to do something similar and I think your result is just a coincidence.
I created a very simple venv with just streamlit and streamlit-authenticator. I used python 3.10.11, but I’ve also faced this bug in 3.9.6.
First, this is the code I used:
import time
import uuid
from datetime import datetime
exec_id = uuid.uuid4().hex[:6]
print(f'{exec_id} Rerunning page')
print(f'{exec_id} Importing streamlit')
import streamlit as st
print(f'{exec_id} Sleeping before import authenticator, {datetime.now()}')
time.sleep(5)
print(f'{exec_id} Importing Authenticator, {datetime.now()}')
import streamlit_authenticator as stauth
print(f'{exec_id} Importing yaml')
import yaml
from yaml.loader import SafeLoader
with open('user_config.yaml') as file:
config = yaml.load(file, Loader=SafeLoader)
authenticator = stauth.Authenticate(
config['credentials'],
config['cookie']['name'],
config['cookie']['key'],
config['cookie']['expiry_days'],
config['preauthorized']
)
name, authentication_status, username = authenticator.login('Login', 'main')
if authentication_status:
authenticator.logout('Logout', 'main', key='unique_key')
st.write(f'Welcome *{name}*')
st.title('Some content')
elif authentication_status is False:
st.error('Username/password is incorrect')
elif authentication_status is None:
st.warning('Please enter your username and password')
Notice that the only widget I use here is the streamlit-authenticator login form. Also, before importing st-authenticator I use sleep to wait a little bit.
To further understand the problem, I placed some prints in the imports of the strealit-authenticator init.py file:
print('Reading st-authenticator __init__')
import yaml
print('Importing streamlit inside authenticator __init__')
import streamlit as st
from yaml.loader import SafeLoader
print('Importing streamlit components inside authenticator __init__')
import streamlit.components.v1 as components
from .hasher import Hasher
print('Importing authenticator obj inside __init__')
from .authenticate import Authenticate
Finally, my terminal output:
(env) [mateus@fedora st-analytics]$ streamlit run test.py
You can now view your Streamlit app in your browser.
Local URL: http://localhost:8501
Network URL: http://192.168.0.92:8501
073453 Rerunning page
073453 Importing streamlit
073453 Sleeping before import authenticator, 2023-08-19 10:38:00.129267
33f3ce Rerunning page
33f3ce Importing streamlit
33f3ce Sleeping before import authenticator, 2023-08-19 10:38:00.142133
2023-08-19 10:38:00.146 Uncaught app exception
Traceback (most recent call last):
File "/home/mateus/Projects/st-analytics/env/lib64/python3.10/site-packages/streamlit/runtime/state/session_state.py", line 378, in __getitem__
return self._getitem(widget_id, key)
File "/home/mateus/Projects/st-analytics/env/lib64/python3.10/site-packages/streamlit/runtime/state/session_state.py", line 423, in _getitem
raise KeyError
KeyError
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/home/mateus/Projects/st-analytics/env/lib64/python3.10/site-packages/streamlit/runtime/scriptrunner/script_runner.py", line 548, in _run_script
self._session_state.on_script_will_rerun(rerun_data.widget_states)
File "/home/mateus/Projects/st-analytics/env/lib64/python3.10/site-packages/streamlit/runtime/state/safe_session_state.py", line 68, in on_script_will_rerun
self._state.on_script_will_rerun(latest_widget_states)
File "/home/mateus/Projects/st-analytics/env/lib64/python3.10/site-packages/streamlit/runtime/state/session_state.py", line 482, in on_script_will_rerun
self._compact_state()
File "/home/mateus/Projects/st-analytics/env/lib64/python3.10/site-packages/streamlit/runtime/state/session_state.py", line 300, in _compact_state
self._old_state[key_or_wid] = self[key_or_wid]
File "/home/mateus/Projects/st-analytics/env/lib64/python3.10/site-packages/streamlit/runtime/state/session_state.py", line 380, in __getitem__
raise KeyError(_missing_key_error_message(key))
KeyError: 'st.session_state has no key "$$WIDGET_ID-1a8279410f90d35adda3725d5aedbfc0-init". Did you forget to initialize it? More info: https://docs.streamlit.io/library/advanced-features/session-state#initialization'
7df6d3 Rerunning page
7df6d3 Importing streamlit
7df6d3 Sleeping before import authenticator, 2023-08-19 10:38:00.218844
2023-08-19 10:38:00.222 Uncaught app exception
Traceback (most recent call last):
File "/home/mateus/Projects/st-analytics/env/lib64/python3.10/site-packages/streamlit/runtime/state/session_state.py", line 378, in __getitem__
return self._getitem(widget_id, key)
File "/home/mateus/Projects/st-analytics/env/lib64/python3.10/site-packages/streamlit/runtime/state/session_state.py", line 423, in _getitem
raise KeyError
KeyError
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/home/mateus/Projects/st-analytics/env/lib64/python3.10/site-packages/streamlit/runtime/scriptrunner/script_runner.py", line 548, in _run_script
self._session_state.on_script_will_rerun(rerun_data.widget_states)
File "/home/mateus/Projects/st-analytics/env/lib64/python3.10/site-packages/streamlit/runtime/state/safe_session_state.py", line 68, in on_script_will_rerun
self._state.on_script_will_rerun(latest_widget_states)
File "/home/mateus/Projects/st-analytics/env/lib64/python3.10/site-packages/streamlit/runtime/state/session_state.py", line 482, in on_script_will_rerun
self._compact_state()
File "/home/mateus/Projects/st-analytics/env/lib64/python3.10/site-packages/streamlit/runtime/state/session_state.py", line 300, in _compact_state
self._old_state[key_or_wid] = self[key_or_wid]
File "/home/mateus/Projects/st-analytics/env/lib64/python3.10/site-packages/streamlit/runtime/state/session_state.py", line 380, in __getitem__
raise KeyError(_missing_key_error_message(key))
KeyError: 'st.session_state has no key "$$WIDGET_ID-1a8279410f90d35adda3725d5aedbfc0-init". Did you forget to initialize it? More info: https://docs.streamlit.io/library/advanced-features/session-state#initialization'
2fda37 Rerunning page
2fda37 Importing streamlit
2fda37 Sleeping before import authenticator, 2023-08-19 10:38:00.553266
e5fdaa Rerunning page
e5fdaa Importing streamlit
e5fdaa Sleeping before import authenticator, 2023-08-19 10:38:00.573324
2023-08-19 10:38:00.597 Uncaught app exception
Traceback (most recent call last):
File "/home/mateus/Projects/st-analytics/env/lib64/python3.10/site-packages/streamlit/runtime/state/session_state.py", line 378, in __getitem__
return self._getitem(widget_id, key)
File "/home/mateus/Projects/st-analytics/env/lib64/python3.10/site-packages/streamlit/runtime/state/session_state.py", line 423, in _getitem
raise KeyError
KeyError
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/home/mateus/Projects/st-analytics/env/lib64/python3.10/site-packages/streamlit/runtime/scriptrunner/script_runner.py", line 548, in _run_script
self._session_state.on_script_will_rerun(rerun_data.widget_states)
File "/home/mateus/Projects/st-analytics/env/lib64/python3.10/site-packages/streamlit/runtime/state/safe_session_state.py", line 68, in on_script_will_rerun
self._state.on_script_will_rerun(latest_widget_states)
File "/home/mateus/Projects/st-analytics/env/lib64/python3.10/site-packages/streamlit/runtime/state/session_state.py", line 482, in on_script_will_rerun
self._compact_state()
File "/home/mateus/Projects/st-analytics/env/lib64/python3.10/site-packages/streamlit/runtime/state/session_state.py", line 300, in _compact_state
self._old_state[key_or_wid] = self[key_or_wid]
File "/home/mateus/Projects/st-analytics/env/lib64/python3.10/site-packages/streamlit/runtime/state/session_state.py", line 380, in __getitem__
raise KeyError(_missing_key_error_message(key))
KeyError: 'st.session_state has no key "$$WIDGET_ID-1a8279410f90d35adda3725d5aedbfc0-init". Did you forget to initialize it? More info: https://docs.streamlit.io/library/advanced-features/session-state#initialization'
073453 Importing Authenticator, 2023-08-19 10:38:05.134165
Reading st-authenticator __init__
33f3ce Importing Authenticator, 2023-08-19 10:38:05.152152
Importing streamlit inside authenticator __init__
Importing streamlit components inside authenticator __init__
Importing authenticator obj inside __init__
073453 Importing yaml
7df6d3 Importing Authenticator, 2023-08-19 10:38:05.223408
7df6d3 Importing yaml
33f3ce Importing yaml
291412 Rerunning page
291412 Importing streamlit
291412 Sleeping before import authenticator, 2023-08-19 10:38:05.499713
2fda37 Importing Authenticator, 2023-08-19 10:38:05.558069
2fda37 Importing yaml
e5fdaa Importing Authenticator, 2023-08-19 10:38:05.592168
e5fdaa Importing yaml
c9d441 Rerunning page
c9d441 Importing streamlit
c9d441 Sleeping before import authenticator, 2023-08-19 10:38:05.864105
291412 Importing Authenticator, 2023-08-19 10:38:10.504818
291412 Importing yaml
c9d441 Importing Authenticator, 2023-08-19 10:38:10.865419
c9d441 Importing yaml
I had three tabs open before rebooting streamlit’s server to reproduce the bug. Notice how the error happened anyway before importing streamlit-authenticator. I repeated this test a couple times and always get the same result.
So, my conclusion is that it’s streamlits’s code that is generating the bug when rebooting the server. Maybe it has to do with authenticator anyway, because I had to use it in first place to open the webpage and then shutdown the server. But, this is something that streamlit’s team could also investigate.
Interesting thanks for the investigation…
I encountered a KeyError
when using st.session_state
in the deployed Streamlit apps. This error manifested itself when session state keys were not initialized, as there wasn’t a clear reason for these keys to be absent.
Solution: That worked for me
To tackle this problem, ensure that all session state keys are initialized right at the onset before any conditions or checks come into play. Simply put, kick off your app by initializing these session state keys.
def initialize_session_state():
if 'name' not in st.session_state:
st.session_state['name'] = None
if 'authentication_status' not in st.session_state:
st.session_state['authentication_status'] = None
if 'username' not in st.session_state:
st.session_state['username'] = None
initialize_session_state()
By setting up the session state keys upfront, you’re effectively shielding your app from any unexpected KeyErrors
that might spring up later.
I’ve have incorporated libraries such as:
- streamlit-elements==0.1.0
- streamlit-option-menu==0.3.6
For an added layer of safety, I’ve introduced this function:
def get_session_value(key, default=None):
return st.session_state.get(key, default)
and I used it
name, authentication_status, username, authenticator = create_login_widget(credentials)
st.session_state['authentication_status'] = authentication_status
auth_status = get_session_value('authentication_status')
if auth_status == False:
col2.error("Username/password is incorrect")
elif auth_status == None:
col2.warning("Please enter your username and password")
else:
st("Logged in")
This doesn’t work for me. Notice this topic is about a missing widget ID key, for example:
KeyError: 'st.session_state has no key “$$WIDGET_ID-1a8279410f90d35adda3725d5aedbfc0-init”. Did you forget to initialize it?
Tried the code below with no success.
import time
import uuid
from datetime import datetime
exec_id = uuid.uuid4().hex[:6]
print(f'{exec_id} Rerunning page')
print(f'{exec_id} Importing streamlit')
import streamlit as st
def initialize_session_state():
if 'name' not in st.session_state:
st.session_state['name'] = None
if 'authentication_status' not in st.session_state:
st.session_state['authentication_status'] = None
if 'username' not in st.session_state:
st.session_state['username'] = None
initialize_session_state()
print(f'{exec_id} Sleeping before import authenticator, {datetime.now()}')
time.sleep(5)
print(f'{exec_id} Importing Authenticator, {datetime.now()}')
import streamlit_authenticator as stauth
authenticator = stauth.Authenticate(
{'usernames': {'mateus': {'email': None, 'name': 'mateus', 'password': 2341234}}},
'st_debug_cookie',
'kjsdnfkjdsnjfknskd',
30,
{'emails': None}
)
name, authentication_status, username = authenticator.login('Login', 'main')
if authentication_status:
st.write(f'Welcome *{name}*')
st.title('Some content')
elif authentication_status is False:
st.error('Username/password is incorrect')
elif authentication_status is None:
st.warning('Please enter your username and password')
It really seems something internal. Btw, I opened an issue about this problem: Widget ID not found in session_state after server reboot · Issue #7206 · streamlit/streamlit · GitHub
Hi,
I was doing some investigation of this and I found that this bug was caused by our fastRerun config being turned on in 1.19.0.
In order to get rid of this, you can put in your .streamlit/config.toml
:
[runner]
# Default: true
fastReruns = false
This will turn off our fastReruns as it looks like we are running into some threading issues. I’m not sure of the solution to resolve this as I’m not a threading expert but I will attempt to look at this some more. However, I’m just trying to give a temporary workaround and what’s going on.
I’ve also been running into a variety of key errors with streamlit when hosted on community cloud. Not sure what’s going on in the backend, but deploying the same app on HuggingFace spaces with the streamlit integration seems to have resolved all of these issues. Might be a useful alternative for those still facing these issues!
hi,
i am getting error for the below code.
import streamlit as st
import os
import google.generativeai as genai
Initialize session state for chat history and conversation if they don’t exist
if ‘chat_history’ not in st.session_state:
st.session_state[‘chat_history’] =
if ‘conversation’ not in st.session_state:
st.session_state[‘conversation’] = None
GOOGLE_API_KEY=‘AIzaSyCLb_hvq9dddfH00cP-MQTKEdb7itY9PpA’
genai.configure(api_key=GOOGLE_API_KEY)
function to load Gemini Pro model and get responses
model=genai.GenerativeModel(“gemini-pro”)
chat = model.start_chat(history=)
def get_gemini_response(question):
response=chat.send_message(question,stream=True)
return response
#initialize our streamlit app
st.set_page_config(page_title=“Q&A Demo”)
st.header(“DKM College Chatbot”)
input=st.text_input("Input: ",key=“input”)
submit=st.button(“Ask the question”)
if submit and input:
response=get_gemini_response(input)
# Add user query and response to session state chat history
st.session_state[‘chat_history’].append((“You”, input))
st.subheader(“The Response is”)
for chunk in response:
st.write(chunk.text)
st.session_state[‘chat_history’].append((“Bot”, chunk.text))
st.subheader(“The Chat History is”)
for role, text in st.session_state[‘chat_history’]:
st.write(f"{role}: {text}")
error:
File “C:\Python\Python311\Lib\site-packages\streamlit\runtime\state\session_state_proxy.py”, line 90, in getitem
return get_session_state()[key]
~~~~~~~~~~~~~~~~~~~^^^^^
File “C:\Python\Python311\Lib\site-packages\streamlit\runtime\state\safe_session_state.py”, line 89, in getitem
return self._state[key]
~~~~~~~~~~~^^^^^
File “C:\Python\Python311\Lib\site-packages\streamlit\runtime\state\session_state.py”, line 396, in getitem
raise KeyError(_missing_key_error_message(key))
KeyError: ‘st.session_state has no key “chat_history”. Did you forget to initialize it? More info: Add statefulness to apps<!-- --> - Streamlit Docs’
This topic was automatically closed 365 days after the last reply. New replies are no longer allowed.