Suor / django-cacheops

A slick ORM cache with automatic granular event-driven invalidation.
BSD 3-Clause "New" or "Revised" License
2.12k stars 227 forks source link

cache views that have different content according to user privileges #397

Closed fcoppey closed 3 years ago

fcoppey commented 3 years ago

is it possible to do that?

in my html template I have some parts that are admin related therefore I test if user is staff and if it's the case I display extra content. thing is when caching this view I don't know how to cache a version for admins and a version for normal users. any idea?

thanks a lot

Suor commented 3 years ago

You can use a nested function to build up a key, which includes that:

from cacheops import cached_view_as

def your_view(request, ...):
    @cached_view_as(queryset, extra=request.user.is_staff)
    def _your_view(request, ...):
        # ... do the stuff
        return render(...)

    return _your_view(request, ...)

You may also look at articles_block() example in README.

fcoppey commented 3 years ago

Ok thanks. How would it work for class based ListView or DetailView?

On 22 Apr 2021, at 06:49, Alexander Schepanovski @.**@.>> wrote:

You can use a nested function to build up a key, which includes that:

from cacheops import cached_view_as

def your_view(request, ...): @cached_view_as(queryset, extra=request.user.is_staff) def _your_view(request, ...):

... do the stuff

    return render(...)

return _your_view(request, ...)

You may also look at articles_block() example in README.

— You are receiving this because you authored the thread. Reply to this email directly, view it on GitHubhttps://github.com/Suor/django-cacheops/issues/397#issuecomment-824535397, or unsubscribehttps://github.com/notifications/unsubscribe-auth/AKFMG6PDZQACCGVMJ7PAP6LTJ6TEVANCNFSM43LLIGUA.

Suor commented 3 years ago

How do you use them currently?

fcoppey commented 3 years ago

I have followed recommendation :

class NewsIndex(ListView): model = News

news_index = cached_view_as(News)(NewsIndex.as_view())

My question is how can I condition this view to the user privileges?

On 22 Apr 2021, at 09:51, Alexander Schepanovski @.**@.>> wrote:

How do you use them currently?

— You are receiving this because you authored the thread. Reply to this email directly, view it on GitHubhttps://github.com/Suor/django-cacheops/issues/397#issuecomment-824623754, or unsubscribehttps://github.com/notifications/unsubscribe-auth/AKFMG6IHKYGH6FMCLVTGDK3TJ7IQFANCNFSM43LLIGUA.

Suor commented 3 years ago

Added an ability to use callable as extra in latest master:

cached_view_as(News, extra=lambda req: req.user.is_staff)

You can try that.