當前位置: 首頁>>代碼示例>>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;未經允許,請勿轉載。