Search code examples
djangocaching

unique user based caching in django


In django 3.2 what's the cleanest way to access a user id in functions called from views or outside views?

I want to implement caching in my project but it needs to be specific to each user. I thought I could simply access the user id and integrate it in the cache key. The problem is doing so requires access to the request object and I often need access within functions called by a view.

I don't want to change all my functions to add a request object, unless that's the best solution.

Can something like a global be set for the duration of the request to access it anywhere once it hits the view? It looks like this gets into threads and seems hacky.

FWIW Currently I'm using django-cache-memoize which does everything I need https://github.com/peterbe/django-cache-memoize

and memcached which I also like.


Solution

  • My best recommendation would be to add LocMemCache as a non-standard cache and then specify to use that whenever you need thread-local caching:

    # settings.py
    CACHES = {
        'default': {
            'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache',
        },
        'local': {
            'BACKEND': 'django.core.cache.backends.locmem.LocMemCache',
        },
    
    # views.py
    from django.core.cache import caches
    def view(request):
        cache = caches['local']
        cache.set('user', request.user)
    
    # functions.py
    from django.core.cache import caches
    
    cache = caches['local']
    
    def function():
        user = cache.get('user')
    

    The caveat here is that the cache won't have any way of expiring specifically at the end of the request. You can do that manually ... Or if you have a lot of views, you can write a middleware that sets and deletes the cache key upon request and response respectively.