flask學(xué)習(xí)筆記4-jinja2模版

1. 模版基本使用語(yǔ)法

基本傳鍵值對(duì)的方式不做介紹,直接上一個(gè)傳字典的demo:

字典的值可以是任何python的基本類型(字符串、數(shù)值、list、dict)

flask模版demo
模版html文件


2. 過(guò)濾器

2.1 字符串filter

safe:禁用轉(zhuǎn)義;處理xss攻擊

????{{ 'hello' | safe }}

capitalize:把變量值的首字母轉(zhuǎn)成大寫,其余字母轉(zhuǎn)小寫;

????{{ 'hello' | capitalize }}

lower:把值轉(zhuǎn)成小寫;

????{{ 'HELLO' | lower }}

upper:把值轉(zhuǎn)成大寫;

????{{ 'hello' | upper }}

title:把值中的每個(gè)單詞的首字母都轉(zhuǎn)成大寫;

????{{ 'hello' | title }}

trim:把值的首尾空格去掉;

????{{ ' hello world ' | trim }}

reverse:字符串反轉(zhuǎn);

????{{ 'olleh' | reverse }}

format:格式化輸出;

????{{ '%s is %d' | format('name',17) }}

striptags:渲染之前把值中所有的HTML標(biāo)簽都刪掉;

????{{ 'hello' | striptags }}


2.2 鏈?zhǔn)竭^(guò)濾

????<p>{{ “hello world? “ | trim | upper }}</p>


2.3 列表過(guò)濾器

first:取第一個(gè)元素

????{{ [1,2,3,4,5,6] | first }}

last:取最后一個(gè)元素

????{{ [1,2,3,4,5,6] | last }}

length:獲取列表長(zhǎng)度

????{{ [1,2,3,4,5,6] | length }}

sum:列表求和

????{{ [1,2,3,4,5,6] | sum }}

sort:列表排序

????{{[6,2,3,1,5,4] | sort }}


2.4 自定義過(guò)濾器

自定義的過(guò)濾器名稱如果和內(nèi)置的過(guò)濾器重名,會(huì)覆蓋內(nèi)置的過(guò)濾器。

方式一:通過(guò)add_template_filter (過(guò)濾器函數(shù),模板中使用的過(guò)濾器名字)

def filter_double_sort(ls):

???return ls[::2]

app.add_template_filter(filter_double_sort,'double_2')

方式二:通過(guò)裝飾器? app.template_filter (模板中使用的裝飾器名字)

@app.template_filter('db3')

def filter_double_sort(ls):

???return ls[::-3]


3. 表單

使用Flask-WTF表單擴(kuò)展,可以幫助進(jìn)行CSRF驗(yàn)證,幫助我們快速定義表單模板,而且可以幫助我們?cè)谝晥D中驗(yàn)證表的數(shù)據(jù)

pipinstall Flask-WTF

3.1 不使用Flask-WTF擴(kuò)展

模版文件:

<form method='post'>

? ? <input type="text"

name="username" placeholder='Username'>

? ??<input type="password"

name="password" placeholder='password'>

? ??<input type="submit">

</form>

Flask視圖程序:

from flask importFlask,render_template,request


@app.route('/login',methods=['GET','POST'])

def login():

???if request.method == 'POST':

???????username = request.form['username']

???????password = request.form['password']

???????print username,password

??? ???????? return“success”

???????? else:

?????????????????? returnrender_template(“l(fā)ogin.html”)


3.2 使用Flask-WTF擴(kuò)展

需要設(shè)置 SECRET_KEY 的配置參數(shù)

模板頁(yè):

<form method="post">

???????#設(shè)置csrf_token

???????{{ form.csrf_token() }}

? ? ? ?{{ form.us.label }}

????????<p>{{ form.us }}</p>

???????{{ form.ps.label }}

????????<p>{{ form.ps }}</p>

???????{{ form.ps2.label }}

????????<p>{{ form.ps2 }}</p>

????????<p>{{ form.submit() }}</p>

???????{% for x in get_flashed_messages() %}

???????????{{ x }}

???????{% endfor %}

</form>

Flask視圖程序:

rf#coding=utf-8

from flask import Flask,render_template,redirect,url_for,session,request,flash

#導(dǎo)入wtf擴(kuò)展的表單類

from flask_wtf import FlaskForm

#導(dǎo)入自定義表單需要的字段

from wtforms importSubmitField,StringField,PasswordField

#導(dǎo)入wtf擴(kuò)展提供的表單驗(yàn)證器

from wtforms.validators importDataRequired,EqualTo


app = Flask(__name__)

app.config['SECRET_KEY']='1'


#自定義表單類,文本字段、密碼字段、提交按鈕

class Login(Flask Form):

???us = StringField(label=u'用戶:',validators=[DataRequired()])

???ps = PasswordField(label=u'密碼',validators=[DataRequired(),EqualTo('ps2','err')])

???ps2 = PasswordField(label=u'確認(rèn)密碼',validators=[DataRequired()])

???submit = SubmitField(u'提交')


#定義根路由視圖函數(shù),生成表單對(duì)象,獲取表單數(shù)據(jù),進(jìn)行表單數(shù)據(jù)驗(yàn)證

@app.route('/',methods=['GET','POST'])

def index():

???form = Login()

???if form.validate_on_submit():

???????name = form.us.data

???????pswd = form.ps.data

???????pswd2 = form.ps2.data

???????print name,pswd,pswd2

???????return redirect(url_for('login'))

???else:

???????if request.method=='POST':

flash(u'信息有誤,請(qǐng)重新輸入!')


???return render_template('index.html',form=form)

if __name__ == '__main__':

???app.run(debug=True)

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

友情鏈接更多精彩內(nèi)容