• Flask表单(form)的应用


    导入模块request模块


    #指定请求方式,使用methods属性
    @app.route("/",methods=['GET','POST'])
    def index():
    #判断client发送的请求类型
    #自己请求自己的逻辑中,GET只用来解析模板,而POST用来判断数据逻辑
    if request.method == "POST":
    #使用from属性来接收表单提交过来的数据
    username = request.form.get("username")
    password = request.form.get("password")
    password1 = request.form.get("password1")

    #模拟登陆,将用户和密码存到session中
    session['username'] = username
    session['password'] = password

    #判断数据是否同时存在
    #等同于 if username == '' or password == '' or password1 == ''
    if not all([username,password,password1]):
    #利用闪现消息来提醒用户
    flash("参数不足")
    elif password != password1:
    flash("密码不匹配")
    else:
    flash("注册成功")
    #第一种直接跳转网址
    return redirect("http://localhost")
    #第二种可以用url_for方法跳转
    return redirect(url_for("hello"))

    #将定义好的表单类传递给模板,进行方法化设置
    return render_template('day4_form.html')
    然后新建一个html文件
    <!DOCTYPE html>
    <html lang="en">
    <head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>flask普通表单提交数据,使用flask消息闪现来将反馈显示给用户</title>
    </head>
    <body>
    <h1>用户注册</h1>

    <br /><br />
    {# action属性,如果不写,默认提交给自己,methods属性,指定该表单的提交方式#}
    <form method="post">
    <label>用户名</label>
    {# form提交数据通过name选择器来提交#}
    <input type="text" name="username" placeholder="请输入用户名" />
     
    <br />
    <label>密码</label>
    <input type="password" name="password" placeholder="请输入密码" />

    <br />
    <label>确认密码</label>
    <input type="password" name="password1" />

    <br /><br />


    {# 将flash消息闪现和后台联系起来 #}
    {# 将消息闪现里面的所有消息遍历,取出需要返回给用户的消息 #}
    {% for message in get_flashed_messages() %}
    {{message}}
    {% endfor %}
    <input type="submit" value="注册" />
    </form>
    </body>
    </html>
  • 相关阅读:
    CentOS7上Mongodb安装、卸载
    CentOS7上Redis安装与配置
    vmware centos7系统虚拟机复制到其他电脑后不能联网问题解决
    流程项目点水笔记
    CentOS7图形界面启动报错unable to connect to X server
    本地Chrome测试JS代码报错:XMLHttpRequest cannot load
    iptables相关操作以及简单理解端口和服务之间关系
    git revert 和 git reset的区别
    Linux中_ALIGN宏背后的原理——内存对齐
    SPI协议及其工作原理浅析
  • 原文地址:https://www.cnblogs.com/antique/p/10170515.html
Copyright © 2020-2023  润新知