tags:

views:

365

answers:

3

Hello!

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):
    ...
+8  A: 

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.

Ayman Hourieh
+1 particularly for note in last sentence.
Carl Meyer
+3  A: 

Yes, they are the same. Decorators are syntactic sugar for wrapping a function in another one. So in either case, you are wrapping login_required around views.add_media.

Johnny G
+3  A: 

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.

Jarret Hardie