本文整理汇总了Python中marshmallow.ValidationError方法的典型用法代码示例。如果您正苦于以下问题:Python marshmallow.ValidationError方法的具体用法?Python marshmallow.ValidationError怎么用?Python marshmallow.ValidationError使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类marshmallow
的用法示例。
在下文中一共展示了marshmallow.ValidationError方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: validate_statuses
# 需要导入模块: import marshmallow [as 别名]
# 或者: from marshmallow import ValidationError [as 别名]
def validate_statuses(record):
"""Validate that the extension action can be performed."""
if record["status"] != "ON_LOAN":
raise ValidationError(
"This interlibrary loan is currently not on loan."
)
ext_status = (
record.get("patron_loan", {}).get("extension", {}).get("status")
)
# status = None is valid, no extension requested yet
has_status = ext_status is not None
is_valid = ext_status in BorrowingRequest.EXTENSION_STATUSES
if has_status and not is_valid:
# should never happen, a status that is not in the valid ones
raise ValidationError(
"The current extension status ({}) is invalid.".format(ext_status)
)
return ext_status
示例2: validate_action
# 需要导入模块: import marshmallow [as 别名]
# 或者: from marshmallow import ValidationError [as 别名]
def validate_action(self, data=None, **kwargs):
"""Validate action."""
no_payload = data is None
if no_payload:
# marshmallow needs a default empty payload
data = {}
record = self.context["record"]
ext_status = validate_statuses(record)
if ext_status == "PENDING":
raise ValidationError(
"An extension for this interlibrary loan has already been "
"requested."
)
elif ext_status == "DECLINED":
raise ValidationError(
"Cannot request an extension for this interlibrary loan "
"because the most recent extension request has been declined."
)
return data
示例3: postload_checks
# 需要导入模块: import marshmallow [as 别名]
# 或者: from marshmallow import ValidationError [as 别名]
def postload_checks(self, data, **kwargs):
"""Validate dates values."""
if "end_date" in data and "start_date" not in data:
raise ValidationError(
_("Start date is required when end date provided."),
field_names=["start_date", "end_date"],
)
if "start_date" in data and "end_date" in data:
start = arrow.get(data["start_date"]).date()
end = arrow.get(data["end_date"]).date()
if end < start:
raise ValidationError(
_("The loan end date cannot be before the start date."),
field_names=["start_date", "end_date"],
)
return data
示例4: run_add_shortcut
# 需要导入模块: import marshmallow [as 别名]
# 或者: from marshmallow import ValidationError [as 别名]
def run_add_shortcut(config):
"""
Runs add_shortcut from the command line. Does error handling.
:type config: Config Object
:param config: Config of adding shortcut
:return:
"""
if not valid_directory(config.query_directory):
logger.error("Invalid Drift Detection Directory")
return
try:
add_shortcut(FileSystem, ShortcutSchema(), config.query_directory, config.shortcut, config.filename)
except ValidationError as err:
msg = "Could not load shortcut file from json file {} in query directory {}.".format(
err.messages,
config.query_directory,
)
logger.exception(msg)
示例5: validate_fields
# 需要导入模块: import marshmallow [as 别名]
# 或者: from marshmallow import ValidationError [as 别名]
def validate_fields(self, data, **kwargs):
"""
Validate schema fields.
Args:
data: The data to validate
Raises:
ValidationError: If any of the fields do not validate
"""
if data.get("did"):
if data.get("recipient_keys"):
raise ValidationError(
"Fields are incompatible", ("did", "recipientKeys")
)
if data.get("endpoint"):
raise ValidationError(
"Fields are incompatible", ("did", "serviceEndpoint")
)
elif not data.get("recipient_keys") or not data.get("endpoint"):
raise ValidationError(
"Missing required field(s)", ("did", "recipientKeys", "serviceEndpoint")
)
示例6: validate_fields
# 需要导入模块: import marshmallow [as 别名]
# 或者: from marshmallow import ValidationError [as 别名]
def validate_fields(self, data, **kwargs):
"""
Validate schema fields.
Args:
data: The data to validate
Raises:
ValidationError: If any of the fields do not validate
"""
handshake_protocols = data.get("handshake_protocols")
request_attach = data.get("request_attach")
if not (
(handshake_protocols and len(handshake_protocols) > 0)
or (request_attach and len(request_attach) > 0)
):
raise ValidationError(
"Model must include non-empty "
+ "handshake_protocols or request_attach or both"
)
# service = data.get("service")
# if not ((service and len(service) > 0)):
# raise ValidationError(
# "Model must include non-empty service array"
# )
示例7: deserialize
# 需要导入模块: import marshmallow [as 别名]
# 或者: from marshmallow import ValidationError [as 别名]
def deserialize(cls, obj):
"""
Convert from JSON representation to a model instance.
Args:
obj: The dict to load into a model instance
Returns:
A model instance for this data
"""
schema = cls._get_schema_class()(unknown=EXCLUDE)
try:
return schema.loads(obj) if isinstance(obj, str) else schema.load(obj)
except ValidationError as e:
LOGGER.exception(f"{cls.__name__} message validation error:")
raise BaseModelError(f"{cls.__name__} schema validation failed") from e
示例8: serialize
# 需要导入模块: import marshmallow [as 别名]
# 或者: from marshmallow import ValidationError [as 别名]
def serialize(self, as_string=False) -> dict:
"""
Create a JSON-compatible dict representation of the model instance.
Args:
as_string: Return a string of JSON instead of a dict
Returns:
A dict representation of this model, or a JSON string if as_string is True
"""
schema = self.Schema(unknown=EXCLUDE)
try:
return schema.dumps(self) if as_string else schema.dump(self)
except ValidationError as e:
LOGGER.exception(f"{self.__class__.__name__} message serialization error:")
raise BaseModelError(
f"{self.__class__.__name__} schema validation failed"
) from e
示例9: test_jws_header_kid
# 需要导入模块: import marshmallow [as 别名]
# 或者: from marshmallow import ValidationError [as 别名]
def test_jws_header_kid(self):
non_kids = [
"http://not-this.one",
"did:sov:i", # too short
"did:key:Q4zqM7aXqm7gDQkUVLng9h" # missing leading z
"did:key:zI4zqM7aXqm7gDQkUVLng9h", # 'I' not a base58 char
]
for non_kid in non_kids:
with self.assertRaises(ValidationError):
JWS_HEADER_KID["validate"](non_kid)
JWS_HEADER_KID["validate"]("did:key:zQ4zqM7aXqm7gDQkUVLng9h")
JWS_HEADER_KID["validate"]("did:sov:Q4zqM7aXqm7gDQkUVLng9h#abc-123")
JWS_HEADER_KID["validate"](
"did:sov:Q4zqM7aXqm7gDQkUVLng9h?version-time=1234567890#abc-123"
)
JWS_HEADER_KID["validate"](
"did:sov:Q4zqM7aXqm7gDQkUVLng9h?version-time=1234567890&a=b#abc-123"
)
JWS_HEADER_KID["validate"](
"did:sov:Q4zqM7aXqm7gDQkUVLng9h;foo:bar=low;a=b?version-id=1&a=b#abc-123"
)
示例10: test_cred_def_id
# 需要导入模块: import marshmallow [as 别名]
# 或者: from marshmallow import ValidationError [as 别名]
def test_cred_def_id(self):
non_cred_def_ids = [
"Q4zqM7aXqm7gDQkUVLng9h:4:CL:18:0",
"Q4zqM7aXqm7gDQkUVLng9h::CL:18:0",
"Q4zqM7aXqm7gDQkUVLng9I:3:CL:18:tag",
"Q4zqM7aXqm7gDQkUVLng9h:3::18:tag",
"Q4zqM7aXqm7gDQkUVLng9h:3:18:tag",
]
for non_cred_def_id in non_cred_def_ids:
with self.assertRaises(ValidationError):
INDY_CRED_DEF_ID["validate"](non_cred_def_id)
INDY_CRED_DEF_ID["validate"]("Q4zqM7aXqm7gDQkUVLng9h:3:CL:18:tag") # short
INDY_CRED_DEF_ID["validate"](
"Q4zqM7aXqm7gDQkUVLng9h:3:CL:Q4zqM7aXqm7gDQkUVLng9h:2:bc-reg:1.0:tag"
) # long
示例11: test_schema_id
# 需要导入模块: import marshmallow [as 别名]
# 或者: from marshmallow import ValidationError [as 别名]
def test_schema_id(self):
non_schema_ids = [
"Q4zqM7aXqm7gDQkUVLng9h:3:bc-reg:1.0",
"Q4zqM7aXqm7gDQkUVLng9h::bc-reg:1.0",
"Q4zqM7aXqm7gDQkUVLng9h:bc-reg:1.0",
"Q4zqM7aXqm7gDQkUVLng9h:2:1.0",
"Q4zqM7aXqm7gDQkUVLng9h:2::1.0",
"Q4zqM7aXqm7gDQkUVLng9h:2:bc-reg:",
"Q4zqM7aXqm7gDQkUVLng9h:2:bc-reg:1.0a",
"Q4zqM7aXqm7gDQkUVLng9I:2:bc-reg:1.0", # I is not in base58
]
for non_schema_id in non_schema_ids:
with self.assertRaises(ValidationError):
INDY_SCHEMA_ID["validate"](non_schema_id)
INDY_SCHEMA_ID["validate"]("Q4zqM7aXqm7gDQkUVLng9h:2:bc-reg:1.0")
示例12: test_indy_date
# 需要导入模块: import marshmallow [as 别名]
# 或者: from marshmallow import ValidationError [as 别名]
def test_indy_date(self):
non_datetimes = [
"nope",
"2020-01-01",
"2020-01-01:00:00:00Z",
"2020.01.01 00:00:00Z",
"2020-01-01T00:00.123456+00:00",
"2020-01-01T00:00:00.123456+0:00",
]
for non_datetime in non_datetimes:
with self.assertRaises(ValidationError):
INDY_ISO8601_DATETIME["validate"](non_datetime)
INDY_ISO8601_DATETIME["validate"]("2020-01-01 00:00:00Z")
INDY_ISO8601_DATETIME["validate"]("2020-01-01T00:00:00Z")
INDY_ISO8601_DATETIME["validate"]("2020-01-01T00:00:00")
INDY_ISO8601_DATETIME["validate"]("2020-01-01 00:00:00")
INDY_ISO8601_DATETIME["validate"]("2020-01-01 00:00:00+00:00")
INDY_ISO8601_DATETIME["validate"]("2020-01-01 00:00:00-00:00")
INDY_ISO8601_DATETIME["validate"]("2020-01-01 00:00-00:00")
INDY_ISO8601_DATETIME["validate"]("2020-01-01 00:00:00.1-00:00")
INDY_ISO8601_DATETIME["validate"]("2020-01-01 00:00:00.123456-00:00")
示例13: test_sha256
# 需要导入模块: import marshmallow [as 别名]
# 或者: from marshmallow import ValidationError [as 别名]
def test_sha256(self):
non_sha256s = [
"####",
"abcd123",
"________________________________________________________________",
"gggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggg",
]
for non_sha256 in non_sha256s:
with self.assertRaises(ValidationError):
SHA256["validate"](non_sha256)
SHA256["validate"](
"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
)
SHA256["validate"](
"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"
)
示例14: test_endpoint
# 需要导入模块: import marshmallow [as 别名]
# 或者: from marshmallow import ValidationError [as 别名]
def test_endpoint(self):
non_endpoints = [
"123",
"",
"/path/only",
"https://1.2.3.4?query=true&url=false",
"http://no_tld/bad",
"no-proto:8080/my/path",
"smtp:8080/my/path#fragment",
]
for non_endpoint in non_endpoints:
with self.assertRaises(ValidationError):
ENDPOINT["validate"](non_endpoint)
ENDPOINT["validate"]("http://github.com")
ENDPOINT["validate"]("https://localhost:8080")
ENDPOINT["validate"]("newproto://myhost.ca:8080/path")
ENDPOINT["validate"]("ftp://10.10.100.90:8021")
ENDPOINT["validate"]("zzzp://someplace.ca:9999/path")
示例15: post
# 需要导入模块: import marshmallow [as 别名]
# 或者: from marshmallow import ValidationError [as 别名]
def post(self):
raw_dict = request.get_json(force=True)
try:
schema.validate(raw_dict)
user_dict = raw_dict['data']['attributes']
user = Users(user_dict['email'], user_dict['name'],user_dict['is_active'])
user.add(user)
query = Users.query.get(user.id)
results = schema.dump(query).data
return results, 201
except ValidationError as err:
resp = jsonify({"error": err.messages})
resp.status_code = 403
return resp
except SQLAlchemyError as e:
db.session.rollback()
resp = jsonify({"error": str(e)})
resp.status_code = 403
return resp