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


Python schema.Schema方法代码示例

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


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

示例1: mobile_b2c

# 需要导入模块: import schema [as 别名]
# 或者: from schema import Schema [as 别名]
def mobile_b2c(self, product_name, consumers, callback=None):

        reasons = PaymentService.REASON.values()
        schema = Schema([
            {
                'name': And(str, len),
                'phoneNumber': And(str, lambda s: validate_phone(s)),
                'currencyCode': And(str, lambda s: len(s) == 3),
                'amount': And(lambda f: float(f) > 0),
                Optional('providerChannel'): And(str, len),
                Optional('reason'): And(str, lambda s: s in reasons),
                Optional('metadata'): And(dict)
            }
        ])
        consumers = schema.validate(consumers)
        url = self._make_url('/mobile/b2c/request')
        headers = dict(self._headers)
        headers['Content-Type'] = 'application/json'
        data = json.dumps({
            'username': self._username,
            'productName': product_name,
            'recipients': consumers
        })
        return self._make_request(url, 'POST', headers=headers, params=None, data=data, callback=callback) 
开发者ID:AfricasTalkingLtd,项目名称:africastalking-python,代码行数:26,代码来源:Payment.py

示例2: mobile_b2b

# 需要导入模块: import schema [as 别名]
# 或者: from schema import Schema [as 别名]
def mobile_b2b(self, product_name, business, callback=None):

        providers = PaymentService.PROVIDER.values()
        types = PaymentService.TRANSFER_TYPE.values()
        schema = Schema({
            'provider': And(str, lambda s: s in providers),
            'transferType': And(str, lambda s: s in types),
            'currencyCode': And(str, lambda s: len(s) == 3),
            'amount': And(lambda f: float(f) > 0),
            'destinationChannel': And(str, len),
            'destinationAccount': And(str, len),
            Optional('metadata'): And(dict)
        })
        business = schema.validate(business)
        url = self._make_url('/mobile/b2b/request')
        headers = dict(self._headers)
        headers['Content-Type'] = 'application/json'
        data = business.copy()
        data.update({
            'username': self._username,
            'productName': product_name,
        })
        data = json.dumps(data)
        return self._make_request(url, 'POST', headers=headers, params=None, data=data, callback=callback) 
开发者ID:AfricasTalkingLtd,项目名称:africastalking-python,代码行数:26,代码来源:Payment.py

示例3: mobile_data

# 需要导入模块: import schema [as 别名]
# 或者: from schema import Schema [as 别名]
def mobile_data(self, product_name, recipients, callback=None):

        schema = Schema([{
            'phoneNumber': And(str, lambda s: validate_phone(s)),
            'quantity': And(lambda f: float(f) > 0),
            'unit': And(str, lambda s: validate_data_units(s)),
            'validity': And(str, lambda s: validate_data_validity(s)),
            Optional('metadata'): And(dict)
        }])
        recipients = schema.validate(recipients)
        url = self._make_url('/mobile/data/request')
        headers = dict(self._headers)
        headers['Content-Type'] = 'application/json'
        data = {
            'username': self._username,
            'productName': product_name,
            'recipients': recipients,
        }
        data = json.dumps(data)
        return self._make_request(url, 'POST', headers=headers, params=None, data=data, callback=callback) 
开发者ID:AfricasTalkingLtd,项目名称:africastalking-python,代码行数:22,代码来源:Payment.py

示例4: bank_transfer

# 需要导入模块: import schema [as 别名]
# 或者: from schema import Schema [as 别名]
def bank_transfer(self, product_name, recipients, callback=None):

        bank_account_schema = Schema({
            'accountNumber': And(str, len),
            'bankCode': And(int, lambda i: i in PaymentService.BANK.values()),
            Optional('accountName'): And(str, len),
        })
        schema = Schema([{
            'bankAccount': And(dict, lambda s: bank_account_schema.validate(s)),
            'currencyCode': And(str, lambda s: len(s) == 3),
            'amount': And(lambda f: float(f) > 0),
            'narration': And(str, len),
            Optional('metadata'): And(dict)
        }])
        recipients = schema.validate(recipients)
        url = self._make_url('/bank/transfer')
        headers = dict(self._headers)
        headers['Content-Type'] = 'application/json'
        data = {
            'username': self._username,
            'productName': product_name,
            'recipients': recipients,
        }
        data = json.dumps(data)
        return self._make_request(url, 'POST', headers=headers, params=None, data=data, callback=callback) 
开发者ID:AfricasTalkingLtd,项目名称:africastalking-python,代码行数:27,代码来源:Payment.py

示例5: build_schema

# 需要导入模块: import schema [as 别名]
# 或者: from schema import Schema [as 别名]
def build_schema(cls):
        """
        Build a validation schema using the config options defined in
        this class and its parent classes.
        """
        config_options = cls.get_options().copy()

        # All parent classes that are subclasses of Config
        parents = [
            p
            for p in inspect.getmro(cls)[1:]
            if issubclass(p, Config) and p != Config
        ]

        for p in parents:
            update_options(target=config_options, source=p.get_options())

        return Schema(config_options, ignore_extra_keys=cls.ignore_extra_keys) 
