gpt4 book ai didi

如果用户登录,Django 会阻止缓存 View

转载 作者:行者123 更新时间:2023-12-04 23:07:44 24 4
gpt4 key购买 nike

我的访问者从 Varnish 获得页面的缓存版本。
我希望管理员用户始终看到页面的当前版本。
这样,所有更改都是直接可见的。

这样的东西存在吗?
我知道 @never_cache 装饰器。
我正在寻找类似的东西,只有当用户没有登录时。

如果它与 Django-CMS 一起工作,则加分!

最佳答案

我假设您正在使用缓存装饰器。下面的代码是一个装饰器,仅当用户不是管理员时才返回用另一个装饰器(即 cache_page )装饰的 View 。因此管理员将始终获得未修饰(非缓存)页面,而其他用户将获得修饰(因此可能缓存)页面。它适用于所有可能的装饰器(不仅适用于 cache_page )。

def conditional_cache(decorator):
""" Returns decorated view if user is not admin. Un-decorated otherwise """

def _decorator(view):

decorated_view = decorator(view) # This holds the view with cache decorator

def _view(request, *args, **kwargs):

if request.user.is_staff: # If user is staff
return view(request, *args, **kwargs) # view without @cache
else:
return decorated_view(request, *args, **kwargs) # view with @cache

return _view

return _decorator

要使用它,而不是典型的语法:
@cache_page(123)
def testview(request):
(...)

用:
@conditional_cache(decorator=cache_page(123))  # The argument is what you usually do with views, but without the @
def testview(request):
(...)

关于如果用户登录,Django 会阻止缓存 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7315862/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com