Django视图的Python装饰器:检查UserProfile中的特定设置
我想写一个装饰器,用在我网站的各个视图上,首先检查登录用户的用户资料(UserProfile)是否有一个特定的设置。在我的情况下,就是检查用户的状态(user.get_profile.user_status),这个状态可能是“过期”(expired)或者“活跃”(active)。如果用户的状态是“过期”,我想把他们重定向到一个账单账户更新页面。如果他们的状态是“活跃”,那么就可以继续访问。
我希望这个装饰器的名字像 @must_be_active
或者 @paywall_check
这样。
我之前从来没有写过装饰器。有没有好的建议让我开始呢?
2 个回答
3
其实,如果你不写装饰器,事情会简单很多。
from django.contrib.auth.decorators import user_passes_test
def must_be_active( user ):
if .... whatever ....
def paywall_check( user ):
if .... whatever ....
@user_passes_test(must_be_active)
def my_view(request):
do the work
@user_pass_test(paywall_check)
def another_view(request):
do the work