我在python应用程序中使用flask。我在过去的两天里遇到了一个奇怪的问题,我的代码没有做任何改动。我的登录信息会将我重定向回我的登录页面,因为函数 form.validate_on_submit()返回false。当我调试时,我发现下面的函数是成功的假。此功能存在于 wtforms / form.py
中def validate(self, extra_validators=None):
"""
Validates the form by calling `validate` on each field.
:param extra_validators:
If provided, is a dict mapping field names to a sequence of
callables which will be passed as extra validators to the field's
`validate` method.
Returns `True` if no errors occur.
"""
self._errors = None
success = True
for name, field in iteritems(self._fields):
if extra_validators is not None and name in extra_validators:
extra = extra_validators[name]
else:
extra = tuple()
if not field.validate(self, extra):
success = False
return success
这就是我的forms.py类看起来像
from wtforms import StringField, BooleanField, PasswordField, validators, ValidationError, HiddenField
from flask_wtf import Form
class RedirectForm(Form):
ref = HiddenField()
def __init__(self, *args, **kwargs):
Form.__init__(self, *args, **kwargs)
if not self.ref.data:
self.ref.data = get_redirect_target() or ''
def redirect(self, endpoint='index', **values):
if is_safe_url(self.ref.data):
return redirect(self.ref.data)
target = get_redirect_target()
return redirect(target or url_for(endpoint, **values))
class LoginForm(RedirectForm):
email = StringField('Email', [
validators.DataRequired(),
validators.Email('Invalid Email Address')
])
password = PasswordField('Password', [
validators.DataRequired()
])
def validate(self):
if not Form.validate(self):
return False
user = User.query.filter_by(email=self.email.data.lower()).first()
if user and user.check_password(self.password.data):
self.user = user
return True
else:
self.email.errors.append("Invalid e-mail or password")
return False
def get_user(self):
return self.user
使用Flask-WTF版本0.10.3和WTForms版本2.0.1。如果我在forms.py类中注释掉Form.validate(self)函数,它可以工作,但我将冒着我的网站安全风险。这应该是什么问题?毫无头绪。