使用Flask从WTForm进行电子邮件验证

时间:2014-08-15 09:25:43

标签: python validation email flask-wtforms

我正在关注来自http://code.tutsplus.com/tutorials/intro-to-flask-adding-a-contact-page--net-28982的Flask教程,目前我已停留在验证步骤中:

旧版本有以下内容:

from flask.ext.wtf import Form, TextField, TextAreaField, SubmitField, validators, ValidationError

class ContactForm(Form):
name = TextField("Name",  [validators.Required("Please enter your name.")])
email = TextField("Email",  [validators.Required("Please enter your email address."), validators.Email("Please enter your email address.")])
submit = SubmitField("Send")

阅读评论我将其更新为:(用InputRequired替换validators.Required)

(same fields)  

class ContactForm(Form):  
name = TextField("Name", validators=[InputRequired('Please enter your name.')])
email = EmailField("Email",  validators=[InputRequired("Please enter your email address.")]), validators.Email("Please enter your email address.")])
submit = SubmitField("Send")

我唯一的问题是我不知道如何处理validators.Email。我得到的错误信息是:

NameError: name 'validators' is not defined

我查看了文档,或许我没有深入研究,但我似乎无法找到电子邮件验证的示例。

6 个答案:

答案 0 :(得分:25)

试试这个:

from flask.ext.wtf import Form
from wtforms import validators
from wtforms.fields.html5 import EmailField

class ContactForm(Form):
    email = EmailField('Email address', [validators.DataRequired(), validators.Email()])

答案 1 :(得分:5)

我通过相同的教程作为复习(我几年没有看过烧瓶)。

问题是由于Flask-WTF在0.9版本上发生了变化。 Here,他们说:

  

注意:从版本0.9.0开始,Flask-WTF将不会导入任何内容   wtforms,你需要从wtforms导入字段。

要直接导入,forms.py应为:

from flask.ext.wtf import Form
from wtforms import StringField, TextAreaField, SubmitField
from wtforms.validators import InputRequired, Email

class ContactForm(Form):
  name = StringField("Name",  [InputRequired("Please enter your name.")])
  email = StringField("Email",  [InputRequired("Please enter your email address."), Email("This field requires a valid email address")])
  subject = StringField("Subject",  [InputRequired("Please enter a subject.")])
  message = TextAreaField("Message",  [InputRequired("Not including a message would be stupid")])
  submit = SubmitField("Send")

请注意StringField取代TextFieldInputRequired is preferred over DataRequired。在导入整个命名空间时直接导入验证器是个人偏好。这也有效:from wtforms import *,格式为:name = StringField("Name", [validators.InputRequired("message")

在更新到最新版本的Flask-WTF时,您也可以在视图中使用validate_on_submit()as recommended here)。

  

方便验证validate_on_submit将检查它是否是POST   请求,如果有效。

答案 2 :(得分:1)

此错误的原因是您很可能使用from foo import bar import语句导入了没有命名空间的验证程序。

为了使其更具可读性并修复示例代码中的语法错误:

from flask.ext.wtf import Form
from wtforms import TextField, SubmitField
from wtforms.validators import InputRequired, Email
from wtforms.fields.html5 import EmailField  

class ContactForm(Form):  
    name = TextField("Name", validators=[InputRequired('Please enter your name.')])
    email = EmailField("Email",  validators=[InputRequired("Please enter your email address."), Email("Please enter your email address.")])
    submit = SubmitField("Send")

仅在TextFieldSubmitFieldEmail字段以及InputRequiredEmail验证程序中加载。然后简单地将validators关键字参数中的验证器链接起来就可以了。或者,正如@Mehdi Sadeghi在代码中指出的那样,直接提供验证器列表作为该字段的第二个参数,在这种情况下,您的电子邮件字段将如下所示:

email = EmailField("Email", [InputRequired("Please enter your email address."), Email("Please enter your email address.")])

请注意,通过使用语法from foo import bar仅导入所需内容,您将丢弃模块命名空间,因为您在删除validators.前缀时也注意到了。有些人发现离开这个命名空间更好,因此使用点表示法,只是为了防止可能的名称冲突,并立即看到一个对象属于哪个模块(无需回头查看导入语句)。

一如既往的选择是你的!

答案 3 :(得分:1)

  from flask_wtf import FlaskForm from wtforms import StringField, PasswordField, BooleanField, SubmitField 
  from wtforms.fields.html5 import EmailField 
  from wtforms.validators import DataRequired, Email

  class LoginForm(FlaskForm):
      username = StringField('Username', validators=[DataRequired()])
      email = EmailField('Email Address', validators=[DataRequired()])
      password = PasswordField('Password', validators=[DataRequired(), Email()])
      remember_me = BooleanField('Remember me')
      submit = SubmitField('Sign In')

答案 4 :(得分:1)

# Define a function

def parse_file():
    users = []
    filename = "auth.log"
    file = open(filename, 'r')
    string = "invalid user"

# Parsing auth.log file, detect invalid users, sort them and return the result

    for i in file:
        i = i.lower()
        pos = i.find(string)
        if pos >= 0:
            index = pos + len(string) + 1
            user = i[index:].split(" ")[0]
            users.append(user)
    users.sort()
    return users


if __name__ == "__main__":
    print(parse_file( ))

答案 5 :(得分:0)

只需使用 pip 安装 email_validator 例如

pip install email_validator