Check if a function has a decorator

為{幸葍}努か 提交于 2019-11-30 02:11:38

问题


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.


回答1:


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?




回答2:


It seems that your situation is as follows: 1. You have pages that are secured and behind a login-required decorator 2. You have pages that are non-secure and can be visited in both a logged-in state and anonymous state.

If I understand your requirements, you want a user to be redirected to Main Page (Assuming this to be the Welcome Page that can be visited in both a logged-in and Anonymous state) when a user logs out.

Why wouldn't you just limit the user's ability to logout from only secure pages, and then set your redirect_url on logout to the welcome screen?



来源:https://stackoverflow.com/questions/5489649/check-if-a-function-has-a-decorator

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!