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


Python mongoengine.DoesNotExist方法代码示例

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


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

示例1: update_host

# 需要导入模块: import mongoengine [as 别名]
# 或者: from mongoengine import DoesNotExist [as 别名]
def update_host(self):
        try:
            host = self.host
        except DoesNotExist:
            host = None
        hostname = self.state.hostname.upper()

        if not isinstance(host, Host):
            host = Host.update_existing(hostname=hostname)
            self.modify(host=host)

        if self.state.fqdn is not None and host.fqdn is None:
            host.update(fqdn=self.state.fqdn)

        elif host.fqdn is not None and self.state.fqdn is None:
            self.modify(state__fqdn=host.fqdn.upper())

        if 'user' in self.fields and self and self.state.user:
            host.update(add_to_set__users=self.state.user) 
开发者ID:mitre,项目名称:cascade-server,代码行数:21,代码来源:event.py

示例2: fetch

# 需要导入模块: import mongoengine [as 别名]
# 或者: from mongoengine import DoesNotExist [as 别名]
def fetch(retry=0):
    proxy = 'http://{}'.format(Proxy.get_random()['address'])
    headers = {'user-agent': get_user_agent()}
    conn = aiohttp.ProxyConnector(proxy=proxy)

    url = 'http://httpbin.org/ip'

    try:
        with aiohttp.ClientSession(connector=conn) as session:
            with aiohttp.Timeout(TIMEOUT):
                async with session.get(url, headers=headers) as resp:
                    return await resp.json()
    except (ProxyConnectionError, TimeoutError):
        try:
            p = Proxy.objects.get(address=proxy)
            if p:
                p.delete()
        except DoesNotExist:
            pass
        retry += 1
        if retry > 5:
            raise TimeoutError()
        await asyncio.sleep(1)
        return await fetch(retry=retry) 
开发者ID:dongweiming,项目名称:web_develop,代码行数:26,代码来源:aiohttp_fetcher.py

示例3: test_create

# 需要导入模块: import mongoengine [as 别名]
# 或者: from mongoengine import DoesNotExist [as 别名]
def test_create(self):
        """
        This test will pass if the target is created.
        """

        with self.assertRaises(DoesNotExist):
            Database.get_target('TEST Target')

        data = APIClient.create_target(
            self.client,
            'TEST Target',
            'AA:BB:CC:DD:EE:FF',
            {'test_fact': 'hello'})

        self.assertEqual(False, data['error'])

        target = Database.get_target('TEST Target')
        self.assertIsNotNone(target)
        self.assertEqual(target.name, 'TEST Target')
        self.assertEqual('AA:BB:CC:DD:EE:FF', target.uuid)
        self.assertDictEqual({'test_fact': 'hello'}, target.facts) 
开发者ID:KCarretto,项目名称:Arsenal,代码行数:23,代码来源:target_test.py

示例4: test_target_rename

# 需要导入模块: import mongoengine [as 别名]
# 或者: from mongoengine import DoesNotExist [as 别名]
def test_target_rename(self):
        """
        Tests the RenameTarget API function.
        """
        target = Database.create_target('NOTTHIS')
        data = APIClient.rename_target(self.client, target.name, 'TEST')
        self.assertEqual(data['error'], False)
        target = Database.get_target('TEST')
        self.assertIsNotNone(target)
        self.assertEqual(target.name, 'TEST')
        with self.assertRaises(DoesNotExist):
            Database.get_target('NOTTHIS')

        target2 = Database.create_target()
        data = APIClient.rename_target(self.client, target2.name, 'TEST')
        self.assertEqual(data['error'], True)
        self.assertEqual(data['error_type'], 'cannot-rename-target')
        self.assertIsNotNone(Database.get_target(target2.name)) 
开发者ID:KCarretto,项目名称:Arsenal,代码行数:20,代码来源:target_test.py

示例5: _get_or_create_variant

# 需要导入模块: import mongoengine [as 别名]
# 或者: from mongoengine import DoesNotExist [as 别名]
def _get_or_create_variant(self, record):
        try:
            var_hash = make_var_hash(record.REF, record.POS, [
                str(a) for a in record.ALT])
            v = Variant.objects.get(var_hash=var_hash)
            v.add_to_variant_set(self.vcf_variant_set)
        except DoesNotExist:
            try:
                reference = self.references[record.CHROM]
            except KeyError as e:
                raise KeyError(
                    "Reference %s cannot be found in reference set %s (%s). Please add it to the database." %
                    (record.CHROM, self.reference_set.id, self.reference_set.name))
            v = Variant.create_and_save(
                variant_sets=self.variant_sets,
                start=record.POS,
                reference_bases=record.REF,
                alternate_bases=[
                    str(a) for a in record.ALT],
                reference=reference,
                names=[record.ID])
        return v 
