moving validators

This commit is contained in:
Samuel Colvin
2017-05-05 18:17:50 +01:00
parent 7254ddc5e6
commit 35953d20ef
4 changed files with 6 additions and 82 deletions
+1 -1
View File
@@ -9,7 +9,7 @@ Data validation and settings management using python 3.6 type hinting.
TODO:
* datetime types
* datetime types, enums
* other types: regex, email field
* exotic typing: Union, List, Dict
* more info: alt names and descriptions
+2 -79
View File
@@ -1,87 +1,10 @@
import inspect
from collections import OrderedDict
from enum import IntEnum
from pathlib import Path
from typing import Any, Callable, List, Optional, Type
from typing import Any, Callable, List, Type
from .exceptions import ConfigError
NoneType = type(None)
def not_none_validator(v):
if v is None:
raise TypeError('None is not an allow value')
return v
def str_validator(v) -> str:
if isinstance(v, (str, NoneType)):
return v
elif isinstance(v, bytes):
return v.decode()
return str(v)
def bytes_validator(v) -> bytes:
if isinstance(v, (bytes, NoneType)):
return v
return str_validator(v).encode()
BOOL_STRINGS = {
'1',
'TRUE',
'ON',
}
def bool_validator(v) -> bool:
if isinstance(v, bool):
return v
if isinstance(v, bytes):
v = v.decode()
if isinstance(v, str):
return v.upper() in BOOL_STRINGS
return bool(v)
def number_size_validator(v, m):
if m.config.min_number_size <= v <= m.config.max_number_size:
return v
raise ValueError(f'size not in range {m.config.min_number_size} to {m.config.max_number_size}')
def anystr_length_validator(v, m):
if v is None or m.config.min_anystr_length <= len(v) <= m.config.max_anystr_length:
return v
raise ValueError(f'length not in range {m.config.max_anystr_length} to {m.config.max_anystr_length}')
def dict_validator(v) -> dict:
if isinstance(v, dict):
return v
return dict(v)
VALIDATORS_LOOKUP = {
int: [int, number_size_validator],
float: [float, number_size_validator],
bool: [bool_validator],
Path: [Path],
# TODO could do this better by detecting option Unions, removing not_none_validator and dealing with it directly
Optional[str]: [str_validator, anystr_length_validator],
str: [not_none_validator, str_validator, anystr_length_validator],
Optional[bytes]: [bytes_validator, anystr_length_validator],
bytes: [not_none_validator, bytes_validator, anystr_length_validator],
dict: [not_none_validator, dict_validator]
# TODO list, List, Dict, Union, datetime, date, time, custom types
}
from .validators import VALIDATORS_LOOKUP
class ValidatorSignature(IntEnum):
+2 -1
View File
@@ -2,7 +2,8 @@ from collections import OrderedDict
from types import FunctionType
from .exceptions import ValidationError
from .fields import Field, dict_validator
from .fields import Field
from .validators import dict_validator
class BaseConfig:
+1 -1
View File
@@ -1,7 +1,7 @@
from typing import Optional, Type
from .fields import str_validator
from .utils import import_string, make_dsn
from .validators import str_validator
__all__ = [
'NoneStr',