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


Python exceptions.ValidationError方法代码示例

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


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

示例1: post

# 需要导入模块: from marshmallow import exceptions [as 别名]
# 或者: from marshmallow.exceptions import ValidationError [as 别名]
def post(self):
        context = await self.shared_response()

        if settings.DISABLE_INVITES:
            return context

        try:
            invite = self.schema.load(await self.request.post())

            if await self.allowed_email(invite["email"]):
                await self.request.app["slack_client_legacy"].query(
                    url="users.admin.invite", data={"email": invite["email"], "resend": True}
                )
            context["success"] = True
        except ValidationError as e:
            context["errors"] = e.normalized_messages()
        except slack.exceptions.SlackAPIError as e:
            logger.warning("Error sending slack invite: %s", e.error, extra=e.data)
            context["errors"].update(non_field=[e.error])
        except slack.exceptions.HTTPException:
            logger.exception("Error contacting slack API")
            context["errors"].update(non_field=["Error contacting slack API"])

        return context 
开发者ID:pyslackers,项目名称:website,代码行数:26,代码来源:views.py

示例2: from_config

# 需要导入模块: from marshmallow import exceptions [as 别名]
# 或者: from marshmallow.exceptions import ValidationError [as 别名]
def from_config(cls, corpus_config, feature_config, labels, manifest="train"):
        try:
            cfg = CorporaConfiguration().load(corpus_config)
            if len(cfg.errors) > 0:
                raise ValidationError(cfg.errors)
        except ValidationError as err:
            raise err
        config = cfg.data
        datasets = {x['name']: x for x in config['datasets']}
        if manifest not in datasets:
            raise KeyError("Requested dataset ({}) doesn't exist.".format(manifest))
        dataset = datasets[manifest]

        augmentation_config = config['augmentation'] if dataset['augment'] else []
        featurizer = PerturbedSpectrogramFeaturizer.from_config(feature_config,
                                                                perturbation_configs=augmentation_config)

        return cls(dataset['manifest'], labels, featurizer, max_duration=config['max_duration'],
                   min_duration=config['min_duration']) 
开发者ID:ryanleary,项目名称:patter,代码行数:21,代码来源:dataset.py

示例3: validate_options

# 需要导入模块: from marshmallow import exceptions [as 别名]
# 或者: from marshmallow.exceptions import ValidationError [as 别名]
def validate_options(options):
    """
    Ensures that the plugin options are valid.
    :param options:
    :return:
    """
    interval = get_plugin_option("interval", options)
    unit = get_plugin_option("unit", options)

    if not interval and not unit:
        return

    if unit == "month":
        interval *= 30

    elif unit == "week":
        interval *= 7

    if interval > 90:
        raise ValidationError(
            "Notification cannot be more than 90 days into the future."
        ) 
开发者ID:Netflix,项目名称:lemur,代码行数:24,代码来源:schemas.py

示例4: get_object_attribute

# 需要导入模块: from marshmallow import exceptions [as 别名]
# 或者: from marshmallow.exceptions import ValidationError [as 别名]
def get_object_attribute(data, many=False):
    if many:
        ids = [d.get("id") for d in data]
        names = [d.get("name") for d in data]

        if None in ids:
            if None in names:
                raise ValidationError("Associated object require a name or id.")
            else:
                return "name"
        return "id"
    else:
        if data.get("id"):
            return "id"
        elif data.get("name"):
            return "name"
        else:
            raise ValidationError("Associated object require a name or id.") 
开发者ID:Netflix,项目名称:lemur,代码行数:20,代码来源:schemas.py

示例5: get_sans_from_csr

# 需要导入模块: from marshmallow import exceptions [as 别名]
# 或者: from marshmallow.exceptions import ValidationError [as 别名]
def get_sans_from_csr(data):
    """
    Fetches SubjectAlternativeNames from CSR.
    Works with any kind of SubjectAlternativeName
    :param data: PEM-encoded string with CSR
    :return: List of LemurAPI-compatible subAltNames
    """
    sub_alt_names = []
    try:
        request = x509.load_pem_x509_csr(data.encode("utf-8"), default_backend())
    except Exception:
        raise ValidationError("CSR presented is not valid.")

    try:
        alt_names = request.extensions.get_extension_for_class(
            x509.SubjectAlternativeName
        )
        for alt_name in alt_names.value:
            sub_alt_names.append(
                {"nameType": type(alt_name).__name__, "value": alt_name.value}
            )
    except x509.ExtensionNotFound:
        pass

    return sub_alt_names 
开发者ID:Netflix,项目名称:lemur,代码行数:27,代码来源:utils.py

