数据可视化-Flask学习笔记2

前面基本了解了一下Flask框架,现在学习一下基础语法

MVC架构

image-20210515173849937

这就是传说中的MVC:Model-View-Controller,中文名“模型-视图-控制器”。
Python处理URL的函数就是C:Controller,Controller负责业务逻辑,比如检查用户名是否存在,取出用户信息等等;
包含变量的模板就是V:View,View负责显示逻辑,通过简单地替换一些变量,View最终输出的就是用户看到的HTML。
MVC中的Model在哪?Model是用来传给View的,这样View在替换变量的时候,就可以从Model中取出相应的数据。
——摘自第四篇参考文章

模板

前面说过static文件夹存放一些静态文件,比如css、js等,templates文件夹存放模板,模板就是HTML文件,只不过里面除了基本的HTML之外,还有一些需要Jinja2渲染的变量等等。

路由

路由就是根据用户访问的路径匹配相应的视图函数

路由的本质是URL绑定,装饰器@app.route()把一个函数绑定在一个URL上

基础路由

这就是一个最简单的路由,通过访问根路径http://127.0.0.1:5000/,返回html相关内容(这里就是Hello World!)

1
2
3
@app.route('/') #路由解析,通过用户访问的路径匹配相应的函数
def hello_world():
return 'Hello World!'

结果图:

image-20210515184502472

Werkzeug(请求路由转发)和Jinja2(模板渲染)就是这个意思

1
2
3
@app.route("/index") #这两行代码是Werkzeug干的,帮助判断哪个路径执行哪个函数
def hello():
return "你好" #返回是jinja2实现的

结果图:

image-20210515184528285

接受动态参数的路由

动态参数用<>包裹,通过访问路径,获取动态的参数

1
2
3
4
5
6
7
8
9
#通过访问路径,获取用户的字符串参数
@app.route("/user/<name>")
def welcome(name):
return "你好,{}".format(name)

#通过访问路径,获取用户的整形参数。此外,还有float类型
@app.route("/user/<int:id>")
def welcome2(id):
return "你好,{}号的会员".format(id)

要注意,路由路径不能重复,用户通过唯一路径访问特定的函数

结果图:

image-20210515184232321

image-20210515184310924

渲染

通过render_template()函数渲染网页文件

1
2
3
4
5
返回给用户渲染后的网页文件
@app.route("/")
def index():
return render_template("index.html")
#jinja2会帮你检查html里有没有什么jinja2能识别的符号,如果有就把它转成html

