[Tutor] Cannot understand object initiation

Kush Goyal kushgoyal.89 at gmail.com
Sat Oct 12 17:01:04 CEST 2013


Hi,

I am learning web development by using flask framework. The below code
is used to create a class LoginForm which inherits from the class
Form.

In the method 'validate' of class 'LoginForm' the variable 'user' is
initialized by using:

"user = User.query.filter_by ( username = self.username.data ).first() "

now this I do not understand.

Can a object be create by using a method of a class instead of the
class consturctor? I mean shouldn't it be:

user = User()

Later in the code "user.check_password(self.password.data)" is used.
So here also how can check_password be used when the object 'user' has
not been initiated using a constructor?

Also, 'User' is a class which inherits from 'db.Model'. And db is
initialized as: db = SQLAlchemy(app)

So, here is db is an object and Model is a variable of class
SQLAlchemy. Can someone please explain what is db.Model and can
SQLAlchemy.Model be used in place of db.Model?

I hope my questions are clear. Thanks in advance.

Below is the code.

Kush



from flask.wtf import Form, TextField, PasswordField, validators
from myapplication.models import User


class LoginForm(Form):
    username = TextField('Username', [validators.Required()])
    password = PasswordField('Password', [validators.Required()])

    def __init__(self, *args, **kwargs):
        Form.__init__(self, *args, **kwargs)
        self.user = None

    def validate(self):
        rv = Form.validate(self)
        if not rv:
            return False

        user = User.query.filter_by(
            username=self.username.data).first()
        if user is None:
            self.username.errors.append('Unknown username')
            return False

        if not user.check_password(self.password.data):
            self.password.errors.append('Invalid password')
            return False

        self.user = user
        return True


More information about the Tutor mailing list