Python Flask-web表單,pythonflask-web

來源:互聯網
上載者:User

Python Flask-web表單,pythonflask-web

Flask-WTF擴充可以把處理web表單的過程變成一種愉悅的體驗。

一、跨站請求偽造保護

預設情況下,Flask-WTF能夠保護所有表單免受跨站請求偽造的攻擊。惡意網站把請求發送到被攻擊者已登入的網站時就會引起CSRF攻擊。

為了實現CSRF保護,Flask-WTF需要程式設定一個密鑰。Flask-WTF使用這個密鑰產生加密令牌,再用令牌驗證請求中表單資料的真偽。設定密鑰的方法如下所示:

app = Flask(__name__)app.config['SECRET_KEY']='hard to guess string'

 

二、表單類

使用Flask-WTF時,每個web表單都由一個繼承自Form的類表示。這個定義表單中的一組欄位,每個欄位都用對象表示。欄位對象可附屬一個或多個驗證函式。驗證函式用來驗證使用者提交的輸入值是否符合要求。

#!/usr/bin/env python#簡單的web表單,包含一個文字欄位和一個提交按鈕from flask_wtf import Formfrom wtforms import StringField,SubmitFieldfrom wtforms.validators import Requiredclass NameForm(Form):    name = StringField('What is your name?',validators=[Required()])    submit = SubmitField('Submit')

StringField類表示屬性為type="text"的<input>元素,SubmitField類表示屬性為type="submit"的<input>元素。

WTForms支援的HTML標準欄位

欄位類型 說明
StringField 文字欄位
TextAreaField 多行文字欄位
PasswordField 密碼文字欄位
HiddenField 隱藏文字欄位
DateField 文字欄位,值為datetime.date格式
IntegerField 文字欄位,值為整數
FloatField 文字欄位,值為浮點數
SelectField 下拉式清單
SubmitField 表單提交按鈕

WTForms驗證函式

驗證函式 說明
Email 驗證電子郵件地址
EqualTo 比較兩個欄位的值,常用於要求輸入兩次密碼進行確認的情況
IPAddress 驗證IPv4網路地址
Length 驗證輸入字串的長度
NumberRange 驗證輸入的值在數字範圍內
Optional 無輸入值時跳過其他驗證函式
Required 確保欄位中有資料
Regexp 使用Regex驗證輸入值
URL 驗證URL
AnyOf 確保輸入值在可選值列表中
NoneOf 確保輸入值不在可選值列表中

 

四、把表單渲染成HTML

表單欄位是可用的,在模板中調用後會渲染成HTML。假設視圖函數把一個NameForm執行個體通過參數form傳入模板,在模板中可以產生一個簡單的表單,如下所示:

<form method="POST">    {{ form.hidden_tag() }}    {{ form.name.label }} {{ form.name() }}    {{ form.submit() }}</form>
<form method="POST">    {{ form.hidden_tag() }}    {{ form.name.label }} {{ form.name(id='my-text-field') }}    {{ form.submit() }}</form>

Flask-Bootstrap提供了一個非常高端的輔助函數,可以使用Bootstrap中預先定義好的表單樣式渲染整個Flask-WTF表單,而這些操作只需調用一次即可完成。

{% import "boostrap/wtf.html" as wtf %}{{ wtf.quick_form(form) }}
#使用Flask-WTF和Flask-Bootstrap渲染表單{% extends "base.html" %}{% import "bootstrap/wtf.html" as wtf %}{% block title %}Flasky{% endblock %}{% block page_content %}<div class="page-header">    <h1>Hello,{% if name %}{{ name }}{% else %}Stranger{% endif %}</h1></div>{{ wtf.quick_form(form) }}{% endblock %}

 

四、在視圖函數中處理表單
@app.route('/',methods=['GET','POST'])def index():    name = None    form = NameForm()    if form.validate_on_submit():        name = form.name.data        form.name.data = ''    return render_template('index.html',form=form,name=name)

app.route修飾器中添加的methods參數告訴Flask在URL映射中把這個視圖函數註冊為GET和POST請求的處理常式。如果沒指定methods參數,就只把視圖函數註冊為GET請求的處理常式。

 五、重新導向和使用者會話
#!/usr/bin/env pythonfrom flask import Flask,render_template,session,redirect,url_forapp = Flask(__name__)@app.route('/',methods=['GET','POST'])def index():    form = NameForm()    if form.validate_on_submit():        session['name'] = form.name.data        return redirect(url_for('index'))    return render_template('index.html',form=form,name=session.get('name'))

 

六、Flash訊息

例子:提示使用者名稱或密碼錯誤,快顯視窗

from flask import Flask,render_template,session,redirect,url_for,flashapp = Flask(__name__)@app.route('/',methods=['GET','POST'])def index():    form = NameForm()    if form.validata_on_submit():        old_name = session.get('name')        if old_name is not None and old_name != form.name.data:            flash('Looks like you have changed your name!')        session['name'] = form.name.data        return redirect(url_for('index'))    return render_template('index.html',form=form,name=session.get('name'))
#渲染Flash訊息{% block content %}<div class="container">    {% for message in get_flashed_messages() %}    <div class="alert alert-warning">        <button type="button" class="close" data-dismiss="alert">×</button>        {{ message }}    </div>    {% endfor %}    {% block page_content %}{% endblock %}</div>{% endblock %}

  

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.