开发者ID:Mykrobe-tools,项目名称:mykrobe,代码行数:24,代码来源:models.py

示例6: run_make_probes_from_vcf_file

# 需要导入模块: import mongoengine [as 别名]
# 或者: from mongoengine import DoesNotExist [as 别名]
def run_make_probes_from_vcf_file(args):
    # Make VariantSet from vcf
    reference = os.path.basename(args.reference_filepath).split(".fa")[0]
    try:
        reference_set = ReferenceSet.objects.get(name=reference)
    except DoesNotExist:
        reference_set = ReferenceSet.create_and_save(name=reference)
        # Hack
    try:
        reference = Reference.create_and_save(
            name=reference, reference_sets=[reference_set], md5checksum=reference
        )
    except NotUniqueError:
        pass
    vcf = VCF(
        args.vcf,
        reference_set.id,
        method="tmp",
        force=True,
        append_to_global_variant_set=False,
    )
    vcf.add_to_database() 
开发者ID:Mykrobe-tools,项目名称:mykrobe,代码行数:24,代码来源:makeprobes.py

示例7: normalize_db

# 需要导入模块: import mongoengine [as 别名]
# 或者: from mongoengine import DoesNotExist [as 别名]
def normalize_db(self, data):
        try:
            news = QueryNewsModel.objects.get(
                id=data['id']
            )
            news.update(
                version=data.get('version', news.version),
                title=data.get('title', news.title),
                content=data.get('content', news.content),
                author=data.get('author', news.author),
                published_at=data.get('published_at', news.published_at),
                tags=data.get('tags', news.tags),
            )
            news.reload()
        except mongoengine.DoesNotExist:
            QueryNewsModel(
                id=data['id'],
                version=data['version'],
                title=data.get('title'),
                content=data.get('content'),
                author=data.get('author'),
                tags=data.get('tags'),
            ).save()
        except Exception as e:
            return e 
开发者ID:PacktPublishing,项目名称:Microservice-Patterns-and-Best-Practices,代码行数:27,代码来源:services.py

示例8: update_news

# 需要导入模块: import mongoengine [as 别名]
# 或者: from mongoengine import DoesNotExist [as 别名]
def update_news():
    try:
        post_data = request.get_json()
        news = News.objects.get(id=post_data['news_id'])
        news.update(
            title=post_data.get('title', news.title),
            content=post_data.get('content', news.content),
            author=post_data.get('author', news.author),
            tags=post_data.get('tags', news.tags),
        )
        news.reload()
        response_object = {
            'status': 'success',
            'news': news,
        }
        return jsonify(response_object), 200
    except mongoengine.DoesNotExist:
        return jsonify(response_object), 404 
开发者ID:PacktPublishing,项目名称:Microservice-Patterns-and-Best-Practices,代码行数:20,代码来源:views.py

示例9: inv_import

# 需要导入模块: import mongoengine [as 别名]
# 或者: from mongoengine import DoesNotExist [as 别名]
def inv_import(self):
        if request.method == "GET":
            return render_template(
                "{}/import.html".format(self.klass.__name__.lower()),
                groups=get_user_groups())
        else:
            text = request.form.get('text')
            url = request.form.get('url')
            sharing = request.form.get('sharing')

            if text:
                investigation = Investigation(
                    created_by=current_user.username, import_text=text)
                # set sharing permissions
                investigation.save()
                investigation.sharing_permissions(sharing)
                return redirect(
                    url_for(
                        'frontend.InvestigationView:import_from',
                        id=investigation.id))
            else:
                try:
                    if url:
                        import_method = ImportMethod.objects.get(acts_on="url")
                        results = import_method.run(url)
                    elif "file" in request.files:
                        target = AttachedFile.from_upload(request.files['file'])
                        import_method = ImportMethod.objects.get(
                            acts_on=target.content_type)
                        results = import_method.run(target)
                    else:
                        flash("You need to provide an input", "danger")
                        return redirect(request.referrer)
                    return redirect(
                        url_for(
                            'frontend.InvestigationView:import_wait',
                            id=results.id))
                except DoesNotExist:
                    flash("This file type is not supported.", "danger")
                    return render_template(
                        "{}/import.html".format(self.klass.__name__.lower())) 
开发者ID:yeti-platform,项目名称:yeti,代码行数:43,代码来源:investigations.py

示例10: get_id

# 需要导入模块: import mongoengine [as 别名]
# 或者: from mongoengine import DoesNotExist [as 别名]
def get_id(self, id):
        """Retrieves a file's content.

        :<id ObjectId corresponding to the file ObjectId
        """
        try:
            fileobj = self.objectmanager.objects.get(id=id)
            return Response(
                fileobj.body.stream_contents(), mimetype=fileobj.mime_type)
        except DoesNotExist:
            abort(404) 
