本文整理汇总了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)
示例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)
示例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)
示例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))
示例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
示例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()
示例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
示例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
示例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()))
示例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)
示例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)
示例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()
示例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
示例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()
示例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))