Python check if cache key exists

Viewed 2263

I have the following python function that uses cache functions:

from cachetools import cached, TTLCache

cache = TTLCache(maxsize=100, ttl=3600)

@cached(cache)
def load_data():
   # run slow data to get all user data
   load_response = requests.request(
       'GET',
       url=my_url
   )

   return load_response

Is there a way to check if the key exists in the cache first so that i can implement an else functionality?

I am trying to implement another cache to fetch data from there when the cache key does not exist here.

1 Answers

Access cache like a regular dictionary without using the decorator

item = cache.get(key, None)
if item is not None:
   ...
else:
   ...
   # get item the slow way
   cache[key] = item
Related