sanic-wtf
sanic-wtf copied to clipboard
Async validators?
Are there any plans for supporting them?
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:
- replace
field._run_validation_chainmethod 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
- Provide our own Fields e.g. StringField, EmailField etc. and let all custom fields inherit from AsyncField instead of Field.
- In
SanicForm.validate_on_submitloop over each field inself._fields. If a field has any async validators, validate seperately. Then delete the async validators and continue with normal validation routine. - Mehhh, async validators suck...
What do you guys think?