《flask Web 開發(fā)》讀書筆記 & chapter4

chapter 2 - chapter 3 - 源碼

概念剖析-flask表單對象

  • request.form 能夠獲取 POST 請求中提交的表單對象,但是需要很多重復(fù)的操作,如:生成表單的HTML代碼和驗(yàn)證提交的表單數(shù)據(jù)。
  • Flask-WTF 擴(kuò)展能夠方便的處理表單,pip install flask-wtf

跨站請求偽造保護(hù)

  • Flask-WTF,需要程序設(shè)置一個密鑰,Flask-WTF利用密鑰生成加密令牌,再利用令牌驗(yàn)證請求中表單數(shù)據(jù)的真?zhèn)巍?/li>
  • app.config 字典能用來存儲框架、擴(kuò)展和程序本身的配置變量。
  • app.config['SECRET_KEY'] = 'scret word' 設(shè)置通用密鑰,可在 FLask 和多個第三方庫中使用。
  • 為了增強(qiáng)安全性,密鑰不應(yīng)該直接輸入代碼,而要保存在環(huán)境變量中。
  app = FLask(__name__)
  app.config['SECRET_KEY'] = "hard to guess string"

表單類

廖雪峰-Python教程-使用元類

  • flask-web 中的每個表單都由繼承自 Form 的一個類表示,這個類定義表單中一組字段,每個字段都用對象表示。類似于ORM的技術(shù)
  • 每個字段都可附屬一個或多個驗(yàn)證函數(shù),驗(yàn)證用戶輸入是否符合要求

hello.py 文件:

from wtforms import StringField, SubmitField
from wtforms.validators import Required

class NameForm(Form):
  name = StringField("What's your name", validators=[Required()] )
  submit = SubmitField('Submit')
# ---------------------------------------------------- #
# ---------------------------------------------------- #
# 路由的 GET 和 POST 的區(qū)別是什么,及執(zhí)行過程?
@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 )

index.html 文件:

{% extends "base.html" %}
<!-- 導(dǎo)入 wtf.html --> 
{% import "bootstrap/wtf.html" as wtf %}
{% block title %} Flasky - index {% endblock %}
{% block page_content %}
  <div class="page-header">
     <h1> Hello {% if name %} {{name}} {% else %} Stranger{% endif %} !</h1>
  </div>
  <!-- 表單渲染成 html -->
  {{ wtf.quick_form(form) }}
{% endblock %}
  • git add., git commit -m "flask-wtf first demo ", git tag 4a

重定向和用戶會話

頁面刷新時,瀏覽器會自動的發(fā)送之前已經(jīng)發(fā)送給過的 post 請求,會彈出警告頁面
Post / 重定向 / Get模式 Web開發(fā)設(shè)計(jì)模式PRG:Post/Redirect/Get,防止重復(fù)提交表單 通俗來說,PRG就是用戶提交 post 請求,服務(wù)器返回 get 的重定向,客戶端請求 get 請求,當(dāng)刷新時,瀏覽器提交 get 請求。此時需要采用 會話對象 保存表單數(shù)據(jù)。

hello.py 文件:

@app.route('/', methods=['GET', 'POST'])
def index():
    name=None
    form = NameForm()
    if form.validate_on_submit():
        # 使用 session 保存數(shù)據(jù)
        session['name'] = form.name.data
        return redirect( url_for('index'))
    return render_template( 'index.html', form=form, name=session.get('name') )
OUTPUT:
127.0.0.1 - - [21/Apr/2017 21:31:51] "GET / HTTP/1.1" 200 -                    # 啟動瀏覽器,get index.html
127.0.0.1 - - [21/Apr/2017 21:31:52] "GET /static/favicon.ico HTTP/1.1" 200 -  # 加載圖標(biāo)文件
127.0.0.1 - - [21/Apr/2017 21:32:02] "POST / HTTP/1.1" 302 -                   # 表單的 post 請求
127.0.0.1 - - [21/Apr/2017 21:32:02] "GET / HTTP/1.1" 200 -                    # 重定向 get 請求
  • git add., git commit -m "post_redirect_get and session "

flash推送狀態(tài)變化消息

hello.py 修改

from flask import Flask, render_template, session, url_for, redirect, flash
...
@app.route('/', methods=['GET', 'POST'])
def index():
    name=None
    form = NameForm()
    if form.validate_on_submit():
        old_name = session['name']
        if old_name is not None and old_name != form.name.data:
            # flash 推送狀態(tài)信息
            flash('Looks like you have changed your name!')
        # 使用 session 保存數(shù)據(jù)
        session['name'] = form.name.data
        return redirect( url_for('index'))
    return render_template( 'index.html', form=form, name=session.get('name') )

base.html 添加渲染

<div class="container">

<!-- 渲染 flash 信息 --> 
{% for message in get_flashed_messages() %}
<div class="alert alert-warning">
    <button type = "button" class="close" data-dismiss="alert">×</button>
    {{ message }}
</div>
  • git add., git commit -m "flash alert " ,git tag 4b
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

推薦閱讀更多精彩內(nèi)容