python的基础以及提高

Python day42_Flask入门

2018-07-05  本文已影响0人  g_s_007

模板代码复用

在模板中,可能会遇到以下情况:

像遇到这种情况,可以使用 JinJa2 模板中的 宏、继承、包含来进行实现

包含

包含(Include):它的功能是将另一个模板整个加载到当前模板中,并直接渲染

上代码:

Python部分:

@app.route('/index4')
def index4():
    return render_template('04_index.html')

04_index.html 部分

<p>这是一个p标签</p>
<p>包含在使用时,如果包含的模板文件不存在时,
    程序会抛出TemplateNotFound异常,
    可以加上 ignore missing 关键字。
    如果包含的模板文件不存在,
    会忽略这条include语句</p>
# include.html 将要加载过来的html文件
{% include 'include.html' ignore missing %}
<p>这是第二个p标签</p>
</body>

include.html部分

<body>
    <ul>
        <li>列表1</li>
        <li>列表2</li>
        <li>列表3</li>
        <li>列表4</li>
    </ul>
</body>

模板继承

模板继承是为了重用模板中的公共内容。一般Web开发中,继承主要使用在网站的顶部菜单、底部。这些内容可以定义在父模板中,子模板直接继承,而不需要重复书写。

实例:

python部分:

@app.route('/index2')
def index2():
    return render_template('02_index.html')


父模板部分:base.html

<p>这是网页顶部内容</p>
# 用block 占位 用center(可以任意起名) 声明这段内容
{% block center %}
    <p>这是父模板的中间内容</p>
{% endblock %}
<p>这是网页底部内容</p>

字模板部分:02_index.html

<body>
# 用extends 声明这个模板继承自哪个html文件
{% extends 'base.html' %}
# 用block重写 center 这段的内容,如果想要父类内容,用super()继承
{% block center %}
    {{ super() }}
    <p>这是子模板的中间部分</p>
{% endblock %}
</body>

宏(macro):

实例:

#在macro.html中定义一个form表单 input函数


{% macro input(label = "",type = "text",name = "",value = "") %}
     <label>{{ label }}</label><input type="{{ type }}" name="{{ name }}" value="{{ value }}"><br/>
{% endmacro %}

#在06_index.html中引入macro.html

{% import 'macro.html' as func %}

#在06_index.html中使用模板

<form>
    {{ func.input('用户名:',name='username') }}
    {{func.input('身份证号:',name='idcard') }}
{{ func.input('密码:',type="password",name='password') }}
    {{ func.input('确认密码:',type="password" ,name="password2") }}
    {{ func.input(type="submit",value="注册") }}
</form>

#python 部分:
    
@app.route('/index6')
def index6():
    return render_template('06_index.html')

模板中特有的变量和函数

web表单

Web 表单是 Web 应用程序的基本功能。

它是HTML页面中负责数据采集的部件。表单有三个部分组成:表单标签、表单域、表单按钮。表单允许用户输入数据,负责HTML页面数据采集,通过表单将用户输入的数据提交给服务器。

在Flask中,为了处理web表单,我们可以使用 Flask-WTF 扩展,它封装了 WTForms,并且它有验证表单数据的功能

08.JPG 09.JPG

使用 Flask-WTF 需要配置参数 SECRET_KEY。

CSRF_ENABLED是为了CSRF(跨站请求伪造)保护。 SECRET_KEY用来生成加密令牌,当CSRF激活的时候,该设置会根据设置的密匙生成加密令牌。

上一篇 下一篇

猜你喜欢

热点阅读