Python mongoengine.ValidationError() Examples

The following are 30 code examples of mongoengine.ValidationError(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module mongoengine , or try the search function .
Example #1
Source File: test_id.py    From django-rest-framework-mongoengine with MIT License 6 votes vote down vote up
def test_incorrect(self):
        """This test shows that if we've overridden id field on a model and
        haven't explicitly specified an id field on serializer, like in
        IncorrectSerializer, the serializer successfully passes DRFME
        validation, but Mongoengine validation raises a ValidationError
        with a puzzling error message.

        We need a more explicit error message here, which tells DRFME user to
        override id field on serializer; don't know, how to implement this.
        """
        serializer = IncorrectSerializer(data=self.data)
        assert serializer.is_valid()
        with self.assertRaises(me_ValidationError):
            serializer.save()
#        #print "serializer.fields = %s" % serializer.fields
#        #print "serializer.validated_data = %s" % serializer.validated_data
#        #serializer.save()
#
#    def test_readable(self):
#        serializer = IncorrectSerializer() 
Example #2
Source File: action_db.py    From st2 with Apache License 2.0 6 votes vote down vote up
def get_liveaction_by_id(liveaction_id):
    """
        Get LiveAction by id.

        On error, raise ST2DBObjectNotFoundError.
    """
    liveaction = None

    try:
        liveaction = LiveAction.get_by_id(liveaction_id)
    except (ValidationError, ValueError) as e:
        LOG.error('Database lookup for LiveAction with id="%s" resulted in '
                  'exception: %s', liveaction_id, e)
        raise StackStormDBObjectNotFoundError('Unable to find LiveAction with '
                                              'id="%s"' % liveaction_id)

    return liveaction 
Example #3
Source File: action_db.py    From st2 with Apache License 2.0 6 votes vote down vote up
def get_action_by_id(action_id):
    """
        Get Action by id.

        On error, raise StackStormDBObjectNotFoundError
    """
    action = None

    try:
        action = Action.get_by_id(action_id)
    except (ValueError, ValidationError) as e:
        LOG.warning('Database lookup for action with id="%s" resulted in '
                    'exception: %s', action_id, e)
        raise StackStormDBObjectNotFoundError('Unable to find action with '
                                              'id="%s"' % action_id)

    return action 
Example #4
Source File: action_db.py    From st2 with Apache License 2.0 6 votes vote down vote up
def get_runnertype_by_name(runnertype_name):
    """
        Get an runnertype by name.
        On error, raise ST2ObjectNotFoundError.
    """
    try:
        runnertypes = RunnerType.query(name=runnertype_name)
    except (ValueError, ValidationError) as e:
        LOG.error('Database lookup for name="%s" resulted in exception: %s',
                  runnertype_name, e)
        raise StackStormDBObjectNotFoundError('Unable to find runnertype with name="%s"'
                                              % runnertype_name)

    if not runnertypes:
        raise StackStormDBObjectNotFoundError('Unable to find RunnerType with name="%s"'
                                              % runnertype_name)

    if len(runnertypes) > 1:
        LOG.warning('More than one RunnerType returned from DB lookup by name. '
                    'Result list is: %s', runnertypes)

    return runnertypes[0] 
Example #5
Source File: triggers.py    From st2 with Apache License 2.0 6 votes vote down vote up
def _create_shadow_trigger(triggertype_db):
        try:
            trigger_type_ref = triggertype_db.get_reference().ref
            trigger = {'name': triggertype_db.name,
                       'pack': triggertype_db.pack,
                       'type': trigger_type_ref,
                       'parameters': {}}
            trigger_db = TriggerService.create_or_update_trigger_db(trigger)

            extra = {'trigger_db': trigger_db}
            LOG.audit('Trigger created for parameter-less TriggerType. Trigger.id=%s' %
                      (trigger_db.id), extra=extra)
        except (ValidationError, ValueError) as e:
            LOG.exception('Validation failed for trigger data=%s.', trigger)
            # Not aborting as this is convenience.
            return
        except StackStormDBObjectConflictError as e:
            LOG.warn('Trigger creation of "%s" failed with uniqueness conflict. Exception: %s',
                     trigger, six.text_type(e))
            # Not aborting as this is convenience.
            return 
Example #6
Source File: triggers.py    From st2 with Apache License 2.0 6 votes vote down vote up
def post(self, trigger):
        """
            Create a new trigger.

            Handles requests:
                POST /triggers/
        """
        try:
            trigger_db = TriggerService.create_trigger_db(trigger)
        except (ValidationError, ValueError) as e:
            LOG.exception('Validation failed for trigger data=%s.', trigger)
            abort(http_client.BAD_REQUEST, six.text_type(e))
            return

        extra = {'trigger': trigger_db}
        LOG.audit('Trigger created. Trigger.id=%s' % (trigger_db.id), extra=extra)
        trigger_api = TriggerAPI.from_model(trigger_db)

        return Response(json=trigger_api, status=http_client.CREATED) 
Example #7
Source File: triggers.py    From st2 with Apache License 2.0 6 votes vote down vote up
def put(self, trigger, trigger_id):
        trigger_db = TriggerController.__get_by_id(trigger_id)
        try:
            if trigger.id is not None and trigger.id != '' and trigger.id != trigger_id:
                LOG.warning('Discarding mismatched id=%s found in payload and using uri_id=%s.',
                            trigger.id, trigger_id)
            trigger_db = TriggerAPI.to_model(trigger)
            trigger_db.id = trigger_id
            trigger_db = Trigger.add_or_update(trigger_db)
        except (ValidationError, ValueError) as e:
            LOG.exception('Validation failed for trigger data=%s', trigger)
            abort(http_client.BAD_REQUEST, six.text_type(e))
            return

        extra = {'old_trigger_db': trigger, 'new_trigger_db': trigger_db}
        LOG.audit('Trigger updated. Trigger.id=%s' % (trigger.id), extra=extra)
        trigger_api = TriggerAPI.from_model(trigger_db)

        return trigger_api 
Example #8
Source File: fields.py    From marshmallow-mongoengine with MIT License 6 votes vote down vote up
def _deserialize(self, value, attr, data):
        # To deserialize a generic reference, we need a _cls field in addition
        # with the id field
        if not isinstance(value, dict) or not value.get('id') or not value.get('_cls'):
            raise ValidationError("Need a dict with 'id' and '_cls' fields")
        doc_id = value['id']
        doc_cls_name = value['_cls']
        if self.document_class_choices and doc_cls_name not in self.document_class_choices:
            raise ValidationError("Invalid _cls field `%s`, must be one of %s" %
                                  (doc_cls_name, self.document_class_choices))
        try:
            doc_cls = get_document(doc_cls_name)
        except NotRegistered:
            raise ValidationError("Invalid _cls field `%s`" % doc_cls_name)
        try:
            doc = doc_cls.objects.get(pk=doc_id)
        except (doc_cls.DoesNotExist, MongoValidationError, ValueError, TypeError):
            raise ValidationError('unknown document %s `%s`' %
                                  (doc_cls_name, value))
        return doc 
Example #9
Source File: triggers.py    From st2 with Apache License 2.0 5 votes vote down vote up
def __get_by_id(trigger_id):
        try:
            return Trigger.get_by_id(trigger_id)
        except (ValueError, ValidationError):
            LOG.exception('Database lookup for id="%s" resulted in exception.', trigger_id)
            abort(http_client.NOT_FOUND) 
Example #10
Source File: test_models.py    From celerybeat-mongo with Apache License 2.0 5 votes vote down vote up
def test_cannot_save_interval_schduler_with_a_invalid_period(self):
        periodic = PeriodicTask(task="foo")
        with self.assertRaises(ValidationError):
            periodic.interval = PeriodicTask.Interval(every=1, period="days111")
            periodic.save() 
Example #11
Source File: test_models.py    From celerybeat-mongo with Apache License 2.0 5 votes vote down vote up
def test_must_define_interval_or_crontab(self):
        with self.assertRaises(ValidationError) as err:
            periodic = PeriodicTask(task="foo")
            periodic.save()
        self.assertTrue("Must defined either interval or crontab schedule." in err.exception.message) 
Example #12
Source File: test_models.py    From celerybeat-mongo with Apache License 2.0 5 votes vote down vote up
def test_cannot_define_both_interval_and_contrab(self):
        periodic = PeriodicTask(task="foo")
        periodic.interval = PeriodicTask.Interval(every=1, period="days")
        periodic.crontab = PeriodicTask.Crontab(minute="0", hour="*", day_of_week="*",
                                                day_of_month="10-15", month_of_year="*")
        with self.assertRaises(ValidationError) as err:
            periodic.save()
        self.assertTrue("Cannot define both interval and crontab schedule." in err.exception.message) 
Example #13
Source File: generics.py    From django-rest-framework-mongoengine with MIT License 5 votes vote down vote up
def get_object_or_404(queryset, *args, **kwargs):
    """ replacement of rest_framework.generics and django.shrtcuts analogues """
    try:
        return queryset.get(*args, **kwargs)
    except (ValueError, TypeError, DoesNotExist, ValidationError):
        raise Http404() 
Example #14
Source File: policies.py    From st2 with Apache License 2.0 5 votes vote down vote up
def put(self, instance, ref_or_id, requester_user):
        op = 'PUT /policies/%s/' % ref_or_id

        db_model = self._get_by_ref_or_id(ref_or_id=ref_or_id)
        LOG.debug('%s found object: %s', op, db_model)

        permission_type = PermissionType.POLICY_MODIFY
        rbac_utils = get_rbac_backend().get_utils_class()
        rbac_utils.assert_user_has_resource_db_permission(user_db=requester_user,
                                                          resource_db=db_model,
                                                          permission_type=permission_type)

        db_model_id = db_model.id

        try:
            validate_not_part_of_system_pack(db_model)
        except ValueValidationException as e:
            LOG.exception('%s unable to update object from system pack.', op)
            abort(http_client.BAD_REQUEST, six.text_type(e))

        if not getattr(instance, 'pack', None):
            instance.pack = db_model.pack

        try:
            db_model = self.model.to_model(instance)
            db_model.id = db_model_id
            db_model = self.access.add_or_update(db_model)
        except (ValidationError, ValueError) as e:
            LOG.exception('%s unable to update object: %s', op, db_model)
            abort(http_client.BAD_REQUEST, six.text_type(e))
            return

        LOG.debug('%s updated object: %s', op, db_model)
        LOG.audit('Policy updated. Policy.id=%s' % (db_model.id), extra={'policy_db': db_model})

        exec_result = self.model.from_model(db_model)

        return Response(json=exec_result, status=http_client.OK) 
Example #15
Source File: triggers.py    From st2 with Apache License 2.0 5 votes vote down vote up
def put(self, triggertype, triggertype_ref_or_id):
        triggertype_db = self._get_by_ref_or_id(ref_or_id=triggertype_ref_or_id)
        triggertype_id = triggertype_db.id

        try:
            validate_not_part_of_system_pack(triggertype_db)
        except ValueValidationException as e:
            abort(http_client.BAD_REQUEST, six.text_type(e))

        try:
            triggertype_db = TriggerTypeAPI.to_model(triggertype)
            if triggertype.id is not None and len(triggertype.id) > 0 and \
               triggertype.id != triggertype_id:
                LOG.warning('Discarding mismatched id=%s found in payload and using uri_id=%s.',
                            triggertype.id, triggertype_id)
            triggertype_db.id = triggertype_id
            old_triggertype_db = triggertype_db
            triggertype_db = TriggerType.add_or_update(triggertype_db)
        except (ValidationError, ValueError) as e:
            LOG.exception('Validation failed for triggertype data=%s', triggertype)
            abort(http_client.BAD_REQUEST, six.text_type(e))
            return

        extra = {'old_triggertype_db': old_triggertype_db, 'new_triggertype_db': triggertype_db}
        LOG.audit('TriggerType updated. TriggerType.id=%s' % (triggertype_db.id), extra=extra)

        triggertype_api = TriggerTypeAPI.from_model(triggertype_db)
        return triggertype_api 
Example #16
Source File: action_views.py    From st2 with Apache License 2.0 5 votes vote down vote up
def _get_runner_by_name(name):
        try:
            return RunnerType.get_by_name(name)
        except (ValueError, ValidationError) as e:
            msg = 'Database lookup for name="%s" resulted in exception. %s' % (id, e)
            LOG.exception(msg)
            abort(http_client.NOT_FOUND, msg) 
Example #17
Source File: action_views.py    From st2 with Apache License 2.0 5 votes vote down vote up
def _get_runner_by_id(id):
        try:
            return RunnerType.get_by_id(id)
        except (ValueError, ValidationError) as e:
            msg = 'Database lookup for id="%s" resulted in exception. %s' % (id, e)
            LOG.exception(msg)
            abort(http_client.NOT_FOUND, msg) 
Example #18
Source File: actionalias.py    From st2 with Apache License 2.0 5 votes vote down vote up
def put(self, action_alias, ref_or_id, requester_user):
        """
            Update an action alias.

            Handles requests:
                PUT /actionalias/1
        """
        action_alias_db = self._get_by_ref_or_id(ref_or_id=ref_or_id)
        LOG.debug('PUT /actionalias/ lookup with id=%s found object: %s', ref_or_id,
                  action_alias_db)

        permission_type = PermissionType.ACTION_ALIAS_MODIFY
        rbac_utils = get_rbac_backend().get_utils_class()
        rbac_utils.assert_user_has_resource_db_permission(user_db=requester_user,
                                                          resource_db=action_alias_db,
                                                          permission_type=permission_type)

        if not hasattr(action_alias, 'id'):
            action_alias.id = None

        try:
            if action_alias.id is not None and action_alias.id != '' and \
               action_alias.id != ref_or_id:
                LOG.warning('Discarding mismatched id=%s found in payload and using uri_id=%s.',
                            action_alias.id, ref_or_id)
            old_action_alias_db = action_alias_db
            action_alias_db = ActionAliasAPI.to_model(action_alias)
            action_alias_db.id = ref_or_id
            action_alias_db = ActionAlias.add_or_update(action_alias_db)
        except (ValidationError, ValueError) as e:
            LOG.exception('Validation failed for action alias data=%s', action_alias)
            abort(http_client.BAD_REQUEST, six.text_type(e))
            return

        extra = {'old_action_alias_db': old_action_alias_db, 'new_action_alias_db': action_alias_db}
        LOG.audit('Action alias updated. ActionAlias.id=%s.' % (action_alias_db.id), extra=extra)
        action_alias_api = ActionAliasAPI.from_model(action_alias_db)

        return action_alias_api 
Example #19
Source File: actionalias.py    From st2 with Apache License 2.0 5 votes vote down vote up
def post(self, action_alias, requester_user):
        """
            Create a new ActionAlias.

            Handles requests:
                POST /actionalias/
        """

        permission_type = PermissionType.ACTION_ALIAS_CREATE
        rbac_utils = get_rbac_backend().get_utils_class()
        rbac_utils.assert_user_has_resource_api_permission(user_db=requester_user,
                                                           resource_api=action_alias,
                                                           permission_type=permission_type)

        try:
            action_alias_db = ActionAliasAPI.to_model(action_alias)
            LOG.debug('/actionalias/ POST verified ActionAliasAPI and formulated ActionAliasDB=%s',
                      action_alias_db)
            action_alias_db = ActionAlias.add_or_update(action_alias_db)
        except (ValidationError, ValueError, ValueValidationException) as e:
            LOG.exception('Validation failed for action alias data=%s.', action_alias)
            abort(http_client.BAD_REQUEST, six.text_type(e))
            return

        extra = {'action_alias_db': action_alias_db}
        LOG.audit('Action alias created. ActionAlias.id=%s' % (action_alias_db.id), extra=extra)
        action_alias_api = ActionAliasAPI.from_model(action_alias_db)

        return Response(json=action_alias_api, status=http_client.CREATED) 
Example #20
Source File: auth.py    From st2 with Apache License 2.0 5 votes vote down vote up
def get_one(self, api_key_id_or_key, requester_user, show_secrets=None):
        """
            List api keys.

            Handle:
                GET /apikeys/1
        """
        api_key_db = None
        try:
            api_key_db = ApiKey.get_by_key_or_id(api_key_id_or_key)
        except ApiKeyNotFoundError:
            msg = ('ApiKey matching %s for reference and id not found.' % (api_key_id_or_key))
            LOG.exception(msg)
            abort(http_client.NOT_FOUND, msg)

        permission_type = PermissionType.API_KEY_VIEW
        rbac_utils = get_rbac_backend().get_utils_class()
        rbac_utils.assert_user_has_resource_db_permission(user_db=requester_user,
                                                          resource_db=api_key_db,
                                                          permission_type=permission_type)

        try:
            mask_secrets = self._get_mask_secrets(show_secrets=show_secrets,
                                                  requester_user=requester_user)
            return ApiKeyAPI.from_model(api_key_db, mask_secrets=mask_secrets)
        except (ValidationError, ValueError) as e:
            LOG.exception('Failed to serialize API key.')
            abort(http_client.INTERNAL_SERVER_ERROR, six.text_type(e)) 
Example #21
Source File: ruletypes.py    From st2 with Apache License 2.0 5 votes vote down vote up
def __get_by_id(id):
        try:
            return RuleType.get_by_id(id)
        except (ValueError, ValidationError) as e:
            msg = 'Database lookup for id="%s" resulted in exception. %s' % (id, e)
            LOG.exception(msg)
            abort(http_client.NOT_FOUND, msg) 
Example #22
Source File: database.py    From cascade-server with Apache License 2.0 5 votes vote down vote up
def validate(self, value):
        if isinstance(value, datetime.timedelta):
            pass
        elif isinstance(value, int) or isinstance(value, float):
            pass
        elif isinstance(value, str):
            # Attempt to convert it from a string
            self.from_str(value)
        else:
            raise mongoengine.ValidationError("type {} can't be converted to timedelta".format(type(value))) 
Example #23
Source File: views.py    From pfont with GNU General Public License v2.0 5 votes vote down vote up
def donate():
    try:
        form = DonatorForm(request.form)

        if form.validate():
            # temporary naughty way

            try:
                donator_obj = Donator.objects.get(email=form.email.data.lower())

            except (ValidationError, DoesNotExist):
                donator_obj = Donator(email=form.email.data.lower(), nickname=form.nickname.data)

            donator_obj.save()

            donate_obj = Donate(amount=form.amount.data, donator=donator_obj)

            donate_obj.save()

            cl = Client(current_app.config['ZARINPAL_WEBSERVICE'])

            result = cl.service.PaymentRequest(current_app.config['MMERCHANT_ID'],
                                               donate_obj.amount,
                                               u'هدیه از طرف %s' % donator_obj.name,
                                               donator_obj.email,
                                               '',
                                               str(url_for('main.donate_callback', _external=True, donate_id=donate_obj.pk)))
            if result.Status == 100:
                # connect to bank here
                return jsonify({'status': 1, 'redirect': 'https://www.zarinpal.com/pg/StartPay/' + result.Authority})
            else:
                return jsonify({'status': 3, 'error': english_num_to_persian(result.Status), 'form': minify(render_template('donate_form.html', form=form))})

        return jsonify({'status': 2, 'form': minify(render_template('donate_form.html', form=form))})
    except Exception as e:
        traceback.print_exc()
        print e.message
        return abort(500) 
Example #24
Source File: test_reference.py    From st2 with Apache License 2.0 5 votes vote down vote up
def test_to_model_unknown_id(self):
        try:
            reference.get_model_from_ref(Trigger, {'id': '1'})
            self.assertTrue(False, 'Exception expected.')
        except mongoengine.ValidationError:
            self.assertTrue(True) 
Example #25
Source File: test_tags.py    From st2 with Apache License 2.0 5 votes vote down vote up
def test_value_exceeds_max_size(self):
        instance = TaggedModel()
        instance.tags = [stormbase.TagField(name='n1',
                                            value=self._gen_random_string(1025))]
        try:
            instance.save()
            self.assertTrue(False, 'Expected save to fail')
        except ValidationError:
            pass 
Example #26
Source File: test_tags.py    From st2 with Apache License 2.0 5 votes vote down vote up
def test_name_exceeds_max_size(self):
        instance = TaggedModel()
        instance.tags = [stormbase.TagField(name=self._gen_random_string(1025),
                                            value='v1')]
        try:
            instance.save()
            self.assertTrue(False, 'Expected save to fail')
        except ValidationError:
            pass 
Example #27
Source File: action_db.py    From st2 with Apache License 2.0 5 votes vote down vote up
def get_runnertype_by_id(runnertype_id):
    """
        Get RunnerType by id.

        On error, raise StackStormDBObjectNotFoundError
    """
    try:
        runnertype = RunnerType.get_by_id(runnertype_id)
    except (ValueError, ValidationError) as e:
        LOG.warning('Database lookup for runnertype with id="%s" resulted in '
                    'exception: %s', runnertype_id, e)
        raise StackStormDBObjectNotFoundError('Unable to find runnertype with '
                                              'id="%s"' % runnertype_id)

    return runnertype 
Example #28
Source File: trace.py    From st2 with Apache License 2.0 5 votes vote down vote up
def get_trace(trace_context, ignore_trace_tag=False):
    """
    :param trace_context: context object using which a trace can be found.
    :type trace_context: ``dict`` or ``TraceContext``

    :param ignore_trace_tag: Even if a trace_tag is provided will be ignored.
    :type ignore_trace_tag: ``str``

    :rtype: ``TraceDB``
    """

    trace_context = _get_valid_trace_context(trace_context)

    if not trace_context.id_ and not trace_context.trace_tag:
        raise ValueError('Atleast one of id_ or trace_tag should be specified.')

    if trace_context.id_:
        try:
            return Trace.get_by_id(trace_context.id_)
        except (ValidationError, ValueError):
            LOG.warning('Database lookup for Trace with id="%s" failed.',
                        trace_context.id_, exc_info=True)
            raise StackStormDBObjectNotFoundError(
                'Unable to find Trace with id="%s"' % trace_context.id_)

    if ignore_trace_tag:
        return None

    traces = Trace.query(trace_tag=trace_context.trace_tag)

    # Assume this method only handles 1 trace.
    if len(traces) > 1:
        raise UniqueTraceNotFoundException(
            'More than 1 Trace matching %s found.' % trace_context.trace_tag)

    return traces[0] 
Example #29
Source File: test_models.py    From baleen with MIT License 5 votes vote down vote up
def test_url_requred(self):
        """
        Assert that the post url is required
        """
        post = Post(title="My Awesome Post", content="socks")
        with self.assertRaises(me.ValidationError):
            post.save() 
Example #30
Source File: test_models.py    From baleen with MIT License 5 votes vote down vote up
def test_link_requred(self):
        """
        Assert that the feed link is required
        """
        feed = Feed(title="My Awesome Feed", category="socks")
        with self.assertRaises(me.ValidationError):
            feed.save()