本文實例講述了python flask框架模板操作。分享給大家供大家參考,具體如下:
模板
在前面的示例中,視圖函數的主要作用是生成請求的響應,這是最簡單的請求。實際上,視圖函數有兩個作用:處理業務邏輯和返回響應內容。在大型應用中,把業務邏輯和表現內容放在一起,會增加代碼的復雜度和維護成本。本節學到的模板,它的作用即是承擔視圖函數的另一個作用,即返回響應內容。 模板其實是一個包含響應文本的文件,其中用占位符(變量)表示動態部分,告訴模板引擎其具體值需要從使用的數據中獲取。使用真實值替換變量,再返回最終得到的字符串,這個過程稱為“渲染”。flask使用jinja2這個模板引擎來渲染模板。jinja2能識別所有類型的變量,包括{}。 jinja2模板引擎,flask提供的render_template函數封裝了該模板引擎,render_template函數的第一個參數是模板的文件名,后面的參數都是鍵值對,表示模板中變量對應的真實值。
Jinja2官方文檔(http://docs.jinkan.org/docs/jinja2/)
我們先來認識下模板的基本語法:
1
2
3
4
5
6
7
8
|
{ % if user % } {{ user }} { % else % } hello! <ul> { % for index in indexs % } <li> {{ index }} < / li> < / ul> |
通過修改一下前面的示例,來學習下模板的簡單使用:
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 }}結構表示變量,是一種特殊的占位符,告訴模板引擎這個位置的值,從渲染模板時使用的數據中獲取;jinja2除了能識別基本類型的變量,還能識別{};
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()輔助函數,可以使用程序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:
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) |
自定義錯誤頁面:
1
2
3
4
|
from flask import flask,render_template @app .errorhandler( 404 ) def page_not_found(e): return render_template( '404.html' ), 404 |
過濾器:
過濾器的本質就是函數。有時候我們不僅僅只是需要輸出變量的值,我們還需要修改變量的顯示,甚至格式化、運算等等,這就用到了過濾器。 過濾器的使用方式為:變量名 | 過濾器。 過濾器名寫在變量名后面,中間用 | 分隔。如:{{variable | capitalize}},這個過濾器的作用:把變量variable的值的首字母轉換為大寫,其他字母轉換為小寫。 其他常用過濾器如下:
safe:禁用轉義;
1
|
<p>{{ '<em>hello</em>' | safe }}< / p> |
capitalize:把變量值的首字母轉成大寫,其余字母轉小寫;
1
|
<p>{{ 'hello' | capitalize }}< / p> |
lower:把值轉成小寫;
1
|
<p>{{ 'hello' | lower }}< / p> |
upper:把值轉成大寫;
1
|
<p>{{ 'hello' | upper }}< / p> |
title:把值中的每個單詞的首字母都轉成大寫;
1
|
<p>{{ 'hello' | title }}< / p> |
trim:把值的首尾空格去掉;
1
|
<p>{{ ' hello world ' | trim }}< / p> |
reverse:字符串反轉;
1
|
<p>{{ 'olleh' | reverse }}< / p> |
format:格式化輸出;
1
|
<p>{{ '%s is %d' | format ( 'name' , 17 ) }}< / p> |
striptags:渲染之前把值中所有的html標簽都刪掉;
1
|
<p>{{ '<em>hello</em>' | striptags }}< / p> |
語句塊過濾(不常用):
1
2
3
|
{ % filter upper % } this is a flask jinja2 introduction { % endfilter % } |
自定義過濾器:
通過flask應用對象的add_template_filter方法,函數的第一個參數是過濾器函數,第二個參數是過濾器名稱。然后,在模板中就可以使用自定義的過濾器。
1
2
3
|
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標準字段
wtforms常用驗證函數
使用flask-wtf需要配置參數secret_key。
csrf_enabled是為了csrf(跨站請求偽造)保護。 secret_key用來生成加密令牌,當csrf激活的時候,該設置會根據設置的密匙生成加密令牌。
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) |
配置參數:
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 #導入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控制語句
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循環語句
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中的函數,宏的作用就是在模板中重復利用代碼,避免代碼冗余。
jinja2支持宏,還可以導入宏,需要在多處重復使用的模板代碼片段可以寫入單獨的文件,再包含在所有模板中,以避免重復。
定義宏
1
2
3
4
5
6
|
{ % macro input () % } < input type = "text" name = "username" value = "" size = "30" / > { % endmacro % } |
調用宏
1
2
3
4
5
6
7
|
{{ input ()}} #定義帶參數的宏 #調用宏,并傳遞參數 < input type = "password" name = "" value = "name" size = "40" / > |
模板繼承:
模板繼承是為了重用模板中的公共內容。{% block head %}標簽定義的元素可以在衍生模板中修改,extends指令聲明這個模板繼承自哪?父模板中定義的塊在子模板中被重新定義,在子模板中調用父模板的內容可以使用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 對象:
config 對象就是flask的config對象,也就是 app.config 對象。
1
|
{{ config.sqlalchemy_database_uri }} |
request 對象:
就是 flask 中表示當前請求的 request 對象。
1
|
{{ request.url }} |
url_for 方法:
url_for() 會返回傳入的路由函數對應的url,所謂路由函數就是被 app.route() 路由裝飾器裝飾的函數。如果我們定義的路由函數是帶有參數的,則可以將這些參數作為命名參數傳入。
1
2
|
{{ url_for( 'index' ) }} {{ url_for( 'post' , post_id = 1024 ) }} |
get_flashed_messages方法:
返回之前在flask中通過 flash() 傳入的信息列表。把字符串對象表示的消息加入到一個消息隊列中,然后通過調用 get_flashed_messages() 方法取出。
1
2
3
|
{ % for message in get_flashed_messages() % } {{ message }} { % endfor % } |
希望本文所述對大家基于flask框架的python程序設計有所幫助。
原文鏈接:https://blog.csdn.net/xuezhangjun0121/article/details/77824771