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

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?


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:

  • http://www.python.org/dev/peps/pep-0318/
  • http://wiki.python.org/moin/PythonDecorators#What_is_a_Decorator
  • 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.


    A decorator is in effect a function wrapping another function or class. The function behind the decorator in your case is named login_required . Look in your imports to find it.


    A decorator is a function which wraps another function. Say you have a function f(x) and you have a decorator h(x), the decorator function takes as argument your function f(x) and so in effect what you will have is a new function h(f(x)). It makes for cleaner code as for instance in your login_required, you do not have to put in the same code to test if a user is logged in rather you can wrap the function in a login_required function so that such a function is called only if the user is logged in. Study 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
    
    链接地址: http://www.djcxy.com/p/23802.html

    上一篇: Python装饰器,嵌套函数

    下一篇: Python装饰器是做什么的,它的代码在哪里?