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

相关文章

pandas中的series数据类型详解

本文介绍了pandas中的series数据类型详解,分享给大家,具体如下: import pandas as pd import numpy as np import names...

Python中请不要再用re.compile了

Python中请不要再用re.compile了

前言 如果大家在网上搜索Python 正则表达式,你将会看到大量的垃圾文章会这样写代码: import re pattern = re.compile('正则表达式') text...

Python如何使用字符打印照片

Python如何使用字符打印照片

这篇文章主要介绍了Python如何使用字符打印照片,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 1. 前言 第一次在学校机房里见到...

python飞机大战 pygame游戏创建快速入门详解

python飞机大战 pygame游戏创建快速入门详解

本文实例讲述了python飞机大战 pygame游戏创建。分享给大家供大家参考,具体如下: 目标 项目准备 使用 pygame 创建图形窗口 理解 图像 并实现图像绘制...

python实现多层感知器

python实现多层感知器

写了个多层感知器,用bp梯度下降更新,拟合正弦曲线,效果凑合。 # -*- coding: utf-8 -*- import numpy as np import matplotli...