Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

login_required decorator in django

Tags:

django

Is there any difference in using login_required decorator in urls.py and in views.py ? If I put this line:

url(r'^add/$', login_required(views.add_media), name = 'add_media_action')

into urls.py will I achieve the same effect as decorating add_media function in views.py:

@login_required
def add_media(request):
    ...
like image 829
Konstantin Avatar asked May 20 '09 18:05

Konstantin


2 Answers

In Python, a decorator is a function that takes a function as an argument, and returns a decorated function. The @login_required syntax can be translated to:

def add_media(request):
  ...
add_media = login_required(add_media)

So if you apply the decorator manually (as in your first snippet), it should generate the same effect.

The approach in your first snippet is useful if you want to use both the decorated and undecorated versions of your view.

like image 126
Ayman Hourieh Avatar answered Jan 01 '23 20:01

Ayman Hourieh


As others have pointed out, they are indeed equivalent. Two additional things to consider if you wish to take this approach:

  1. Doing it in the urls.py divorces the login requirement from the place in the code where the thing being decorated is defined. Because of this, you (or other maintainers) may forget that the function has been decorated.

  2. Because you're applying security in the urls file, it is possible for someone to mistakenly add another URL that points to the same function, but forget to wrap the function in login_required, thus leading to a security hole.

Hope that helps.

like image 45
Jarret Hardie Avatar answered Jan 01 '23 20:01

Jarret Hardie