检查一个函数是否有一个装饰器 [英] Check if a function has a decorator

查看:262
本文介绍了检查一个函数是否有一个装饰器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的问题是一般的,但我的应用程序是Django的login_required装饰器。



如果有办法检查是否有视图,我很好奇/ function有一个特定的装饰器(在这种情况下是login_required装饰器)



我在登录用户后重定向,如果页面,我想重定向到主页面他们当前正在登录_请求的装饰器。

解决方案

构建您自己的 login_required 装饰器,并将其标记为装饰的功能 - 可能是标记它的最佳位置将在 func_dict 中。



django.contrib.auth.decorators导入login_required为django_l_r

#在这里您定义自己的装饰器,名为`login_required`
#它使用Django的内置`login_required`装饰器
def login_required(func):
decorated_func = django_l_r(func)
decorated_func.func_dict ['login_is_required'] = True
return decorated_func

@login_required#你的装饰器
def authenticatedd_view(request):
pass

def unauthenticated_view(request):
pass

现在你可以检查一下视图是否像这样装饰...

 #假设`a_view`是查看函数
& GT;>> a_view.func_dict.get('login_is_required',False)






如果您对Python装饰器感到困惑,请参阅此SO问题/答案:如何使功能装饰器链?


My question is a general one, but specifically my application is the login_required decorator for Django.

I'm curious if there is a way to check if a view/function has a specific decorator (in this case the login_required decorator)

I am redirecting after logging a user out, and I want to redirect to the main page if the page they are currently on has the login_required decorator. My searches have yielded no results so far.

解决方案

Build your own login_required decorator and have it mark the function as decorated--probably the best place to mark it would be in the 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

Now you can check to see if a view was decorated like this...

# Assume `a_view` is view function
>>> a_view.func_dict.get('login_is_required',False)


If you're confused about Python decorators see this SO question/answer: How to make a chain of function decorators?

这篇关于检查一个函数是否有一个装饰器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