示例6: validate_cert_chain

# 需要导入模块: from marshmallow import exceptions [as 别名]
# 或者: from marshmallow.exceptions import ValidationError [as 别名]
def validate_cert_chain(self, data):
        cert = None
        if data.get("body"):
            try:
                cert = utils.parse_certificate(data["body"])
            except ValueError:
                raise ValidationError(
                    "Public certificate presented is not valid.", field_names=["body"]
                )

        if data.get("chain"):
            try:
                chain = utils.parse_cert_chain(data["chain"])
            except ValueError:
                raise ValidationError(
                    "Invalid certificate in certificate chain.", field_names=["chain"]
                )

            # Throws ValidationError
            validators.verify_cert_chain([cert] + chain) 
开发者ID:Netflix,项目名称:lemur,代码行数:22,代码来源:schemas.py

示例7: test_dates

# 需要导入模块: from marshmallow import exceptions [as 别名]
# 或者: from marshmallow.exceptions import ValidationError [as 别名]
def test_dates(session):
    from lemur.common.validators import dates

    dates(dict(validity_start=datetime(2016, 1, 1), validity_end=datetime(2016, 1, 5)))

    with pytest.raises(ValidationError):
        dates(dict(validity_start=datetime(2016, 1, 1)))

    with pytest.raises(ValidationError):
        dates(dict(validity_end=datetime(2016, 1, 1)))

    with pytest.raises(ValidationError):
        dates(
            dict(validity_start=datetime(2016, 1, 5), validity_end=datetime(2016, 1, 1))
        )

    with pytest.raises(ValidationError):
        dates(
            dict(
                validity_start=datetime(2016, 1, 1), validity_end=datetime(2016, 1, 10)
            )
        ) 
开发者ID:Netflix,项目名称:lemur,代码行数:24,代码来源:test_validators.py

示例8: test_get_object_attribute

# 需要导入模块: from marshmallow import exceptions [as 别名]
# 或者: from marshmallow.exceptions import ValidationError [as 别名]
def test_get_object_attribute():
    from lemur.schemas import get_object_attribute

    with pytest.raises(ValidationError):
        get_object_attribute({})

    with pytest.raises(ValidationError):
        get_object_attribute([{}], many=True)

    with pytest.raises(ValidationError):
        get_object_attribute([{}, {"id": 1}], many=True)

    with pytest.raises(ValidationError):
        get_object_attribute([{}, {"name": "test"}], many=True)

    assert get_object_attribute({"name": "test"}) == "name"
    assert get_object_attribute({"id": 1}) == "id"
    assert get_object_attribute([{"name": "test"}], many=True) == "name"
    assert get_object_attribute([{"id": 1}], many=True) == "id" 
开发者ID:Netflix,项目名称:lemur,代码行数:21,代码来源:test_schemas.py

示例9: sub_alt_type

# 需要导入模块: from marshmallow import exceptions [as 别名]
# 或者: from marshmallow.exceptions import ValidationError [as 别名]
def sub_alt_type(alt_type):
    """
    Determines if the specified subject alternate type is valid.
    :param alt_type:
    :return:
    """
    valid_types = [
        "DNSName",
        "IPAddress",
        "uniFormResourceIdentifier",
        "directoryName",
        "rfc822Name",
        "registrationID",
        "otherName",
        "x400Address",
        "EDIPartyName",
    ]
    if alt_type.lower() not in [a_type.lower() for a_type in valid_types]:
        raise ValidationError(
            "Invalid SubAltName Type: {0} choose from {1}".format(
                type, ",".join(valid_types)
            )
        ) 
开发者ID:Netflix,项目名称:lemur,代码行数:25,代码来源:validators.py

示例10: handle_error

# 需要导入模块: from marshmallow import exceptions [as 别名]
# 或者: from marshmallow.exceptions import ValidationError [as 别名]
def handle_error(self,
                     error: MarshmallowValidationError,
                     data: Any,  # skipcq: PYL-W0613 (unused arg)
                     **kwargs
                     ) -> None:
        """
        Customize the error messages for required/not-null validators with
        dynamically generated field names. This is definitely a little hacky (it
        mutates state, uses hardcoded strings), but unsure how better to do it
        """
        required_messages = {'Missing data for required field.',
                             'Field may not be null.'}
        for field_name in error.normalized_messages():
            for i, msg in enumerate(error.messages[field_name]):
                if isinstance(msg, _LazyString):
                    msg = str(msg)
                if msg in required_messages:
                    label = title_case(field_name)
                    error.messages[field_name][i] = f'{label} is required.' 
