• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

Python validictory.validate函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Python中validictory.validate函数的典型用法代码示例。如果您正苦于以下问题:Python validate函数的具体用法?Python validate怎么用?Python validate使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



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

示例1: validate

def validate(value, **kwds):
  """ Validate a python value against json schema:
  validate(value, schemaPath)
  validate(value, schemaDict)

  value:          python object to validate against the schema

  The json schema may be specified either as a path of the file containing
  the json schema or as a python dictionary using one of the
  following keywords as arguments:
    schemaPath:     Path of file containing the json schema object.
    schemaDict:     Python dictionary containing the json schema object

  Returns: nothing

  Raises:
          ValidationError when value fails json validation
  """

  assert len(kwds.keys()) >= 1
  assert 'schemaPath' in kwds or 'schemaDict' in kwds

  schemaDict = None
  if 'schemaPath' in kwds:
    schemaPath = kwds.pop('schemaPath')
    schemaDict = loadJsonValueFromFile(schemaPath)
  elif 'schemaDict' in kwds:
    schemaDict = kwds.pop('schemaDict')

  try:
    validictory.validate(value, schemaDict, **kwds)
  except validictory.ValidationError as e:
    raise ValidationError(e)
开发者ID:runt18,项目名称:nupic,代码行数:33,代码来源:utils.py


示例2: test_patternproperties_nonmatch

    def test_patternproperties_nonmatch(self):
        data = { 'a': True, 'd': 'foo' }

        try:
            validictory.validate(data, self.schema)
        except ValueError as e:
            self.fail("Unexpected failure: %s" % e)
开发者ID:filod,项目名称:validictory,代码行数:7,代码来源:test_properties.py


示例3: test_format_utcmillisec_pass

    def test_format_utcmillisec_pass(self):
        data = 1294915735

        try:
            validictory.validate(data, self.schema_utcmillisec)
        except ValueError as e:
            self.fail("Unexpected failure: %s" % e)
开发者ID:Homeloc,项目名称:validictory,代码行数:7,代码来源:test_values.py


示例4: test_additionalItems_false_no_additional_items_pass

    def test_additionalItems_false_no_additional_items_pass(self):
        data = [12482, "Yes, more strings", False]

        try:
            validictory.validate(data, self.schema1)
        except ValueError, e:
            self.fail("Unexpected failure: %s" % e)
开发者ID:fvieira,项目名称:validictory,代码行数:7,代码来源:test_items.py


示例5: test_pattern_pass_nonstring

    def test_pattern_pass_nonstring(self):
        data = 123

        try:
            validictory.validate(data, self.schema)
        except ValueError as e:
            self.fail("Unexpected failure: %s" % e)
开发者ID:Homeloc,项目名称:validictory,代码行数:7,代码来源:test_values.py


示例6: test_format_date_pass

    def test_format_date_pass(self):
        data = "2011-01-13"

        try:
            validictory.validate(data, self.schema_date)
        except ValueError as e:
            self.fail("Unexpected failure: %s" % e)
开发者ID:Homeloc,项目名称:validictory,代码行数:7,代码来源:test_values.py


示例7: validate

def validate(json_object, orderly_object):
    """Validates the JSON object with an Orderly definition"""
    if type(orderly_object) in (str, unicode):
        orderly_object = parse(orderly_object)
    if type(json_object) in (str, unicode):
        json_object = json.loads(json_object)
    validictory.validate(json_object, orderly_object)
开发者ID:bboc,项目名称:orderlyjson,代码行数:7,代码来源:__init__.py


示例8: step_args_validator

def step_args_validator(node, value):
    if value:
        try:
            validictory.validate(value.split(), _STEP_ARGS_VALIDICTORY_SCHEMA)
        except Exception as err:
            raise colander.Invalid(node, _(u'Got Error: ${err}',
                                   mapping=dict(err=err)))
开发者ID:t2y,项目名称:kotti_mapreduce,代码行数:7,代码来源:views.py


示例9: validate

 def validate(self, value, model_instance):
     super(JSONField, self).validate(value, model_instance)
     if self.schema:
         try:
             validictory.validate(value, self.schema)
         except ValueError as e:
             raise self.ValidationError(e)
开发者ID:Syncano,项目名称:syncano-python,代码行数:7,代码来源:fields.py


示例10: validate

