Flask 应用
为了测试 Flask 的安装,在编辑器中输入以下代码并保存为 Hello.py
from flask import Flask
app = Flask(__name__)
@app.route('/')
def hello_world():
return 'Hello World'
if __name__ == '__main__':
app.run()
在项目中导入 flask 模块是必需的。Flask class 的一个对象就是我们的 WSGI 应用。
Flask 构造函数以 当前模块名称 (__name__) 作为参数。
Flask class 的 route() 函数是一个 decorator,它告诉应用哪个 URL 应该调用关联的函数。
app.route(rule, options)
rule 参数表示 URL 与函数的绑定。
options 是一个参数列表,将被转发给底层的 Rule 对象。
在上例中,/ URL 与 hello_world() 函数绑定。因此,当在浏览器中打开 web 服务器的主页时,该函数的输出将被渲染。
最后,Flask class 的 run() 方法在本地开发服务器上运行应用。
app.run(host, port, debug, options)
所有参数均为可选
| Sr.No. | 参数与描述 |
|---|---|
| 1 |
host 监听的主机名。默认为 127.0.0.1 (localhost)。设置为 0.0.0.0 可使服务器外部访问可用 |
| 2 |
port 默认为 5000 |
| 3 |
debug 默认为 false。如果设置为 true,将提供调试信息 |
| 4 |
options 转发给底层的 Werkzeug 服务器。 |
上述 Python 脚本通过 Python shell 执行。
Python Hello.py
Python shell 中的消息会告知你:
* Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
在浏览器中打开上述 URL (localhost:5000)。Hello World 消息将被显示。
调试模式
Flask 应用通过调用 run() 方法启动。然而,在开发过程中,每次代码更改都需要手动重启应用。为了避免这种不便,可以启用 debug 支持。服务器将在代码更改时自动重载。它还会提供有用的调试器来跟踪应用中的任何错误。
Debug 模式通过在运行前将 application 对象的 debug 属性设置为 True,或将 debug 参数传递给 run() 方法来启用。
app.debug = True app.run() app.run(debug = True)