Python sqlalchemy.orm 模块,validates() 实例源码

我们从Python开源项目中,提取了以下2个代码示例,用于说明如何使用sqlalchemy.orm.validates()

项目:ozelot    作者:trycs    | 项目源码 | 文件源码
def truncate_to_field_length(self, field, value):
        """Truncate the value of a string field to the field's max length.

        Use this in a validator to check/truncate values before inserting them into the database.
        Copy the below example code after ``@validates`` to your model class and replace ``field1`` and ``field2`` with
        your field name(s).

        :Example:

            from sqlalchemy.orm import validates
            # ... omitting other imports ...

            class MyModel(base.Base):

                field1 = Column(String(128))
                field2 = Column(String(64))

                @validates('field1', 'field2')
                def truncate(self, field, value):
                    return self.truncate_to_field_length(field, value)

        Args:
            field (str): field name to validate
            value (str/unicode): value to validate

        Returns:
            str/unicode: value truncated to field max length

        """
        max_len = getattr(self.__class__, field).prop.columns[0].type.length
        if value and len(value) > max_len:
            return value[:max_len]
        else:
            return value
项目:restfulpy    作者:Carrene    | 项目源码 | 文件源码
def receive_class_instrument(cls):
    for field in cls.iter_columns(relationships=False, synonyms=False, use_inspection=False):
        if not isinstance(field, Field) or not field.can_validate:
            continue
        method_name = 'validate_%s' % field.name
        if not hasattr(cls, method_name):
            def validator(self, key, value):
                return self.get_column(key).validate(value)

            setattr(cls, method_name, validates(field.name)(validator))