sanic-wtf icon indicating copy to clipboard operation
sanic-wtf copied to clipboard

Async validators?

Open omarryhan opened this issue 6 years ago • 1 comments

Are there any plans for supporting them?

omarryhan avatar Dec 23 '18 18:12 omarryhan

I just looked at how this could be implemented.

On each of its fields, a form calls field.validate() which then calls field._run_validation_chain(). Unfortunately, fields weren't designed with async in mind.

At this point, I think our options are:

  1. replace field._run_validation_chain method with the one below (Not sure whether or not asyncio.gather will block here) maybe it won't even work!:
import asyncio
from wtforms.fields.core import Field


class AsyncField(Field):
    def _run_validation_chain(self, form, validators):
        async_validators = [validator for validator in validators if asyncio.iscoroutinefunction(validator)]
        # Probably shouldn't use create_task as it's py37 exclusive.
        tasks = [asyncio.create_task(async_validator(form, field)) for validator in validators]
        return asyncio.gather(*tasks) if tasks else False  # False as in no errors found
  1. Provide our own Fields e.g. StringField, EmailField etc. and let all custom fields inherit from AsyncField instead of Field.
  2. In SanicForm.validate_on_submit loop over each field in self._fields. If a field has any async validators, validate seperately. Then delete the async validators and continue with normal validation routine.
  3. Mehhh, async validators suck...

What do you guys think?

omarryhan avatar Dec 23 '18 21:12 omarryhan