标签:格式 ber val field 逻辑 mamicode data class err
定义一个基类form,用于获取错误信息
from wtforms import Form
class BaseForm(Form):
def get_error(self):
# a = {‘aaa‘: [xxx], ‘bbb‘: [www]} a.popitem()[1][0]=xxx
message = self.errors.popitem()[1][0] # 取第一个错误的错误信息
return message
form验证,继承自定义的BaseForm
from wtforms import StringField, IntegerField
from wtforms.validators import Email, InputRequired, Length, EqualTo
from ..forms import BaseForm
class ResetpwdForm(BaseForm):
oldpwd = StringField(validators=[InputRequired(message=‘请输入密码‘), Length(6, 20, message=‘密码6~20位‘)])
newpwd = StringField(validators=[InputRequired(message=‘请输入密码‘), Length(6, 20, message=‘密码6~20位‘)])
newpwd2 = StringField(validators=[EqualTo(‘newpwd‘, message=‘两次密码不一致‘)])
class LoginForm(BaseForm):
email = StringField(validators=[InputRequired(message=‘请输入邮箱‘), Email(message=‘邮箱格式错误‘)])
password = StringField(validators=[InputRequired(message=‘请输入密码‘), Length(6, 20, message=‘密码6~20位‘)])
remember = IntegerField()
视图逻辑
class ResetPwd(views.MethodView):
decorators = [login_required] # 校验登录状态
def get(self, message=None):
return render_template(‘cms/cms_resetpwd.html‘, message=message)
def post(self):
form = ResetpwdForm(request.form)
if form.validate():
newpwd = form.newpwd.data
oldpwd = form.oldpwd.data
user = g.cms_user
if user.check_password(oldpwd):
user.password = newpwd
db.session.commit()
return jsonify({‘code‘: 200, ‘message‘: ‘修改成功‘})
else:
return jsonify({‘code‘: 400, ‘message‘: ‘旧密码错误‘})
else:
return jsonify({‘code‘: 400, ‘message‘: form.get_error()})
bp.add_url_rule(‘/resetpwd/‘, view_func=ResetPwd.as_view(‘resetpwd‘))
请求
标签:格式 ber val field 逻辑 mamicode data class err
原文地址:https://www.cnblogs.com/zhongyehai/p/11914808.html