【簡說Python WEB】Form提交表單


系統環境:Ubuntu 18.04.1 LTS

Python使用的是虛擬環境:virutalenv

Python的版本:Python 3.6.9

【簡說Python WEB】Form提交表單

B/S架構的核心,一個get數據,另外一個post數據。很多交互性的網站,都需要通過Form表單來向服務器提交數據。這里介紹,簡單做一個From表單。感受一下post數據和與服務器端的交互。

安裝flask-wtf

pip install flask-wtf

代碼樹

├── app.py
└── templates
   ├── 404.html
   ├── 500.html
   ├── base.html
   └── index.html

app.py源碼中表單類:

設置一個密鑰,是防止表單遭到跨站請求偽造(CSRF).保證其安全。會生成一個令牌,加密簽名的。

app.config['SECRET_KEY'] = 'wojiubugaosuni'

這里的wojiubugaosuni不能明文寫入配置文件,應該通過環境變量傳入,保證安全性。

添加了一個FlaskForm表格。表格中有如下字段 :

  • 一個name的文本字段,其中StringField構造函數中的validators的參數,確保提交的字段不能為空。
  • 一個名為submit的按鈕
from flask_wtf import FlaskForm
from wtforms import StringField, SubmitField
from wtforms.validators import DataRequired

class NameForm(FlaskForm):
    name = StringField('你的名字叫什么', validators=[DataRequired()])
    submit = SubmitField('Submit')

index.html的源碼修改:渲染form表單

{% extends "base.html" %}
{% import "bootstrap/wtf.html" as wtf %}

{% block title %}zsdblog{% endblock %}


{% block content %}
<div class="container">
        <div class="page-header">
        <h1>您好, {{ name }},歡迎來到我的博客!</h1>
    </div>
</div>
{{ wtf.quick_form(form) }}
{% endblock %}

其中添加了{% import "bootstrap/wtf.html" as wtf %}{{ wtf.quick_form(form) }}使用bootstrap來渲染form表單元素。

app.py源碼中from表單處理

@app.route('/', methods=['GET', 'POST'])
def index():
    name = '游客'
    form = NameForm()
    if form.validate_on_submit():
        name = form.name.data
        form.name.data = ''
    return render_template('index.html', form=form, name=name)

效果演示:

輸入小明之后的演示效果:

不輸入任何字符,會觸發StringField構造函數中的驗證效果:

就會有請填寫此字段的驗證效果

會話和重定向

提交表單之后,按F5刷新瀏覽器,會報出一個警告。如下頁面:

為了讓數據保持,就保存在一個session之中。修改app.py代碼如下 :

from flask import Flask, render_template,session,redirect,url_for


    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'))

讓代碼自己重定向redirect(url_for('index'))


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM