九十三:CMS系统之cms后台登录功能
config
form
from wtforms import Form, StringField, IntegerField
from wtforms.validators import Email, InputRequired, Length
class LoginForm(Form):
email = StringField(validators=[InputRequired(message='请输入邮箱'), Email(message='邮箱格式错误')])
password = StringField(validators=[InputRequired(message='请输入密码'), Length(6, 20, message='密码6~20位')])
remember = IntegerField()
from flask import Blueprint, views, render_template, request, session, redirect, url_for
from .forms import LoginForm
from .models import CMSUser
import config
bp = Blueprint('cms', __name__, url_prefix='/cms')
@bp.route('/')
def index():
return 'cms index'
class LoginView(views.MethodView):
def get(self, message=None):
return render_template('cms/cms_login.html', message=message)
def post(self):
form = LoginForm(request.form)
if form.validate():
email = form.email.data
password = form.password.data
remember = form.remember.data
user = CMSUser.query.filter_by(email=email).first()
if user and user.check_password(password):
session[config.CMS_USER_ID] = user.id
if remember:
session.permanent = True # 有效期31天
return redirect(url_for('cms.index'))
else:
return self.get(message='邮箱或密码错误')
else:
# a = {'aaa': [xxx], 'bbb': [www]} a.popitem()[1][0]=xxx
message = form.errors.popitem()[1][0] # 取第一个错误的错误信息
return self.get(message=message)
bp.add_url_rule('/login/', view_func=LoginView.as_view('login'))
讨论群:249728408