开发者ID:Morgan-Stanley,项目名称:testplan,代码行数:20,代码来源:base.py

示例6: param

# 需要导入模块: import schema [as 别名]
# 或者: from schema import Schema [as 别名]
def param(self, schema):
        """A decorator for validate request data"""
        if not isinstance(schema, collections.Mapping):
            raise TypeError('schema must be Mapping')
        # add error message
        schema = {k: And(v, error='%s invalid' % k)
                  for k, v in schema.items()}
        validate = Schema(schema).validate

        def decorator(f):
            @functools.wraps(f)
            def wrapper(*args, **kwargs):
                data = self.get_data()
                try:
                    data = validate(data)
                except SchemaError as ex:
                    self.handle_error(str(ex))
                kwargs.update(data)
                return f(*args, **kwargs)
            return wrapper
        return decorator 
开发者ID:NetEaseGame,项目名称:git-webhook,代码行数:23,代码来源:validator.py

示例7: validate_ebs_volume_parameters

# 需要导入模块: import schema [as 别名]
# 或者: from schema import Schema [as 别名]
def validate_ebs_volume_parameters(params: dict):
    from spotty.providers.aws.deployment.project_resources.ebs_volume import EbsVolume

    schema = Schema({
        Optional('volumeName', default=''): And(str, Regex(r'^[\w-]{1,255}$')),
        Optional('mountDir', default=''): str,  # all the checks happened in the base configuration
        Optional('size', default=0): And(int, lambda x: x > 0),
        # TODO: add the "iops" parameter to support the "io1" EBS volume type
        Optional('type', default='gp2'): lambda x: x in ['gp2', 'sc1', 'st1', 'standard'],
        Optional('deletionPolicy', default=EbsVolume.DP_CREATE_SNAPSHOT): And(
            str,
            lambda x: x in [EbsVolume.DP_CREATE_SNAPSHOT,
                            EbsVolume.DP_UPDATE_SNAPSHOT,
                            EbsVolume.DP_RETAIN,
                            EbsVolume.DP_DELETE], error='Incorrect value for "deletionPolicy".'
        ),
    })

    return validate_config(schema, params) 
开发者ID:apls777,项目名称:spotty,代码行数:21,代码来源:validation.py

示例8: validate_disk_volume_parameters

# 需要导入模块: import schema [as 别名]
# 或者: from schema import Schema [as 别名]
def validate_disk_volume_parameters(params: dict):
    from spotty.providers.gcp.deployment.project_resources.disk_volume import DiskVolume

    schema = Schema({
        Optional('diskName', default=''): And(str, Regex(r'^[\w-]{1,255}$')),
        Optional('mountDir', default=''): str,  # all the checks happened in the base configuration
        Optional('size', default=0): And(int, lambda x: x > 0),
        Optional('deletionPolicy', default=DiskVolume.DP_CREATE_SNAPSHOT): And(
            str,
            lambda x: x in [DiskVolume.DP_CREATE_SNAPSHOT,
                            DiskVolume.DP_UPDATE_SNAPSHOT,
                            DiskVolume.DP_RETAIN,
                            DiskVolume.DP_DELETE], error='Incorrect value for "deletionPolicy".'
        ),
    })

    return validate_config(schema, params) 
开发者ID:apls777,项目名称:spotty,代码行数:19,代码来源:validation.py

示例9: _modify_schema

# 需要导入模块: import schema [as 别名]
# 或者: from schema import Schema [as 别名]
def _modify_schema(self, data_schema, model, logger):
        if not data_schema:
            return data_schema

        for k in data_schema[0]:
            old_schema = data_schema[0][k]
            if k == 'op_types' or (isinstance(k, Schema) and k._schema == 'op_types'):
                new_schema = And(old_schema, lambda n: validate_op_types(model, n, logger))
                data_schema[0][k] = new_schema
            if k == 'op_names' or (isinstance(k, Schema) and k._schema == 'op_names'):
                new_schema = And(old_schema, lambda n: validate_op_names(model, n, logger))
                data_schema[0][k] = new_schema

        data_schema[0] = And(data_schema[0], lambda d: validate_op_types_op_names(d))

        return data_schema 
开发者ID:microsoft,项目名称:nni,代码行数:18,代码来源:config_validation.py

示例10: validate_config

# 需要导入模块: import schema [as 别名]
# 或者: from schema import Schema [as 别名]
def validate_config(self, model, config_list):
        """
        Parameters
        ----------
        model : torch.nn.module
            Model to be pruned
        config_list : list of dict
            List of configurations
        """
        schema = CompressorSchema([{
            Optional('quant_types'): Schema([lambda x: x in ['weight', 'output']]),
            Optional('quant_bits'): Or(And(int, lambda n: 0 < n < 32), Schema({
                Optional('weight'): And(int, lambda n: 0 < n < 32),
                Optional('output'): And(int, lambda n: 0 < n < 32),
            })),
            Optional('quant_start_step'): And(int, lambda n: n >= 0),
            Optional('op_types'): [str],
            Optional('op_names'): [str]
        }], model, logger)

        schema.validate(config_list) 
