本文整理汇总了Python中tinydb.where函数的典型用法代码示例。如果您正苦于以下问题:Python where函数的具体用法?Python where怎么用?Python where使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了where函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: reference_energy
def reference_energy(self, phase, symbols, param_search):
"""
Returns the weighted average of the endmember energies
in symbolic form.
"""
# TODO: Handle wildcards in constituent array
pure_energy_term = S.Zero
# Normalize site ratios
site_ratio_normalization = 0
for idx, sublattice in enumerate(phase.constituents):
# sublattices with only vacancies don't count
if len(sublattice) == 1 and sublattice[0] == 'VA':
continue
site_ratio_normalization += phase.sublattices[idx]
pure_param_query = (
(where('phase_name') == phase.name) & \
(where('parameter_order') == 0) & \
(where('parameter_type') == "G") & \
(where('constituent_array').test(self._purity_test))
)
pure_params = param_search(pure_param_query)
for param in pure_params:
site_fraction_product = S.One
for subl_index, comp in enumerate(param['constituent_array']):
# We know that comp has one entry, by filtering
sitefrac = \
v.SiteFraction(phase.name, subl_index, comp[0])
site_fraction_product *= sitefrac
pure_energy_term += (
site_fraction_product * param['parameter'].subs(symbols)
) / site_ratio_normalization
return pure_energy_term
示例2: test_json_readwrite
def test_json_readwrite(tmpdir):
"""
Regression test for issue #1
"""
path = str(tmpdir.join('test.db'))
# Create TinyDB instance
db = TinyDB(path, storage=JSONStorage)
item = {'name': 'A very long entry'}
item2 = {'name': 'A short one'}
get = lambda s: db.get(where('name') == s)
db.insert(item)
assert get('A very long entry') == item
db.remove(where('name') == 'A very long entry')
assert get('A very long entry') is None
db.insert(item2)
assert get('A short one') == item2
db.remove(where('name') == 'A short one')
assert get('A short one') is None
示例3: getfeed
def getfeed(cid):
postrec = []
print "feed"
for bid in msgtable.search(where ('customer_id') == cid):
print bid
postrec.append(posttable.search(where ('busid') == bid['busid']))
return postrec
示例4: test_write_back
def test_write_back(db):
docs = db.search(where('int') == 1)
for doc in docs:
doc['int'] = [1, 2, 3]
db.write_back(docs)
assert db.count(where('int') == [1, 2, 3]) == 3
示例5: scan
def scan(self):
print "Scan Start"
while True:
cell = Cell.all(interface)
print "Rescanning"
timer = 0
while timer < 100:
timer +=1
S = []
count = 0
for c in cell:
count += 1
#print ":"+ str(count), " ssid:", c.ssid
#create dictionary with informnation on the accesss point
SSIDS = {"no" : count ,"ssid": c.ssid, "channel":c.channel,"encrypted":c.encrypted, \
"frequency":c.frequency,"address":c.address, "signal":c.signal, "mode":c.mode}
#if not db.search((where('ssid') == ap["ssid"])) == []:
# res = db.search(where('ssid') == c.ssid)
#print db.search(where('ssid') == c.ssid)
print "=----------------------------------"
# print c.address
print "---------------------------------------"
if db.contains(where('ssid') == c.ssid):
print (db.contains((where('ssid') == c.ssid) & (where('address') == str(c.address))))
示例6: test_smart_query_cache
def test_smart_query_cache(db):
db.table_class = SmartCacheTable
table = db.table('table3')
query = where('int') == 1
dummy = where('int') == 2
assert not table.search(query)
assert not table.search(dummy)
# Test insert
table.insert({'int': 1})
assert len(table._query_cache) == 2
assert len(table._query_cache[query]) == 1
# Test update
table.update({'int': 2}, where('int') == 1)
assert len(table._query_cache[dummy]) == 1
assert table.count(query) == 0
# Test remove
table.insert({'int': 1})
table.remove(where('int') == 1)
assert table.count(where('int') == 1) == 0
示例7: main
def main():
if len(sys.argv) == 1 or sys.argv[1] == "proximity":
pprint(db.search(tinydb.where('seen') >= int(time.time()) - 60*15))
elif sys.argv[1] == "hostnames":
pprint(db.search(tinydb.where('hostname')))
else:
print("Unknown debug command")
示例8: update_document
def update_document(self, field, new_val, doc_id):
if type(new_val) is list:
self._db.update(_update_entry_list(field, new_val), where('id') == doc_id)
else:
if type(new_val) is set:
new_val = list(new_val)
self._db.update({field: new_val}, where('id') == doc_id)
示例9: test_search_path
def test_search_path(db):
assert not db._query_cache
assert len(db.search(where('int'))) == 3
assert len(db._query_cache) == 1
assert len(db.search(where('asd'))) == 0
assert len(db.search(where('int'))) == 3 # Query result from cache
示例10: search
def search(args):
filename = args['<outputfile>']
if args['--fuzzy']:
results = db.search(where('outputs').any(lambda x: re.match(".+%s.+" % filename, x)))
elif args['--regex']:
results = db.search(where('outputs').any(lambda x: re.match(filename, x)))
else:
results = db.search(where('outputs').any(os.path.abspath(filename)))
results = [_change_date(result) for result in results]
# Sort the results
results = sorted(results, key = lambda x: parse(x['date']))
if len(results) == 0:
print("No results found")
else:
if args['--all']:
for r in results:
print_result(r)
print("-"*40)
else:
print_result(results[-1])
if len(results) > 1:
print("** Previous runs creating this output have been found. Run with --all to show. **")
if args['--diff']:
if 'diff' in results[-1]:
print("\n\n")
print(results[-1]['diff'])
db.close()
示例11: is_user_existent
def is_user_existent(name):
field_existence = user_table.search(where('name').exists())
if not field_existence:
return False
user_existence = user_table.search(where('name') == name)
return True if len(user_existence) is 1 else False
示例12: ticket_detail
def ticket_detail(ticket_id):
if not session.get("logged_in"):
return redirect(url_for("login"))
else:
if request.method == "GET":
results = ticket_db.search(where("uuid") == ticket_id)
action_url = request.path
status = int(request.args.get("status", 10))
if status < 0 or status > 3:
pass
else:
t = ticket_db.get(where('uuid') == ticket_id)
t["status"] = status
ticket_db.update(t, eids=[t.eid])
if len(results) == 0:
abort(404)
else:
results[0]["text"].replace("\;", ";")
return render_template("ticket_detail.html", details=results[0], actionurl=action_url)
else:
content = request.form["content"].replace("\n", "<br>")
user = session.get("username")
t = ticket_db.get(where('uuid') == ticket_id)
if t["replies"] == None:
t["replies"] = []
t["replies"].append({"content" : content, "author": user})
ticket_db.update(t, eids=[t.eid])
return redirect(request.path)
示例13: get_obj_by_brush_and_mtl
def get_obj_by_brush_and_mtl(self, brush, mtl):
if self.db.contains(
(where("brush") == str(brush)) & (where("mtl") == str(mtl))
):
return self.db.search(
(where("brush") == str(brush)) & (where("mtl") == str(mtl))
)[0]
示例14: test_one_table
def test_one_table(db):
table1 = db.table('table1')
table1.insert_multiple({'int': 1, 'char': c} for c in 'abc')
assert table1.get(where('int') == 1)['char'] == 'a'
assert table1.get(where('char') == 'b')['char'] == 'b'
示例15: index
def index():
form = SearchForm()
query = request.args.get('query', '').strip()
db = TinyDB(recipyGui.config.get('tinydb'))
if not query:
runs = db.all()
else:
# Search run outputs using the query string
runs = db.search(
where('outputs').any(lambda x: listsearch(query, x)) |
where('inputs').any(lambda x: listsearch(query, x)) |
where('script').search(query) |
where('notes').search(query) |
where('unique_id').search(query))
runs = sorted(runs, key = lambda x: parse(x['date'].replace('{TinyDate}:', '')) if x['date'] is not None else x['eid'], reverse=True)
run_ids = []
for run in runs:
if 'notes' in run.keys():
run['notes'] = str(escape(run['notes']))
run_ids.append(run.eid)
db.close()
return render_template('list.html', runs=runs, query=query, form=form,
run_ids=str(run_ids),
dbfile=recipyGui.config.get('tinydb'))