Flask(七)——登录功能实现

import random
import string

from flask import Blueprint,render_template,request,redirect,url_for,jsonify,session
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,check_password_hash

bp=Blueprint("user",__name__,url_prefix="/user")

#实现登录功能
@bp.route("/login",method=['GET','POST'])
def login():
    if request.method=='GET':
        return render_template("login.html")
    else:
        form = LoginForm(request.form)
        if form.validate():
            email=form.email.data
            password=form.password.data
            user=UserModel.query.filter_by(email=email).first()
            if user and check_password_hash(user.password,password):
                session['user_id']=user.id
                return redirect("/")
            else:
                return redirect(url_for("user.login"))
        else:
            return redirect(url_for("user.login"))


@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":"请先传递邮箱!"})




#表单函数:
import wtforms
from wtforms.validators import length,email,EqualTo
from models import EmailCaptchaModel


class LoginForm(wtforms.Form):
    email = wtforms.StringField(validators=[email()])
    password = wtforms.StringField(validators=[length(min=6, max=20)])

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("邮箱已经存在!")


{% extends "base.html" %}

{% block title %}问答-登录{% endblock %}

{% block head %}

{% endblock %}

{% block body %}
{% endblock %}

但是如果密码与注册不匹配时,并不会提示错误消息,会使用户使用不便,所以需要改进。

import random
import string

from flask import Blueprint,render_template,request,redirect,url_for,jsonify,session,flash
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,check_password_hash

bp=Blueprint("user",__name__,url_prefix="/user")

#实现登录功能
@bp.route("/login",method=['GET','POST'])
def login():
    if request.method=='GET':
        return render_template("login.html")
    else:
        form = LoginForm(request.form)
        if form.validate():
            email=form.email.data
            password=form.password.data
            user=UserModel.query.filter_by(email=email).first()
            if user and check_password_hash(user.password,password):
                session['user_id']=user.id
                return redirect("/")
            else:
                flash("邮箱和密码不匹配!")
                return redirect(url_for("user.login"))
        else:
            flash("邮箱或密码格式错误!")
            return redirect(url_for("user.login"))
{% extends "base.html" %}

{% block title %}问答-登录{% endblock %}

{% block head %}

{% endblock %}

{% block body %}
{% for message in get_flashed_messages() %}
{{ message }}
{% endfor %}
{% endblock %}

结果:

Flask(七)——登录功能实现_第1张图片

Flask(七)——登录功能实现_第2张图片 

 

你可能感兴趣的:(flask,python,后端)