定義一個基類form,用於獲取錯誤信息html
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驗證,繼承自定義的BaseFormjson
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()
視圖邏輯session
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'))
請求post