如何验证字段并获得验证输出

2024-10-01 09:35:15 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图验证模型中的值,并将验证后的值作为输出。文档中唯一的例子是下面的代码,它没有显示这是如何完成的,所以我无法对其进行扩展。你知道吗

>>> from schematics.models import Model
>>> from schematics.types import StringType, BooleanType
>>> from schematics.exceptions import ValidationError
>>>
>>> class Signup(Model):
...     name = StringType()
...     call_me = BooleanType(default=False)
...     def validate_call_me(self, data, value):
...         if data['name'] == u'Brad' and data['call_me'] is True:
...             raise ValidationError(u'He prefers email.')
...         return value
...
>>> Signup({'name': u'Brad'}).validate()
>>> Signup({'name': u'Brad', 'call_me': True}).validate()
Traceback (most recent call last):
...
ModelValidationError: {'call_me': [u'He prefers email.']}

我做了一个版本,但是从参数中删除了datavalueClient是我的模型的名称。因此,当我执行以下操作时,我会得到所需的结果作为输出:

client.validate_client(client.to_native())

但是

  • 首先,这似乎不是一个干净的方式。client已经有了所有的值,所以我不需要这样做。

  • 另外,我想让它作为验证的结果来更新client的值。

在第一部分,我做了以下几行:

def validate_client(self):
    data = self.to_native()

    ...

    return data

但我不认为这是最好的方法,我也不确定更新值的第二个问题。有办法吗?你知道吗

编辑:

这是我的代码,我希望雇主的client值设置为'unspecified',client full_name设置为函数中指定的值。你知道吗

class LowerCaseEmailType(EmailType):

    def convert(self, value, context=None):
        value = super(LowerCaseEmailType, self).convert(value, context)
        return value.lower()


class CleanedStringType(StringType):
    converters = []

    def __init__(self, **kwargs):
        """
        This takes in all the inputs as String Type, but takes in an extra
        input called converters.
        Converters must be a list of functions, and each of those functions
        must take in exactly 1 value , and return the transformed input
        """
        if 'converters' in kwargs:
            self.converters = kwargs['converters']
        del kwargs['converters']
        super(CleanedStringType, self).__init__(**kwargs)

    def convert(self, value, context=None):
        value = super(CleanedStringType, self).convert(value, context)
        for func in self.converters:
            value = func(value)
        return value  # will have a value after going through all the conversions in order


class Client(Model):
    """
    Client Model
    """
    first_name = CleanedStringType(required=False,
                                   converters=[lambda x: re.sub(r"[!@#$%&\(\)\^]+", ' ', x),
                                               lambda x: x.strip()])
    last_name = CleanedStringType(required=False,
                                  converters=[lambda x: re.sub(r"[!@#$%&\(\)\^]+", ' ', x),
                                              lambda x: x.strip()])
    full_name = CleanedStringType(required=False,  
                                  converters=[lambda x: re.sub(r"[!@#$%&\(\)\^]+", ' ', x),
                                              lambda x: x.strip()])
    employer = StringType(required=False)
    created = StringType(default=" ")    
    updated = StringType(default=" ")     
    email = LowerCaseEmailType(required=False)

    def validate_client(self):
        data = self.to_native()

        if data.get('first_name') and data.get('last_name'):
            data['full_name'] = ' '.join([data['first_name'], data['last_name']])

        if data.get('full_name') is None:
            if data.get('first_name') is None:
                error_message = 'first name missing'
            else:
                error_message = 'last name missing'
            logger.error('info: {} for {}'.format(error_message, data))
            raise ValidationError(error_message)

        if data.get('employer') is None:
            logger.warning('info: employer missing for {}'.format(data))
            data['employer'] = 'unspecified'

        return data

Tags: nameinselfclientfalsedatareturnif
1条回答
网友
1楼 · 发布于 2024-10-01 09:35:15

我想你想要^{}。当您设置一个模型的值(code有问题)时,它用值调用。你知道吗

对于雇主,我想你应该设置一个默认值。在我看来,这一切都是你想要的。你知道吗

我认为fullname不应该出现在模型上,因为在firstname + lastname != fullname中可能有不一致的数据。如果以后需要它,可以通过^{}实现。你知道吗

相关问题 更多 >