python中Flask?Web?表單的使用方法介紹
簡(jiǎn)介
表單的操作是Web程序開發(fā)中最核心的模塊之一,絕大多數(shù)的動(dòng)態(tài)交互功能都是通過表單的形式實(shí)現(xiàn)的。本文會(huì)教大家實(shí)現(xiàn)簡(jiǎn)單的表單操作。
普通表單提交
在創(chuàng)建模板login.html頁面中直接寫form表單。
login.html
<!DOCTYPE html>
<html lang="en">
<head>
? ?<meta charset="UTF-8">
? ?<meta http-equiv="X-UA-Compatible" content="IE=edge">
? ?<meta name="viewport" content="width=device-width, initial-scale=1.0">
? ?<title>Document</title>
</head>
<body>
? ?<form action="" method="post">
? ? ? ?<input type="text" name="username" placeholder="Username">
? ? ? ?<input type="password" name="password" placeholder="Password">
? ? ? ?<input type="submit" value="提交">
? ?</form>
? {% if method == 'GET' %}
? ? ? 請(qǐng)求方式:{{method}}
? {% elif method == 'POST' %}
? ? ? 請(qǐng)求方式:{{method}}
? ? ? 用戶名:{{ username }}
? ? ? 密碼:{{ password }}
? {% endif %}
? ?
</body>
</html>接下來,在視圖函數(shù)中獲取表單數(shù)據(jù)
login.py
from flask import Flask, render_template, request?
app = Flask(__name__)?
# index 視圖函數(shù)
@app.route('/login', methods=['GET', 'POST'])
def login():
? ?context = dict()
? ?if request.method == 'POST':
? ? ? ?username = request.form['username']
? ? ? ?password = request.form['password']
? ? ? ?print(username, password)
? ? ? ?context = {
? ? ? ? ? ?'username': username,
? ? ? ? ? ?'password': password,
? ? ? }
? ? ? ?context.update({'method': request.method})
? ?else:
? ? ? ?context.update({'method': request.method})
? ?return render_template('login.html', **context)
@app.route('/')
def index():
? ?return 'hello'
if __name__ == '__main__':
? ?app.run(debug=True)
當(dāng)我們點(diǎn)擊提交之后,則會(huì)顯示:

