[Python] Field validator calls a parser - how to save the parsed value?

Discussão em 'Python' iniciado por Stack, Julho 2, 2025.

  1. Stack

    Stack Membro Participativo

    A form has a field. The field has a validator. The validator calls a parser. If and only if the parsing succeeds, the validation is successful.

    However, later I have to call the parser again to get the parsed value. How can I avoid this duplication? Should I attach the result to the field object as a new attribute?

    Simplified Flask code:

    def data_validator(form, field):
    try:
    result = parse(field.data) # <-- first parser call, but the result will be lost
    except Exception as err:
    raise ValidationError(f"Invalid data: {err}") from None

    class DataForm(FlaskForm):
    datafield = wtf.fields.StringField('Enter data', validators=[data_validator])
    ...

    @app.post('/some/url')
    def view_function():
    form = DataForm()
    if form.validate_on_submit():
    result = parse(form.datafield.data) # <-- second parser call
    ...

    Continue reading...

Compartilhe esta Página