In our django app, we are calling an API of another app multiple times from different places with the same inputs.
One solution could be to store the response in the request context after it gets called. However, the request context is not passed into the calling methods. The calling methods are deep inside the control flow.
Therefore, I thought another solution could be store the response in a thread local storage. However, I learnt from a question here that the thread locals last longer than the request itself. I don't want that. I want this storage to last only as long as the request itself.
I implemented a decorator to wrap the calling function and it looks like the below.
import threading
threadlocal = threading.local()
threadlocal.cache = {}
def cache(func):
def inner(*args, **kwargs):
cache_key = (args, str(kwargs))
if cache_key in threadlocal.cache:
return threadlocal.cache[cache_key]
response = func(*args, **kwargs)
threadlocal.cache[cachekey] = response
return response
return inner
Is there a better storage mechanism here other than threading.local?