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程序设计有所帮助。

相关文章

linecache模块加载和缓存文件内容详解

linecache模块 接触到linecache这个模块是因为前两天读attrs源码的时候看到内部代码引用了这个模块来模拟一个假文件,带着一脸疑问顺便读了一下这个模块的源码,发现其实也就...

详解Numpy数组转置的三种方法T、transpose、swapaxes

详解Numpy数组转置的三种方法T、transpose、swapaxes

Numpy是高性能科学计算和数据分析的基础包,里面包含了许多对数组进行快速运算的标准数学函数,掌握这些方法,能摆脱数据处理时的循环。 1.首先数组转置(T) 创建二维数组data如下:...

用Python编写一个每天都在系统下新建一个文件夹的脚本

这个程序的功能非常的简单,就是每天在系统中新建一个文件夹。文件夹即当前的时间。此代码是在同事那边看到的,为了锻炼下自己薄弱的Python能力,所以花时间重新写了一个。具体代码如下:...

python递归删除指定目录及其所有内容的方法

实例如下: #! /usr/bin/python # -*- coding: utf-8 -*- import os def del_dir_tree(path): ''' 递...

python二分法实现实例

1.算法:(设查找的数组期间为array[low, high]) (1)确定该期间的中间位置K(2)将查找的值T与array[k]比较。若相等,查找成功返回此位置;否则确定新的查找区域,...