上面的實(shí)現(xiàn)方式是直接采用表單的提交方式。但是有個(gè)弊端,假如參數(shù)很多的情況下,后臺(tái)也需要一一進(jìn)行驗(yàn)證,每次都是先接收參數(shù),再對(duì)參數(shù)進(jìn)行校驗(yàn)的話,工作量就會(huì)非常的龐大,而且還會(huì)出現(xiàn)csrf攻擊,這時(shí)我們就可以采用Flask-WTF來創(chuàng)建表單,從而避免上述弊端。
Flask-WTF基礎(chǔ)
Flask-WTF的主要作用是對(duì)用戶的請(qǐng)求數(shù)據(jù)進(jìn)行驗(yàn)證。我們可以使用pip命令安裝該依賴,
pip install flask-wtf
在flask web程序中,因?yàn)轭怓laskForm由Flask-WTF拓展定義,所以可以從flask.wtf中導(dǎo)入FlaskForm。而字段和函數(shù)可以直接從WTForms包中導(dǎo)入,WTForms包中可以支持如下所示的HTML標(biāo)準(zhǔn)字段。
| 字段 | 說明 |
|---|---|
| StringField | 表示文本字段 |
| TextAreaField | 表示多行文本字段 |
| PasswordField | 表示密碼文本字段 |
| HiddenField | 表示隱藏文本字段 |
| DateField | 表示日期的文本字段 |
| DateTimeFiled | 表示時(shí)間的文本字段 |
| IntegerFiled | 表示整數(shù)類型的文本字段 |
| DecimalField | 表示Decimal類型的文本字段 |
| FloatFiled | 表示Float類型的文本字段 |
| RadioFiled | 表示單選框字段 |
| SelectFiled | 表示下拉列表字段 |
WTForm也包含驗(yàn)證器,它對(duì)表單字段進(jìn)行驗(yàn)證,非常方便。
| 字段 | 說明 |
|---|---|
| DataRequire | 檢查輸入的字段是否為空 |
| 檢查字段是否符合郵件格式的約定 | |
| IPAddress | 在輸入字段中驗(yàn)證IP地址 |
| Length | 驗(yàn)證輸入字段中的字符串長(zhǎng)度是否符合給定長(zhǎng)度 |
| NumberRange | 驗(yàn)證給定范圍內(nèi)輸入字段中的文字 |
| URL | 驗(yàn)證是否為合法的URL |
使用Flask-WTF處理表單
編寫兩個(gè)視圖函數(shù),以及一個(gè)form表單類,用于注冊(cè)以及跳轉(zhuǎn)index頁面。
login.py
from flask import Flask, render_template, redirect, url_for, session
from flask_wtf import FlaskForm
from wtforms import StringField, PasswordField, SubmitField
from wtforms.validators import DataRequired, EqualTo
app = Flask(__name__)
app.config["SECRET_KEY"] = "xhosd6f982yfhowefy29f"?
class RegisterForm(FlaskForm):
? ?username = StringField(label="用戶名", validators=[DataRequired('用戶名不能為空')])
? ?password = PasswordField(label="密碼", validators=[DataRequired('密碼不能為空')])
? ?password_comfirm = PasswordField(label="確認(rèn)密碼", validators=[DataRequired('密碼不能為空'), EqualTo('password', '兩次密碼不一致')])
? ?submit = SubmitField(label='提交')?
@app.route('/register', methods=['GET', 'POST'])
def register():
? ?form = RegisterForm()
? ?if form.validate_on_submit():
? ? ? ?uname = form.username.data
? ? ? ?pwd = form.password.data
? ? ? ?pwd_com = form.password_comfirm.data
? ? ? ?print(uname, pwd, pwd_com)
? ? ? ?session['username'] = uname
? ? ? ?return redirect(url_for('index'))
? ?return render_template('register.html', form=form)
@app.route('/index')
def index():
? ?username = session.get('username', '')
? ?return 'hello %s' % username
if __name__ == '__main__':
? ?app.run(debug=True)接下來編寫一個(gè)html模板文件,用于用戶注冊(cè)使用。
register.html
<!DOCTYPE html>
<html lang="en">
<head>
? ?<meta charset="UTF-8">
? ?<meta http-equiv="X-UA-Compatible" content="IE=edge">
? ?<meta name="viewport" content="width=device-width, initial-scale=1.0">
? ?<title>Document</title>
</head>
<body>
? ?<form action="" method="post">
? ? ? {{form.csrf_token}}
? ? ? {{form.username.label}}
? ? ? ?<p>{{ form.username }}</p>
? ? ? {% for msg in form.username.errors %}
? ? ? ? ? ?<p>{{ msg }}</p>
? ? ? {% endfor %}
?
? ? ? {{form.password.label}}
? ? ? ?<p>{{ form.password }}</p>
? ? ? {% for msg in form.password.errors %}
? ? ? ? ? ?<p>{{ msg }}</p>
? ? ? {% endfor %}
?
? ? ? {{form.password_comfirm.label}}
? ? ? ?<p>{{ form.password_comfirm }}</p>
? ? ? {% for msg in form.password.errors %}
? ? ? ? ? ?<p>{{ msg }}</p>
? ? ? {% endfor %}
?
? ? ? {{ form.submit }}
? ?</form>
</body>
</html>Flask消息閃現(xiàn)
在Flask框架中,方法flash()功能是實(shí)現(xiàn)消息閃現(xiàn)提示效果。Flask官方對(duì)閃現(xiàn)的解釋是對(duì)用戶的請(qǐng)求做出無刷新的響應(yīng)。類似于Ajax的刷新效果。
舉一個(gè)簡(jiǎn)單的例子,當(dāng)用戶通過表單發(fā)送完請(qǐng)求之后,假如用戶名或者是密碼輸入錯(cuò)誤,那么服務(wù)器就會(huì)返回錯(cuò)誤的提示信息,并在表單頁面上顯示。
具體代碼,如下所示:
login.py
from flask import Flask, flash, redirect, render_template, request, url_for
app = Flask(__name__)
app.secret_key = 'random string'
@app.route('/')
def index():
? ?return render_template('index.html')
@app.route('/login', methods=['GET', 'POST'])
def login():
? ?error = None
? ?if request.method == 'POST':
? ? ? ?if request.form['username'] != 'admin' or request.form['password'] != 'admin':
? ? ? ? ? ?flash("用戶名或密碼錯(cuò)誤")
? ? ? ?else:
? ? ? ? ? ?flash('登錄成功')
? ? ? ? ? ?return redirect(url_for('index'))
? ?return render_template('login.html')
if __name__ == '__main__':
? ?app.run(debug=True)login.html
<!DOCTYPE html>
<html lang="en">
<head>
? ?<meta charset="UTF-8">
? ?<meta http-equiv="X-UA-Compatible" content="IE=edge">
? ?<meta name="viewport" content="width=device-width, initial-scale=1.0">
? ?<title>登錄</title>
</head>
<body>
? ?<form action="" method="post">
? ? ? ?<p>username</p>
? ? ? ?<input type="text" name="username">
? ? ? ?<p>password</p>
? ? ? ?<input type="password" name="password">
? ? ? ?<input type="submit" value="登錄">
? ?</form>
? {% for message in get_flashed_messages() %}
? ? ? {% if message %}
? ? ? ? ? {{message}}
? ? ? {% endif %}
? {% endfor %}
</body>
</html>index.html
<!DOCTYPE html>
<html lang="en">
<head>
? ?<meta charset="UTF-8">
? ?<meta http-equiv="X-UA-Compatible" content="IE=edge">
? ?<meta name="viewport" content="width=device-width, initial-scale=1.0">
? ?<title>Document</title>
</head>
<body>
? {% with messages = get_flashed_messages() %}
? ? ? {% if messages %}
? ? ? ? ? {% for message in messages %}
? ? ? ? ? ? ? ?<p>{{ message }}</p>
? ? ? ? ? {% endfor %}
? ? ? {% endif %}
? {% endwith %}
? ?<h3>welcome</h3>
? ?<a href="{{url_for('login')}}" rel="external nofollow" >login</a>
</body>
</html>上面的代碼實(shí)現(xiàn)了URL的跳轉(zhuǎn),我們首先會(huì)進(jìn)入首頁,首頁中包含了進(jìn)入登錄頁面的鏈接。



