teşekkür ederiz . Eğer daha SQLAlchemy belirli bir çözüm gerek ve spesifik arayüzlerini kullanarak sakıncası yoksa
ardından SQLAlchemy niteliklerini olayları yakalamak için bir uzatma mekanizması vardır. o kullanan bir doğrulayıcı şöyle görünecektir:
from sqlalchemy.orm.interfaces import AttributeExtension, InstrumentationManager
from sqlalchemy.orm import ColumnProperty
class InstallValidatorListeners(InstrumentationManager):
def post_configure_attribute(self, class_, key, inst):
"""Add validators for any attributes that can be validated."""
prop = inst.prop
# Only interested in simple columns, not relations
if isinstance(prop, ColumnProperty) and len(prop.columns) == 1:
col = prop.columns[0]
# if we have string column with a length, install a length validator
if isinstance(col.type, String) and col.type.length:
inst.impl.extensions.insert(0, LengthValidator(col.type.length))
class ValidationError(Exception):
pass
class LengthValidator(AttributeExtension):
def __init__(self, max_length):
self.max_length = max_length
def set(self, state, value, oldvalue, initiator):
if len(value) > self.max_length:
raise ValidationError("Length %d exceeds allowed %d" %
(len(value), self.max_length))
return value
Daha sonra valide istediğiniz sınıfın üzerine __sa_instrumentation_manager__ = InstallValidatorListeners
ayarlayarak bu uzantıyı kullanmak. Ayrıca, ondan türetilen tüm sınıflara uygulanmasını istiyorsanız, bunu Temel sınıfta da ayarlayabilirsiniz.
class InstallValidatorListeners(InstrumentationManager):
def post_configure_attribute(self, class_, key, inst):
"""Add validators for any attributes that can be validated."""
prop = inst.prop
# Only interested in simple columns, not relations
if isinstance(prop, ColumnProperty) and len(prop.columns) == 1:
col = prop.columns[0]
if isinstance(col.type, String) and col.type.length:
sqlalchemy.event.listen(
getattr(class_, key), 'set', LengthValidator(col.type.length), retval=True)
class ValidationError(Exception):
pass
class LengthValidator(AttributeExtension):
def __init__(self, max_length):
self.max_length = max_length
def __call__(self, state, value, oldvalue, initiator):
if len(value) > self.max_length:
raise ValidationError(
"Length %d exceeds allowed %d" % (len(value), self.max_length))
return value
masayı ve sınıfına eşleme tanımlamak için kullandığınız kodunu belirtin: Burada –
@ S.Lott MySQL, insert/update üzerindeki string uzunluğunu kontrol etmez. Çok uzun olan dizeleri sessizce keser. – codeape