1

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?

Community
  • 1
  • 1
Sriram
  • 513
  • 3
  • 15
  • 1
    possible duplicate of [Per-request cache in Django?](http://stackoverflow.com/questions/3151469/per-request-cache-in-django) – nofinator Sep 18 '14 at 15:08
  • ^ Thanks. From the linked question, "I would like to implement a decorator that provides per-request caching to any method, not just views." "Is there a way to get the current request object from Django, w/o passing it around?" seems to be similar to my requirement. I need to try out the accepted solution to see it works for me. – Sriram Sep 18 '14 at 15:51
  • The above solution works. Thanks! – Sriram Oct 27 '14 at 06:14

0 Answers0