Python Flask框架模板操作實(shí)例分析
本文實(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è)過(guò)程稱為“渲染”。Flask使用Jinja2這個(gè)模板引擎來(lái)渲染模板。Jinja2能識(shí)別所有類型的變量,包括{}。 Jinja2模板引擎,F(xiàn)lask提供的render_template函數(shù)封裝了該模板引擎,render_template函數(shù)的第一個(gè)參數(shù)是模板的文件名,后面的參數(shù)都是鍵值對(duì),表示模板中變量對(duì)應(yīng)的真實(shí)值。
Jinja2官方文檔(http://docs.jinkan.org/docs/jinja2/)
我們先來(lái)認(rèn)識(shí)下模板的基本語(yǔ)法:
{% if user %} {{ user }} {% else %} hello! <ul> {% for index in indexs %} <li> {{ index }} </li> </ul>
通過(guò)修改一下前面的示例,來(lái)學(xué)習(xí)下模板的簡(jiǎn)單使用:
@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í)別{};
<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()輔助函數(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:
@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ò)誤頁(yè)面:
from flask import Flask,render_template @app.errorhandler(404) def page_not_found(e): return render_template('404.html'), 404
過(guò)濾器:
過(guò)濾器的本質(zhì)就是函數(shù)。有時(shí)候我們不僅僅只是需要輸出變量的值,我們還需要修改變量的顯示,甚至格式化、運(yùn)算等等,這就用到了過(guò)濾器。 過(guò)濾器的使用方式為:變量名 | 過(guò)濾器。 過(guò)濾器名寫在變量名后面,中間用 | 分隔。如:{{variable | capitalize}},這個(gè)過(guò)濾器的作用:把變量variable的值的首字母轉(zhuǎn)換為大寫,其他字母轉(zhuǎn)換為小寫。 其他常用過(guò)濾器如下:
safe:禁用轉(zhuǎn)義;
<p>{{ '<em>hello</em>' | safe }}</p>
capitalize:把變量值的首字母轉(zhuǎn)成大寫,其余字母轉(zhuǎn)小寫;
<p>{{ 'hello' | capitalize }}</p>
lower:把值轉(zhuǎn)成小寫;
<p>{{ 'HELLO' | lower }}</p>
upper:把值轉(zhuǎn)成大寫;
<p>{{ 'hello' | upper }}</p>
title:把值中的每個(gè)單詞的首字母都轉(zhuǎn)成大寫;
<p>{{ 'hello' | title }}</p>
trim:把值的首尾空格去掉;
<p>{{ ' hello world ' | trim }}</p>
reverse:字符串反轉(zhuǎn);
<p>{{ 'olleh' | reverse }}</p>
format:格式化輸出;
<p>{{ '%s is %d' | format('name',17) }}</p>
striptags:渲染之前把值中所有的HTML標(biāo)簽都刪掉;
<p>{{ '<em>hello</em>' | striptags }}</p>
語(yǔ)句塊過(guò)濾(不常用):
{% filter upper %} this is a Flask Jinja2 introduction {% endfilter %}
自定義過(guò)濾器:
通過(guò)Flask應(yīng)用對(duì)象的add_template_filter方法,函數(shù)的第一個(gè)參數(shù)是過(guò)濾器函數(shù),第二個(gè)參數(shù)是過(guò)濾器名稱。然后,在模板中就可以使用自定義的過(guò)濾器。
def filter_double_sort(ls): return ls[::2] app.add_template_filter(filter_double_sort,'double_2')
Web表單:
web表單是web應(yīng)用程序的基本功能。
它是HTML頁(yè)面中負(fù)責(zé)數(shù)據(jù)采集的部件。表單有三個(gè)部分組成:表單標(biāo)簽、表單域、表單按鈕。表單允許用戶輸入數(shù)據(jù),負(fù)責(zé)HTML頁(yè)面數(shù)據(jù)采集,通過(guò)表單將用戶輸入的數(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用來(lái)生成加密令牌,當(dāng)CSRF激活的時(shí)候,該設(shè)置會(huì)根據(jù)設(shè)置的密匙生成加密令牌。
<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)
配置參數(shù):
app.config['SECRET_KEY'] = 'silents is gold' {{ form.username.label }} {{ form.username() }} {{ form.password.label }} {{ form.password() }} {{ form.submit() }}
我們通過(guò)登錄頁(yè)面來(lái)演示表單的使用。
#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)
控制語(yǔ)句
常用的幾種控制語(yǔ)句:
模板中的if控制語(yǔ)句
@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循環(huán)語(yǔ)句
@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中的函數(shù),宏的作用就是在模板中重復(fù)利用代碼,避免代碼冗余。
Jinja2支持宏,還可以導(dǎo)入宏,需要在多處重復(fù)使用的模板代碼片段可以寫入單獨(dú)的文件,再包含在所有模板中,以避免重復(fù)。
定義宏
{% macro input() %} <input type="text" name="username" value="" size="30"/> {% endmacro %}
調(diào)用宏
{{ 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()。
{% extends 'base.html' %} {% block content %} <h1> hi,{{ name }} </h1> {% for index in fruit %} <p> {{ index }} </p> {% endfor %} {% endblock %}
Flask中的特殊變量和方法:
在Flask中,有一些特殊的變量和方法是可以在模板文件中直接訪問(wèn)的。
config 對(duì)象:
config 對(duì)象就是Flask的config對(duì)象,也就是 app.config 對(duì)象。
{{ config.SQLALCHEMY_DATABASE_URI }}
request 對(duì)象:
就是 Flask 中表示當(dāng)前請(qǐng)求的 request 對(duì)象。
{{ request.url }}
url_for 方法:
url_for() 會(huì)返回傳入的路由函數(shù)對(duì)應(yīng)的URL,所謂路由函數(shù)就是被 app.route() 路由裝飾器裝飾的函數(shù)。如果我們定義的路由函數(shù)是帶有參數(shù)的,則可以將這些參數(shù)作為命名參數(shù)傳入。
{{ url_for('index') }} {{ url_for('post', post_id=1024) }}
get_flashed_messages方法:
返回之前在Flask中通過(guò) flash() 傳入的信息列表。把字符串對(duì)象表示的消息加入到一個(gè)消息隊(duì)列中,然后通過(guò)調(diào)用 get_flashed_messages() 方法取出。
{% for message in get_flashed_messages() %} {{ message }} {% endfor %}
希望本文所述對(duì)大家基于flask框架的Python程序設(shè)計(jì)有所幫助。
相關(guān)文章
python 讀文件,然后轉(zhuǎn)化為矩陣的實(shí)例
下面小編就為大家分享一篇python 讀文件,然后轉(zhuǎn)化為矩陣的實(shí)例,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2018-04-04教你用Python實(shí)現(xiàn)自動(dòng)提取并收集信息的功能
今天教大家怎么用Python實(shí)現(xiàn)自動(dòng)提取并收集信息的功能,文中介紹的非常詳細(xì),有很多代碼示例,對(duì)正在學(xué)習(xí)python的小伙伴們很有幫助,需要的朋友可以參考下2021-05-05Python爬取視頻時(shí)長(zhǎng)場(chǎng)景實(shí)踐示例
這篇文章主要為大家介紹了Python獲取視頻時(shí)長(zhǎng)場(chǎng)景實(shí)踐示例,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-07-07python卸載numpy出現(xiàn)WinError:拒絕訪問(wèn)的解決方案
這篇文章主要介紹了python卸載numpy出現(xiàn)WinError:拒絕訪問(wèn)的解決方案,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-08-08