Flask是一个Python环境下一款常用的轻量级Web服务程序,他简单、易用、灵活,可以用于简单的网页应用或者api服务。Flask与大多数python库相同的安装过程,使用pip:

pip3 install flask

下面是一个简单的基于flask的show_web.py示例代码:

1
2
3
4
5
6
7
8
from flask import Flask
from flask import render_template
app=Flask(__name__)
@app.route('/')
def index():
   return render_template('index.html')
if __name__ == '__main__':
   app.run()

主要功能是浏览器访问服务器时,返回一个index.html网页。要注意的一点是index.html要保存在show_web.py同级目录的templates文件夹下,所以需要事先创建templates文件夹,并且将index.html文件置于其中。index.html文件只是简单地输出”hello world”,代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<!DOCTYPE html>
<html lang=”en”>
<head>
<meta charset=”UTF-8″>
<title>Title</title>
</head>

<body>
<table class=”table table-bordered”>
<tr>
<th>hello</th>
<th>world</th>
</tr>
</table>
</body>
</html>

如何启动flask呢?主要使用命令:FLASK_APP=show_web.py  flask run,如图1所示。

图1 启动flask

启动以后,打开浏览器,在搜索框中输入:127.0.0.1:5000,即可看到网页效果,如图2所示。

图2 网页显示效果