bbangert / beaker

WSGI middleware for sessions and caching
https://beaker.readthedocs.org/
Other
517 stars 146 forks source link

how to conditional cache function result based on the result of the function #169

Closed ohadperry closed 5 years ago

ohadperry commented 5 years ago

wondering if there is a way to implement conditional cache for a function based on it's results

def should_cache(function_result):
     # if already cached, shouldn't get here 
     if function_result['status'] in FINAL_STEPS:
          return True

@cache_region('long_term', 'get_something', should_cache)
def get_something(**kwargs):
      ... something really expensive that should be cached if the status is in it's final steps 
amol- commented 5 years ago

The best way to do so is to use the cache programmatically.

IE:

manager = CacheManager()

cache = manager.get_cache_region('get_something', 'long_term')

def get_do_samething():
    try:
        return cache.get('cache_key')
    except KeyError:
         result = do_something_for_real()
         if result['status'] in FINAL_STEPS:
             cache.put('cache_key', result)
         return result
ohadperry commented 5 years ago

Thanks!