Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Be able to close cached resources (@st.cache_resource) #8674

@gerbenoostra

Description

@gerbenoostra

Checklist

  • I have searched the existing issues for similar feature requests.
  • I added a descriptive title and summary to this issue.

Summary

@st.cache_resource is recommended to use for non-hashable resources like database connections. However, such resources might require closing.

Why?

@st.cache_resource is recommended to use for non-hashable resources like database connection. From the doc:

 @st.cache_resource
 def get_database_session(_sessionmaker, url):
     # Create a database connection object that points to the URL.
     return connection

However, these resources could require closing (closing the database connection, stopping a SparkSession).

In the current implementation I'm not able to close the connection, requiring the streamlit instance to be restarted. For database connections this will result in dangling connections.

How?

Ideally I'd be able to close the resource in the same function similar to PyTest yields usage:

 @st.cache_resource
 def get_database_session(_sessionmaker, url):
     # Create a database connection object that points to the URL.
     yield connection
     connection.close()

Alternatively, perhaps a close callback:

 @st.cache_resource(close= lambda con: con.close())
 def get_database_session(_sessionmaker, url):
     # Create a database connection object that points to the URL.
     return connection

Additional Context

No response

Metadata

Metadata

Labels

feature:cacheRelated to `st.cache_data` and `st.cache_resource`type:enhancementRequests for feature enhancements or new features

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions