What does the Python decorator do, and where is its code?

Possible duplicate:
Understanding Python Decorators

What does the Python decorator do? And where can I see codes that work when I add a decorator to a method?

For example, when I add @login_required at the top of the method, will any code replace this line? How exactly does this line validate a user session?

+4
source share
3 answers

When I add @login_required at the top of the method, will any code replace this line?

View. Adding @login_required before your view function has the same effect as this:

 def your_view_function(request): # Function body your_view_function = login_required(your_view_function) 

For an explanation of decorators in Python, see:

Thus, decorator functions take the original function and return a function that (possibly) calls the original function, but also does something else.

In the case of login_required , I think it checks the request object passed to view the functions to check if the user is verified.

+4
source

A decorator is a function that wraps another function or class. The function behind the decorator in your case is called login_required . Look in your import to find it.

0
source

A decorator is a function that wraps another function. Say you have a function f (x), and you have a h (x) decorator, the decorator function takes your f (x) function as an argument, and therefore essentially what you will have is a new function h ( f (x)), It does for cleaner code, for example, in your login_required, you do not need to enter the same code to check if the user is registered, and you can wrap the function in the login_required function to call such a function only if the user is logged in. Check out this snippet below.

 def login_required(restricted_func): """Decorator function for restricting access to restricted pages. Redirects a user to login page if user is not authenticated. Args: a function for returning a restricted page Returns: a function """ def permitted_helper(*args, **kwargs): """tests for authentication and then call restricted_func if authenticated""" if is_authenticated(): return restricted_func(*args, **kwargs) else: bottle.redirect("/login") return permitted_helper 
0
source

Source: https://habr.com/ru/post/1435750/


All Articles