Saturnix
Saturnix

Reputation: 10554

Django/Python caching solution that I can access with complex keys rather than only strings

It is my understanding that all caching solutions for Django/Python are essentially based on key/value dictionaries.

cache.store(“key”, “value”)

cache.get(“key”) # <- “value”

I understand there are decorators and other abstractions that allow you to store in cache based on the view function, but they’re agnostic towards the inputs of this function (POST/GET parameters, for example).

Here’s my problem: I need to cache results of computations of complex sets of inputs, including (but not limited to), the user that’s performing the request, dictionaries, booleans, ecc...

I could, in theory, serialize these inputs into a string and use this string as the key for caching but I was wondering if there are some pre-made solutions to solve this problem.

Something like this:

def my_view(request):

    output = cache.get(request, None)
    if output is None:
        output = complex_stuff(request) # <- can be serialized as string
        cache.store(request, output)

Or, even better, where I can use an arbitrary dictionary as a key, instead of a string.

This is not merely caching per user (Django per user view caching). Caching per user would be insufficient as I need it per user and per user input.

Upvotes: 1

Views: 121

Answers (1)

Yiling
Yiling

Reputation: 26

I think you can try this package, django-cache-memoize, which auto memoize arguments and keyword arguments. Or if you use redis, and need more control, you can also try my package Django-Cacheme

Upvotes: 1

Related Questions