当前位置: 首页>>代码示例>>Python>>正文


Python Validator.validate方法代码示例

本文整理汇总了Python中cerberus.Validator.validate方法的典型用法代码示例。如果您正苦于以下问题:Python Validator.validate方法的具体用法?Python Validator.validate怎么用?Python Validator.validate使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在cerberus.Validator的用法示例。


在下文中一共展示了Validator.validate方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: _validate

# 需要导入模块: from cerberus import Validator [as 别名]
# 或者: from cerberus.Validator import validate [as 别名]
    def _validate(self, doc, **kwargs):
        lookup = {'act': doc['act'], 'type': doc[ITEM_TYPE]}
        use_headline = kwargs and 'headline' in kwargs
        validators = superdesk.get_resource_service('validators').get(req=None, lookup=lookup)
        for validator in validators:
            v = Validator()
            v.allow_unknown = True
            v.validate(doc['validate'], validator['schema'])
            error_list = v.errors
            response = []
            for e in error_list:
                if error_list[e] == 'required field' or type(error_list[e]) is dict:
                    message = '{} is a required field'.format(e.upper())
                elif 'min length is' in error_list[e]:
                    message = '{} is too short'.format(e.upper())
                elif 'max length is' in error_list[e]:
                    message = '{} is too long'.format(e.upper())
                else:
                    message = '{} {}'.format(e.upper(), error_list[e])

                if use_headline:
                    response.append('{}: {}'.format(doc['validate'].get('headline',
                                                                        doc['validate'].get('_id')), message))
                else:
                    response.append(message)
            return response
        else:
            return ['validator was not found for {}'.format(doc['act'])]
开发者ID:actionless,项目名称:superdesk,代码行数:30,代码来源:validate.py

示例2: test_readonly_field_first_rule

# 需要导入模块: from cerberus import Validator [as 别名]
# 或者: from cerberus.Validator import validate [as 别名]
def test_readonly_field_first_rule():
    # test that readonly rule is checked before any other rule, and blocks.
    # See #63.
    schema = {"a_readonly_number": {"type": "integer", "readonly": True, "max": 1}}
    v = Validator(schema)
    v.validate({"a_readonly_number": 2})
    # it would be a list if there's more than one error; we get a dict
    # instead.
    assert "read-only" in v.errors["a_readonly_number"][0]
开发者ID:nicolaiarocci,项目名称:cerberus,代码行数:11,代码来源:test_validation.py

示例3: test_callable_validator

# 需要导入模块: from cerberus import Validator [as 别名]
# 或者: from cerberus.Validator import validate [as 别名]
def test_callable_validator():
    """
    Validator instance is callable, functions as a shorthand
    passthrough to validate()
    """
    schema = {"test_field": {"type": "string"}}
    v = Validator(schema)
    assert v.validate({"test_field": "foo"})
    assert v({"test_field": "foo"})
    assert not v.validate({"test_field": 1})
    assert not v({"test_field": 1})
开发者ID:nicolaiarocci,项目名称:cerberus,代码行数:13,代码来源:test_validation.py

示例4: max_min_length_example

# 需要导入模块: from cerberus import Validator [as 别名]
# 或者: from cerberus.Validator import validate [as 别名]
def max_min_length_example():
    """对于字符串项, 可以限制字符串的长度。
    """
    schema = {"password": {"type": "string", "minlength": 8, "maxlength": 20}}
    v = Validator(schema)
    
    print(v.validate({"password": "123456"}))
    print(v.errors)

    print(v.validate({"password": "abcdefghijklmnopqrstuvwxyz"}))
    print(v.errors)
开发者ID:MacHu-GWU,项目名称:Learn-Cerberus,代码行数:13,代码来源:lsn01_quickstart.py

示例5: regex_example

# 需要导入模块: from cerberus import Validator [as 别名]
# 或者: from cerberus.Validator import validate [as 别名]
def regex_example():
    """对字符串进行正则匹配验证。
    """
    email_regex ="([a-z0-9!#$%&'*+\/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+\/=?^_`{|}~-]+)*(@|\sat\s)(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?(\.|\sdot\s))+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?)" 
    schema = {"email": {"type": "string", "regex": email_regex}}
    v = Validator(schema)
    
    print(v.validate({"email": "[email protected]"}))
    
    print(v.validate({"email": "123456"}))
    print(v.errors)
