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 实现求解字符串集的最长公共前缀方法

问题比较简单,给定一个字符串集合求解其中最长的公共前缀即可,这样的问题有点类似于最长公共子序列的问题,但是比求解最长最长公共子序列简单很多,因为是公共前缀,这样的话只需要挨个遍历即可,只...

Python字符串对象实现原理详解

Python字符串对象实现原理详解

在Python世界中将对象分为两种:一种是定长对象,比如整数,整数对象定义的时候就能确定它所占用的内存空间大小,另一种是变长对象,在对象定义时并不知道是多少,比如:str,list, s...

对python 矩阵转置transpose的实例讲解

在读图片时,会用到这么的一段代码: image_vector_len = np.prod(image_size)#总元素大小,3*55*47 img = Image.open(pat...

跟老齐学Python之集合的关系

跟老齐学Python之集合的关系

冻结的集合 前面一节讲述了集合的基本概念,注意,那里所涉及到的集合都是可原处修改的集合。还有一种集合,不能在原处修改。这种集合的创建方法是: >>> f_set =...

Python入门教程4. 元组基本操作 原创

前面简单介绍了Python列表基本操作,这里再来简单讲述一下Python元组相关操作 >>> dir(tuple) #查看元组的属性和方法 ['__add__',...