本文整理汇总了Python中tinydb.TinyDB.search方法的典型用法代码示例。如果您正苦于以下问题:Python TinyDB.search方法的具体用法?Python TinyDB.search怎么用?Python TinyDB.search使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类tinydb.TinyDB
的用法示例。
在下文中一共展示了TinyDB.search方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: download
# 需要导入模块: from tinydb import TinyDB [as 别名]
# 或者: from tinydb.TinyDB import search [as 别名]
def download(name,force=False):
db=TinyDB(path_db_)
temp = Query()
data=requests.get("https://raw.githubusercontent.com/PyThaiNLP/pythainlp-corpus/master/db.json")
data_json=data.json()
if name in list(data_json.keys()):
temp_name=data_json[name]
print("Download : "+name)
if len(db.search(temp.name==name))==0:
print(name+" "+temp_name['version'])
download_(temp_name['download'],temp_name['file_name'])
db.insert({'name': name, 'version': temp_name['version'],'file':temp_name['file_name']})
else:
if len(db.search(temp.name==name and temp.version==temp_name['version']))==0:
print("have update")
print("from "+name+" "+db.search(temp.name==name)[0]['version']+" update to "+name+" "+temp_name['version'])
yes_no="y"
if force==False:
yes_no=str(input("y or n : ")).lower()
if "y"==yes_no:
download_(temp_name['download'],temp_name['file_name'])
db.update({'version':temp_name['version']},temp.name==name)
else:
print("re-download")
print("from "+name+" "+db.search(temp.name==name)[0]['version']+" update to "+name+" "+temp_name['version'])
yes_no="y"
if force==False:
yes_no=str(input("y or n : ")).lower()
if "y"==yes_no:
download_(temp_name['download'],temp_name['file_name'])
db.update({'version':temp_name['version']},temp.name==name)
db.close()
示例2: dragon_greet
# 需要导入模块: from tinydb import TinyDB [as 别名]
# 或者: from tinydb.TinyDB import search [as 别名]
def dragon_greet():
print("_______________________________________________________________\n")
time = datetime.datetime.now().time()
global user_full_name
global user_prefix
global config_file
command = "getent passwd $LOGNAME | cut -d: -f5 | cut -d, -f1"
user_full_name = os.popen(command).read()
user_full_name = user_full_name[:-1] # .decode("utf8")
home = expanduser("~")
config_file = TinyDB(home + '/.dragonfire_config.json')
callme_config = config_file.search(Query().datatype == 'callme')
if callme_config:
user_prefix = callme_config[0]['title']
else:
gender_config = config_file.search(Query().datatype == 'gender')
if gender_config:
user_prefix = GENDER_PREFIX[gender_config[0]['gender']]
else:
gender = Classifier.gender(user_full_name.split(' ', 1)[0])
config_file.insert({'datatype': 'gender', 'gender': gender})
user_prefix = GENDER_PREFIX[gender]
if time < datetime.time(12):
time_of_day = "morning"
elif datetime.time(12) < time < datetime.time(18):
time_of_day = "afternoon"
else:
time_of_day = "evening"
userin.execute(["echo"], "To activate say 'Dragonfire!' or 'Wake Up!'")
userin.say(" ".join(["Good", time_of_day, user_prefix]))
示例3: get_file
# 需要导入模块: from tinydb import TinyDB [as 别名]
# 或者: from tinydb.TinyDB import search [as 别名]
def get_file(name):
db=TinyDB(path_db_)
temp = Query()
if len(db.search(temp.name==name))>0:
path= get_path_data(db.search(temp.name==name)[0]['file'])
db.close()
if not os.path.exists(path):
download(name)
return path
示例4: TinyDBConvertor
# 需要导入模块: from tinydb import TinyDB [as 别名]
# 或者: from tinydb.TinyDB import search [as 别名]
class TinyDBConvertor(object):
def __init__(self, collection_name, db_name, db_path=LOCAL_DIR):
self.local_db_fullpath = os.path.join(db_path, db_name)
self.local_db = TinyDB(self.local_db_fullpath)
self.collection_name = collection_name
def reload(self):
self.local_db.close()
self.local_db = TinyDB(self.local_db_fullpath)
def find(self):
self.reload()
query = Query()
resp = self.local_db.search(query.type == self.collection_name)
self.local_db.close()
return resp
def find_one(self, entry):
self.reload()
query = Query()
resp = self.local_db.search((query.type == self.collection_name) &
(query.fqu == entry['fqu']))
self.local_db.close()
if len(resp) == 0:
return None
else:
return resp[0]
def save(self, new_entry):
self.reload()
new_entry['type'] = self.collection_name
resp = self.local_db.insert(new_entry)
self.local_db.close()
return resp
def remove(self, entry):
self.reload()
query = Query()
resp = self.local_db.remove((query.type == self.collection_name) &
(query.fqu == entry['fqu']))
self.local_db.close()
return resp
示例5: test_delete
# 需要导入模块: from tinydb import TinyDB [as 别名]
# 或者: from tinydb.TinyDB import search [as 别名]
def test_delete(tmpdir):
path = str(tmpdir.join('db.json'))
db = TinyDB(path, ensure_ascii=False)
q = Query()
db.insert({'network': {'id': '114', 'name': 'ok', 'rpc': 'dac',
'ticker': 'mkay'}})
assert db.search(q.network.id == '114') == [
{'network': {'id': '114', 'name': 'ok', 'rpc': 'dac',
'ticker': 'mkay'}}
]
db.remove(q.network.id == '114')
assert db.search(q.network.id == '114') == []
示例6: TinyDBStore
# 需要导入模块: from tinydb import TinyDB [as 别名]
# 或者: from tinydb.TinyDB import search [as 别名]
class TinyDBStore(object):
def __init__(self):
self.drafts_db = TinyDB('event_drafts.json')
self.events_db = TinyDB('events.json')
# Drafts
def contains_draft(self, user_id):
return self.drafts_db.contains(Query().user_id == user_id)
def new_draft(self, user_id):
if self.contains_draft(user_id):
self.drafts_db.remove(Query().user_id == user_id)
self.drafts_db.insert({
'user_id': user_id,
'current_field': 0,
'event': {}
})
def update_draft(self, user_id, event, current_field):
self.drafts_db.update({
'user_id': user_id,
'current_field': current_field,
'event': event
}, Query().user_id == user_id)
def get_draft(self, user_id):
return self.drafts_db.get(Query().user_id == user_id)
def remove_draft(self, user_id):
self.drafts_db.remove(Query().user_id == user_id)
# Events
def insert_event(self, event):
event_id = self.events_db.insert(event)
event['id'] = event_id
return event
def update_event(self, event):
self.events_db.update(event, eids=[event.eid])
def remove_event(self, event):
self.events_db.remove(eids=[event['id']])
def get_events(self, user_id, name=None):
if name:
return self.events_db.search((Query().user_id == user_id) & (Query().name.test(lambda v: name in v)))
return self.events_db.search(Query().user_id == user_id)
def get_event(self, event_id):
return self.events_db.get(eid=int(event_id))
示例7: new_database_report_user_data
# 需要导入模块: from tinydb import TinyDB [as 别名]
# 或者: from tinydb.TinyDB import search [as 别名]
def new_database_report_user_data(self):
bank = TinyDB(JSONDBOUT)
values = bank.search(self.query.user.exists())
report = "nome:{user: >40} idade: {idade: >4} ano: {ano} dia+hora: {hora} genero: {sexo} "
for i, name in enumerate(values):
jogadas = sum(len(copy["jogada"])
for copy in bank.search(self.query.user == name["user"]))
tempos = [copy["jogada"]
for copy in bank.search(self.query.user == name["user"])]
tempos = [lance["tempo"] for copy in tempos for lance in copy]
# tempo = strptime(max(tempos), "%c")-strptime(min(tempos), "%c")
tempo = (max(tempos)) - (min(tempos))
print("{:3d}".format(i), "Lances: {:4d}".format(jogadas),
"T:{:>9}".format(str(tempo)), report.format(**name))
示例8: crawl
# 需要导入模块: from tinydb import TinyDB [as 别名]
# 或者: from tinydb.TinyDB import search [as 别名]
def crawl(sr=0, er=3):
archive = dict()
url = "https://community.topcoder.com/tc?module=ProblemArchive&sr=%d&er=%d" % (sr, er)
print "requesting seed page..."
r = requests.get(url)
html = h.unescape(r.content.decode('utf-8'))
doc = pq(html)
for i in doc('table.paddingTable2').eq(2).children()[3:]:
round_name = pq(i).children().eq(2).find('a').text()
sub_url = pq(i).children().eq(2).find('a').attr.href
if sub_url is not None:
rid = sub_url.split('rd=')[-1]
archive[round_name] = {'rid': rid, 'round': round_name}
db = TinyDB("data/db.json")
tot = len(archive.values())
cur = 0
prob_cnt = 0
for k in archive.values():
problems = crawl_round(k['rid'], k['round'])
print 'parse result:'
for p in problems:
for pk, pv in p.items():
print "%-15s: %s" % (pk, pv)
prob_cnt += 1
q = Query()
if not db.search(q.name == p['name']):
print '>>>>>>> insert problem: %s' % p['name']
db.insert(p)
print '-' * 10
cur += 1
print '*' * 10, 'finish', k['round'], ',tot rounds:', tot, 'cur round:', cur, 'round problems:', len(problems), '*' * 10
print 'done, total round: %d, total problems: %d' % (cur, prob_cnt)
示例9: MovedFileHandler
# 需要导入模块: from tinydb import TinyDB [as 别名]
# 或者: from tinydb.TinyDB import search [as 别名]
class MovedFileHandler(events.FileSystemEventHandler):
def __init__(self, *args, **kwargs):
self.dry_run = kwargs.pop('dry_run', True)
self.verbose = kwargs.pop('verbose', True)
super().__init__(*args, **kwargs)
os.chdir(os.path.expanduser('~'))
self.db = TinyDB('.sdpp-sync.json')
def on_moved(self, event):
path = event.src_path
if not path.endswith('.pdf') or path.endswith('.PDF'):
return
home = os.path.expanduser('~/')
dest = event.dest_path
if path.startswith(home):
path = path[len(home):]
if dest.startswith(home):
dest = dest[len(home):]
box_old = to_sony_filename(path)
box_new = to_sony_filename(dest)
os.rename(box_old, box_new)
q = Query()
elem = self.db.search(q.box == box_old)
elem['box'] = box_new
elem['modtime'] = os.stat(box_new).st_mtime
elem['paperpile'] = dest
示例10: index
# 需要导入模块: from tinydb import TinyDB [as 别名]
# 或者: from tinydb.TinyDB import search [as 别名]
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'))
示例11: __init__
# 需要导入模块: from tinydb import TinyDB [as 别名]
# 或者: from tinydb.TinyDB import search [as 别名]
class DB:
def __init__(self,db_path):
self.db = TinyDB(db_path)
def add(self, data):
# Only add it if you can't find it
Track = Query()
if not self.db.get(Track.display_id == data['display_id']):
return self.db.insert(data)
def searchById(self, video_id):
Track = Query()
return self.db.get(Track.display_id == video_id)
def search(self, text):
pattern = re.compile(text,re.IGNORECASE)
def test(txt):
return pattern.search(txt)
Track = Query()
q = Track.title.test(test) | Track.description.test(test)
return self.db.search(q)
def all(self):
return self.db.all()
示例12: check_prediction_cache
# 需要导入模块: from tinydb import TinyDB [as 别名]
# 或者: from tinydb.TinyDB import search [as 别名]
def check_prediction_cache(
region_id,
type_id,
cache_path=CACHE_PATH,
db_filename='prophet.json'
):
"""check tinyDB for cached predictions
Args:
region_id (int): EVE Online region ID
type_id (int): EVE Online type ID
cache_path (str): path to caches
db_filename (str): name of tinydb
Returns:
pandas.DataFrame: cached prediction
"""
utc_today = datetime.utcnow().strftime('%Y-%m-%d')
prediction_db = TinyDB(path.join(cache_path, db_filename))
raw_data = prediction_db.search(
(Query().cache_date == utc_today) &
(Query().region_id == region_id) &
(Query().type_id == type_id)
)
prediction_db.close()
if raw_data:
panda_data = pd.read_json(raw_data[0]['prediction'])
return panda_data
else:
return None
示例13: process_and_add_one
# 需要导入模块: from tinydb import TinyDB [as 别名]
# 或者: from tinydb.TinyDB import search [as 别名]
def process_and_add_one(pdf_path):
pdf_name = pdf_path.split("/")
pdf_name = pdf_name[-1]
directory = pdf_path[0 : -len(pdf_name)]
stripped_name = pdf_name[0:-4]
title_path = title_dir + "/" + stripped_name + ".xml"
extract_title(pdf_path, title_path)
# check if title extraction worked, otherwise stop with this one
tf = open(title_path, "r")
txml = tf.read()
if txml == "title extraction failed":
return None
# build dictionary with info we've got
tf = open(title_path, "r")
txml = tf.read()
txml = txml.split(">")
title = "title not found"
for line in txml:
if "</title" in line:
title = line[0:-7]
print title
break
# save nice text version of title
txt_name_path = title_path[0:-4] + ".txt"
ftxt = open(txt_name_path, "a")
ftxt.write(title)
if title == "title not found":
return None
# if title was found, get DOI from it
currDOI = get_DOI_from_title(title)
# open/create tiny db
db = TinyDB(db_loc)
# make sure the paper isnt in the db already
paper = Query()
gotit = db.search(paper.ownDOI == currDOI)
if gotit:
return currDOI
text_path_xml = text_dir + "/" + stripped_name + ".xml"
text_path_txt = text_dir + "/" + stripped_name + ".txt"
if not extract_text(pdf_path, text_path_xml, text_path_txt):
print ("text extraction failed")
return None
# only extract bibtex if you don't have it already, because this is the long part
# TODO: Return before doing bib extraction
bib_path = bib_dir + "/" + stripped_name + ".bib"
if not extract_bibtex(pdf_path, bib_path):
print ("caught in the new code")
return None
refDOIs = get_ref_list_DOIs(bib_path)
new_dict = {"ownDOI": currDOI, "refDOIs": refDOIs, "filename": stripped_name}
db.insert(new_dict)
return currDOI
示例14: test_gc
# 需要导入模块: from tinydb import TinyDB [as 别名]
# 或者: from tinydb.TinyDB import search [as 别名]
def test_gc(tmpdir):
# See https://github.com/msiemens/tinydb/issues/92
path = str(tmpdir.join('db.json'))
table = TinyDB(path).table('foo')
table.insert({'something': 'else'})
table.insert({'int': 13})
assert len(table.search(where('int') == 13)) == 1
assert table.all() == [{'something': 'else'}, {'int': 13}]
示例15: api
# 需要导入模块: from tinydb import TinyDB [as 别名]
# 或者: from tinydb.TinyDB import search [as 别名]
def api():
db = TinyDB(DB_FILENAME)
results = db.search((Query().hidden == False) | (Query().starred == True))
db.close()
for result in results:
result['eid'] = result.eid
result['url'] = url_for('goto', eid=result.eid)
results.sort(key=lambda r: r['created_at'])
return json.dumps(results)