【问题标题】:What does a Python decorator do, and where is its code? [duplicate]Python 装饰器是做什么的,它的代码在哪里? [复制]
【发布时间】:2012-09-15 04:26:59
【问题描述】:

可能重复:
Understanding Python decorators

Python 装饰器有什么作用?当我将装饰器添加到方法时,我在哪里可以看到正在运行的代码?

例如,当我在方法顶部添加@login_required 时,是否有任何代码替换该行?这一行究竟是如何检查用户会话的?

【问题讨论】:

标签: python django decorator login-required


【解决方案1】:

当我在方法顶部添加@login_required 时,是否有任何代码替换该行?

有点。在视图函数之前添加@login_required 与这样做的效果相同:

def your_view_function(request):
    # Function body

your_view_function = login_required(your_view_function)

有关 Python 中装饰器的解释,请参见:

所以装饰器函数接受一个原始函数,并返回一个(可能)调用原始函数的函数,但也执行其他操作。

对于login_required,我认为它会检查传递给视图函数的请求对象以查看用户是否经过身份验证。

【讨论】:

    【解决方案2】:

    装饰器实际上是包装另一个函数或类的函数。在您的案例中,装饰器背后的函数名为login_required。查看您的导入以找到它。

    【讨论】:

    • 不,它是在后者定义之后操作函数或类的任意可调用对象。虽然您的版本更简单并包含许多常见用途,但也有许多有用的装饰器不符合该定义。
    【解决方案3】:

    装饰器是包装另一个函数的函数。假设你有一个函数 f(x) 并且你有一个装饰器 h(x),装饰器函数将你的函数 f(x) 作为参数,所以实际上你将拥有一个新函数 h(f(x)) .它使代码更简洁,例如在您的 login_required 中,您不必输入相同的代码来测试用户是否登录,而是可以将函数包装在 login_required 函数中,以便仅在用户已登录。研究下面这个sn-p

    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
    

    【讨论】:

      猜你喜欢
      • 2021-08-13
      • 2016-11-25
      • 1970-01-01
      • 2020-06-29
      • 2015-12-31
      • 1970-01-01
      • 2019-10-02
      • 2014-01-26
      • 2016-03-28
      相关资源
      最近更新 更多