Python Flask框架模板操作实例分析

作者:xuezhangjun 时间:2022-09-21 02:56:23 

本文实例讲述了Python Flask框架模板操作。分享给大家供大家参考,具体如下:

模板

在前面的示例中,视图函数的主要作用是生成请求的响应,这是最简单的请求。实际上,视图函数有两个作用:处理业务逻辑和返回响应内容。在大型应用中,把业务逻辑和表现内容放在一起,会增加代码的复杂度和维护成本。本节学到的模板,它的作用即是承担视图函数的另一个作用,即返回响应内容。 模板其实是一个包含响应文本的文件,其中用占位符(变量)表示动态部分,告诉模板引擎其具体值需要从使用的数据中获取。使用真实值替换变量,再返回最终得到的字符串,这个过程称为“渲染”。Flask使用Jinja2这个模板引擎来渲染模板。Jinja2能识别所有类型的变量,包括{}。 Jinja2模板引擎,Flask提供的render_template函数封装了该模板引擎,render_template函数的第一个参数是模板的文件名,后面的参数都是键值对,表示模板中变量对应的真实值。

Jinja2官方文档(http://docs.jinkan.org/docs/jinja2/)

我们先来认识下模板的基本语法:


{% if user %}
 {{ user }}
{% else %}
 hello!
<ul>
 {% for index in indexs %}
 <li> {{ index }} </li>
</ul>

通过修改一下前面的示例,来学习下模板的简单使用:


@app.route('/')
def hello_itcast():
 return render_template('index.html')
@app.route('/user/<name>')
def hello_user(name):
 return render_template('index.html',name=name)

变量

在模板中{{ variable }}结构表示变量,是一种特殊的占位符,告诉模板引擎这个位置的值,从渲染模板时使用的数据中获取;Jinja2除了能识别基本类型的变量,还能识别{};


<span>{{mydict['key']}}</span>
<br/>
<span>{{mylist[1]}}</span>
<br/>
<span>{{mylist[myvariable]}}</span>


from flask import Flask,render_template
app = Flask(__name__)
@app.route('/')
def index():
 mydict = {'key':'silence is gold'}
 mylist = ['Speech', 'is','silver']
 myintvar = 0
 return render_template('vars.html',
             mydict=mydict,
             mylist=mylist,
             myintvar=myintvar
             )
if __name__ == '__main__':
 app.run(debug=True)

反向路由: Flask提供了url_for()辅助函数,可以使用程序URL映射中保存的信息生成URL;url_for()接收视图函数名作为参数,返回对应的URL;

如调用url_for('index',_external=True)返回的是绝对地址,在下面这个示例中是http://localhost:5000/。

如调用url_for('index',name='apple',_external=True)返回的是:
http://localhost:5000/index/apple:


@app.route('/')
def hello_itcast():
 return render_template('index.html')
@app.route('/user/<name>')
def hello_user(name):
 return url_for('hello_itcast',_external=True)

自定义错误页面:


from flask import Flask,render_template
@app.errorhandler(404)
def page_not_found(e):
 return render_template('404.html'), 404

过滤器:

过滤器的本质就是函数。有时候我们不仅仅只是需要输出变量的值,我们还需要修改变量的显示,甚至格式化、运算等等,这就用到了过滤器。 过滤器的使用方式为:变量名 | 过滤器。 过滤器名写在变量名后面,中间用 | 分隔。如:{{variable | capitalize}},这个过滤器的作用:把变量variable的值的首字母转换为大写,其他字母转换为小写。 其他常用过滤器如下:

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>

语句块过滤(不常用):


{% filter upper %}
 this is a Flask Jinja2 introduction
{% endfilter %}

自定义过滤器:

通过Flask应用对象的add_template_filter方法,函数的第一个参数是过滤器函数,第二个参数是过滤器名称。然后,在模板中就可以使用自定义的过滤器。


def filter_double_sort(ls):
 return ls[::2]
app.add_template_filter(filter_double_sort,'double_2')

Web表单:

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

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

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

WTForms支持的HTML标准字段

Python Flask框架模板操作实例分析

WTForms常用验证函数

Python Flask框架模板操作实例分析

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

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


<form method='post'>
 <input type="text" name="username" placeholder='Username'>
 <input type="password" name="password" placeholder='password'>
 <input type="submit">
</form>


from flask import Flask,render_template
@app.route('/login',methods=['GET','POST'])
def login():
 if request.method == 'POST':
   username = request.form['username']
   password = request.form['password']
   print username,password
 return render_template('login.html',method=request.method)

配置参数:


app.config['SECRET_KEY'] = 'silents is gold'
{{ form.username.label }}
{{ form.username() }}
{{ form.password.label }}
{{ form.password() }}
{{ form.submit() }}

我们通过登录页面来演示表单的使用。


#coding=utf-8
from flask import Flask,render_template,\
 flash,redirect,url_for,session
#导入WTF扩展包的Form基类
from flask_wtf import Form
from wtforms.validators import DataRequired,EqualTo
from wtforms import StringField,PasswordField,SubmitField
app = Flask(__name__)
#设置secret_key,防止跨站请求攻击
app.config['SECRET_KEY'] = '2017'
#自定义表单类,继承Form
class Login(Form):
 us = StringField(validators=[DataRequired()])
 ps = PasswordField(validators=[DataRequired(),EqualTo('ps2','error')])
 ps2 = PasswordField(validators=[DataRequired()])
 submit = SubmitField()
#定义视图函数,实例化自定义的表单类,
@app.route('/',methods=['GET','POST'])
def forms():
 #实例化表单对象
 form = Login()
 if form.validate_on_submit():
 #获取表单数据
   user = form.us.data
   pswd = form.ps.data
   pswd2 = form.ps2.data
   print user,pswd,pswd2
   session['name'] = form.us.data
   flash(u'登陆成功')
   return redirect(url_for('forms'))
 else:
   print form.validate_on_submit()
 return render_template('forms.html',form=form)
if __name__ == "__main__":
 app.run(debug=True)

控制语句

常用的几种控制语句:

模板中的if控制语句


@app.route('/user')
def user():
 user = 'dongGe'
 return render_template('user.html',user=user)


<html>
<head>
  {% if user %}
   <title> hello {{user}} </title>
 {% else %}
    <title> welcome to flask </title>    
 {% endif %}
</head>
<body>
  <h1>hello world</h1>
</body>
</html>

模板中的for循环语句


@app.route('/loop')
def loop():
 fruit = ['apple','orange','pear','grape']
 return render_template('loop.html',fruit=fruit)


<html>
<head>
  {% if user %}
   <title> hello {{user}} </title>
 {% else %}
    <title> welcome to flask </title>    
 {% endif %}
</head>
<body>
  <h1>hello world</h1>
 <ul>
   {% for index in fruit %}
     <li>{{ index }}</li>
   {% endfor %}
 </ul>
</body>
</html>

宏:

类似于python中的函数,宏的作用就是在模板中重复利用代码,避免代码冗余。

Jinja2支持宏,还可以导入宏,需要在多处重复使用的模板代码片段可以写入单独的文件,再包含在所有模板中,以避免重复。

定义宏


{% macro input() %}
<input type="text"
    name="username"
    value=""
    size="30"/>
{% endmacro %}

调用宏


{{ input()}}
#定义带参数的宏
#调用宏,并传递参数
 <input type="password"
     name=""
     value="name"
     size="40"/>

模板继承:

模板继承是为了重用模板中的公共内容。{% block head %}标签定义的元素可以在衍生模板中修改,extends指令声明这个模板继承自哪?父模板中定义的块在子模板中被重新定义,在子模板中调用父模板的内容可以使用super()。


{% extends 'base.html' %}
{% block content %}
 <h1> hi,{{ name }} </h1>
{% for index in fruit %}
 <p> {{ index }} </p>
{% endfor %}
{% endblock %}

Flask中的特殊变量和方法:

在Flask中,有一些特殊的变量和方法是可以在模板文件中直接访问的。

config 对象:

config 对象就是Flask的config对象,也就是 app.config 对象。


{{ config.SQLALCHEMY_DATABASE_URI }}

request 对象:

就是 Flask 中表示当前请求的 request 对象。


{{ request.url }}

url_for 方法:

url_for() 会返回传入的路由函数对应的URL,所谓路由函数就是被 app.route() 路由装饰器装饰的函数。如果我们定义的路由函数是带有参数的,则可以将这些参数作为命名参数传入。


{{ url_for('index') }}
{{ url_for('post', post_id=1024) }}

get_flashed_messages方法:

返回之前在Flask中通过 flash() 传入的信息列表。把字符串对象表示的消息加入到一个消息队列中,然后通过调用 get_flashed_messages() 方法取出。


{% for message in get_flashed_messages() %}
 {{ message }}
{% endfor %}

希望本文所述对大家基于flask框架的Python程序设计有所帮助。

来源:https://blog.csdn.net/xuezhangjun0121/article/details/77824771

标签:Python,Flask框架,模板
0
投稿

猜你喜欢

  • python并发编程之多进程、多线程、异步和协程详解

    2021-12-10 00:20:35
  • 在MySQL中使用更新日志文件

    2009-02-26 16:22:00
  • 破解 屏蔽 防框架代码 top.location != self.location

    2008-11-27 12:59:00
  • 详解Python的Django框架中的templates设置

    2021-12-15 15:16:06
  • ubutu 16.04环境下,PHP与mysql数据库,网页登录验证实例讲解

    2023-11-22 08:18:27
  • php实现通过cookie换肤的方法

    2023-11-23 17:57:07
  • Python的函数的一些高阶特性

    2022-06-04 15:06:28
  • delete from online where datediff

    2009-06-07 18:46:00
  • 极简主义网站设计:寓丰富于简单

    2009-12-07 21:37:00
  • 三种禁用FileSystemObject组件的方法

    2007-09-23 15:52:00
  • QQ影音感念亲恩皮肤,不只是大按钮这么简单

    2009-01-04 14:16:00
  • 带你深入了解SQL Server 2008的独到之处

    2009-01-07 14:20:00
  • Python操作mongodb的9个步骤

    2023-03-11 15:37:53
  • 妙用Dreamweaver MX共享WPS Office文件

    2010-09-05 21:18:00
  • Python中单线程、多线程和多进程的效率对比实验实例

    2022-12-01 09:25:55
  • CSS应用的必要步骤:样式重设

    2008-06-11 13:29:00
  • centos 安装mysql中遇到问题的解决办法

    2010-12-14 15:11:00
  • python循环监控远程端口的方法

    2023-08-07 14:53:22
  • 用javascript实现给出的盒子的序列是否可连为一矩型

    2023-09-09 22:34:02
  • 高性能网站建设指南:性能提升的14个原则

    2011-07-14 16:04:54
  • asp之家 网络编程 m.aspxhome.com