start implementing a validation layer, refs #215
This commit is contained in:
@ -1,4 +1,5 @@
|
||||
from abc import ABC, abstractmethod
|
||||
from owrx.property.validators import Validator
|
||||
import logging
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
@ -23,6 +24,7 @@ class Subscription(object):
|
||||
class PropertyManager(ABC):
|
||||
def __init__(self):
|
||||
self.subscribers = []
|
||||
self.validators = {}
|
||||
|
||||
@abstractmethod
|
||||
def __getitem__(self, item):
|
||||
@ -81,6 +83,9 @@ class PropertyManager(ABC):
|
||||
except Exception as e:
|
||||
logger.exception(e)
|
||||
|
||||
def setValidator(self, name, validator):
|
||||
self.validators[name] = Validator.of(validator)
|
||||
|
||||
|
||||
class PropertyLayer(PropertyManager):
|
||||
def __init__(self):
|
||||
|
42
owrx/property/validators.py
Normal file
42
owrx/property/validators.py
Normal file
@ -0,0 +1,42 @@
|
||||
from abc import ABC, abstractmethod
|
||||
|
||||
|
||||
class ValidatorException(Exception):
|
||||
pass
|
||||
|
||||
|
||||
class Validator(ABC):
|
||||
@staticmethod
|
||||
def of(x):
|
||||
if isinstance(x, Validator):
|
||||
return x
|
||||
if callable(x):
|
||||
return LambdaValidator(x)
|
||||
raise ValidatorException("Cannot create validator")
|
||||
|
||||
@abstractmethod
|
||||
def isValid(self, value):
|
||||
pass
|
||||
|
||||
|
||||
class LambdaValidator(Validator):
|
||||
def __init__(self, c):
|
||||
self.callable = c
|
||||
|
||||
def isValid(self, value):
|
||||
return self.callable(value)
|
||||
|
||||
|
||||
class NumberValidator(Validator):
|
||||
def isValid(self, value):
|
||||
return isinstance(value, int) or isinstance(value, float)
|
||||
|
||||
|
||||
class IntegerValidator(Validator):
|
||||
def isValid(self, value):
|
||||
return isinstance(value, int)
|
||||
|
||||
|
||||
class StringValidator(Validator):
|
||||
def isValid(self, value):
|
||||
return isinstance(value, str)
|
Reference in New Issue
Block a user