update from atlas
This commit is contained in:
@@ -1,15 +1,14 @@
|
||||
# BEGIN MODEL_V5
|
||||
import abc
|
||||
|
||||
|
||||
class AutoStorage: # <1>
|
||||
class AutoStorage:
|
||||
__counter = 0
|
||||
|
||||
def __init__(self):
|
||||
cls = self.__class__
|
||||
prefix = cls.__name__
|
||||
index = cls.__counter
|
||||
self.storage_name = '_{}:{}'.format(prefix, index)
|
||||
self.storage_name = '_{}#{}'.format(prefix, index)
|
||||
cls.__counter += 1
|
||||
|
||||
def __get__(self, instance, owner):
|
||||
@@ -19,41 +18,22 @@ class AutoStorage: # <1>
|
||||
return getattr(instance, self.storage_name)
|
||||
|
||||
def __set__(self, instance, value):
|
||||
setattr(instance, self.storage_name, value) # <2>
|
||||
setattr(instance, self.storage_name, value)
|
||||
|
||||
|
||||
class Validated(abc.ABC, AutoStorage): # <3>
|
||||
class Validated(abc.ABC, AutoStorage):
|
||||
|
||||
def __set__(self, instance, value):
|
||||
value = self.validate(instance, value) # <4>
|
||||
super().__set__(instance, value) # <5>
|
||||
value = self.validate(instance, value)
|
||||
super().__set__(instance, value)
|
||||
|
||||
@abc.abstractmethod
|
||||
def validate(self, instance, value): # <6>
|
||||
def validate(self, instance, value):
|
||||
"""return validated value or raise ValueError"""
|
||||
|
||||
INVALID = object()
|
||||
|
||||
class Check(Validated):
|
||||
|
||||
def __init__(self, checker):
|
||||
super().__init__()
|
||||
self.checker = checker
|
||||
if checker.__doc__ is None:
|
||||
doc = ''
|
||||
else:
|
||||
doc = checker.__doc__ + '; '
|
||||
self.message = doc + '{!r} is not valid.'
|
||||
|
||||
|
||||
def validate(self, instance, value):
|
||||
result = self.checker(value)
|
||||
if result is INVALID:
|
||||
raise ValueError(self.message.format(value))
|
||||
return result
|
||||
|
||||
|
||||
class Quantity(Validated): # <7>
|
||||
class Quantity(Validated):
|
||||
"""a number greater than zero"""
|
||||
|
||||
def validate(self, instance, value):
|
||||
if value <= 0:
|
||||
@@ -62,11 +42,19 @@ class Quantity(Validated): # <7>
|
||||
|
||||
|
||||
class NonBlank(Validated):
|
||||
"""a string with at least one non-space character"""
|
||||
|
||||
def validate(self, instance, value):
|
||||
value = value.strip()
|
||||
if len(value) == 0:
|
||||
raise ValueError('value cannot be empty or blank')
|
||||
return value # <8>
|
||||
return value
|
||||
|
||||
# END MODEL_V5
|
||||
# BEGIN MODEL_V6
|
||||
def entity(cls): # <1>
|
||||
for key, attr in cls.__dict__.items(): # <2>
|
||||
if isinstance(attr, Validated): # <3>
|
||||
type_name = type(attr).__name__
|
||||
attr.storage_name = '_{}#{}'.format(type_name, key) # <4>
|
||||
return cls # <5>
|
||||
# END MODEL_V6
|
||||
|
||||
Reference in New Issue
Block a user