Possible Duplicate:
Understanding Python decorators
What does a Python decorator do? And where can I see the codes that are running when I add a decorator to a method?
For example, when I add @login_required
at the top of a method, does any code replace that line? How exactly does this line check the user session?
Decorators provide a simple syntax for calling higher-order functions. By definition, a decorator is a function that takes another function and extends the behavior of the latter function without explicitly modifying it.
You'll use a decorator when you need to change the behavior of a function without modifying the function itself. A few good examples are when you want to add logging, test performance, perform caching, verify permissions, and so on. You can also use one when you need to run the same code on multiple functions.
A decorator in Python is any callable Python object that is used to modify a function or a class. A reference to a function "func" or a class "C" is passed to a decorator and the decorator returns a modified function or class.
The goal of the decorator module is to make it easy to define signature-preserving function decorators and decorator factories. It also includes an implementation of multiple dispatch and other niceties (please check the docs).
when I add
@login_required
at the top of a method, does any code replace that line?
Kind of. Adding @login_required
before your view function has the same effect as doing this:
def your_view_function(request):
# Function body
your_view_function = login_required(your_view_function)
For explanations of decorators in Python, see:
So decorator functions accept an original function, and return a function that (probably) calls the original function, but does something else too.
In the case of login_required
, I think it checks the request object passed to view functions to see if the user is authenticated.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With