python简单的登录认证

本次学习遇到坑,不知道为什么loginFrom类如果继承FlaskForm,那么loginForm类的对象myform的validate()方法返回一直是false,此时要在html文件表单最后加上{{ form.csrf_token }}。
但是我不知道是什么意思,我也不想加,就把loginFrom类继承Form,那么不加
{{ form.csrf_token }},也可以正常获得取值逻辑运行正常

# Python版本:3.7.4
#db.py
from pymysql import connect

DIALECT = 'mysql'
DRIVER = 'pymysql'
USERNAME = 'root'
PASSWORD = '123456'
HOST = 'localhost'
PORT = '3306'
DATABASE = 'test1'

conn = connect('localhost','root','123456','test1')
cur = conn.cursor()

def addUser(username,password):
    sql = "insert into user(username,password) values ('%s','%s')" % (username,password)
    cur.execute(sql)
    conn.commit()
    conn.close()

def isExist(username,password):
    sql = "select *from user where username = '%s' and password = '%s'" %(username,password)
    cur.execute(sql)
    result = cur.fetchall()
    if (len(result)==0):
        return False
    else:
        return True
# 需求:使用flask框架,配合HTML和JS程序,编写两个页面,第一个页面允许用户填入用户名和密码进行注册,第二个页面登录

# app.py
from flask import Flask, render_template, request, redirect
from db import *

app = Flask(__name__)
app.secret_key = 'development key'

from wtforms import StringField, PasswordField, validators, Form


class loginForm(Form):
    username = StringField("username", [validators.DataRequired()])
    password = PasswordField("password", [validators.DataRequired()])


@app.route('/user', methods=["POST", "GET"])
def login():
    myform = loginForm(request.form)
    if request.method == "POST":
        username = myform.username.data
        password = myform.password.data
        aaa = myform.validate()
        if isExist(username,password) and myform.validate():
            return redirect('http://www.baidu.com')
        else:
            message = 'login failed'
            return render_template('index.html', message=message, form=myform)

    return render_template('index.html', form=myform)


@app.route('/register', methods=["POST", "GET"])
def register():
    myForm = loginForm(request.form)
    if request.method == "POST":
        addUser(myForm.username.data, myForm.password.data)
        return "注册成功"
    return render_template('index.html', form=myForm)

if __name__ == '__main__':
    app.run(debug=True)





    



    
{% if message%} {{message}} {%endif%}
name
{{form.username}}
password
{{form.password}}

#{{ form.csrf_token }}

你可能感兴趣的:(python简单的登录认证)