Using flask wtforms validators without using a form

前端 未结 2 2082
抹茶落季
抹茶落季 2021-02-09 04:18

I\'m receiving user registration data from an iOS application and I\'d like to use the validators that come with wtforms to make sure the email and password are acceptable. How

相关标签:
2条回答
  • 2021-02-09 04:40

    Here's a little utility called Flask-Inputs that I'm working on to solve this. The goal is to allow all incoming data (forms, queries, headers, etc) to be validated with wtform validators.

    Here's how validation would work with your data:

    from flask_inputs import Inputs
    from wtforms.validators import Length, Email, ValidationError
    
    
    class RegisterInputs(Inputs):
        json = {
            'email': [Email(), unique_email],
            'username': [Length(min=3, max=15), unique_username]
        }
    
    def unique_email(form, field):
        if User.query.filter_by(email=field.data).first():
            raise ValidationError('Email is already registered.')
    
    def unique_username(form, field):
        if User.query.filter_by(username=field.data).first():
            raise ValidationError('Username is already registered.')
    
    
    @auth.route('/register', methods=['POST'])
    def register():
        inputs = RegisterInputs(request)
    
        if inputs.validate():
            user = User.register_fromJSON(request.json)
    
            db.session.add(user)
            db.session.commit()
    
            return jsonify(success=1)
        else:
            return jsonify(failure=0, errors=inputs.errors)
    
    0 讨论(0)
  • 2021-02-09 04:46

    Yes, this is entirely possible - the wtforms.Form constructor takes any MultiDict like interface (it just needs to have getlist), so you can just create an instance of werkzeug.datastructures.MultiDict from your JSON:

    data = MultiDict(mapping=request.json)
    form = YourForm(data)
    if form.validate():
        # Data is correct
    

    (assuming the field names match) and things will just work.

    0 讨论(0)
提交回复
热议问题