文件上傳
在Flas Web程序中要實(shí)現(xiàn)文件的上傳非常簡(jiǎn)單,與傳遞post和get非常的類似。基本流程如下:
- (1)將在客戶端上傳的文件保存到flask.request.files對(duì)象。
- (2)使用flask.request.files對(duì)象獲取上傳上來的文件名和文件對(duì)象
- (3)調(diào)用文件對(duì)象中的方法save()將文件保存到指定的目錄中。
簡(jiǎn)易的文件上傳程序如下所示:
upload.py
from flask import Flask, flash, render_template, request
app = Flask(__name__)
?
@app.route('/upload', methods=['GET', 'POST'])
def upload():
? ?if request.method == 'GET':
? ? ? ?return render_template('upload.html')
? ?else:
? ? ? ?file = request.files['file']
? ? ? ?if file:
? ? ? ? ? ?file.save(file.name + '.png')
? ? ? ? ? ?return '上傳成功'
@app.route('/')
def index():
? ?return render_template('index.html')
if __name__ == '__main__':
? ?app.run(debug=True)index.html
<!DOCTYPE html>
<html lang="en">
<head>
? ?<meta charset="UTF-8">
? ?<meta http-equiv="X-UA-Compatible" content="IE=edge">
? ?<meta name="viewport" content="width=device-width, initial-scale=1.0">
? ?<title>Document</title>
</head>
<body>
? ?<h1>文件上傳首頁</h1>
? ?<a href="{{url_for('upload')}}" rel="external nofollow" >文件上傳</a>
</body>
</html>upload.html
<!DOCTYPE html> <html lang="en"> <head> ? ?<meta charset="UTF-8"> ? ?<meta http-equiv="X-UA-Compatible" content="IE=edge"> ? ?<meta name="viewport" content="width=device-width, initial-scale=1.0"> ? ?<title>文件上傳</title> </head> <body> ? ?<form action="" method="post" enctype="multipart/form-data"> ? ? ? ? ?<input type="file" name="file"> ? ? ? ?<input type="submit" value="點(diǎn)擊我上傳"> ? ?</form> </body> </html>
本程序需要點(diǎn)擊跳轉(zhuǎn)之后才能進(jìn)入文件上傳頁面,這樣寫的目的只是因?yàn)槲冶容^懶,不想再瀏覽器中輸入一大串的url。




