Django Caching for Authenticated Users Only

前端 未结 4 1976
走了就别回头了
走了就别回头了 2020-12-24 07:34

Question

In Django, how can create a single cached version of a page (same for all users) that\'s only visible to authenticated users?

Setup

The pag

4条回答
  •  星月不相逢
    2020-12-24 08:24

    The default cache_page decorator accepts a variable called key_prefix. However, it can be passed as a string parameter only. So you can write your own decorator, that will dynamically modify this prefix_key based on the is_authenticated value. Here is an example:

    from django.views.decorators.cache import cache_page
    
    def cache_on_auth(timeout):
        def decorator(view_func):
            @wraps(view_func, assigned=available_attrs(view_func))
            def _wrapped_view(request, *args, **kwargs):
                return cache_page(timeout, key_prefix="_auth_%s_" % request.user.is_authenticated())(view_func)(request, *args, **kwargs)
            return _wrapped_view
        return decorator
    

    and then use it on the view:

    @cache_on_auth(60*60)
    def myview(request)
    

    Then, the generated cache_key will look like:

    cache key:   
    views.decorators.cache.cache_page._auth_False_.GET.123456.123456
    

    if the user is authenticated, and

    cache key:   
    views.decorators.cache.cache_page._auth_True_.GET.789012.789012
    

    if the user is not authenticated.

提交回复
热议问题