31π
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.
10π
As others have pointed out, they are indeed equivalent. Two additional things to consider if you wish to take this approach:
-
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.
-
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.
3π
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
.