flask模板层

模板简介

#使用模板的好处
    视图函数只负责业务逻辑和数据处理(业务逻辑方面)
    而模板则取到视图函数的数据结果进行展示(视图展示方面)
    代码结构清晰,耦合度低

#Flask使用的是jinja2模板
  Flask模板对比django,可以加括号,执行函数,并且可以传参

Flask的模板一般在templatesz(自己创建)中,可以修改,app=Flask()点 falsk进去,修改template_folder="templates"


from flask import Flask,render_template

app=Flask(__name__)

@app.route('/')
def index():
    def text():
        return '看看函数有没有触发执行'

    def add(a,b,c):
        return a+b+c
    return render_template('index.html',text=text,add=add)


#下面的是HTML
<body>

{{ text()}}
{{add(1,2,3)}}

</body>
函数可以传参,加括号执行

2、jinja2处理了XSS攻击

#xss攻击:攻击者将恶意脚本代码嵌入到正常用户会访问到的页面中,当正常用户访问该页面时,则可导致嵌入的恶意脚本代码的执行,从而达到恶意攻击用户的目的。

    #比如,将<script>alert(1)</script>,嵌入到模板层,

视图层,模板层处理转义

#from flask import Flask,Markup
#视图层通过Markup
    s2=Markup(s1)


#模板层通过|safe
from flask import Flask,render_template,Markup

app=Flask(__name__)

@app.route('/')
def index():
    s1='<input type="text"value="pdun"/>'
    #s2=Markup(s1)       视图层通过Markup

    return render_template('index.html',text=s2)

if __name__ == '__main__':
    app.run()


------------------------------------------
#可以查HTML特殊符号

<body>
    <!--{{ text|safe}}-->
#如果不使用|safe转义,前台显示的是代码,不是输入框
#因为视图函数往模板层传递的时候,特殊字符被替换了,替换成下面这种形式,
    &lt; input type="text"value="pdun" &gt;
    <br>
    <hr>
  <input type="text"value="pdun"/> #这样可显示输入框,可通过|safe将转义成这样
    <script>alert(1)</script>
</body>
View Code
原文地址:https://www.cnblogs.com/pdun/p/11200986.html