本文整理汇总了Python中mongoengine.errors.ValidationError方法的典型用法代码示例。如果您正苦于以下问题:Python errors.ValidationError方法的具体用法?Python errors.ValidationError怎么用?Python errors.ValidationError使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类mongoengine.errors
的用法示例。
在下文中一共展示了errors.ValidationError方法的12个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: find_user
# 需要导入模块: from mongoengine import errors [as 别名]
# 或者: from mongoengine.errors import ValidationError [as 别名]
def find_user(self, case_insensitive=False, **kwargs):
from mongoengine.queryset.visitor import Q, QCombination
from mongoengine.errors import ValidationError
try:
if case_insensitive:
# While it is of course possible to pass in multiple keys to filter on
# that isn't the normal use case. If caller asks for case_insensitive
# AND gives multiple keys - throw an error.
if len(kwargs) > 1:
raise ValueError("Case insensitive option only supports single key")
attr, identifier = kwargs.popitem()
query = {f"{attr}__iexact": identifier}
return self.user_model.objects(**query).first()
else:
queries = map(lambda i: Q(**{i[0]: i[1]}), kwargs.items())
query = QCombination(QCombination.AND, queries)
return self.user_model.objects(query).first()
except ValidationError: # pragma: no cover
return None
示例2: test_validate_registered_type_embedded_document
# 需要导入模块: from mongoengine import errors [as 别名]
# 或者: from mongoengine.errors import ValidationError [as 别名]
def test_validate_registered_type_embedded_document(self):
class Tester(db.Document):
extras = db.ExtrasField()
@Tester.extras('test')
class EmbeddedExtra(db.EmbeddedDocument):
name = db.StringField(required=True)
tester = Tester(extras={'test': {}})
with pytest.raises(ValidationError):
tester.validate()
tester.extras['test'] = {'name': 'test'}
tester.validate()
tester.extras['test'] = EmbeddedExtra(name='test')
tester.validate()
示例3: test_encode
# 需要导入模块: from mongoengine import errors [as 别名]
# 或者: from mongoengine.errors import ValidationError [as 别名]
def test_encode(self):
"""Serialization should be failed."""
with self.assertRaises(ValidationError) as e:
self.doc.to_json()
self.assertEqual(e.exception.field_name, "uid")
示例4: test_not_valid
# 需要导入模块: from mongoengine import errors [as 别名]
# 或者: from mongoengine.errors import ValidationError [as 别名]
def test_not_valid(self):
obj = DateTester(a_date='invalid')
with pytest.raises(ValidationError):
obj.save()
示例5: test_empty_but_required
# 需要导入模块: from mongoengine import errors [as 别名]
# 或者: from mongoengine.errors import ValidationError [as 别名]
def test_empty_but_required(self):
obj = RequiredDateRangeTester()
assert obj.temporal is None
with pytest.raises(ValidationError):
obj.save()
示例6: test_public_private
# 需要导入模块: from mongoengine import errors [as 别名]
# 或者: from mongoengine.errors import ValidationError [as 别名]
def test_public_private(self):
url = 'http://10.10.0.2/path/'
PrivateURLTester(url=url).save()
with pytest.raises(ValidationError):
URLTester(url=url).save()
示例7: test_fail_to_validate_wrong_type
# 需要导入模块: from mongoengine import errors [as 别名]
# 或者: from mongoengine.errors import ValidationError [as 别名]
def test_fail_to_validate_wrong_type(self, dbtype, value):
class Tester(db.Document):
extras = db.ExtrasField()
Tester.extras.register('test', dbtype)
with pytest.raises(db.ValidationError):
Tester(extras={'test': value}).validate()
示例8: test_validate_custom_type
# 需要导入模块: from mongoengine import errors [as 别名]
# 或者: from mongoengine.errors import ValidationError [as 别名]
def test_validate_custom_type(self):
class Tester(db.Document):
extras = db.ExtrasField()
@Tester.extras('test')
class Custom(BaseField):
def validate(self, value):
if not isinstance(value, dict):
raise db.ValidationError('Should be a dict instance')
tester = Tester(extras={'test': {}})
tester.validate()
示例9: load_zones
# 需要导入模块: from mongoengine import errors [as 别名]
# 或者: from mongoengine.errors import ValidationError [as 别名]
def load_zones(col, path):
with open(path, 'rb') as fp:
unpacker = msgpack.Unpacker(fp, raw=False)
next(unpacker) # Skip headers.
for i, geozone in enumerate(unpacker):
params = {
'slug': slugify.slugify(geozone['name'], separator='-'),
'level': geozone['level'],
'code': geozone['code'],
'name': geozone['name'],
'keys': geozone.get('keys'),
'parents': geozone.get('parents', []),
'ancestors': geozone.get('ancestors', []),
'successors': geozone.get('successors', []),
'validity': geozone.get('validity'),
'population': geozone.get('population'),
'dbpedia': geozone.get('dbpedia'),
'flag': geozone.get('flag'),
'blazon': geozone.get('blazon'),
'wikidata': geozone.get('wikidata'),
'wikipedia': geozone.get('wikipedia'),
'area': geozone.get('area'),
}
if geozone.get('geom') and (
geozone['geom']['type'] != 'GeometryCollection' or
geozone['geom']['geometries']):
params['geom'] = geozone['geom']
try:
col.objects(id=geozone['_id']).modify(upsert=True, **{
'set__{0}'.format(k): v for k, v in params.items()
})
except errors.ValidationError as e:
log.warning('Validation error (%s) for %s with %s',
e, geozone['_id'], params)
continue
return i
示例10: test_task_create2
# 需要导入模块: from mongoengine import errors [as 别名]
# 或者: from mongoengine.errors import ValidationError [as 别名]
def test_task_create2(client):
"""Test creating a new task fails when no task_id provided"""
msg = "ValidationError (Task:None) (Field is required: ['task_id'])"
with expect.error_to_happen(ValidationError, message=msg):
Task.create_task(None)
with expect.error_to_happen(ValidationError, message=msg):
Task.create_task("")
示例11: run_validators
# 需要导入模块: from mongoengine import errors [as 别名]
# 或者: from mongoengine.errors import ValidationError [as 别名]
def run_validators(self, value):
""" validate value.
Uses document field's ``validate()``
"""
try:
self.model_field.validate(value)
except MongoValidationError as e:
raise ValidationError(e.message)
super(DocumentField, self).run_validators(value)
示例12: create
# 需要导入模块: from mongoengine import errors [as 别名]
# 或者: from mongoengine.errors import ValidationError [as 别名]
def create(self, validated_data):
raise_errors_on_nested_writes('create', self, validated_data)
ModelClass = self.Meta.model
try:
# recursively create EmbeddedDocuments from their validated data
# before creating the document instance itself
instance = self.recursive_save(validated_data)
except TypeError as exc:
msg = (
'Got a `TypeError` when calling `%s.objects.create()`. '
'This may be because you have a writable field on the '
'serializer class that is not a valid argument to '
'`%s.objects.create()`. You may need to make the field '
'read-only, or override the %s.create() method to handle '
'this correctly.\nOriginal exception text was: %s.' %
(
ModelClass.__name__,
ModelClass.__name__,
type(self).__name__,
exc
)
)
raise TypeError(msg)
except me_ValidationError as exc:
msg = (
'Got a `ValidationError` when calling `%s.objects.create()`. '
'This may be because request data satisfies serializer validations '
'but not Mongoengine`s. You may need to check consistency between '
'%s and %s.\nIf that is not the case, please open a ticket '
'regarding this issue on https://github.com/umutbozkurt/django-rest-framework-mongoengine/issues'
'\nOriginal exception was: %s' %
(
ModelClass.__name__,
ModelClass.__name__,
type(self).__name__,
exc
)
)
raise me_ValidationError(msg)
return instance