✊🏿 Black Lives Matter. Please consider donating to Black Girls Code today.
🐇 Announcing Dash VTK for 3d simulation graphics. Check out the March webinar.

How to use flask_caching on functions in modules?

Hi, I have my main app main.py where all the Dash-specific code (layout, callbacks,…) is. I put everything not Dash-specific in a separate folder and import that as a module via import helpers. These are database calls and other slow computations that I want to memoize using the Flask Cache. But I am stuck:

I create the Cache object in main.py:

import dash
from flask_caching import Cache
import helpers
app = dash.Dash()
cache = Cache(app.server, config={
    'CACHE_TYPE': 'filesystem',
    'CACHE_DIR': 'cache'
x = helpers.do_some_slow_computation(1,2,3)

But how can I share this object with the “helpers” module?

1 Like

You’ll want to create a cached function that runs the computation. Just place the cache decorator above the function. Try something like this:

@cache.memoize(timeout=600)  # Number of seconds to cache the result
def compute(): 
    x = helpers.do_some_slow_computation(1,2,3)


There’s some good documentation here: https://flask-caching.readthedocs.io/en/latest/