我的问题是一般性问题,但具体来说,我的应用程序是 Django 的 login_required 装饰器。
我很好奇是否有一种方法可以检查 View /函数是否具有特定的装饰器(在本例中为 login_required 装饰器)
我在注销用户后进行重定向,如果他们当前所在的页面具有 login_required 装饰器,我想重定向到主页。到目前为止,我的搜索没有产生任何结果。
最佳答案
构建您自己的 login_required
装饰器并让它将函数标记为已装饰——最好的标记位置可能是在 func_dict
中。
from django.contrib.auth.decorators import login_required as django_l_r
# Here you're defining your own decorator called `login_required`
# it uses Django's built in `login_required` decorator
def login_required(func):
decorated_func = django_l_r(func)
decorated_func.func_dict['login_is_required'] = True
return decorated_func
@login_required # Your decorator
def authenticatedd_view(request):
pass
def unauthenticated_view(request):
pass
现在您可以检查 View 是否被装饰成这样...
# Assume `a_view` is view function
>>> a_view.func_dict.get('login_is_required',False)
如果您对 Python 装饰器感到困惑,请参阅此 SO 问题/答案:How to make a chain of function decorators?
关于python - 检查函数是否有装饰器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5489649/