AndiLeni
AndiLeni

Reputation: 500

PonyORM - Set field value programatically

I have a User class which has the following structure:

class User(UserMixin, db.Entity):
    id = PrimaryKey(int, auto=True)
    vorname = Required(str)
    nachname = Required(str)
    email = Required(str)
    password_hash = Required(str)
    role = Required(str)

    def set_password_hash(self, password):
        self.password_hash = generate_password_hash(password)

    def check_password(self, password):
        return check_password_hash(self.password_hash, password)

Unfortunately, creating a User object which is then automatically stored in the database is not possible, since I only get the raw password field value from the webform.

with db_session:
    new_user = User(
        vorname=form.vorname.data,
        nachname=form.nachname.data,
        email=form.email.data,
        role=form.role.data,
    )
    new_user.set_password_hash(form.password.data) # this line is not called, since the creation of new_user fails because of the missing password field.

Is it possible to defer saving to the database? Or using my custom function to set the password_hash value?

Upvotes: 1

Views: 88

Answers (1)

Christian Macht
Christian Macht

Reputation: 466

I just faced something similar, also using Flask-Login and pony.

You can of course use password_hash = Optional(str) but if you don't want this, you might consider overriding the models __init__, giving it a plain password and then generate the hash before passing it on:

def __init__(self, *args, password, **kwargs):
    kwargs['password_hash'] = generate_password_hash(password)
    super().__init__(*args, **kwargs)

In your example you could then simply call it like this:

new_user = User(
        vorname=form.vorname.data,
        nachname=form.nachname.data,
        email=form.email.data,
        role=form.role.data,
        password=form.password.data,
    )

Upvotes: 0

Related Questions