Fix: Verify string lengths when creating model objects

This commit is contained in:
Marcus Lindvall 2019-11-20 00:04:37 +01:00
parent 144fdbefb1
commit 1a7ada9d56
2 changed files with 28 additions and 20 deletions

View file

@ -1,5 +1,4 @@
from sqlalchemy.ext.instrumentation import InstrumentationManager
# from sqlalchemy.orm.interfaces import AttributeExtension
from sqlalchemy.orm import ColumnProperty
from sqlalchemy.types import String
from sqlalchemy import event
@ -28,18 +27,17 @@ class JeevesDBError(Error):
self.message = message
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, create a length validator listner
if isinstance(col.type, String) and col.type.length:
event.listen(
getattr(class_, key), 'set', LengthValidator(
col.name, col.type.length), retval=True)
def install_validator_listner(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, create a length validator listner
if isinstance(col.type, String) and col.type.length:
event.listen(
getattr(class_, key), 'set', LengthValidator(
col.name, col.type.length), retval=True)
class LengthValidator():
@ -51,5 +49,6 @@ class LengthValidator():
if len(value) > self.max_length:
raise ValidationError(
"%s.%s: Length %d exceeds allowed %d" % (
state.__class__.__name__, self.col_name, len(value), self.max_length))
state.__class__.__name__, state.__class__._map_columns(self.col_name),
len(value), self.max_length))
return value