【03】flask之url_for函数及过滤器使用
一、url_for
一般我们通过一个URL就可以执行到某一个函数。如果反过来,我们知道一个函数,怎么去获得这个URL呢?url_for函数就可以帮我们实现这个功能。url_for()函数接收两个及以上的参数,他接收函数名作为第一个参数,接收对应URL规则的命名参数,如果还出现其他的参数,则会添加到URL的后面作为查询参数。
通过构建URL的方式而选择直接在代码中拼URL的原因有两点:
- 将来如果修改了
URL,但没有修改该URL对应的函数名,就不用到处去替换URL了。 url_for()函数会转义特殊字符和Unocode数据,这些工作都不需要我们自己处理。
#--html--
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>清宝贝花艺</title> </head> <body> <h1>清宝贝花艺</h1> <!-- {#{{用来存放变量}}#}--> <!-- {#{% 用来执行函数或者逻辑代码 %}#}--> <!-- 首页链接调转到指定页面--> <p><a href={{url_for('huashu')}}>鲜花</a></p> <p><a href={{url_for('lvzhi')}}>绿植</a></p> </body> </html>
#--python--
from flask import Flask,render_template,url_for #指定templates路径 app = Flask(__name__,template_folder=r'D:\untitled\flask_env\templates') @app.route('/') #@app.route,是一个装饰器 #@app.route('/')就是将url中的/映射到hello_world这个视图函数上面 def index(): return render_template('index.html') @app.route('/huashu/') #传递多个参数 def huashu(): context={ 'name':'鲜花', 'price':'¥215', 'describe':{ 'variety1':'玫瑰', 'variety2': '百合' } } return render_template('posts/huashu.html',**context) #传递单个参数 @app.route('/li/lvzhi/') def lvzhi(): context={ 'name':'绿植', 'price':'¥215', 'describe':{ 'variety1':'绿萝', 'variety2': '虎皮椒' } } return render_template('posts/lvzhi.html',**context) if __name__ == '__main__': app.run(host='127.0.0.1',port=5000,debug=True)
二、过滤器
过滤器是通过管道符号(|)进行使用的,例如:{{ name|length }},将返回name的长度。过滤器相当于是一个函数,把当前的变量传入到过滤器中,然后过滤器根据自己的功能,再返回相应的值,之后再将结果渲染到页面中
- 过滤器基本使用
abs(value):返回一个数值的绝对值。 例如:-1|abs。default(value,default_value,boolean=false):如果当前变量没有值,则会使用参数中的值来代替。name|default('xiaotuo')——如果name不存在,则会使用xiaotuo来替代。boolean=False默认是在只有这个变量为undefined的时候才会使用default中的值,如果想使用python的形式判断是否为false,则可以传递boolean=true。也可以使用or来替换。escape(value)或e:转义字符,会将<、>等符号转义成HTML中的符号。例如:content|escape或content|e。first(value):返回一个序列的第一个元素。names|first。-
format(value,*arags,**kwargs):格式化字符串。例如以下代码:{{ "%s" - "%s"|format('Hello?',"Foo!") }}将输出:Helloo? - Foo! -
last(value):返回一个序列的最后一个元素。示例:names|last。 -
length(value):返回一个序列或者字典的长度。示例:names|length。 -
join(value,d=u''):将一个序列用d这个参数的值拼接成字符串。 -
safe(value):如果开启了全局转义,那么safe过滤器会将变量关掉转义。示例:content_html|safe。 -
int(value):将值转换为int类型。 -
float(value):将值转换为float类型。 -
lower(value):将字符串转换为小写。 -
upper(value):将字符串转换为小写。 -
replace(value,old,new): 替换将old替换为new的字符串。 -
truncate(value,length=255,killwords=False):截取length长度的字符串。 -
striptags(value):删除字符串中所有的HTML标签,如果出现多个空格,将替换成一个空格。 -
trim:截取字符串前面和后面的空白字符。 -
string(value):将变量转换成字符串。 -
wordcount(s):计算一个长字符串中单词的个数。
- default默认值过滤器
使用方式“{{value|default(默认值),boolean=True}}”,如果key不存在,设置boolean=True表示使用默认值,此外简写模式可以使用or来替代{{default(默认值),boolean=True}}
--html--
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>清宝贝花艺</title> </head> <body> <h1>清宝贝花艺</h1> <p>花店名称:{{shope_name}}</p> <!-- 花店介绍默认值:没有输入任何介绍时,页面显示的内容--> <!-- <p>花店介绍:{{describe|default('小本经营,童叟无欺',boolean=True)}}</p>--> <!-- 花店介绍默认值简写模式--> <p>花店介绍:{{describe or '小本经营,童叟无欺'}}</p> <!-- {#{{用来存放变量}}#}--> <!-- {#{% 用来执行函数或者逻辑代码 %}#}--> <!-- 首页链接调转到指定页面--> <p><a href={{url_for('huashu')}}>鲜花</a></p> <p><a href={{url_for('lvzhi')}}>绿植</a></p> </body> </html>
--python--
from flask import Flask,render_template,url_for #指定templates路径 app = Flask(__name__,template_folder=r'D:\untitled\flask_env\templates') @app.route('/') #@app.route,是一个装饰器 #@app.route('/')就是将url中的/映射到hello_world这个视图函数上面 def index(): context={ 'shope_name':'清宝贝花房', #指定花点介绍 # 'describe':'花点时间,精致生活从这里开启!' # 未指定花点介绍 'describe':None } return render_template('index.html',**context) if __name__ == '__main__': app.run(host='127.0.0.1',port=5000,debug=True)
- 自定义过滤器
过滤器本质上就是一个函数,如果在模板中调用这个过滤器,那么就会将这个变量的值作为第一个参数传递给过滤器这个函数,然后函数的返回值会作为这个过滤器的返回值。需要用到一个装饰器:‘@app.template_filter('自定义过滤器的名称')’
--html--
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>清宝贝花艺</title> </head> <body> <h1>清宝贝花艺</h1> <p>花店名称:{{shope_name|cut}}</p> <!-- 花店介绍默认值:没有输入任何介绍时,页面显示的内容--> <!-- <p>花店介绍:{{describe|default('小本经营,童叟无欺',boolean=True)}}</p>--> <!-- 花店介绍默认值简写模式--> <p>花店介绍:{{describe or '小本经营,童叟无欺'}}</p> <!-- {#{{用来存放变量}}#}--> <!-- {#{% 用来执行函数或者逻辑代码 %}#}--> <!-- 首页链接调转到指定页面--> <p><a href={{url_for('huashu')}}>鲜花</a></p> <p><a href={{url_for('lvzhi')}}>绿植</a></p> </body> </html>
--python--
from flask import Flask, render_template, url_for # 指定templates路径 app = Flask(__name__, template_folder=r'D:\untitled\flask_env\templates') #保存自动加载程序 app.config['TEMPLATES_AUTO_RELOAD']=True @app.route('/') # @app.route,是一个装饰器 # @app.route('/')就是将url中的/映射到hello_world这个视图函数上面 def index(): context = { 'shope_name': '清宝贝花房', # 指定花点介绍 'describe':'花点时间,精致生活从这里开启!' # 未指定花点介绍 # 'describe': None } return render_template('index.html', **context) @app.template_filter('cut') #把过滤加入到服务,传入的参数是过滤器的名字 # 自定义过滤器 def cut(value): value = value.replace("清宝贝", 'Kissbaby') return value if __name__ == '__main__': app.run(host='127.0.0.1', port=5000, debug=True)
浙公网安备 33010602011771号