08-1-模板-模板与自定义过滤器
模板与自定义过滤器
使用flask 中的render_template渲染模板
# coding:utf-8 from flask import Flask, render_template app = Flask(__name__) @app.route("/index") def index(): data = { "name": "python", "age": 18, "city_dict": {"city": "sz"}, "num_list": [1, 2, 3, 4, 5], "index_int": 0 } return render_template("index.html", **data) # 解包,不然前端都得以data[][] 去取 # 自定义过滤器 # 1_先定义再注册 def list_step_2(li): """自定义的过滤器""" return li[::2] # 注册过滤器 app.add_template_filter(list_step_2, "li2") # 过滤器函数 注册的名字 # 2_装饰器(过滤器名字) @app.template_filter("li3") def list_step_3(li): """自定义的过滤器""" return li[::3] if __name__ == '__main__': app.run(debug=True)

<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <p>name = {{ name }}</p> <p>age = {{ age }}</p> <p>city_dict: city= {{ city_dict["city"] }}</p> <p>city_dict: city= {{ city_dict.city }}</p> <hr> <h3>列表</h3> <p>num_list: {{ num_list }}</p> <p>num_list[index_int]: {{ num_list[index_int] }}</p> <p>num_list[0] + num_list[1] = {{ num_list[0] + num_list[1] }}</p> <hr/> <h3>字符串拼接</h3> <p>{{ "hello" + " python" }}</p> <p>a{{ " flask world " | trim | upper }}a</p> <hr/> <h3>自定义过滤器</h3> <p>{{ num_list | li2 }}</p> <p>{{ num_list | li3 }}</p> </body> </html>
字符串过滤器
safe:禁用转义; <p>{{ '<em>hello</em>' | safe }}</p> capitalize:把变量值的首字母转成大写,其余字母转小写; <p>{{ 'hello' | capitalize }}</p> lower:把值转成小写; <p>{{ 'HELLO' | lower }}</p> upper:把值转成大写; <p>{{ 'hello' | upper }}</p> title:把值中的每个单词的首字母都转成大写; <p>{{ 'hello' | title }}</p> trim:把值的首尾空格去掉; <p>{{ ' hello world ' | trim }}</p> reverse:字符串反转; <p>{{ 'olleh' | reverse }}</p> format:格式化输出; <p>{{ '%s is %d' | format('name',17) }}</p> striptags:渲染之前把值中所有的HTML标签都删掉; <p>{{ '<em>hello</em>' | striptags }}</p> 支持链式使用过滤器 <p>{{ “ hello world “ | trim | upper }}</p>
列表过滤器
first:取第一个元素 <p>{{ [1,2,3,4,5,6] | first }}</p> last:取最后一个元素 <p>{{ [1,2,3,4,5,6] | last }}</p> length:获取列表长度 <p>{{ [1,2,3,4,5,6] | length }}</p> sum:列表求和 <p>{{ [1,2,3,4,5,6] | sum }}</p> sort:列表排序 <p>{{ [6,2,3,1,5,4] | sort }}</p>
xss 攻击
前端文本款提交时,防止恶意提交脚本,flask为了安全默认做了转义
转义后的文本

<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <form method="post"> <textarea name="text"></textarea> <input type="submit" value="提交"> </form> {{ text }} {#{{ text|safe }}#} {# 表示text是安全的,不用转义#} </body> </html>

# coding:utf-8 from flask import Flask, render_template, request app = Flask(__name__) @app.route("/xss", methods=["GET", "POST"]) def xss(): text = "" if request.method == "POST": text = request.form.get("text") # 直接将接受的文本返回 return render_template("xss.html", text=text) if __name__ == '__main__': app.run(debug=True)
本文来自博客园,作者:元贞,转载请注明原文链接:https://www.cnblogs.com/yuleicoder/articles/10286731.html