溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

Flask框架學(xué)習(xí)筆記之使用Flask實現(xiàn)表單開發(fā)詳解

發(fā)布時間:2020-10-16 18:16:03 來源:腳本之家 閱讀:157 作者:Cytues 欄目:開發(fā)技術(shù)

本文實例講述了使用Flask實現(xiàn)表單開發(fā)。分享給大家供大家參考,具體如下:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Title</title>
</head>
<body>
  <div align="center">
  <h2>User Management</h2>
  <form method="post">
    <input type="text" name="username" placeholder="username" />
    <br>
    <input type="password" name="password" placeholder="password" />
    <br>
    <input type="submit" value="Submit">
    <input type="reset" value="Reset">
  </form>
  </div>
</body>
</html>

使用html實現(xiàn)的表單:

Flask框架學(xué)習(xí)筆記之使用Flask實現(xiàn)表單開發(fā)詳解

用flask實現(xiàn)相同功能的表單:

# -*- coding:utf-8 -*-
from flask import Flask, request, render_template, redirect
from wtforms import Form, TextField, PasswordField, validators
app = Flask(__name__)
class LoginForm(Form):
  # validators指定一個由驗證函數(shù)組成的列表
  # 在接受用戶提交的數(shù)據(jù)之前驗證數(shù)據(jù)
  # 驗證函數(shù)Required()確保提交的字段不為空
  username = TextField("username", [validators.Required()])
  password = PasswordField("password", [validators.Required()])
# 定義user路由
@app.route("/user", methods=['GET', 'POST'])
def login():
  myForm = LoginForm(request.form)
  if request.method == 'POST':
    # username = request.form['username']使用request獲取數(shù)據(jù)
    # password = request.form['password']
    # 也可以使用類實例里的表單方法來獲取相應(yīng)的數(shù)據(jù)
    # validate來驗證輸入的表單數(shù)據(jù)是否有效
    if myForm.username.data == "loli" and myForm.password.data == "520" and myForm.validate():
      return redirect("http://www.baidu.com")
    else:
      message = "Login Failed"
      return render_template("form1.html", message=message, form=myForm)
  return render_template("form1.html", form=myForm)
if __name__ == '__main__':
  app.run()

form1模板:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Title</title>
</head>
<body>
  <div align="center">
  <h2>User Management</h2>
  <form method="post">
    {% if message %}
      {{ message }}
    {% endif %}
    <br>
    {{ form.username }}
    <br>
    {{ form.password }}
    <br>
    <input type="submit" value="Submit">
    <input type="reset" value="Reset">
  </form>
  </div>
</body>
</html>

Flask框架學(xué)習(xí)筆記之使用Flask實現(xiàn)表單開發(fā)詳解

一樣的效果圖。

在WTForm3.0中Textfield被移除,使用Stringfield代替。

WTForm主要在flask中用于驗證表單。

參考官方文檔:http://dormousehole.readthedocs.io/en/latest/patterns/wtforms.html

希望本文所述對大家基于flask框架的Python程序設(shè)計有所幫助。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI