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


Python errors.DoesNotExist方法代码示例

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


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

示例1: to_internal_value

# 需要导入模块: from mongoengine import errors [as 别名]
# 或者: from mongoengine.errors import DoesNotExist [as 别名]
def to_internal_value(self, value):
        if not isinstance(value, dict):
            self.fail('not_a_dict', input_type=type(value).__name__)
        try:
            doc_name = value['_cls']
            doc_id = value['_id']
        except KeyError:
            self.fail('missing_items')
        try:
            doc_cls = get_document(doc_name)
        except NotRegistered:
            self.fail('undefined_model', doc_cls=doc_name)

        try:
            doc_id = self.pk_field.to_internal_value(doc_id)
        except:
            self.fail('invalid_id', pk_value=repr(doc_id), pk_type=self.pk_field_class.__name__)

        try:
            return doc_cls.objects.only('id').get(id=doc_id)
        except DoesNotExist:
            self.fail('not_found', pk_value=doc_id) 
开发者ID:umutbozkurt,项目名称:django-rest-framework-mongoengine,代码行数:24,代码来源:fields.py

示例2: activity_feed

# 需要导入模块: from mongoengine import errors [as 别名]
# 或者: from mongoengine.errors import DoesNotExist [as 别名]
def activity_feed():
    activity_keys = request.args.getlist('key')

    feed = AtomFeed(
        current_app.config.get('SITE_TITLE'), feed_url=request.url,
        url=request.url_root)
    activities = (Activity.objects.order_by('-created_at')
                                  .limit(current_site.feed_size))

    for activity in activities.select_related():
        # filter by activity.key
        # /!\ this won't completely honour `feed_size` (only as a max value)
        if activity_keys and activity.key not in activity_keys:
            continue
        try:
            owner = activity.actor or activity.organization
        except DoesNotExist:
            owner = 'deleted'
            owner_url = None
        else:
            owner_url = owner.url_for(_external=True)
        try:
            related = activity.related_to
        except DoesNotExist:
            related = 'deleted'
            related_url = None
        else:
            related_url = related.url_for(_external=True)
        feed.add(
            id='%s#activity=%s' % (
                url_for('site.dashboard', _external=True), activity.id),
            title='%s by %s on %s' % (
                activity.key, owner, related),
            url=related_url,
            author={
                'name': owner,
                'uri': owner_url,
            },
            updated=activity.created_at
        )
    return feed.get_response() 
开发者ID:opendatateam,项目名称:udata,代码行数:43,代码来源:views.py

示例3: get

# 需要导入模块: from mongoengine import errors [as 别名]
# 或者: from mongoengine.errors import DoesNotExist [as 别名]
def get(self):
        '''Fetch site activity, optionally filtered by user of org.'''
        args = activity_parser.parse_args()
        qs = Activity.objects

        if args['organization']:
            qs = qs(db.Q(organization=args['organization']) |
                    db.Q(related_to=args['organization']))

        if args['user']:
            qs = qs(actor=args['user'])

        qs = qs.order_by('-created_at')
        qs = qs.paginate(args['page'], args['page_size'])

        # Filter out DBRefs
        # Always return a result even not complete
        # But log the error (ie. visible in sentry, silent for user)
        # Can happen when someone manually delete an object in DB (ie. without proper purge)
        safe_items = []
        for item in qs.queryset.items:
            try:
                item.related_to
            except DoesNotExist as e:
                log.error(e, exc_info=True)
            else:
                safe_items.append(item)
        qs.queryset.items = safe_items

        return qs 
开发者ID:opendatateam,项目名称:udata,代码行数:32,代码来源:api.py

示例4: create_entities

# 需要导入模块: from mongoengine import errors [as 别名]
# 或者: from mongoengine.errors import DoesNotExist [as 别名]
def create_entities(self, sheet_name, actors_list_info):
        for actor_names, campaigns, tools in actors_list_info:
            primary = actor_names[0]
            # create Actors with aliases
            _actor = Actor.get_or_create(name=primary)
            _actor.aliases = actor_names[1:]
            _actor.save()
            # create the campaign
            for c in campaigns:
                # logging.info(repr(c))
                # BUG Issue #120 - is there a bug where two entities cannot have the same name
                # Naikon the actor conflicts with Naikon the campaign
                _campaign = ''
                try:
                    _campaign = Campaign.get_or_create(name=c)
                except DoesNotExist:
                    _campaign = Campaign.get_or_create(name="CAMPAIGN-" + c)
                _actor.action(_campaign, self.name)
            # create the tools
            for mal in tools:
                _mal = ''
                try:
                    _mal = Malware.get_or_create(name=mal)
                except DoesNotExist:
                    _mal = Malware.get_or_create(name="MALWARE-" + mal)
                _actor.action(_mal, self.name)
        return 
开发者ID:yeti-platform,项目名称:yeti,代码行数:29,代码来源:threattracking.py

示例5: content

# 需要导入模块: from mongoengine import errors [as 别名]
# 或者: from mongoengine.errors import DoesNotExist [as 别名]
def content(self, id):
        """Return export content

        Returns a given export's content.

        :query ObjectID id: Export ID
        :resheader X-Yeti-Export-MD5: The MD5 hash of the exported content. Use it to check the export's integrity
        """
        try:
            e = self.objectmanager.objects.get(id=id)
        except DoesNotExist:
            return render({
                "error": "No Export found for id {}".format(id)
            }), 404
        if e.output_dir.startswith("/"):
            d = e.output_dir
        else:
            d = os.path.join(
                os.path.dirname(
                    os.path.dirname(
                        os.path.dirname(
                            os.path.dirname(os.path.abspath(__file__))))),
                e.output_dir)

        response = make_response(
            send_from_directory(
                d, e.name, as_attachment=True, attachment_filename=e.name))
        response.headers['X-Yeti-Export-MD5'] = e.hash_md5
        return response 
