Refactor some common FormEncode validators, plus add some more

This commit is contained in:
Lance Edgar 2016-05-06 11:38:01 -05:00
parent 691b33cad4
commit dc2104d430

View file

@ -2,7 +2,7 @@
################################################################################ ################################################################################
# #
# Rattail -- Retail Software Framework # Rattail -- Retail Software Framework
# Copyright © 2010-2015 Lance Edgar # Copyright © 2010-2016 Lance Edgar
# #
# This file is part of Rattail. # This file is part of Rattail.
# #
@ -24,53 +24,70 @@
Custom FormEncode Validators Custom FormEncode Validators
""" """
from __future__ import unicode_literals from __future__ import unicode_literals, absolute_import
from rattail.db import model from rattail.db import model
import formencode import formencode as fe
from formencode import validators
from tailbone.db import Session from tailbone.db import Session
class ValidCustomer(validators.FancyValidator): class ModelValidator(fe.validators.FancyValidator):
"""
Generic validator for data model reference fields.
"""
model_class = None
@property
def model_name(self):
self.model_class.__name__
def _to_python(self, value, state):
if value:
obj = Session.query(self.model_class).get(value)
if obj:
return obj
raise formencode.Invalid("{} not found".format(self.model_name), value, state)
class ValidStore(ModelValidator):
"""
Validator for store field.
"""
model_class = model.Store
class ValidCustomer(ModelValidator):
""" """
Validator for customer field. Validator for customer field.
""" """
model_class = model.Customer
def _to_python(self, value, state):
if not value:
return None
customer = Session.query(model.Customer).get(value)
if not customer:
raise formencode.Invalid("Customer not found", value, state)
return customer
class ValidProduct(validators.FancyValidator): class ValidDepartment(ModelValidator):
"""
Validator for department field.
"""
model_class = model.Department
class ValidEmployee(ModelValidator):
"""
Validator for employee field.
"""
model_class = model.Employee
class ValidProduct(ModelValidator):
""" """
Validator for product field. Validator for product field.
""" """
model_class = model.Product
def _to_python(self, value, state):
if not value:
return None
product = Session.query(model.Product).get(value)
if not product:
raise formencode.Invalid("Product not found", value, state)
return product
class ValidUser(validators.FancyValidator): class ValidUser(ModelValidator):
""" """
Validator for product field. Validator for user field.
""" """
model_class = model.User
def to_python(self, value, state):
if not value:
return None
user = Session.query(model.User).get(value)
if not user:
raise formencode.Invalid("User not found.", value, state)
return user