本文實(shí)例講述了python flask框架模板操作。分享給大家供大家參考,具體如下:
模板
在前面的示例中,視圖函數(shù)的主要作用是生成請(qǐng)求的響應(yīng),這是最簡(jiǎn)單的請(qǐng)求。實(shí)際上,視圖函數(shù)有兩個(gè)作用:處理業(yè)務(wù)邏輯和返回響應(yīng)內(nèi)容。在大型應(yīng)用中,把業(yè)務(wù)邏輯和表現(xiàn)內(nèi)容放在一起,會(huì)增加代碼的復(fù)雜度和維護(hù)成本。本節(jié)學(xué)到的模板,它的作用即是承擔(dān)視圖函數(shù)的另一個(gè)作用,即返回響應(yīng)內(nèi)容。 模板其實(shí)是一個(gè)包含響應(yīng)文本的文件,其中用占位符(變量)表示動(dòng)態(tài)部分,告訴模板引擎其具體值需要從使用的數(shù)據(jù)中獲取。使用真實(shí)值替換變量,再返回最終得到的字符串,這個(gè)過程稱為“渲染”。flask使用jinja2這個(gè)模板引擎來渲染模板。jinja2能識(shí)別所有類型的變量,包括{}。 jinja2模板引擎,flask提供的render_template函數(shù)封裝了該模板引擎,render_template函數(shù)的第一個(gè)參數(shù)是模板的文件名,后面的參數(shù)都是鍵值對(duì),表示模板中變量對(duì)應(yīng)的真實(shí)值。
Jinja2官方文檔(http://docs.jinkan.org/docs/jinja2/)
我們先來認(rèn)識(shí)下模板的基本語法:
1
2
3
4
5
6
7
8
|
{ % if user % } {{ user }} { % else % } hello! <ul> { % for index in indexs % } <li> {{ index }} < / li> < / ul> |
通過修改一下前面的示例,來學(xué)習(xí)下模板的簡(jiǎn)單使用:
1
2
3
4
5
6
|
@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 }}結(jié)構(gòu)表示變量,是一種特殊的占位符,告訴模板引擎這個(gè)位置的值,從渲染模板時(shí)使用的數(shù)據(jù)中獲取;jinja2除了能識(shí)別基本類型的變量,還能識(shí)別{};
1
2
3
4
5
|
<span>{{mydict[ 'key' ]}}< / span> <br / > <span>{{mylist[ 1 ]}}< / span> <br / > <span>{{mylist[myvariable]}}< / span> |
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
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()輔助函數(shù),可以使用程序url映射中保存的信息生成url;url_for()接收視圖函數(shù)名作為參數(shù),返回對(duì)應(yīng)的url;
如調(diào)用url_for('index',_external=true)返回的是絕對(duì)地址,在下面這個(gè)示例中是http://localhost:5000/。
如調(diào)用url_for('index',name='apple',_external=true)返回的是:
http://localhost:5000/index/apple:
1
2
3
4
5
6
|
@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) |
自定義錯(cuò)誤頁面:
1
2
3
4
|
from flask import flask,render_template @app .errorhandler( 404 ) def page_not_found(e): return render_template( '404.html' ), 404 |
過濾器:
過濾器的本質(zhì)就是函數(shù)。有時(shí)候我們不僅僅只是需要輸出變量的值,我們還需要修改變量的顯示,甚至格式化、運(yùn)算等等,這就用到了過濾器。 過濾器的使用方式為:變量名 | 過濾器。 過濾器名寫在變量名后面,中間用 | 分隔。如:{{variable | capitalize}},這個(gè)過濾器的作用:把變量variable的值的首字母轉(zhuǎn)換為大寫,其他字母轉(zhuǎn)換為小寫。 其他常用過濾器如下:
safe:禁用轉(zhuǎn)義;
1
|
<p>{{ '<em>hello</em>' | safe }}< / p> |
capitalize:把變量值的首字母轉(zhuǎn)成大寫,其余字母轉(zhuǎn)小寫;
1
|
<p>{{ 'hello' | capitalize }}< / p> |
lower:把值轉(zhuǎn)成小寫;
1
|
<p>{{ 'hello' | lower }}< / p> |
upper:把值轉(zhuǎn)成大寫;
1
|
<p>{{ 'hello' | upper }}< / p> |
title:把值中的每個(gè)單詞的首字母都轉(zhuǎn)成大寫;
1
|
<p>{{ 'hello' | title }}< / p> |
trim:把值的首尾空格去掉;
1
|
<p>{{ ' hello world ' | trim }}< / p> |
reverse:字符串反轉(zhuǎn);
1
|
<p>{{ 'olleh' | reverse }}< / p> |
format:格式化輸出;
1
|
<p>{{ '%s is %d' | format ( 'name' , 17 ) }}< / p> |
striptags:渲染之前把值中所有的html標(biāo)簽都刪掉;
1
|
<p>{{ '<em>hello</em>' | striptags }}< / p> |
語句塊過濾(不常用):
1
2
3
|
{ % filter upper % } this is a flask jinja2 introduction { % endfilter % } |
自定義過濾器:
通過flask應(yīng)用對(duì)象的add_template_filter方法,函數(shù)的第一個(gè)參數(shù)是過濾器函數(shù),第二個(gè)參數(shù)是過濾器名稱。然后,在模板中就可以使用自定義的過濾器。
1
2
3
|
def filter_double_sort(ls): return ls[:: 2 ] app.add_template_filter(filter_double_sort, 'double_2' ) |
web表單:
web表單是web應(yīng)用程序的基本功能。
它是html頁面中負(fù)責(zé)數(shù)據(jù)采集的部件。表單有三個(gè)部分組成:表單標(biāo)簽、表單域、表單按鈕。表單允許用戶輸入數(shù)據(jù),負(fù)責(zé)html頁面數(shù)據(jù)采集,通過表單將用戶輸入的數(shù)據(jù)提交給服務(wù)器。
在flask中,為了處理web表單,我們一般使用flask-wtf擴(kuò)展,它封裝了wtforms,并且它有驗(yàn)證表單數(shù)據(jù)的功能。
wtforms支持的html標(biāo)準(zhǔn)字段
wtforms常用驗(yàn)證函數(shù)
使用flask-wtf需要配置參數(shù)secret_key。
csrf_enabled是為了csrf(跨站請(qǐng)求偽造)保護(hù)。 secret_key用來生成加密令牌,當(dāng)csrf激活的時(shí)候,該設(shè)置會(huì)根據(jù)設(shè)置的密匙生成加密令牌。
1
2
3
4
5
|
<form method = 'post' > < input type = "text" name = "username" placeholder = 'username' > < input type = "password" name = "password" placeholder = 'password' > < input type = "submit" > < / form> |
1
2
3
4
5
6
7
8
|
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) |
配置參數(shù):
1
2
3
4
5
6
|
app.config[ 'secret_key' ] = 'silents is gold' {{ form.username.label }} {{ form.username() }} {{ form.password.label }} {{ form.password() }} {{ form.submit() }} |
我們通過登錄頁面來演示表單的使用。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
|
#coding=utf-8 from flask import flask,render_template,\ flash,redirect,url_for,session #導(dǎo)入wtf擴(kuò)展包的form基類 from flask_wtf import form from wtforms.validators import datarequired,equalto from wtforms import stringfield,passwordfield,submitfield app = flask(__name__) #設(shè)置secret_key,防止跨站請(qǐng)求攻擊 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() #定義視圖函數(shù),實(shí)例化自定義的表單類, @app .route( '/' ,methods = [ 'get' , 'post' ]) def forms(): #實(shí)例化表單對(duì)象 form = login() if form.validate_on_submit(): #獲取表單數(shù)據(jù) 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控制語句
1
2
3
4
|
@app .route( '/user' ) def user(): user = 'dongge' return render_template( 'user.html' ,user = user) |
1
2
3
4
5
6
7
8
9
10
11
12
|
<html> <head> { % if user % } <title> hello {{user}} < / title> { % else % } <title> welcome to flask < / title> { % endif % } < / head> <body> <h1>hello world< / h1> < / body> < / html> |
模板中的for循環(huán)語句
1
2
3
4
|
@app .route( '/loop' ) def loop(): fruit = [ 'apple' , 'orange' , 'pear' , 'grape' ] return render_template( 'loop.html' ,fruit = fruit) |
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
<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中的函數(shù),宏的作用就是在模板中重復(fù)利用代碼,避免代碼冗余。
jinja2支持宏,還可以導(dǎo)入宏,需要在多處重復(fù)使用的模板代碼片段可以寫入單獨(dú)的文件,再包含在所有模板中,以避免重復(fù)。
定義宏
1
2
3
4
5
6
|
{ % macro input () % } < input type = "text" name = "username" value = "" size = "30" / > { % endmacro % } |
調(diào)用宏
1
2
3
4
5
6
7
|
{{ input ()}} #定義帶參數(shù)的宏 #調(diào)用宏,并傳遞參數(shù) < input type = "password" name = "" value = "name" size = "40" / > |
模板繼承:
模板繼承是為了重用模板中的公共內(nèi)容。{% block head %}標(biāo)簽定義的元素可以在衍生模板中修改,extends指令聲明這個(gè)模板繼承自哪?父模板中定義的塊在子模板中被重新定義,在子模板中調(diào)用父模板的內(nèi)容可以使用super()。
1
2
3
4
5
6
7
|
{ % extends 'base.html' % } { % block content % } <h1> hi,{{ name }} < / h1> { % for index in fruit % } <p> {{ index }} < / p> { % endfor % } { % endblock % } |
flask中的特殊變量和方法:
在flask中,有一些特殊的變量和方法是可以在模板文件中直接訪問的。
config 對(duì)象:
config 對(duì)象就是flask的config對(duì)象,也就是 app.config 對(duì)象。
1
|
{{ config.sqlalchemy_database_uri }} |
request 對(duì)象:
就是 flask 中表示當(dāng)前請(qǐng)求的 request 對(duì)象。
1
|
{{ request.url }} |
url_for 方法:
url_for() 會(huì)返回傳入的路由函數(shù)對(duì)應(yīng)的url,所謂路由函數(shù)就是被 app.route() 路由裝飾器裝飾的函數(shù)。如果我們定義的路由函數(shù)是帶有參數(shù)的,則可以將這些參數(shù)作為命名參數(shù)傳入。
1
2
|
{{ url_for( 'index' ) }} {{ url_for( 'post' , post_id = 1024 ) }} |
get_flashed_messages方法:
返回之前在flask中通過 flash() 傳入的信息列表。把字符串對(duì)象表示的消息加入到一個(gè)消息隊(duì)列中,然后通過調(diào)用 get_flashed_messages() 方法取出。
1
2
3
|
{ % for message in get_flashed_messages() % } {{ message }} { % endfor % } |
希望本文所述對(duì)大家基于flask框架的python程序設(shè)計(jì)有所幫助。
原文鏈接:https://blog.csdn.net/xuezhangjun0121/article/details/77824771