开发者ID:microsoft,项目名称:nni,代码行数:23,代码来源:quantizers.py

示例11: load

# 需要导入模块: import schema [as 别名]
# 或者: from schema import Schema [as 别名]
def load(manifest_path: Path) -> Manifest:
    remote_git_server_schema = {"url": str}
    repo_schema = schema.Use(validate_repo)
    group_schema = {"repos": [str], schema.Optional("includes"): [str]}
    # Note: gitlab and github_enterprise_url keys are ignored,
    # and kept here only for backward compatibility reasons
    manifest_schema = schema.Schema(
        {
            "repos": [repo_schema],
            schema.Optional("gitlab"): remote_git_server_schema,
            schema.Optional("github_enterprise"): remote_git_server_schema,
            schema.Optional("groups"): {str: group_schema},
        }
    )
    parsed = tsrc.parse_config(manifest_path, manifest_schema)
    res = Manifest()
    res.apply_config(parsed)
    return res 
开发者ID:TankerHQ,项目名称:tsrc,代码行数:20,代码来源:manifest.py

示例12: parse_config

# 需要导入模块: import schema [as 别名]
# 或者: from schema import Schema [as 别名]
def parse_config(
    file_path: Path, config_schema: Optional[schema.Schema] = None
) -> Config:
    try:
        contents = file_path.read_text()
    except OSError as os_error:
        raise tsrc.InvalidConfig(file_path, os_error)
    try:
        yaml = ruamel.yaml.YAML(typ="safe", pure=True)
        parsed = yaml.load(contents)
    except ruamel.yaml.error.YAMLError as yaml_error:
        raise tsrc.InvalidConfig(file_path, yaml_error)
    if config_schema:
        try:
            config_schema.validate(parsed)
        except schema.SchemaError as schema_error:
            raise tsrc.InvalidConfig(file_path, schema_error)
    return Config(parsed) 
开发者ID:TankerHQ,项目名称:tsrc,代码行数:20,代码来源:config.py

示例13: check

# 需要导入模块: import schema [as 别名]
# 或者: from schema import Schema [as 别名]
def check(conf_schema, conf):
    """
    Validates a user-supplied JSON vs a defined schema.

    Arguments:
        conf_schema: The Schema object that defines the required structure.
        conf: The user-supplied schema to validate against the required structure.
    Returns:
        Boolean: The decision about whether the JSON meets expected Schema requirements
    """
    try:
        conf_schema.validate(conf)
        return True
    except SchemaError as schema_error:
        try:
            # workarounds for Schema's logging approach
            print(schema_error.autos[0])
            detailed_error_message = schema_error.autos[2]
            print(detailed_error_message.split(" in {'")[0])
            # for error in schema_error.autos:
        except:  # pylint: disable=bare-except
            logger.critical(schema_error)
        return False 
开发者ID:salesforce,项目名称:policy_sentry,代码行数:25,代码来源:validate.py

示例14: validate_condition_block

# 需要导入模块: import schema [as 别名]
# 或者: from schema import Schema [as 别名]
def validate_condition_block(condition_block):
    """
    Validates the format of the condition block that should be supplied in the template.

    Arguments:
        condition_block: {"condition_key_string": "ec2:ResourceTag/purpose", "condition_type_string": "StringEquals", "condition_value": "test"}
    Returns:
        Boolean: The decision
    """

    # TODO: Validate that the values are legit somehow
    CONDITION_BLOCK_SCHEMA = Schema(
        {
            "condition_key_string": And(Use(str)),
            "condition_type_string": And(Use(str)),
            "condition_value": And(Use(str)),
        }
    )
    try:
        CONDITION_BLOCK_SCHEMA.validate(condition_block)
        # TODO: Try to validate whether or not the condition keys are legit
        return True
    except SchemaError as s_e:
        logger.warning(s_e)
        return False 
开发者ID:salesforce,项目名称:policy_sentry,代码行数:27,代码来源:validate.py

示例15: _format_tyre_dimensions

# 需要导入模块: import schema [as 别名]
# 或者: from schema import Schema [as 别名]
def _format_tyre_dimensions(tyre_dimensions):
    import schema
    frt = schema.Schema({
        schema.Optional('additional_marks'): schema.Use(str),
        schema.Optional('aspect_ratio'): schema.Use(float),
        schema.Optional('carcass'): schema.Use(str),
        'rim_diameter': schema.Use(float),
        schema.Optional('diameter'): schema.Use(float),
        schema.Optional('load_index'): schema.Use(str),
        schema.Optional('load_range'): schema.Use(str),
        'nominal_section_width': schema.Use(float),
        schema.Optional('speed_rating'): schema.Use(str),
        schema.Optional('use'): schema.Use(str),
        schema.Optional('code'): schema.Use(str),
    })
    m = {k: v for k, v in tyre_dimensions.items() if v is not None}
    return frt.validate(m) 
开发者ID:JRCSTU,项目名称:CO2MPAS-TA,代码行数:19,代码来源:wheels.py


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