当前位置: 首页>>代码示例>>Python>>正文


Python mongoengine.ValidationError方法代码示例

本文整理汇总了Python中mongoengine.ValidationError方法的典型用法代码示例。如果您正苦于以下问题:Python mongoengine.ValidationError方法的具体用法?Python mongoengine.ValidationError怎么用?Python mongoengine.ValidationError使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在mongoengine的用法示例。


在下文中一共展示了mongoengine.ValidationError方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: _deserialize

# 需要导入模块: import mongoengine [as 别名]
# 或者: from mongoengine import ValidationError [as 别名]
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 
开发者ID:touilleMan,项目名称:marshmallow-mongoengine,代码行数:22,代码来源:fields.py

示例2: get_runnertype_by_name

# 需要导入模块: import mongoengine [as 别名]
# 或者: from mongoengine import ValidationError [as 别名]
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] 
开发者ID:StackStorm,项目名称:st2,代码行数:24,代码来源:action_db.py

示例3: get_action_by_id

# 需要导入模块: import mongoengine [as 别名]
# 或者: from mongoengine import ValidationError [as 别名]
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 
开发者ID:StackStorm,项目名称:st2,代码行数:19,代码来源:action_db.py

示例4: get_liveaction_by_id

# 需要导入模块: import mongoengine [as 别名]
# 或者: from mongoengine import ValidationError [as 别名]
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 
开发者ID:StackStorm,项目名称:st2,代码行数:19,代码来源:action_db.py

示例5: _create_shadow_trigger

# 需要导入模块: import mongoengine [as 别名]
# 或者: from mongoengine import ValidationError [as 别名]
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 
开发者ID:StackStorm,项目名称:st2,代码行数:23,代码来源:triggers.py

示例6: post

# 需要导入模块: import mongoengine [as 别名]
# 或者: from mongoengine import ValidationError [as 别名]
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) 
开发者ID:StackStorm,项目名称:st2,代码行数:21,代码来源:triggers.py

示例7: put

# 需要导入模块: import mongoengine [as 别名]
# 或者: from mongoengine import ValidationError [as 别名]
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 
开发者ID:StackStorm,项目名称:st2,代码行数:21,代码来源:triggers.py

示例8: test_incorrect

# 需要导入模块: import mongoengine [as 别名]
# 或者: from mongoengine import ValidationError [as 别名]
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() 
开发者ID:umutbozkurt,项目名称:django-rest-framework-mongoengine,代码行数:22,代码来源:test_id.py

示例9: validate

# 需要导入模块: import mongoengine [as 别名]
# 或者: from mongoengine import ValidationError [as 别名]
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))) 
开发者ID:mitre,项目名称:cascade-server,代码行数:12,代码来源:database.py

示例10: donate

# 需要导入模块: import mongoengine [as 别名]
# 或者: from mongoengine import ValidationError [as 别名]
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) 
开发者ID:hamidfzm,项目名称:pfont,代码行数:40,代码来源:views.py

示例11: test_link_requred

# 需要导入模块: import mongoengine [as 别名]
# 或者: from mongoengine import ValidationError [as 别名]
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() 
开发者ID:DistrictDataLabs,项目名称:baleen,代码行数:9,代码来源:test_models.py

示例12: test_url_requred

# 需要导入模块: import mongoengine [as 别名]
# 或者: from mongoengine import ValidationError [as 别名]
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() 
开发者ID:DistrictDataLabs,项目名称:baleen,代码行数:9,代码来源:test_models.py

示例13: get_trace

# 需要导入模块: import mongoengine [as 别名]
# 或者: from mongoengine import ValidationError [as 别名]
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] 
开发者ID:StackStorm,项目名称:st2,代码行数:38,代码来源:trace.py

示例14: get_runnertype_by_id

# 需要导入模块: import mongoengine [as 别名]
# 或者: from mongoengine import ValidationError [as 别名]
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 
开发者ID:StackStorm,项目名称:st2,代码行数:17,代码来源:action_db.py

示例15: test_name_exceeds_max_size

# 需要导入模块: import mongoengine [as 别名]
# 或者: from mongoengine import ValidationError [as 别名]
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 
开发者ID:StackStorm,项目名称:st2,代码行数:11,代码来源:test_tags.py


注:本文中的mongoengine.ValidationError方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。