Summary
The package Extra-Streamlit-Components provides capacity for cookie management. However, due to Streamlitâs re-running mechanism, a lot of challenges were encountered while implementing read and write operations for cookies. Eventually, I managed to find the correct way to call these operations. Under the stateless protocol of HTTP, in the mechanism of Streamlit, stable read, judge and write operations of cookies can be carried out efficiently.
Steps to reproduce
Code snippet:
cookie_manager = get_manager()
start_time = time.time()
timeout = 0.01 # Preset timeout time
while True:
if 'cookies' not in st.session_state:
st.session_state['cookies'] = cookie_manager.get_all()
elif time.time() - start_time > timeout:
st.warning("Operation timeout. Please refresh the page or check your network connection.")
break # If timed out, exit the loop directly
else:
if 'lzs_userid' not in st.session_state.cookies:
if 'lzs_userid' not in st.session_state:
st.session_state["lzs_userid"] = str(uuid.uuid4())
cookie_manager.set('lzs_userid', st.session_state["lzs_userid"], key="0", expires_at=datetime.datetime(year=2023, month=8, day=2))
if "lzs_pwd" not in st.session_state.cookies:
if "lzs_pwd" not in st.session_state:
random_pwd = ''.join(random.choices(string.ascii_letters + string.digits,k=8))
st.session_state['lzs_pwd'] = bcrypt.hashpw(random_pwd.encode(),bcrypt.gensalt(rounds=10)).decode('utf-8')
cookie_manager.set('lzs_pwd', st.session_state.get('lzs_pwd', ''), key="1", expires_at=datetime.datetime(year=2023, month=8, day=2))
break
If applicable, please provide the steps we should take to reproduce the error or specified behavior.
Expected behavior:
Explain what you expect to happen when you run the code above.
Actual behavior:
Explain the undesired behavior or error you see when you run the code above.
If youâre seeing an error message, share the full contents of the error message here.
Debug info
- Streamlit version: (get it with
$ streamlit version
) - Python version: (get it with
$ python --version
) - Using Conda? PipEnv? PyEnv? Pex?
- OS version:
- Browser version:
Requirements file
Using Conda? PipEnv? PyEnv? Pex? Share the contents of your requirements file here.
Not sure what a requirements file is? Check out this doc and add a requirements file to your app.
Links
- Link to your GitHub repo:
- Link to your deployed app:
Additional information
If needed, add any other context about the problem here.