开发者ID:yeti-platform,项目名称:yeti,代码行数:13,代码来源:file.py

示例11: get_hash

# 需要导入模块: import mongoengine [as 别名]
# 或者: from mongoengine import DoesNotExist [as 别名]
def get_hash(self, hash):
        """Retrieves a file's content.

        :<id ObjectId corresponding to the file ObjectId
        """
        try:
            fileobj = self.objectmanager.objects.get(hashes__value=hash)
            return Response(
                fileobj.body.stream_contents(), mimetype=fileobj.mime_type)
        except DoesNotExist:
            abort(404) 
开发者ID:yeti-platform,项目名称:yeti,代码行数:13,代码来源:file.py

示例12: execute_export

# 需要导入模块: import mongoengine [as 别名]
# 或者: from mongoengine import DoesNotExist [as 别名]
def execute_export(export_id):

    try:
        export = Export.objects.get(
            id=export_id,
            lock=None)  # check if we have implemented locking mechanisms
    except DoesNotExist:
        try:
            Export.objects.get(
                id=export_id, lock=False).modify(
                    lock=True)  # get object and change lock
            export = Export.objects.get(id=export_id)
        except DoesNotExist:
            # no unlocked Export was found, notify and return...
            logging.debug(
                "Export {} is already running...".format(
                    Export.objects.get(id=export_id).name))
            return

    try:
        if export.enabled:
            logging.debug("Running export {}".format(export.name))
            export.update_status("Exporting...")
            export.hash_md5 = export.execute()
            export.update_status("OK")
        else:
            logging.debug("Export {} has been disabled".format(export.name))
    except Exception as e:
        msg = "ERROR executing export: {}".format(e)
        logging.error(msg)
        logging.error(traceback.format_exc())
        export.update_status(msg)

    if export.lock:  # release lock if it was set
        export.lock = False

    export.last_run = datetime.utcnow()
    export.save() 
开发者ID:yeti-platform,项目名称:yeti,代码行数:40,代码来源:export.py

示例13: authenticate

# 需要导入模块: import mongoengine [as 别名]
# 或者: from mongoengine import DoesNotExist [as 别名]
def authenticate(username, password):
    try:
        u = User.objects.get(username=username)
        if check_password_hash(u.password, password):
            userLogger.info("User logged in : %s",username)
            return u
        else:
            userLogger.warn("Attempt to log in to : %s",username)
            return False
    except DoesNotExist:
        return False 
开发者ID:yeti-platform,项目名称:yeti,代码行数:13,代码来源:user_management.py

示例14: schedule

# 需要导入模块: import mongoengine [as 别名]
# 或者: from mongoengine import DoesNotExist [as 别名]
def schedule(id):

    try:
        a = ScheduledAnalytics.objects.get(
            id=id, lock=None)  # check if we have implemented locking mechanisms
    except DoesNotExist:
        try:
            ScheduledAnalytics.objects.get(
                id=id, lock=False).modify(
                    lock=True)  # get object and change lock
            a = ScheduledAnalytics.objects.get(id=id)
        except DoesNotExist:
            # no unlocked ScheduledAnalytics was found, notify and return...
            logging.debug(
                "Task {} is already running...".format(
                    ScheduledAnalytics.objects.get(id=id).name))
            return

    if a.enabled:  # check if Analytics is enabled
        logging.debug("Running analytics {}".format(a.name))
        a.update_status("Running...")
        try:
            a.analyze_outdated()
            a.last_run = datetime.utcnow()
            a.update_status("OK")
        except Exception as e:
            logging.error("Error running Analytics {}: {}".format(a.name, e))
            a.update_status("ERROR")

    else:
        logging.debug("Analytics {} is disabled".format(a.name))

    if a.lock:  # release lock if it was set
        a.lock = False
    a.save() 
开发者ID:yeti-platform,项目名称:yeti,代码行数:37,代码来源:analytics_tasks.py

示例15: each

# 需要导入模块: import mongoengine [as 别名]
# 或者: from mongoengine import DoesNotExist [as 别名]
def each(obj):

        all_tags = set([t.name for t in obj.tags])

        # tag absent produced tags
        for tag in all_tags:
            try:
                db_tag = Tag.objects.get(name=tag)
                produced_tags = db_tag.produces
                obj.tag(
                    [t.name for t in produced_tags if t.name not in all_tags])
            except DoesNotExist:
                logging.error(
                    "Nonexisting tag: {} (found in {})".format(tag, obj.value)) 
开发者ID:yeti-platform,项目名称:yeti,代码行数:16,代码来源:tag_logic.py


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