public
Created

Flask login with wtfoms validation

  • Download Gist
gistfile1.txt
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43
class LoginForm(flask_wtf.Form):
"""
Validate login from
"""
email_validator = [flask_wtf.Required()]
pwd_validator = [flask_wtf.Required(), flask_wtf.Length(2)]
 
email = flask_wtf.TextField(u'email', validators=email_validator)
password = flask_wtf.PasswordField(u'password', validators=pwd_validator)
submit = flask_wtf.SubmitField("Login")
 
def _get_user(self, email):
return mongo.db.users.find_one({'email': email})
 
def validate_email(self, field):
if not self._get_user(field.data):
raise flask_wtf.ValidationError("Invalid email")
 
def validate_password(self, field):
user = self._get_user(self.email.data)
if user and user[u'password'] != field.data:
raise flask_wtf.ValidationError("Invalid password")
 
 
class Login(MethodView):
 
def __init__(self):
self.form = LoginForm()
 
def get(self):
return flask.render_template('login.html', login_form=self.form)
 
def post(self):
if self.form.validate():
flask.session['user'] = self.form.email.data
flask.flash('You were logged in')
return flask.redirect(flask.url_for("index"))
return flask.render_template('login.html', login_form=self.form)
 
 
app.add_url_rule('/login',
view_func=Login.as_view('login'),
methods=['POST', 'GET'])

You cannot do this
def init(self):
self.form = LoginForm()

is out of the scope of working applicatoin contextg

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.