注册功能实现
#model.py:
from exts import db
from datetime import datetime
class EmailCaptchaModel(db.Model):
__tablename__="email_captcha"
id=db.Column(db.Integer,primary_key=True,autoincrement=True)
email=db.Column(db.String(100),nullable=False,unique=True)
captcha=db.Column(db.String(10),nullable=False)
create_time=db.Column(db.DateTime,default=datetime.now)
class UserModel(db.Model):
__tablename__="user"
id=db.Column(db.Integer,primary_key=True,autoincrement=True)
username=db.Column(db.String(200),nullable=False,unique=True)
email=db.Column(db.String(100),nullable=False,unique=True)
password=db.Column(db.String(200),nullable=False)
join_time=db.Column(db.DateTime,default=datetime.now)
#froms.py:
import wtforms
from wtforms.validators import length,email,EqualTo
from models import EmailCaptchaModel
class RegisterForm(wtforms.Form):
username=wtforms.StringField(validators=[length(min=3,max=20)])
email=wtforms.StringField(validators=[email()])
captcha=wtforms.StringField(validators=[length(min=4,max=4)])
password=wtforms.StringField(validators=[length(min=6,max=20)])
password_comfirm = wtforms.StringField(validators=[EqualTo("password")])
def validate_captcha(self,field):
captcha=field.data
email=self.email.data
captcha_model=EmailCaptchaModel.query.filter_by(email=email).first()
if not captcha_model or captcha_model.captcha.lower()!=captcha.lower():
raise wtforms.ValidationError("邮箱验证码错误!")
def validate_email(self,field):
email=field.data
user_model=UserModel.query.filter_by(email=email).first()
if user_model:
raise wtforms.ValidationError("邮箱已经存在!")
#user.py:
import random
import string
from flask import Blueprint,render_template,request,redirect,url_for
from exts import mail,db
from flask_mail import Message
from models import EmailCaptchaModel,UserModel
from datetime import datetime
from .forms import RegisterForm
bp=Blueprint("user",__name__,url_prefix="/user")
@bp.route("/login")
def login():
return render_template("login.html")
@bp.route("/register",methods=['GET','POST'])
def register():
if request.method =='GET':
return render_template("register.html")
else:
form = RegisterForm(request.form)
if form.validate():
email = form.email.data
username = form.username.data
password = form.password.data
user = UserModel(email=email, username=username, password=password)
db.session.add(user)
db.session.commit()
return redirect(url_for("user.login"))
else:
return redirect(url_for("user.register"))
@bp.route("/captcha")
def get_captcha():
email=request.args.get("email")
letter=string.ascii_letters+string.digits
captcha="".join(random.sample(letter,4))
if email:
message = Message(
subject='邮箱测试',
recipients=['[email protected]'],
body=f"您的注册验证码是:{captcha},请不要告诉任何人哦!"
)
mail.send(message)
captcha_model=EmailCaptchaModel.query.filter_by(email=email).first()
if captcha_model:
captcha_model.captcha=captcha
captcha_model.create_time=datetime.now()
db.session.commit()
else:
captcha_model=EmailCaptchaModel(email=email,captcha=captcha)
db.session.add(captcha_model)
db.session.commit()
return "success"
else:
return "没有传递邮箱"
#register.py:
{% extends "base.html" %}
{% block title %}问答-注册{% endblock %}
{% block head %}
{% endblock %}
{% block body %}
{% endblock %}
结果:
1,密码加密
import random
import string
from flask import Blueprint,render_template,request,redirect,url_for
from exts import mail,db
from flask_mail import Message
from models import EmailCaptchaModel,UserModel
from datetime import datetime
from .forms import RegisterForm
from werkzeug.security import generate_password_hash #加密包
bp=Blueprint("user",__name__,url_prefix="/user")
@bp.route("/login")
def login():
return render_template("login.html")
@bp.route("/register",methods=['GET','POST'])
def register():
if request.method =='GET':
return render_template("register.html")
else:
form = RegisterForm(request.form)
if form.validate():
email = form.email.data
username = form.username.data
password = form.password.data
hash_password=generate_password_hash(password) #密码加密
user = UserModel(email=email, username=username, password=password)
db.session.add(user)
db.session.commit()
return redirect(url_for("user.login"))
else:
return redirect(url_for("user.register"))
@bp.route("/captcha")
def get_captcha():
email=request.args.get("email")
letter=string.ascii_letters+string.digits
captcha="".join(random.sample(letter,4))
if email:
message = Message(
subject='邮箱测试',
recipients=['[email protected]'],
body=f"您的注册验证码是:{captcha},请不要告诉任何人哦!"
)
mail.send(message)
captcha_model=EmailCaptchaModel.query.filter_by(email=email).first()
if captcha_model:
captcha_model.captcha=captcha
captcha_model.create_time=datetime.now()
db.session.commit()
else:
captcha_model=EmailCaptchaModel(email=email,captcha=captcha)
db.session.add(captcha_model)
db.session.commit()
return "success"
else:
return "没有传递邮箱"
2,发送AJAX请求
import random
import string
from flask import Blueprint,render_template,request,redirect,url_for,jsonify
from exts import mail,db
from flask_mail import Message
from models import EmailCaptchaModel,UserModel
from datetime import datetime
from .forms import RegisterForm
from werkzeug.security import generate_password_hash
bp=Blueprint("user",__name__,url_prefix="/user")
@bp.route("/login")
def login():
return render_template("login.html")
@bp.route("/register",methods=['GET','POST'])
def register():
if request.method =='GET':
return render_template("register.html")
else:
form = RegisterForm(request.form)
if form.validate():
email = form.email.data
username = form.username.data
password = form.password.data
hash_password=generate_password_hash(password) #密码加密
user = UserModel(email=email, username=username, password=password)
db.session.add(user)
db.session.commit()
return redirect(url_for("user.login"))
else:
return redirect(url_for("user.register"))
@bp.route("/captcha",methods=['POST'])
def get_captcha():
email=request.form.get("email")
letter=string.ascii_letters+string.digits
captcha="".join(random.sample(letter,4))
if email:
message = Message(
subject='邮箱测试',
recipients=['[email protected]'],
body=f"您的注册验证码是:{captcha},请不要告诉任何人哦!"
)
mail.send(message)
captcha_model=EmailCaptchaModel.query.filter_by(email=email).first()
if captcha_model:
captcha_model.captcha=captcha
captcha_model.create_time=datetime.now()
db.session.commit()
else:
captcha_model=EmailCaptchaModel(email=email,captcha=captcha)
db.session.add(captcha_model)
db.session.commit()
#code:200。成功的,正常的请求
return jsonify({"code":200})
else:
#code:400 客户端错误
return jsonify({"code":400,"message":"请先传递邮箱!"})
function bindCaptchaBtnClick(){
$("#captcha-btn").on("click",function (event){
var email=$("input[name='email']").val();
if (!email){
alert("请先输入邮箱!");
return;
}
//通过js发送网络请求:ajax.
$.ajax({
url:"/user/captcha",
method:"POST",
data:{
"email":email
},
success:function (res){
var code=res['code'];
if (code==200){
alert("验证码发送成功")
}else{
alert(res['message']);
}
}
})
});
}
//等网页文档所有元素都加载完成后再执行
$(function () {
bindCaptchaBtnClick();
});
结果: