一、钩子
response参数是视图函数执行之后的返回值
teardown_request在debug模式开启的情况下无法被执行(运行在生产环境中)
二、Flask_Script扩展脚本
pip install Flask_Script
运行测试服务器时,在终端中进行,可以指定ip和port
查看帮助信息
三、模板
flask使用render_template进行模板渲染
向模板传递变量的方式:
1.flask中向模板传递数据时不是字典
2.将字典进行解包,**data,列表中的数据可以在模板中直接相加(str类型实现拼接),django中不能实现
过滤器:
xss攻击(Cross Site Script 跨站脚本攻击):https://blog.csdn.net/xysoul/article/details/45306467
csrf(Cross-site request forgery 跨站请求伪造): https://www.cnblogs.com/hyddd/archive/2009/04/09/1432744.html
可以同时使用多个过滤器,具体的过滤器参看官方文档
自定义过滤器:
1.注册过滤器时,第一个参数时函数名,第二个是定义过滤器的名字
2.直接使用装饰器自定义过滤器,不需要注册
四、模板宏的使用
相似于Python定义函数
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
{% macro input1() %}
<input type="text" value="" size="30">
{% endmacro %}
<h2>input1</h2>
{{ input1() }}
<h2>input2</h2>
{{ input1() }}
{#带有参数的#}
{% macro input2(type, value, size)%}
<input type="{{ type }}" value="{{ value }}" size="{{ size }}">
{% endmacro %}
<h2>input3</h2>
{{ input2("password", "", 20) }}
{#从外部导入#}
<h2>input4</h2>
{% import "macro.html" as func%}
{{ func.input3() }}
</body>
</html>
macro.html代码:
{% macro input3() %}
<input type="text" value="" size="30">
{% endmacro %}
五、模板的继承(和django的一样)
config request url_for等可以直接在模板中使用
六、模板的闪现
一般使用为提示消息,比如用户名或密码错误时
信息闪现过后会从flash中清空
flash中的信息是存在于session中的,所以需要设置密钥
# coding:utf-8
from flask import Flask, render_template, flash
app = Flask(__name__)
a = True
app.secret_key = 'fjnsifwijfdow'
@app.route("/index")
def index():
if a:
flash('hello1')
flash('hello2')
flash('hello3')
global a
a = False
return render_template("index.html")
if __name__ == '__main__':
app.run(debug=True)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
{% for msg in get_flashed_messages() %}
{{ msg }}
{% endfor %}
</body>
</html>