开发者ID:yeti-platform,项目名称:yeti,代码行数:31,代码来源:export.py

示例6: load_user

# 需要导入模块: from mongoengine import errors [as 别名]
# 或者: from mongoengine.errors import DoesNotExist [as 别名]
def load_user(session_token):
    try:
        return User.objects.get(session_token=session_token)
    except DoesNotExist:
        return None 
开发者ID:yeti-platform,项目名称:yeti,代码行数:7,代码来源:webapp.py

示例7: api_auth

# 需要导入模块: from mongoengine import errors [as 别名]
# 或者: from mongoengine.errors import DoesNotExist [as 别名]
def api_auth(request):
    try:
        return User.objects.get(api_key=request.headers.get('X-Api-Key'))
    except DoesNotExist:
        return None 
开发者ID:yeti-platform,项目名称:yeti,代码行数:7,代码来源:webapp.py

示例8: authenticate

# 需要导入模块: from mongoengine import errors [as 别名]
# 或者: from mongoengine.errors import DoesNotExist [as 别名]
def authenticate():
    username = request.environ.get(yeti_config.auth.apache_variable)
    if username is None:
        return False
    try:
        return User.objects.get(username=username)
    except DoesNotExist:
        return create_user(username) 
开发者ID:yeti-platform,项目名称:yeti,代码行数:10,代码来源:user_management.py

示例9: login

# 需要导入模块: from mongoengine import errors [as 别名]
# 或者: from mongoengine.errors import DoesNotExist [as 别名]
def login():
  """
  Login form
  """
  form = LoginForm(request.form)
  # make sure data are valid, but doesn't validate password is right
  if form.validate_on_submit():
    #user = User.query.filter_by(email=form.email.data).first()
    try:
      user = User.objects.get(username=form.username.data)
      # we use werzeug to validate user's password
      if check_password_hash(user.password, form.password.data): #optional: bool(user)
        # the session can't be modified as it's signed,
        # it's a safe place to store the user id
        session['user_id'] = str(user.id)
        session['user'] = user.username
        # user.current_user = True
        # user.save()
        #flash('Success! Welcome %s!' % user.name)
        return redirect(url_for('home'))
    except errors.DoesNotExist:
      #raise#flash('Wrong email or password', 'error-message')
      return render_template("users/login.html",
                             doesnt_exist=True,
                             form=form,
                             user=None)
  return render_template("users/login.html", form=form, user=None) 
开发者ID:distributed-system-analysis,项目名称:sarjitsu,代码行数:29,代码来源:views.py

示例10: test_delete

# 需要导入模块: from mongoengine import errors [as 别名]
# 或者: from mongoengine.errors import DoesNotExist [as 别名]
def test_delete(self):
        """
        Test the DeleteGroup function.
        """
        group = Database.create_group()
        data = APIClient.delete_group(self.client, group.name)
        self.assertEqual(data['error'], False)
        with self.assertRaises(DoesNotExist):
            Database.get_group(group.name) 
开发者ID:KCarretto,项目名称:Arsenal,代码行数:11,代码来源:group_test.py

示例11: GET

# 需要导入模块: from mongoengine import errors [as 别名]
# 或者: from mongoengine.errors import DoesNotExist [as 别名]
def GET(self, **data):
        date = datetime.datetime.now()
        if "date" in data:
            date = datetime.datetime.strptime(data["date"], "%Y-%m-%dt%H:%M:%S")

        if self.name == "moves":
            try:
                _hosts = model.Host.objects()

                result = []
                for _host in _hosts:

                    _scheduled_cloud = _host.default_cloud.name
                    _host_defined_cloud = _host.cloud.name
                    _current_schedule = self.model.current_schedule(host=_host, date=date).first()
                    try:
                        if _current_schedule:
                            _scheduled_cloud = _current_schedule.cloud.name
                        if _scheduled_cloud != _host_defined_cloud:
                            result.append(
                                {
                                    "host": _host.name,
                                    "new": _scheduled_cloud,
                                    "current": _host_defined_cloud,
                                }
                            )
                    except DoesNotExist:
                        continue

                return json.dumps({"result": result})
            except Exception as ex:
                logger.debug(ex)
                logger.info("400 Bad Request")
                cherrypy.response.status = "400 Bad Request"
                return json.dumps({"result": ["400 Bad Request"]}) 
开发者ID:redhat-performance,项目名称:quads,代码行数:37,代码来源:api_v2.py

示例12: remove_image

# 需要导入模块: from mongoengine import errors [as 别名]
# 或者: from mongoengine.errors import DoesNotExist [as 别名]
def remove_image(img_id, resp):
    try:
        img = PicBed.objects.get(img_id=img_id)
        base_dir = current_app.config["UPLOAD_BASE_FOLDER"]
        file_path = Path(base_dir) / img.img_name
        if file_path.is_file():
            img.delete()
            file_path.unlink()
            return resp
    except DoesNotExist:
        pass
    abort(404) 
开发者ID:leollon,项目名称:yet-another-image-bed,代码行数:14,代码来源:utils.py


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