简体   繁体   中英

Pass an argument to a class which becomes a keyword for a function

Using WTForms with Flask and SQLAlchemy. Taking data from a username and email field and making sure it's not already in the database. Here's what I have to do right now.

class IsUnique(object):
    def __init__(self, db_field=None):
        self.db_field = db_field

    def __call__(self, form, field):
        data = field.data
        if self.db_field=='name':
            if User.query.filter_by(name=data).first() != None:
                raise ValidationError('Sorry, that username is taken.')
        if self.db_field=='email':
            if User.query.filter_by(email=data).first() != None:
                raise ValidationError(
                    'Sorry, that email address has already been registered.'
                    )

What I would like to do is to pass the db_field argument to the class instance as a string and pass it into User.query.filter_by(db_field=data . Unfortunately all I know how to do is use an if statement, which works, but is kinda cumbersome. There's gotta be a way to do this right, but I don't know how.

You can pass keyword arguments as a dict , like this:

def __call__(self, form, field):
    key = self.db_field # 'name' or 'email'
    params = { key: field.data }
    if User.query.filter_by(**params).first() != None:
        raise ValidationError('Sorry, that {} is taken.'.format(key))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM