Created
November 1, 2019 07:57
-
-
Save AbdoDabbas/54f1f0ad2312e95e5a43da7f062ef577 to your computer and use it in GitHub Desktop.
A snippet code to map pydantic validation exceptions into api model schema exception.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from pydantic import ValidationError | |
from flask_restplus_pydantic_model import MyModel | |
from flask_restplus_pydantic import ValidationsHelper | |
helper = ValidationsHelper() | |
# use this inside your api endpoint function | |
try: | |
model = MyModel(email='not_valid.email') | |
except ValidationError as ex: | |
# in flask-restplus api you do `return` instead of `raise` | |
print(helper.get_validations(ex)) | |
except Exception as e: | |
pass |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from pydantic import ValidationError | |
class ValidationsHelper(): | |
def __format_prop_name(self, loc: list) -> str: | |
prop_name = '' | |
for ti in loc: | |
tmp = '' | |
if not type(ti) is int: | |
tmp = '.' if prop_name else '' | |
tmp += ti | |
else: | |
tmp = f'[{ti}]' | |
prop_name += tmp | |
return prop_name | |
def __iterate_errors(self, errs_lst): | |
err_dict = {} | |
for err in errs_lst: | |
prop_name = self.__format_prop_name(err['loc']) | |
msg = err['msg'] | |
err_dict.update({prop_name: msg}) | |
return err_dict | |
def __extract_errors(self, ex) -> dict: | |
result = {} | |
result.update( | |
self.__iterate_errors(ex.errors()) | |
) | |
return result | |
def get_validations(self, ex: ValidationError) -> dict: | |
validations = {} | |
if not ex: | |
return validations | |
errors = self.__extract_errors(ex) | |
validations = { | |
"errors": errors, | |
"message": "Input payload validation failed" | |
} | |
return validations |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from pydantic import BaseModel, validator | |
import re | |
EMAIL_REGEX = re.compile(r'\S+@\S+\.\S+') | |
class MyModel(BaseModel): | |
email: str | |
@validator('email') | |
def validate_email(cls, val): | |
if not EMAIL_REGEX.match(val): | |
raise ValueError('email value is not a valid.') | |
return val |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment