本文整理汇总了Python中tinydb.Query方法的典型用法代码示例。如果您正苦于以下问题:Python tinydb.Query方法的具体用法?Python tinydb.Query怎么用?Python tinydb.Query使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类tinydb
的用法示例。
在下文中一共展示了tinydb.Query方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: _search_field_exists
# 需要导入模块: import tinydb [as 别名]
# 或者: from tinydb import Query [as 别名]
def _search_field_exists(self, field, base="", baseq=None):
if baseq is None:
baseq = Query()
if '.' not in field:
return getattr(baseq, field).exists()
field, nextfields = field.split('.', 1)
if base:
fullfield = "%s.%s" % (base, field)
else:
fullfield = field
if fullfield in self.list_fields:
return getattr(baseq, field).any(
self._search_field_exists(nextfields, base=fullfield)
)
return self._search_field_exists(nextfields, base=fullfield,
baseq=getattr(baseq, field))
示例2: searchport
# 需要导入模块: import tinydb [as 别名]
# 或者: from tinydb import Query [as 别名]
def searchport(port, protocol='tcp', state='open', neg=False):
"""Filters (if `neg` == True, filters out) records with
specified protocol/port at required state. Be aware that when
a host has a lot of ports filtered or closed, it will not
report all of them, but only a summary, and thus the filter
might not work as expected. This filter will always work to
find open ports.
"""
q = Query()
if port == "host":
res = (q.port > 0) if neg else (q.port == -1)
else:
res = (q.port == port) & (q.protocol == protocol)
if neg:
return q.ports.any(res & (q.state_state != state)) | \
q.ports.all(~res)
res &= q.state_state == state
return q.ports.any(res)
示例3: searchcountopenports
# 需要导入模块: import tinydb [as 别名]
# 或者: from tinydb import Query [as 别名]
def searchcountopenports(cls, minn=None, maxn=None, neg=False):
"Filters records with open port number between minn and maxn"
assert minn is not None or maxn is not None
res = []
q = Query()
if minn == maxn:
if neg:
return q.openports.count != minn
return q.openports.count == minn
if minn is not None:
if neg:
res.append(q.openports.count < minn)
else:
res.append(q.openports.count >= minn)
if maxn is not None:
if neg:
res.append(q.openports.count > maxn)
else:
res.append(q.openports.count <= maxn)
if neg:
return cls.flt_or(*res)
return cls.flt_and(*res)
示例4: searchcpe
# 需要导入模块: import tinydb [as 别名]
# 或者: from tinydb import Query [as 别名]
def searchcpe(cls, cpe_type=None, vendor=None, product=None, version=None):
"""Look for a CPE by type (a, o or h), vendor, product or version (the
part after the column following the product). No argument will just
check for cpe existence.
"""
q = Query()
fields = [
("type", cpe_type),
("vendor", vendor),
("product", product),
("version", version),
]
flt = [cls._searchstring_re(getattr(q, field), value)
for field, value in fields
if value is not None]
if not flt:
return q.cpes.exists()
return q.cpes.any(cls.flt_and(*flt))
示例5: remove
# 需要导入模块: import tinydb [as 别名]
# 或者: from tinydb import Query [as 别名]
def remove(self, rec):
"""Removes the record from the active column. `rec` must be the
record as returned by `.get()` or the record id.
"""
q = Query()
if isinstance(rec, dict):
scanids = rec.get("scanid", [])
else:
try:
scanids = self.get(q._id == rec)[0].get("scanid", [])
except IndexError:
scanids = []
super(TinyDBNmap, self).remove(rec)
for scanid in scanids:
if not self.db.get(q.scanid.any([scanid])):
self.db_scans.remove(cond=Query()._id == scanid)
示例6: assign_agent
# 需要导入模块: import tinydb [as 别名]
# 或者: from tinydb import Query [as 别名]
def assign_agent(self, agentid, scanid,
only_if_unassigned=False,
force=False):
q = Query()
flt = []
if only_if_unassigned:
flt.append(q.scan == None) # noqa: E711
elif not force:
flt.append(q.scan != False) # noqa: E712
if flt:
flt = self.flt_and(*flt)
else:
flt = self.flt_empty
self.db.update({"scan": scanid}, cond=flt, doc_ids=[agentid])
agent = self.get_agent(agentid)
if scanid is not None and scanid is not False \
and scanid == agent["scan"]:
self.db_scans.update(add("agents", [agentid]),
cond=~q.agents.any([agentid]),
doc_ids=[scanid])
示例7: _get_flow_key
# 需要导入模块: import tinydb [as 别名]
# 或者: from tinydb import Query [as 别名]
def _get_flow_key(rec):
"""Returns a query that matches the flow"""
q = Query()
insertspec = {'src_addr': rec['src_addr'],
'dst_addr': rec['dst_addr'],
'proto': rec['proto'],
'schema_version': flow.SCHEMA_VERSION}
res = ((q.src_addr == rec['src_addr']) &
(q.dst_addr == rec['dst_addr']) &
(q.proto == rec['proto']) &
(q.schema_version == flow.SCHEMA_VERSION))
if rec['proto'] in ['udp', 'tcp']:
insertspec['dport'] = rec['dport']
res &= q.dport == rec['dport']
elif rec['proto'] == 'icmp':
insertspec['type'] = rec['type']
res &= q.type == rec['type']
return res, insertspec
示例8: flt_from_clause
# 需要导入模块: import tinydb [as 别名]
# 或者: from tinydb import Query [as 别名]
def flt_from_clause(cls, clause):
q = Query()
clause['attr'] = cls._fix_attr_name(clause['attr'])
if clause['operator'] is None:
if clause['attr'] == 'addr':
res = (q.src_addr.exists() | q.dst_addr.exists())
else:
res = cls._base_from_attr(
clause['attr'],
op="exists",
array_mode=clause['array_mode'],
)
if clause['neg']:
return ~res
return res
if clause['len_mode']:
clause['value'] = int(clause['value'])
clause['operator'] = cls._fix_operator(clause['operator'])
if clause['attr'] in ['addr', 'src_addr', 'dst_addr']:
return cls._flt_from_clause_addr(clause)
return cls._flt_from_clause_any(clause)
示例9: from_filters
# 需要导入模块: import tinydb [as 别名]
# 或者: from tinydb import Query [as 别名]
def from_filters(cls, filters, limit=None, skip=0, orderby="", mode=None,
timeline=False, after=None, before=None, precision=None):
"""Overloads from_filters method from TinyDB.
It transforms a flow.Query object returned by
super().from_filters into a TinyDB query and returns it.
Note: limit, skip, orderby, mode, timeline are IGNORED. They
are present only for compatibility reasons.
"""
q = Query()
query = (super(TinyDBFlow, cls)
.from_filters(filters, limit=limit, skip=skip,
orderby=orderby, mode=mode, timeline=timeline))
flt = cls.flt_from_query(query)
times_filter = []
if after:
times_filter.append(q.start >= after)
if before:
times_filter.append(q.start < before)
if precision:
times_filter.append(q.duration == precision)
if times_filter:
flt &= q.times.any(cls.flt_and(*times_filter))
return flt
示例10: test_search_function
# 需要导入模块: import tinydb [as 别名]
# 或者: from tinydb import Query [as 别名]
def test_search_function(tmpdir):
# Setup and run three experiments
root = tmpdir.strpath
run_test_experiment(exp_name="experiment 1 alpha", exp_id="1234", root_dir=root)
run_test_experiment(exp_name="experiment 2 beta", exp_id="5678", root_dir=root)
run_test_experiment(
exp_name="experiment 3 alpha beta", exp_id="9990", root_dir=root
)
tinydb_reader = TinyDbReader(root)
# Test Fetch by Tinydb Query in search function
record = Query()
q = record.experiment.name.search("experiment [23]")
res = tinydb_reader.search(q)
assert len(res) == 2
res2 = tinydb_reader.fetch_metadata(query=q)
assert strip_file_handles(res) == strip_file_handles(res2)
示例11: __init__
# 需要导入模块: import tinydb [as 别名]
# 或者: from tinydb import Query [as 别名]
def __init__(self, db_name, domain, raise_if_table_doesnt_exist=True, only_enabled=False, only_users=False):
self.db = None
self.table = None
self.only_enabled = (Query().enabled.exists() if only_enabled else Query().ntlmhash.exists()) & ( Query().enabled == True if only_enabled else Query().ntlmhash.exists())
self.only_users = (Query().username.exists() if only_users else Query().ntlmhash.exists()) & (Query().username.test(lambda v: not v.endswith("$")) if only_users else Query().ntlmhash.exists())
serialization = SerializationMiddleware()
serialization.register_serializer(DateTimeSerializer(), "datetime")
self.db = TinyDB(db_name, storage=CachingMiddleware(serialization))
tables = list(self.db.tables())
if raise_if_table_doesnt_exist and domain not in tables:
raise DomainDoesntExist("Hashes for domain '{}' do not exist in database.".format(domain), tables)
self.table = self.db.table(domain)
示例12: _getpk
# 需要导入模块: import tinydb [as 别名]
# 或者: from tinydb import Query [as 别名]
def _getpk(self):
r = self.db.get(Query().name==self.pk)
if r is None:
# todo: return 404 not found error. on GET and _('pipe').post()
raise IOError('{} Not found'.format(self.pk))
elif 'data' in r.keys():
return r['data']
else:
return r
示例13: post
# 需要导入模块: import tinydb [as 别名]
# 或者: from tinydb import Query [as 别名]
def post(self, request_body):
if self.pk is None:
name = request_body['name']
if name in ['pipes','remotes']:
raise APIError('{} is reserved, use another name'.format(name))
if self.db.contains(Query().name == name):
raise APIError('entry {} already exists, needs to be unique'.format(name))
self.db.insert(request_body)
self.pk = name
return self.Request(201), self._getpk()
else:
name = self.pk
self.db.upsert({'name': name, 'data': request_body}, Query().name == self.pk)
return self.Request(200), self._getpk()
示例14: put
# 需要导入模块: import tinydb [as 别名]
# 或者: from tinydb import Query [as 别名]
def put(self, request_body):
if self.pk is not None:
self.db.upsert(request_body, Query().name == self.pk)
return self.Request(200), self._getpk()
示例15: delete
# 需要导入模块: import tinydb [as 别名]
# 或者: from tinydb import Query [as 别名]
def delete(self):
if self.pk is not None:
self.db.remove(Query().name == self.pk)
return self.Request(204),not self.db.contains(Query().name == self.pk)