Python 使用 Flask 从 WTForm 验证电子邮件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25324113/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 20:03:11  来源:igfitidea点击:

Email Validation from WTForm using Flask

pythonvalidationemailflask-wtforms

提问by lost9123193

I'm following a Flask tutorial from http://code.tutsplus.com/tutorials/intro-to-flask-adding-a-contact-page--net-28982and am currently stuck on the validation step:

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

The old version had the following:

旧版本有以下内容:

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")

Reading the comments I updated it to this: (replaced validators.Required with InputRequired)

阅读评论我将其更新为:(用 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")

My only issue is I don't know what to do with the validators.Email. The error message I get is:

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

NameError: name 'validators' is not defined

I've looked over the documentation, perhaps I didn't delve deep enough but I can't seem to find an example for email validation.

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

回答by Mehdi Sadeghi

Try this:

尝试这个:

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()])

回答by Timusan

The reason for this error is that you most likely imported the validators without namespace, using from foo import barimport statements.

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

To make it a bit more readable and to fix the syntax errors in your example code:

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

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")

This only loads in the fields TextField, SubmitFieldand Emailas well as only the InputRequiredand Emailvalidators. Then simply chain the validators in your validatorskeyword argument and you are good to go. Or, as @Mehdi Sadeghi pointed out in the code, directly supply a list of validators as the second argument to the field, in which case your email field would look like this:

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

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

Note that by importing only what you need using the syntax from foo import baryou are throwing away the modules namespace, as you also have noticed when you dropped the validators.prefix. Some find it better to leave this namespace, and thus use the dot notation, simply to prevent possible name clashes and to see right away to which module an object belongs (without needing to look back at the import statements).

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

The choice, as always, is yours!

一如既往,选择权在您!

回答by cstrutton

I worked through the same tutorial as a refresher (I hadn't looked at flask for a couple years).

我完成了与复习相同的教程(我已经有几年没有看过烧瓶了)。

The problem is due yo a change in Flask-WTF at version 0.9. Here, they say:

问题是由于在 0.9 版中 Flask-WTF 发生了变化。 在这里,他们说:

Note: From version 0.9.0, Flask-WTF will not import anything from wtforms, you need to import fields from wtforms.

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

To import directly, forms.py should read:

要直接导入,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")

Note that StringFieldreplaces TextFieldand that InputRequiredis preferred overDataRequired. It was personal preference to import the validators directly over importing the entire namespace. This also works: from wtforms import *and in the form class: name = StringField("Name", [validators.InputRequired("message")

请注意,StringField替换TextFieldInputRequired优先于DataRequired. 直接导入验证器而不是导入整个命名空间是个人偏好。这也有效:from wtforms import *并且在表单类中:name = StringField("Name", [validators.InputRequired("message")

While your updating to the latest version of Flask-WTF you might as well use validate_on_submit()in your view as well (as recommended here).

当您更新到最新版本的 Flask-WTF 时,您也可以validate_on_submit()在您的视图中使用(如此处推荐的那样)。

And the convenience validate_on_submit will check if it is a POST request and if it is valid.

并且方便的 validate_on_submit 将检查它是否是一个 POST 请求以及它是否有效。

回答by J11

  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')

回答by Durgaprasad Nagarkatte

from flask_wtf import FlaskForm
from wtforms import StringField
from wtforms.validators import DataRequired, Email

class ContactForm(FlaskForm):  
    name = StringField("Name", validators=[DataRequired()])
    email = StringField("Email",  validators=[DataRequired(), Email()])
    submit = SubmitField("Send")