Module 02 · Web App Deployment using Flask
Reading: Decorators in Flask阅读:Flask 中的装饰器
Estimated time needed: 10 minutes
预计所需时间:10 分钟
Objectives 目标
After reading this page, you will be able to:
阅读本页面后,您将能够:
- Understand what are decorators
理解什么是装饰器 - Understand the two kind of decorators you come across in a python application.
理解在 Python 应用程序中遇到的两类装饰器。 - When and how to use the decorators.
何时以及如何使用装饰器。
What are decorators 什么是装饰器
Decorators help in annotating the methods and tell what a particular method is meant for. These are different from comments. This is used by the interpreter while running the code.
装饰器有助于注解方法,并说明特定方法是用于什么目的的。它们与注释不同。解释器在运行代码时会使用这些装饰器。
Method decorators 方法装饰器
Let’s say we have a python code where we want all the output to be in JSON format. It doesn’t make sense to include code for these in each of the methods as it makes the lines of code redundant. In such cases, we can handle this with a decorator.
让我们假设我们有一个 Python 代码,其中我们希望所有输出都采用JSON格式。在每个方法中包含这些代码是没有意义的,因为这会使代码行变得冗余。在这种情况下,我们可以使用装饰器来处理这个问题。
def jsonify_decorator(function):
def modifyOutput():
return {"output":function()}
return modifyOutput
@jsonify_decorator
def hello():
return 'hello world'
@jsonify_decorator
def add():
num1 = input("Enter a number - ")
num2 = input("Enter another number - ")
return int(num1)+int(num2)
print(hello())
print(add())
The method decorator is also referred to as the wrapper, which wraps the output of the function, that it decorates. In the above code sample, jsonify-decorator is the decorator method. We have added this decorator to hello() and add(). The output of these method calls will now be wrapped and decorated with the jsonify_decorator.
方法装饰器也被称为包装器,它包装了它所装饰的函数的输出。在上面的代码示例中, jsonify-decorator 是装饰器方法。我们将这个装饰器添加到了 hello() 和 add() 上。现在这些方法调用的输出将被包装并使用jsonify_decorator. 进行装饰。
The output of invoking the above python code will be:
调用上述 Python 代码的输出将是:

As you can see the method call has been wrapped with the decorator. The coder has a free will to choose the name of the decorator. Here the name chosen is jsonify_decorator.
如您所见,方法调用已经被装饰器包装。程序员可以自由选择装饰器的名称。在这里,选择的名称是 jsonify_decorator 。
Route Decorators 路由装饰器
You may have observed when you visit any domain you have the root and then have other end-points you can access. See the examples below.
当你访问任何域名时,你可能已经注意到有根目录,然后有其他可以访问的端点。以下是一些示例。
https://mydomain.com/
https://mydomain.com/about
https://mydomain.com/register
We will look at creating these endpoints when we will create a web application using the flask module in the labs that will follow.
在接下来的实验室中,我们将使用flask 模块创建一个 Web 应用程序时,我们将创建这些端点。
But to define these endpoints in Python we use what we call Route Decorators.
但在 Python 中定义这些端点时,我们使用我们称之为路由装饰器的东西。

@app.route(“/“) is a Python decorator that Flask provides to assign URLs in our app to functions easily. You can easily tell that the decorator is telling our @app that whenever a user visits our application’s domain, in our case, execute the home() function.
@app.route(“/“) 是一个 Python 装饰器,由 Fl 提供,用于轻松地将 URL 分配到我们的应用程序中的函数。您可以轻松地看出,装饰器正在告诉我们的 @app,每当用户访问我们的应用程序域名时,在我们的情况下,执行 home() 函数。
We can handle multiple routes with a single function by just stacking additional route decorators above the method which should be invoked when the route is called. The following is a valid example of serving the same “Hello World!” message for 3 separate routes:
我们可以通过在应该被调用的方法上堆叠额外的路由装饰器来使用单个函数处理多个路由。以下是一个有效的示例,用于为 3 个不同的路由提供相同的“Hello World!”消息:
@app.route("/")
@app.route("/home")
@app.route("/index")
def home():
return "Hello World!"
The route decorators also take method as a second parameter, which can be set to the type of HTTP methods, the route will support. We will learn about this in the later sections.
路由装饰器还接受 method 作为第二个参数,该参数可以设置为路由将支持的各种 HTTP 方法。我们将在后面的章节中学习这一点。
The route decorator can also be more specific. For example, to get the details of a user whose userId is U0001, you may go to
路由装饰器也可以更具体。例如,要获取 userId 为 U0001 的用户的详细信息,您可以前往
http://mydomain.com/userdetails/U0001. It doesn’t make sense to define a different route for each user you may be dealing with. In such cases, we define the route like this.
http://mydomain.com/userdetails/U0001 . 对每个你可能会处理的用户定义不同的路由是没有意义的。在这种情况下,我们这样定义路由。
@app.route("/userdetails/<userid>")
def getUserDetails(userid):
return "User Details for "+userid
Congratulations! You have just learned about decorators in python. Go ahead and use it in your code.
恭喜!你已经学习了 Python 中的装饰器。继续在你的代码中使用它。