def validate(dictionary, schema_id):
    """
        Validate a dictionary using a schema.

        !! DEPRECATED !! Always return True. It just log call stack to var/log/schema.log

        :param dictionary: Dictionary to validate.
        :type dictionary: dict

        :param schema_id: Schema identifier (value of _id field in Mongo document).
        :type schema_id: str

        :returns: True if the validation succeed, False otherwise.
        WARNING: disabled, always returns True.
    """
    call_stack = ''.join(traceback.format_stack())
    schema_logger.critical(
        'call to canopsis.schema.__init__.validate: {}\n'.format(call_stack))

    # FIXIT: Look at the code under this one: we just avoid useless computation
    # while we completely remove calls to this function.
    return True

    schema = get(schema_id)

    try:
        validictory.validate(dictionary, schema, required_by_default=False)
        return True

    except validictory.ValidationError:
        return True
开发者ID:capensis,项目名称:canopsis,代码行数:31,代码来源:__init__.py


示例11: test_format_datetime_with_microseconds_pass

    def test_format_datetime_with_microseconds_pass(self):
        data = "2011-01-13T10:56:53.0438Z"

        try:
            validictory.validate(data, self.schema_datetime)
        except ValueError as e:
            self.fail("Unexpected failure: %s" % e)
开发者ID:jamesturk,项目名称:validictory,代码行数:7,代码来源:test_values.py


示例12: validate_wrap

        def validate_wrap(*args, **kwargs):
            '''
            :param args: function to accept an arbitrary number of arguments.
            :param kwargs: function to accept an arbitrary number of keyword arguments.
            '''
            params = {}
            request = None
            for arg in args:
                if type(arg) == pyramid.request.Request or type(arg) == pyramid.testing.DummyRequest:
                    try:
                        request = arg
                        params = Validator.fix_types_for_schema(schema.get('properties'), arg.GET, True)
                        if getattr(arg, 'method', 'GET') == 'POST' and len(arg.json_body) > 0:  # parse request params in POST
                            params.update(arg.json_body)
                    except ValueError:
                        raise EdApiHTTPPreconditionFailed('Payload cannot be parsed')
                    except Exception as e:
                        raise EdApiHTTPPreconditionFailed('Payload cannot be parsed')
            # validate params against schema

            try:
                validictory.validate(params, schema)

                def validated(request):
                    '''
                    Return validated parameters for this request
                    '''
                    return params
                request.set_property(validated, 'validated_params', reify=True)
            except Exception as e:
                raise EdApiHTTPPreconditionFailed(e)
            return request_handler(*args, **kwargs)
开发者ID:SmarterApp,项目名称:RDW_DataWarehouse,代码行数:32,代码来源:decorators.py


示例13: validate_geojson

def validate_geojson(test_geojson):
    geojson_types = {
        'Point': point,
        'MultiPoint': multipoint,
        'LineString': linestring,
        'MultiLineString': multilinestring,
        'Polygon': polygon,
        'MultiPolygon': multipolygon,
        'GeometryCollection': geometrycollection,
        'Feature': feature,
        'FeatureCollection': featurecollection,
    }

    if not test_geojson['type'] in geojson_types:
        raise GeoJSONValidationException('"%s" is not a valid GeoJSON type.' % test_geojson['type'])

    if test_geojson['type'] in ('Feature', 'FeatureCollection', 'GeometryCollection'):
        #
        # These are special cases that every JSON schema library
        # I've tried doesn't seem to handle properly.
        #
        _validate_special_case(test_geojson)
    else:
        try:
            validictory.validate(test_geojson, geojson_types[test_geojson['type']])
        except validictory.validator.ValidationError as error:
            raise GeoJSONValidationException(str(error))

    if test_geojson['type'] == 'Polygon':
        # First and last coordinates must be coincident
        _validate_polygon(test_geojson)

    return
开发者ID:JasonSanford,项目名称:geojsonlint.com,代码行数:33,代码来源:utils.py


示例14: test_uniqueitems_false_pass

    def test_uniqueitems_false_pass(self):
        data = [1, 1, 1]

        try:
            validictory.validate(data, self.schema_false)
        except ValueError as e:
            self.fail("Unexpected failure: %s" % e)
开发者ID:Homeloc,项目名称:validictory,代码行数:7,代码来源:test_values.py


示例15: WebSection_setObject

def WebSection_setObject(self, id, ob, **kw):
  """
    Make any change related to the file uploaded.
  """
  portal = self.getPortalObject()
  data = self.REQUEST.get('BODY')
  schema = self.WebSite_getJSONSchema()
  structure = json.loads(data)
  # 0 elementh in structure is json in json
  # 1 elementh is just signature
  structure = [json.loads(structure[0]), structure[1]]

  validictory.validate(structure, schema)

  file_name = structure[0].get('file', None)
  expiration_date = structure[0].get('expiration_date', None)

  data_set = portal.portal_catalog.getResultValue(portal_type='Data Set',
                                                  reference=id)
  if data_set is None:
    data_set = portal.data_set_module.newContent(portal_type='Data Set',
                                                 reference=id)
    data_set.publish()


  reference = hashlib.sha512(data).hexdigest()
  ob.setFilename(file_name)
  ob.setFollowUp(data_set.getRelativeUrl())
  ob.setContentType('application/json')
  ob.setReference(reference)
  if expiration_date is not None:
    ob.setExpirationDate(expiration_date)
  ob.publish()
  return ob
