Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if a function has a decorator

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.

like image 426
Piper Merriam Avatar asked Mar 30 '11 17:03

Piper Merriam


People also ask

Which function is a decorator?

By definition, a decorator is a function that takes another function and extends the behavior of the latter function without explicitly modifying it.

Is decorator a function in Python?

A decorator in Python is a function that takes another function as its argument, and returns yet another function . Decorators can be extremely useful as they allow the extension of an existing function, without any modification to the original function source code.

Can a Python function have 2 decorators?

Chaining decorators means applying more than one decorator inside a function. Python allows us to implement more than one decorator to a function. It makes decorators useful for reusable building blocks as it accumulates several effects together. It is also known as nested decorators in Python.


1 Answers

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?

like image 82
Chris W. Avatar answered Oct 04 '22 02:10

Chris W.