Flask 简明教程

Flask – Application

为了检测 Flask 的安装情况,请在编辑器中输入以下代码作为 Hello.py

In order to test Flask installation, type the following code in the editor as Hello.py

from flask import Flask
app = Flask(__name__)

@app.route('/')
def hello_world():
   return 'Hello World'

if __name__ == '__main__':
   app.run()

在项目中导入 flask 模块是强制性的。Flask 类的对象是我们的 WSGI 应用程序。

Importing flask module in the project is mandatory. An object of Flask class is our WSGI application.

Flask 构造器将 current module (name) 的名称作为参数。

Flask constructor takes the name of current module (name) as argument.

Flask 类的 route() 函数是一个装饰器,它告诉应用程序哪个 URL 应调用关联函数。

The route() function of the Flask class is a decorator, which tells the application which URL should call the associated function.

app.route(rule, options)
  1. The rule parameter represents URL binding with the function.

  2. The options is a list of parameters to be forwarded to the underlying Rule object.

原文中的URL ‘/’ 与函数 hello_world() 关联绑定。因此,当在浏览器中打开网络服务器的主页时,该函数的输出数据将被渲染出来。

In the above example, ‘/’ URL is bound with hello_world() function. Hence, when the home page of web server is opened in browser, the output of this function will be rendered.

最后,Flask 类中的 run() 方法将应用程序运行于本地开发服务器上。

Finally the run() method of Flask class runs the application on the local development server.

app.run(host, port, debug, options)

所有参数都是可选的

All parameters are optional

Sr.No.

Parameters & Description

1

host Hostname to listen on. Defaults to 127.0.0.1 (localhost). Set to ‘0.0.0.0’ to have server available externally

2

port Defaults to 5000

3

debug Defaults to false. If set to true, provides a debug information

4

options To be forwarded to underlying Werkzeug server.

上述 Python 脚本是通过 Python shell 执行的。

The above given Python script is executed from Python shell.

Python Hello.py

Python shell 中显示的信息表明你

A message in Python shell informs you that

* Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)

在浏览器中打开上述 URL (localhost:5000)‘Hello World’ 消息将显示于其上。

Open the above URL (localhost:5000) in the browser. ‘Hello World’ message will be displayed on it.

Debug mode

通过调用 run() 方法启动一个 Flask 应用程序。然而,在应用程序的开发阶段,每次代码有变化时,都应手动重新启动应用程序。为了避免这种情况带来的不便,可以启用 debug support 。之后,如果代码有变化,服务器将自行重新载入。它还将提供一个有用的调试器,用于追踪应用程序中存在的任何错误。

A Flask application is started by calling the run() method. However, while the application is under development, it should be restarted manually for each change in the code. To avoid this inconvenience, enable debug support. The server will then reload itself if the code changes. It will also provide a useful debugger to track the errors if any, in the application.

启用 Debug 模式需要在运行或向 run() 方法传递 debug 参数之前,将 application 对象的 debug 属性设置为 True

The Debug mode is enabled by setting the debug property of the application object to True before running or passing the debug parameter to the run() method.

app.debug = True
app.run()
app.run(debug = True)