码农家园

关闭
导航

关于django:Python装饰器decorator 做什么,它的代码在哪里?


decoratordjangologin-requiredpython

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

本问题已经有最佳答案,请猛点这里访问。

Possible Duplicate:
Understanding Python decorators

Python装饰器做什么?当我向一个方法添加一个修饰器时,在哪里可以看到正在运行的代码呢?

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

相关讨论

  • SO:装饰师迷你指南


when I add @login_required at the top of a method, does any code replace that line?

有点。在视图功能之前添加EDOCX1[1]与执行此操作具有相同的效果:

1
2
3
4
def your_view_function(request):
    # Function body

your_view_function = login_required(your_view_function)

有关python中装饰器的说明,请参见:

  • http://www.python.org/dev/peps/pep-0318/
  • http://wiki.python.org/moin/pythondecorators什么是装饰师

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

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


decorator是包装另一个函数的函数。假设您有一个函数f(x),而您有一个装饰器h(x),装饰器函数将您的函数f(x)作为参数,因此实际上您将拥有一个新的函数h(f(x))。它提供了更干净的代码,例如在您的登录中,您不必输入相同的代码来测试用户是否登录,而是可以将函数包装在登录所需的函数中,这样,只有在用户登录时才调用这样的函数。在下面研究这个片段

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
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


实际上,修饰器是一个包装另一个函数或类的函数。在您的例子中,装饰器后面的函数名为login_required。看看你的进口货。

相关讨论

  • 不,它是在函数或类的定义之后任意调用的函数或类。虽然您的版本更简单,并捕获了许多常见的用途,但也有许多有用的装饰器不适合这个定义。


  • python:如何创建功能装饰器链?
  • oop:Python中的元类是什么?
  • python:关键字yield有什么用?
  • Python有三元条件运算符吗?
  • python:if __name__ == "__main__"是什么意思?
  • 将字节转换为字符串?
  • Python有字符串容器吗?子字符串方法?
  • @classmethod和@staticmethod对初学者的意义?
  • 关于python,@property decorator是如何工作的?
  • 关于性能:为什么在python 3中"100000000000000在范围内(100000000000000001)"这么快?

Copyright ©  码农家园 联系:[email protected]