index.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
26
27
28
29
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
今天是{{ var }}欢迎光临。<br/>
今天值班的有:<br/>
{% for data in list %} <!--{# {% %} #}用大括号和百分号括起来是控制语句,for循环和if等等-->
<li> {{ data }} </li>
{% endfor %}

任务:<br/> <!--了解一下如何在页面打印表格,以及如何迭代-->
<table border="1">
{% for key,value in task.items() %}
<!--迭代器,把字典转换成了这种格式的列表[(key,value),(key,value),(key,value)],字典的items()方法以列表返回可遍历的(键, 值) 元组数组。-->
<tr>
<td>{{ key }}</td>
<td>{{ value }}</td>
</tr>
{% endfor %}
</table>

</body>
</html>

<!--{# #}是Jinja2注释
既然模板能够复用,那么它里面的内容确定不可能写死对吧,若是写成固定值那每一个页面的内容都成了同样的了,因此模板就须要写成变量的形式,经过给变量传值来修改模板对应的内容。在flask中,变量的写法是{# {{ 变量值 }} #}这种两个大括号(又叫大胡须)的形式。在模板文件中使用变量的语法是双大括号{# {{ }} #},将变量写在两个大括号里,接收服务器传过来的变量,然后通过Jinja2来解析这个变量,这种语法在前端叫胡子语法,两个大括号又叫大胡须-->

render_template()里用逗号分隔写变量,向页面传递变量:

1
2
3
4
5
6
7
8
9
#向页面传递一个变量
@app.route("/")
def index2():
time=datetime.date.today() #普通变量
name=["小张","小王","小赵"] #列表类型
task={"任务":"打扫卫生","时间":"3小时"} #字典类型
return render_template("index.html",var=time,list=name,task=task)
# 前者(var、list、task)是网页渲染里用的变量,后者(time、name、task)是函数里定义的变量。常用的写法是最后那种(task=task),前面写法只是为了区分清楚谁是谁
#render_template的功能是先引入index.html,同时根据后面传入的参数,对html进行修改渲染。

结果图:

image-20210515184151838

反向路由

反向路由顾名思义就是通过视图函数表现出url地址,本质是根据函数名反向生成url,使用函数url_for()来针对一个特定的函数构建一个URL(根据函数匹配路径)

路由也可以修改当前的http方法来打开,flask路由默认的http方法是GET,下面使用methods=['POST','GET']将http方法改为POST与GET。

1
2
3
4
5
6
7
8
9
10
11
#表单提交
@app.route("/test/register") #路径
def register():
return render_template("test/register.html") #templates文件夹下的文件结构

#接受表单提交的路由,需要指定methods为post
@app.route("/test/result",methods=['POST','GET']) #methods不写,默认是get
def result():
if request.method=="POST":
result=request.form #获得表单字典,name值是键,输入的内容是值
return render_template("test/result.html",result=result)

register.html:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<!--url_for("result")里的result指向app.py中的result()函数
反向路由,本质是根据函数名反向生成url,使用函数url_for()来针对一个特定的函数构建一个URL
根据函数匹配路径
不要写死url,因为可能换端口换域名,用url_for可以帮你动态地找到你所需要的路径
-->
<form action="{{ url_for('result') }}" method="post">
<p>姓名:<input type="text" name="name"></p>
<p>年龄:<input type="text" name="age"></p>
<p>性别:<input type="text" name="sex"></p>
<p>地址:<input type="text" name="address"></p>
<input type="submit" value="提交">
</form>
</body>
</html>

result.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>
<table border="1">
{% for key,value in result.items() %}
<!--迭代器,把字典转换成了这种格式的列表[(key,value),(key,value),(key,value)],字典的items()方法以列表返回可遍历的(键, 值) 元组数组。-->
<tr>
<th>{{ key }}</th>
<td>{{ value }}</td>
</tr>
{% endfor %}
</table>
</body>
</html>

结果图:

image-20210515184022757

image-20210515184046531

完整笔记

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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
# -*- coding:utf-8 -*-
from flask import Flask,render_template,request
#导入Flask类,render_template模板引擎,.request中包含了前端发送过来的所有数据 ,请求的 request 对象中保存了一次HTTP请求的一切信息。
#模板的位置放在templates文件夹下面,一般是html文件.
#模板简单理解就是把前后的代码分离让开发者高效的开发,让代码结构清晰,耦合度降低
import datetime
app = Flask(__name__) #初始化了一个对象,导入了flask框架

# 这就是传说中的MVC:Model-View-Controller,中文名“模型-视图-控制器”。
# Python处理URL的函数就是C:Controller,Controller负责业务逻辑,比如检查用户名是否存在,取出用户信息等等;
# 包含变量{{ name }}的模板就是V:View,View负责显示逻辑,通过简单地替换一些变量,View最终输出的就是用户看到的HTML。
# MVC中的Model在哪?Model是用来传给View的,这样View在替换变量的时候,就可以从Model中取出相应的数据。


# @app.route('/') #路由解析,通过用户访问的路径匹配相应的函数
# def hello_world():
# return 'Hello World!'


@app.route("/index") #这两行代码是Werkzeug干的,帮助判断哪个路径执行哪个函数
def hello():
return "你好" #返回是jinja2实现的

#动态参数用<>包裹,通过访问路径,获取用户的字符串参数
@app.route("/user/<name>")
def welcome(name):
return "你好,{}".format(name)

#通过访问路径,获取用户的整形参数。此外,还有float类型
@app.route("/user/<int:id>")
def welcome2(id):
return "你好,{}号的会员".format(id)

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


# 返回给用户渲染后的网页文件
# @app.route("/")
# def index():
# return render_template("index.html")
# #jinja2会帮你检查html里有没有什么jinja2能识别的符号,如果有就把它转成html

#向页面传递一个变量
@app.route("/")
def index2():
time=datetime.date.today() #普通变量
name=["小张","小王","小赵"] #列表类型
task={"任务":"打扫卫生","时间":"3小时"} #字典类型
return render_template("index.html",var=time,list=name,task=task)
# 前者(var、list、task)是网页渲染用的,后者(time、name、task)是函数里定义的。
# 常用的写法是最后那种(task=task),前面写法只是为了区分清楚谁是谁

#render_template的功能是先引入index.html,同时根据后面传入的参数,对html进行修改渲染。

#表单提交
@app.route("/test/register") #路径
def register():
return render_template("test/register.html") #templates文件夹下的文件结构

#接受表单提交的路由,需要指定methods为post
@app.route("/test/result",methods=['POST','GET']) #methods不写,默认是get
def result():
if request.method=="POST":
result=request.form #获得表单字典,name值是键,输入的内容是值
return render_template("test/result.html",result=result)

if __name__ == '__main__':
app.run() #Flask应用程序实例的run方法启动WEB服务器

感觉笔记写的比较乱,博客写的也很乱,虽然自己看得懂Orz,表述能力还有待提高!

参考

https://www.bilibili.com/video/BV12E411A7ZQ?t=322&p=31

https://www.jb51.net/article/167477.htm

https://m9u.cn/post/flask/flask_render_template/

https://blog.csdn.net/GeekLeee/article/details/52505605

https://blog.csdn.net/weiyongxuan/article/details/48544629

https://blog.csdn.net/wei18791957243/article/details/85123870

https://www.shangmayuan.com/a/b37f40a8816041f8a106f22a.html

  • Copyright: Copyright is owned by the author. For commercial reprints, please contact the author for authorization. For non-commercial reprints, please indicate the source.

扫一扫,分享到微信

微信分享二维码
  • Copyrights © 2020-2021 Blog of Tianze

请我喝杯咖啡吧~

支付宝
微信