开发者ID:MacHu-GWU,项目名称:Learn-Cerberus,代码行数:13,代码来源:lsn01_quickstart.py

示例6: allow_unknown_example

# 需要导入模块: from cerberus import Validator [as 别名]
# 或者: from cerberus.Validator import validate [as 别名]
def allow_unknown_example():
    """默认需要data中所有的key都要在schema中被预定义。而设置allow_unknown = True可以允许出现
    没有被预定义的key
    """
    schema = {"name": {"type": "string", "maxlength": 10}}
    v = Validator(schema)
    print(v.validate({"name": "john", "sex": "M"}))
    print(v.errors)
    
    v.allow_unknown = True
    print(v.validate({"name": "john", "sex": "M"}))
开发者ID:MacHu-GWU,项目名称:Learn-Cerberus,代码行数:13,代码来源:lsn01_quickstart.py

示例7: function_based_custom_validators

# 需要导入模块: from cerberus import Validator [as 别名]
# 或者: from cerberus.Validator import validate [as 别名]
def function_based_custom_validators():
    """以函数的方式自定义你的validator
    """
    def validate_oddity(field, value, error):
        if not bool(value & 1):
            error(field, "Must be an odd number")
            
    schema = {"oddity": {"validator": validate_oddity}}
    v = Validator(schema)
    print(v.validate({"oddity": 10}))
    print(v.errors)
    
    print(v.validate({"oddity": 9}))
开发者ID:MacHu-GWU,项目名称:Learn-Cerberus,代码行数:15,代码来源:lsn02_custom_validator.py

示例8: max_min_example

# 需要导入模块: from cerberus import Validator [as 别名]
# 或者: from cerberus.Validator import validate [as 别名]
def max_min_example():
    """对于数值项, 可以限制其最大值和最小值。
    """
    schema = {"value": {"type": "number", "min": 0, "max": 1}}
    v = Validator(schema)
    
    print(v.validate({"value": 1.5}))
    
    print(v.validate({"value": -0.5}))
    print(v.errors)
    
    print(v.validate({"value": 1.5}))
    print(v.errors)
开发者ID:MacHu-GWU,项目名称:Learn-Cerberus,代码行数:15,代码来源:lsn01_quickstart.py

示例9: allowed_example

# 需要导入模块: from cerberus import Validator [as 别名]
# 或者: from cerberus.Validator import validate [as 别名]
def allowed_example():
    """对list中的值的取值进行限制。
    
    我们可以通过设定::
    
        "allowed": [item1, item2, ...]
        
    使得list中的值必须是allowed中的元素
    """
    schema = {"role": {"type": "list", "allowed": ["agent", "client", "supplier"]}}
    v = Validator(schema)
    
    print(v.validate({"role": ["agent", "supplier"]}))
    print(v.validate({"role": ["agent", "boss"]}))
    print(v.errors)
开发者ID:MacHu-GWU,项目名称:Learn-Cerberus,代码行数:17,代码来源:lsn01_quickstart.py

示例10: test_readonly_field_first_rule

# 需要导入模块: from cerberus import Validator [as 别名]
# 或者: from cerberus.Validator import validate [as 别名]
def test_readonly_field_first_rule():
    # test that readonly rule is checked before any other rule, and blocks.
    # See #63.
    schema = {
        'a_readonly_number': {
            'type': 'integer',
            'readonly': True,
            'max': 1
        }
    }
    v = Validator(schema)
    v.validate({'a_readonly_number': 2})
    # it would be a list if there's more than one error; we get a dict
    # instead.
    assert 'read-only' in v.errors['a_readonly_number'][0]
开发者ID:peterdemin,项目名称:cerberus,代码行数:17,代码来源:test_validation.py

示例11: validate

# 需要导入模块: from cerberus import Validator [as 别名]
# 或者: from cerberus.Validator import validate [as 别名]
    def validate(self):

        """
        Validates the action_block based on the cerberus schema
        example:
        action_block :: sample ::
        - name: manipulate_inventory
          type: shell
          path: /tmp/shellscripts
          actions:
            - thisisshell.sh
        """

        schema = {
            'name': {'type': 'string', 'required': True},
            'type': {
                'type': 'string',
                'allowed': ['shell', 'subprocess']
            },
            'path': {'type': 'string', 'required': False},
            'context': {'type': 'boolean', 'required': False},
            'actions': {
                'type': 'list',
                'schema': {'type': 'string'},
                'required': True
            }
        }

        v = Validator(schema)
        status = v.validate(self.action_data)

        if not status:
            raise HookError("Invalid Syntax: {0}".format(str(v.errors)))
        else:
            return status
