DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>登录页面title>
head>
<body>
<form action="/login/" method="post">
<table>
<tr>
<th>用户名:th>
<td><input type="text" name="uname">td>
tr>
<tr>
<th>密码:th>
<td><input type="text" name="pwd">td>
tr>
<tr>
<th>验证码:th>
<td><input type="text" name="code" maxlength="4"> <span style="background-color: aqua;">{{code}}span>td>
tr>
<tr>
<th>th>
<td><input type="submit" value="登录">td>
tr>
table>
form>
body>
html>
from flask import session
from wtforms import Form,StringField
from wtforms.validators import Length,ValidationError
class loginForm(Form):
code = StringField(validators=[Length(4,4)])
def validate_code(self,field):
font_code = field.data
server_code = str(session.get('code'))
if font_code != server_code:
raise ValidationError('验证码不一致!!!请重新输入!')
#coding=utf-8
from flask import Flask,render_template,request,session
from random import randint
from loginForm import loginForm
app = Flask(__name__)
app.secret_key = 'adada'
@app.route('/')
def index():
return 'Hello~'
@app.route('/login/',methods=['GET','POST'])
def login():
if request.method == 'GET':
code = randint(1000,9999)
session['code'] = code
return render_template('login.html',code=code)
else:
form = loginForm(request.form)
if form.validate():
return '验证成功!'
return f'验证失败!失败信息:{form.errors}'
if __name__ == '__main__':
app.run(debug=True)