python - 检查函数是否有装饰器

标签 python django decorator login-required

我的问题是一般性问题,但具体来说,我的应用程序是 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/

相关文章:

python - 在图像中找到矩形,最好使用 skimage

python - SQLAlchemy 中带有子句的递归 CTE

python - 如何将自定义过滤字段添加到Django Rest Framework APIListView

django - 使用 Django 在图像上设置远期到期的最佳方法是什么?

python - 装饰方法

python - 使用opencv python检测二进制图像中的补丁

python - 将字节打印为十六进制

python - 线程启动时出现未处理的异常 python manage.py runserver

c# - 装饰器模式 - 从装饰器访问包装对象中的值

python - 为什么不能跨定义链接 Python 装饰器?