开发者ID:CentOS-PaaS-SIG,项目名称:linch-pin,代码行数:37,代码来源:subprocess_action_manager.py

示例12: validate

# 需要导入模块: from cerberus import Validator [as 别名]
# 或者: from cerberus.Validator import validate [as 别名]
 def validate(self):
     # pdb.set_trace()
     v = Validator(self.schema)
     status = v.validate(self.result)
     if not status:
         return v.errors
     return None
开发者ID:Msms-NJ,项目名称:zual,代码行数:9,代码来源:admin.py

示例13: allowed_for_single_value

# 需要导入模块: from cerberus import Validator [as 别名]
# 或者: from cerberus.Validator import validate [as 别名]
def allowed_for_single_value():
    """对于值进行限制, 只能使预定义的几个值中的一个。
    """
    schema = {"label": {"type": "integer", "allowed": [1, 2, 3]}}
    v = Validator(schema)
    
    print(v.validate({"label": 1}))
开发者ID:MacHu-GWU,项目名称:Learn-Cerberus,代码行数:9,代码来源:lsn01_quickstart.py

示例14: validate_filter

# 需要导入模块: from cerberus import Validator [as 别名]
# 或者: from cerberus.Validator import validate [as 别名]
    def validate_filter(filter):
        for key, value in filter.items():
            if '*' not in allowed and key not in allowed:
                return "filter on '%s' not allowed" % key

            if key in ('$or', '$and', '$nor'):
                if not isinstance(value, list):
                    return "operator '%s' expects a list of sub-queries" % key
                for v in value:
                    if not isinstance(v, dict):
                        return "operator '%s' expects a list of sub-queries" \
                            % key
                    r = validate_filter(v)
                    if r:
                        return r
            else:
                if config.VALIDATE_FILTERS:
                    res_schema = config.DOMAIN[resource]['schema']
                    if key not in res_schema:
                        return "filter on '%s' is invalid"
                    else:
                        field_schema = res_schema.get(key)
                        v = Validator({key: field_schema})
                        if not v.validate({key: value}):
                            return "filter on '%s' is invalid"
                        else:
                            return None
开发者ID:idserge7,项目名称:eve,代码行数:29,代码来源:utils.py

示例15: put

# 需要导入模块: from cerberus import Validator [as 别名]
# 或者: from cerberus.Validator import validate [as 别名]
    def put(self, request, *args, **kwargs):
        team_info = json.loads(request.body.decode('utf-8'))

        validator = Validator(team_schema)
        if not validator.validate(team_info):
            return JsonResponse({'error': validator.errors})

        try:
            team = Team.objects.get(id=int(self.kwargs['team_id']))
        except ObjectDoesNotExist:
            return JsonResponse({'error': [{"Team ID": "Team not found for ID in request"}]})

        check_scope(request, team)

        report = team.report_set.first()
        if 'send_time' in team_info:
            report.survey_send_time = parser.parse(team_info['send_time']).replace(second=0, microsecond=0)
        if 'summary_time' in team_info:
            report.summary_send_time = parser.parse(team_info['summary_time']).replace(second=0, microsecond=0)
        if 'days_of_week' in team_info:
            rule = recurrence.Rule(recurrence.WEEKLY, byday=team_info['days_of_week'])
            rec = recurrence.Recurrence(rrules=[rule])
            report.recurrences = rec
        if 'name' in team_info:
            team.name = team_info['name']
        report.save()

        try:
            team.save()
        except IntegrityError:
            return JsonResponse({'error': {"name": _("team with this name already exists")}})

        team_dict = model_to_dict(team, exclude=['users'])
        team_dict['report'] = self.report_dict(team)
        return JsonResponse({'team': team_dict})
开发者ID:agilentia,项目名称:teamreporter,代码行数:37,代码来源:views.py


注:本文中的cerberus.Validator.validate方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。