Flask入门

  • Flask作为web框架,它的作用主要是为了开发we应用程序。
  • 开启debug
  • 基本操作
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
from flask import Flask,render_template
import datetime


app = Flask(__name__)

# @app.route('/')
# def hello_world(): # put application's code here
# return 'Hello!'

@app.route("/index")
def index():
return "hello"

# 通过访问路径,获取用户的字符串参数
@app.route("/user/<name>")
def name(name):
return "你好 %s" %name

# 通过访问路径,获取用户的字符串参数 此外还有float类型
@app.route("/user/<int:id>")
def id(id):
return "你好 %d 号的会员" %id

# 路由路径不能重复,用户只能通过唯一路径来访问特点的函数

# 返回给用户网页文件
# @app.route("/")
# def index2():
# return render_template("index.html")

# 向页面传递变量
@app.route("/")
def index2():
time = datetime.date.today() # 普通变量
name = ["张","王","李","赵"] # 列表类型
task = {"任务":"睡觉","时间":"24hours"} # 字典类型
return render_template("index.html", var = time, list = name, task = task)


if __name__ == '__main__':
app.run()
  • 在templates下新建html文件
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
今天是{{ var}},欢迎你!<br/>
今天值班的有:<br/>
{% for data in list %} <!--用大括号和百分号扩起来是控制结构-->
<li>{{ data }}</li>
{% endfor %}

任务:<br/> <!--在页面打印表格,迭代-->
<table border="1">
{% for key,value in task.items() %} #<!--[(key,value),(key,value),(key,value)]-->
<tr>
<td>{{ key }}</td>
<td>{{ value }}</td>
</tr>
{% endfor %}
</table>

</body>
</html>

表单提交

  • app.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
from flask import Flask,render_template,request
import datetime


app = Flask(__name__)

# 表单提交,需要指定methods为post
@app.route("/test/register")
def register():
return render_template("test/register.html")

@app.route("/result",methods=['POST','GET'])
def result():
if request.method == 'POST':
result = request.form

return render_template("test/result.html",result=result)

if __name__ == '__main__':
app.run()
  • register.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>

<form action="{{ url_for('result') }}" method="post">
<p>姓名:<input type="text" name="姓名"></p>
<p>姓名:<input type="text" name="年龄"></p>
<p>姓名:<input type="text" name="性别"></p>
<p>姓名:<input type="text" name="地址"></p>
<p><input type="submit" value="提交"></p>
</form>

</body>
</html>
  • result.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<table border="1">
{% for key,value in result.items() %} #<!--[(key,value),(key,value),(key,value)]-->
<tr>
<th>{{ key }}</th>
<th>{{ value }}</th>
</tr>
{% endfor %}
</table>
</body>
</html>