目前上述程序僅僅可以上傳圖片!
文件上傳的另一種寫法
在Flask中上傳文件的步驟非常簡(jiǎn)單,首先需要一個(gè)HTML表單,將enctype屬性設(shè)置為"multipart/form-data"即可。URL處理程序會(huì)從request.file[]對(duì)象中提取文件,并將它保存到所需要的位置上。
每個(gè)上傳的文件首先會(huì)保存到服務(wù)器上的臨時(shí)位置,然后將其保存到最終的實(shí)際位置。建議使用secure_filename函數(shù)獲取。
index.html
<!DOCTYPE html> <html lang="en"> <head> ? ?<meta charset="UTF-8"> ? ?<meta http-equiv="X-UA-Compatible" content="IE=edge"> ? ?<meta name="viewport" content="width=device-width, initial-scale=1.0"> ? ?<title>Document</title> </head> <body> ? ?<form action="/uploader" method="post" enctype="multipart/form-data"> ? ? ? ?<input type="file" name="file"> ? ? ? ?<input type="submit" value="提交"> ? ?</form> </body> </html>
upload.py
from flask import Flask, render_template, request
from werkzeug.utils import secure_filename
import os
app = Flask(__name__)
app.config['UPLOAD_FLODER']= 'upload/' # 設(shè)置文件保存的路徑
@app.route('/')
def upload_file():
? ?return render_template('upload.html')
@app.route('/uploader', methods=['GET', 'POST'])
def uploader():
? ?if request.method == 'POST':
? ? ? ?f = request.files['file']
? ? ? ?print(request.files)
? ? ? ?f.save(os.path.join(app.config['UPLOAD_FLODER'], secure_filename(f.filename)))
? ? ? ?return '上傳成功'
? ?else:
? ? ? ?render_template('upload.html')
if __name__ == '__main__':
? ?app.run(debug=True)到此這篇關(guān)于python中Flask Web 表單的使用方法介紹的文章就介紹到這了,更多相關(guān)Java Flask 表單內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Python從數(shù)據(jù)庫(kù)讀取大量數(shù)據(jù)批量寫入文件的方法
今天小編就為大家分享一篇Python從數(shù)據(jù)庫(kù)讀取大量數(shù)據(jù)批量寫入文件的方法,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2018-12-12
python def 定義函數(shù),調(diào)用函數(shù)方式
這篇文章主要介紹了python def 定義函數(shù),調(diào)用函數(shù)方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2020-06-06
關(guān)于Python?Tkinter?復(fù)選框?->Checkbutton
這篇文章主要介紹了關(guān)于Python?Tkinter復(fù)選框Checkbutton,文章圍繞主題展開詳細(xì)的內(nèi)容介紹,具有一定的參考價(jià)值,需要的小伙伴可以參考一下2022-09-09
PyTorch中的神經(jīng)網(wǎng)絡(luò) Mnist 分類任務(wù)
這篇文章主要介紹了PyTorch中的神經(jīng)網(wǎng)絡(luò) Mnist 分類任務(wù),在本次的分類任務(wù)當(dāng)中,我們使用的數(shù)據(jù)集是 Mnist 數(shù)據(jù)集,這個(gè)數(shù)據(jù)集大家都比較熟悉,需要的朋友可以參考下2023-03-03
Python 字符串大小寫轉(zhuǎn)換的簡(jiǎn)單實(shí)例
下面小編就為大家?guī)硪黄狿ython 字符串大小寫轉(zhuǎn)換的簡(jiǎn)單實(shí)例。小編覺得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2017-01-01
文件上傳服務(wù)器-jupyter 中python解壓及壓縮方式
這篇文章主要介紹了文件上傳服務(wù)器-jupyter 中python解壓及壓縮方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2020-04-04