开发者ID:briancappello,项目名称:flask-unchained,代码行数:21,代码来源:model_serializer.py

示例11: _deserialize

# 需要导入模块: from marshmallow import exceptions [as 别名]
# 或者: from marshmallow.exceptions import ValidationError [as 别名]
def _deserialize(self, value, attr, data, **kwargs):
        repo = self.context.get("repository")
        if not repo:
            return value

        if not self.validate_ref and not self.resolve_to:
            return value

        try:
            revision = revisions.identify_revision(
                repo, value, with_vcs=self.validate_ref
            )
        except UnknownRevision as e:
            if self.validate_ref:
                current_app.logger.warn("invalid ref received", exc_info=True)
                raise ValidationError("unknown revision: {}".format(value)) from e
        else:
            if self.resolve_to:
                # XXX(dcramer): we'd prefer to make this a compound field
                # but Marshmallow wont let us bind this
                self.context["resolved_{}".format(self.resolve_to)] = revision
        return value 
开发者ID:getsentry,项目名称:zeus,代码行数:24,代码来源:revision.py

示例12: invitation_create

# 需要导入模块: from marshmallow import exceptions [as 别名]
# 或者: from marshmallow.exceptions import ValidationError [as 别名]
def invitation_create(request: web.BaseRequest):
    """
    Request handler for creating a new connection invitation.

    Args:
        request: aiohttp request object

    Returns:
        The out of band invitation details

    """
    context = request.app["request_context"]

    body = await request.json()

    attachments = body.get("attachments")
    include_handshake = body.get("include_handshake")
    use_public_did = body.get("use_public_did")
    multi_use = json.loads(request.query.get("multi_use", "false"))
    oob_mgr = OutOfBandManager(context)

    try:
        invitation = await oob_mgr.create_invitation(
            multi_use=multi_use,
            attachments=attachments,
            include_handshake=include_handshake,
            use_public_did=use_public_did,
        )
    except (StorageNotFoundError, ValidationError, OutOfBandManagerError) as e:
        raise web.HTTPBadRequest(reason=str(e))

    return web.json_response(invitation.serialize()) 
开发者ID:hyperledger,项目名称:aries-cloudagent-python,代码行数:34,代码来源:routes.py

示例13: validate_fields

# 需要导入模块: from marshmallow import exceptions [as 别名]
# 或者: from marshmallow.exceptions import ValidationError [as 别名]
def validate_fields(self, data, **kwargs):
        """
        Validate schema fields - must have from, to, or both.

        Args:
            data: The data to validate

        Raises:
            ValidationError: if data has neither from nor to

        """
        if not (data.get("from") or data.get("to")):
            raise ValidationError(
                "Non-revocation interval must have at least one end", ("fro", "to")
            ) 
开发者ID:hyperledger,项目名称:aries-cloudagent-python,代码行数:17,代码来源:routes.py

示例14: __call__

# 需要导入模块: from marshmallow import exceptions [as 别名]
# 或者: from marshmallow.exceptions import ValidationError [as 别名]
def __call__(self, value):
        """Validate input value."""

        if type(value) != int:
            raise ValidationError("Value {input} is not a valid whole number")
        super().__call__(value) 
开发者ID:hyperledger,项目名称:aries-cloudagent-python,代码行数:8,代码来源:valid.py

示例15: test_schema_context_validation_type_field

# 需要导入模块: from marshmallow import exceptions [as 别名]
# 或者: from marshmallow.exceptions import ValidationError [as 别名]
def test_schema_context_validation_type_field():
    """Test schema context validation for type field"""
    from swag_client.backend import SWAGManager
    from swag_client.util import parse_swag_config_options

    swag_opts = {
        'swag.schema_context': {
            'type': ['billing', 'security', 'shared-service', 'service'],
        }
    }
    swag = SWAGManager(**parse_swag_config_options(swag_opts))

    data = {
        "aliases": ["test"],
        "contacts": ["admins@test.net"],
        "description": "This is just a test.",
        "email": "test@example.net",
        "environment": "dev",
        "id": "012345678910",
        "name": "testaccount",
        "owner": "netflix",
        "provider": "aws",
    }

    # Test with invalid account type
    with pytest.raises(ValidationError):
        data['type'] = 'bad_type'
        swag.create(data)

    # Test with a valid account type
    data['type'] = 'billing'
    account = swag.create(data)
    assert account.get('type') == 'billing' 
开发者ID:Netflix-Skunkworks,项目名称:swag-client,代码行数:35,代码来源:test_swag.py


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