How to display values from DB in a slider

Summary

I’m trying to cache a value from a slider in a Redis DB and display it in the value parameter section.
It’s partially working, but the slider is jumping back (every second time) if the slider gets set to a new value.

Steps to reproduce

Code snippet:

import streamlit as st
import redis

host = 'localhost'
redis_port = '6379'

r = redis.Redis(
    host = host,
    port = redis_port,
    decode_responses=True,
)

def load_data():
    db_value = r.get('slider_value')
    return float(db_value)

values = st.slider('Select a range of values', 0.0, 100.0, value=load_data())
st.write('Values:', values)
r.set('slider_value', values)
st.write(r.get('slider_value'))
st.write(load_data())

If applicable, please provide the steps we should take to reproduce the error or specified behavior.

Expected behavior:

Set value with slider
Slider displays current value
Update DB
Read value from DB
Display value from DB in slider parameter

Actual behavior:

The slider is jumping back (every second time) if the slider gets set to a new value.

Debug info

  • Streamlit version: (1.70)
  • Redis (7.0.5)
  • Python version: (3.9)
  • OS version: Montery
  • Browser version:

Requirements file

Links

Additional information

I have tried using st.cache() for the load_data function, but this did not solve the issue because it’s not updating the new values anymore. Is there maybe a way to trigger the st.cache manually at the end of the script?

If needed, add any other context about the problem here.

I was able to get it working with a small tweak – rather than simply saving the value to redis below the slider code, set it in a function with on_change:

import redis
import streamlit as st

host = "localhost"
redis_port = 6379

r = redis.Redis(
    host=host,
    port=redis_port,
    decode_responses=True,
)


def load_data():
    db_value = r.get("slider_value")
    try:
        return float(db_value)
    except TypeError:
        return 1.0


def set_data():
    slider_value = st.session_state["slider_key"]
    r.set("slider_value", slider_value)


values = st.slider(
    "Select a range of values",
    0.0,
    100.0,
    value=load_data(),
    key="slider_key",
    on_change=set_data,
)
st.write("Values:", values)
st.write(r.get("slider_value"))
st.write(load_data())
1 Like