本文整理匯總了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
示例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'])
示例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."
)
示例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.")
示例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
示例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)
示例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)
)
)
示例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"
示例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)
)
)
示例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.'
示例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
示例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())
示例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")
)
示例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)
示例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'