liveBook · Manning

St.cache_resource

As explained in Build Python Web Apps with Streamlit

st.cache_resource is a Streamlit decorator that caches shared resources, such as database connections, across users and app sessions.

When several people open a Streamlit app, each gets a new app instance. A database connection is different: creating one for every user or browser tab is unnecessary. st.cache_resource is a decorator for keeping a resource shared across users and sessions. section 8.2.5

For a connection created with st.connection, there is no need to add the decorator yourself: Streamlit applies it internally to the returned connection. By contrast, st.cache_data is for values such as dataframes and API results. section 8.2.5

class Database:
  def __init__(self):
    self.conn = st.connection("haikuconn", type="sql")

The Database initializer obtains its SQL connection through st.connection, without an explicit caching decorator. section 8.2.5

How Build Python Web Apps with Streamlit covers it

How deep it goes
Defines the decorator’s role and explains automatic use by st.connection, but does not develop a custom decorated function.
Examples
Shows a Database class obtaining a named SQL connection with st.connection.
What you can do after
Apply it via Streamlit’s st.connection to share a database connection without adding a decorator to the Database class.
How it connects
Contrasts st.cache_data for cached data and API results with st.cache_resource for database connections.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Build Python Web Apps with Streamlit. The section links point to the parts of the book it draws on.