當前位置: 首頁>>代碼示例>>Python>>正文


Python errors.ValidationError方法代碼示例

本文整理匯總了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 
開發者ID:Flask-Middleware,項目名稱:flask-security,代碼行數:22,代碼來源:datastore.py

示例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() 
開發者ID:opendatateam,項目名稱:udata,代碼行數:19,代碼來源:test_model.py

示例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") 
開發者ID:hiroaki-yamamoto,項目名稱:mongoengine-goodjson,代碼行數:7,代碼來源:test_objectid.py

示例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() 
開發者ID:opendatateam,項目名稱:udata,代碼行數:6,代碼來源:test_model.py

示例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() 
開發者ID:opendatateam,項目名稱:udata,代碼行數:7,代碼來源:test_model.py

示例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() 
開發者ID:opendatateam,項目名稱:udata,代碼行數:7,代碼來源:test_model.py

示例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() 
開發者ID:opendatateam,項目名稱:udata,代碼行數:10,代碼來源:test_model.py

示例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() 
開發者ID:opendatateam,項目名稱:udata,代碼行數:14,代碼來源:test_model.py

示例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 
開發者ID:opendatateam,項目名稱:udata,代碼行數:38,代碼來源:commands.py

示例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("") 
開發者ID:fastlane-queue,項目名稱:fastlane,代碼行數:10,代碼來源:test_task.py

示例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) 
開發者ID:umutbozkurt,項目名稱:django-rest-framework-mongoengine,代碼行數:12,代碼來源:fields.py

示例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 
開發者ID:umutbozkurt,項目名稱:django-rest-framework-mongoengine,代碼行數:44,代碼來源:serializers.py


注:本文中的mongoengine.errors.ValidationError方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。