开发者ID:MarkTang,项目名称:erp5,代码行数:34,代码来源:extension.erp5.ShaDir.py


示例16: test_pattern_pass

    def test_pattern_pass(self):
        data = "[email protected]"

        try:
            validictory.validate(data, self.schema)
        except ValueError as e:
            self.fail("Unexpected failure: %s" % e)
开发者ID:Homeloc,项目名称:validictory,代码行数:7,代码来源:test_values.py


示例17: update_schedule

def update_schedule(username, sid, mongodb):
    '''
    Input: json schedule document with updates
    Output: Status 204 No Content, and Location with the schedule id

    Checks for valid user session. If the session checks out, the schedule
    is updated with the new values in the request. If the session is not valid,
    status 401 Unauthorized is returned.
    '''
    # Check session cookie. Returns username if matched; otherwise, None.
    session_user = request.get_cookie('session', secret=secret_key)
    if session_user:    # Do your thing, man.
        user = mongodb.users.find_one({'username': username}, {'_id': 1})
        if user:
            if session_user in [username, 'admin']:
                try:
                    # Validate json data from request.
                    validictory.validate(request.json, schedule_schema)
                    # Update schedule
                    if 'courses' not in request.json.keys():
                        # Clears all courses from schedule document if courses is
                        # not in the json object in the request.
                        request.json['courses'] = []
                    mongodb.schedules.update({'_id': ObjectId(sid)}, {'$set': request.json})
                except ValueError, error:
                    # Return 400 status and error from validation.
                    return HTTPResponse(status=400, output=error)

                response.status = 204
                response.headers['location'] = '/api/users/%s/schedules/%s' % (username, sid)
                return
            else:
                return HTTPResponse(status=401, output="You do not have permission.")
        else:
            return HTTPResponse(status=401, output="Not a valid user.")
开发者ID:nimbus154,项目名称:Bottle473,代码行数:35,代码来源:schedules.py


示例18: test_blank_true

 def test_blank_true(self):
     try:
         validictory.validate("", {"blank": True}, blank_by_default=False)
         validictory.validate("test", {"blank": True},
                              blank_by_default=False)
     except ValueError as e:
         self.fail("Unexpected failure: %s" % e)
开发者ID:Homeloc,项目名称:validictory,代码行数:7,代码来源:test_values.py


示例19: testComposeModelCommandResultForDeleteFail

    def testComposeModelCommandResultForDeleteFail(self, repoMock, *_args):
        """ Make sure we can compose a model command result message for publishing
    a failed "deleteModel" on the AMQP exchange
    """
        repoMock.getMetric.side_effect = Exception("getMetric should not have been called here")

        service = anomaly_service.AnomalyService()

        modelID = "123456abcdef"
        result = anomaly_service.ModelCommandResult(
            commandID="123", method="deleteModel", status=1, errorMessage="bad, bad, bad"
        )

        msg = service._composeModelCommandResultMessage(modelID=modelID, cmdResult=result)

        # Validate the message against its JSON schema
        schemaStream = pkg_resources.resource_stream(
            "htmengine.runtime.json_schema", "model_command_result_amqp_message.json"
        )
        jsonSchema = json.load(schemaStream)

        validictory.validate(msg, jsonSchema)

        self.assertEqual(msg.pop("method"), result.method)
        self.assertEqual(msg.pop("modelId"), modelID)
        self.assertEqual(msg.pop("commandId"), result.commandID)
        self.assertEqual(msg.pop("status"), result.status)
        self.assertEqual(msg.pop("errorMessage"), result.errorMessage)

        self.assertFalse(msg)
开发者ID:darreldonnelly,项目名称:numenta-apps,代码行数:30,代码来源:anomaly_service_test.py


示例20: test_format_time_pass

    def test_format_time_pass(self):
        data = "10:56:53"

        try:
            validictory.validate(data, self.schema_time)
        except ValueError as e:
            self.fail("Unexpected failure: %s" % e)
开发者ID:Homeloc,项目名称:validictory,代码行数:7,代码来源:test_values.py



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


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python valslider.ValSlider类代码示例发布时间:2022-05-26
下一篇:
Python valideer.parse函数代码示例发布时间:2022-05-26
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap