Flask框架学习笔记之使用Flask实现表单开发详解

yipeiwu_com6年前Python基础

本文实例讲述了使用Flask实现表单开发。分享给大家供大家参考,具体如下:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Title</title>
</head>
<body>
  <div align="center">
  <h1>User Management</h1>
  <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实现的表单:

用flask实现相同功能的表单:

# -*- 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指定一个由验证函数组成的列表
  # 在接受用户提交的数据之前验证数据
  # 验证函数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获取数据
    # password = request.form['password']
    # 也可以使用类实例里的表单方法来获取相应的数据
    # validate来验证输入的表单数据是否有效
    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">
  <h1>User Management</h1>
  <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>

一样的效果图。

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

WTForm主要在flask中用于验证表单。

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

希望本文所述对大家基于flask框架的Python程序设计有所帮助。

相关文章

Python SQLite3简介

最近需要用Python写一个简易通讯录,但是对于数据存储很发愁。大家都知道,使用 Python 中的列表和字典进行存储数据是很不靠谱的,所以就想到Python有没有内置的数据库模块。 S...

在OpenCV里使用Camshift算法的实现

在OpenCV里使用Camshift算法的实现

前面学习过Meanshift算法,在观察这个结果标记时,会发现有这样一个问题,如下图: 汽车比较远时,用一个很小的窗口就可以把它框住,这是符合近大远小的投影原理,当比较近的时候如下:...

pytorch之添加BN的实现

pytorch之添加BN的实现

pytorch之添加BN层 批标准化 模型训练并不容易,特别是一些非常复杂的模型,并不能非常好的训练得到收敛的结果,所以对数据增加一些预处理,同时使用批标准化能够得到非常好的收敛结果,这...

Python中dictionary items()系列函数的用法实例

本文实例讲述了Python中dictionary items()系列函数的用法,对Python程序设计有很好的参考借鉴价值。具体分析如下: 先来看一个示例: import html...

详解Python3序列赋值、序列解包

上节我们提到解决赋值中等号两边参数不一致的方法可以通过切片,但在Python3中我们可以利用特定的语法更加方便的处理这种情况,如下示例。 当带 * 出现在结尾间时 L = [1, 2...