本文整理汇总了Python中tinydb.TinyDB.remove方法的典型用法代码示例。如果您正苦于以下问题:Python TinyDB.remove方法的具体用法?Python TinyDB.remove怎么用?Python TinyDB.remove使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类tinydb.TinyDB
的用法示例。
在下文中一共展示了TinyDB.remove方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: test_json_readwrite
# 需要导入模块: from tinydb import TinyDB [as 别名]
# 或者: from tinydb.TinyDB import remove [as 别名]
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
示例2: remove
# 需要导入模块: from tinydb import TinyDB [as 别名]
# 或者: from tinydb.TinyDB import remove [as 别名]
def remove(name):
db=TinyDB(path_db_)
temp = Query()
data=db.search(temp.name==name)
if len(data)>0:
path=get_file(name)
os.remove(path)
db.remove(temp.name==name)
return True
return False
示例3: test_delete
# 需要导入模块: from tinydb import TinyDB [as 别名]
# 或者: from tinydb.TinyDB import remove [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') == []
示例4: Test_004_Delete_existing_data_by_valid_query_Function
# 需要导入模块: from tinydb import TinyDB [as 别名]
# 或者: from tinydb.TinyDB import remove [as 别名]
class Test_004_Delete_existing_data_by_valid_query_Function(unittest.TestCase):
def setUp(self):
self.db = TinyDB('db.json')
def tearDown(self):
self.db.purge()
self.db.all()
def test_simple_delete_valid_exist(self):
print("case 4 delete existing data by valid query")
self.db.insert({'Name': 'Greg', 'Email': '[email protected]', 'int' : 1, 'char':1})
self.db.remove(where('Name') == 'Greg')
result=self.db.search(where('Name') == 'Greg')
self.assertEqual(result,[])
示例5: ListCache
# 需要导入模块: from tinydb import TinyDB [as 别名]
# 或者: from tinydb.TinyDB import remove [as 别名]
class ListCache(object):
DB_FILE = 'listing_db.json'
DB_TTL = timedelta(hours=12)
def __init__(self):
self.db = TinyDB(os.path.join(os.path.join(os.getcwd(), os.path.dirname(__file__)), ListCache.DB_FILE))
@property
def db(self):
return self._db
@db.setter
def db(self, db):
self._db = db
def listing_in_cache(self, listing):
lquery = Query()
return self.db.contains(lquery.hsh == listing.hsh)
def retrieve_listing(self, listing):
lquery = Query()
list_dict = self.db.get(lquery.hsh == listing.hsh)
return Listing.from_dict(list_dict)
def insert_listing(self, listing):
if self.listing_in_cache(listing):
self.update_listing(listing)
else:
list_dict = listing.as_dict()
list_dict['last_updated'] = datetime.now().isoformat()
list_dict['hsh'] = listing.hsh
self.db.insert(list_dict)
def remove_listing(self, listing):
lquery = Query()
self.db.remove(lquery.hsh == listing.hsh)
def update_listing(self, listing):
lquery = Query()
if self.listing_in_cache(listing):
self.remove_listing(listing)
self.insert_listing(listing)
def remove_old_listings(self):
list_ar = self.db.all()
for listing in list_ar:
if datetime.strptime(listing['last_updated'], '%Y-%m-%dT%H:%M:%S.%f') < datetime.now() - ListCache.DB_TTL:
self.remove_listing(Listing.from_dict(listing))
示例6: write_prediction_cache
# 需要导入模块: from tinydb import TinyDB [as 别名]
# 或者: from tinydb.TinyDB import remove [as 别名]
def write_prediction_cache(
region_id,
type_id,
prediction_data,
cache_path=CACHE_PATH,
db_filename='prophet.json',
logger=logging.getLogger('publicAPI')
):
"""update tinydb latest prediction
Args:
region_id (int): EVE Online region ID
type_id (int): EVE Online type ID
prediction_data (:obj:`pandas.DataFrame`): data to write to cache
cache_path (str, optional): path to caches
db_filename (str, optional): name of tinydb
Returns:
None
"""
logger.info('--caching result')
utc_today = datetime.utcnow().strftime('%Y-%m-%d')
prediction_db = TinyDB(path.join(cache_path, db_filename))
## clear previous cache ##
prediction_db.remove(
(Query().cache_date <= utc_today) &
(Query().region_id == region_id) &
(Query().type_id == type_id)
)
## Prepare new entry for cache ##
cleaned_data = prediction_data.to_json(
date_format='iso',
orient='records'
)
data = {
'cache_date': utc_today,
'region_id': region_id,
'type_id': type_id,
'lastWrite': datetime.utcnow().timestamp(),
'prediction':cleaned_data
}
logger.debug(data)
prediction_db.insert(data)
prediction_db.close()
示例7: NumberStore
# 需要导入模块: from tinydb import TinyDB [as 别名]
# 或者: from tinydb.TinyDB import remove [as 别名]
class NumberStore():
def __init__(self, filename):
self.db = TinyDB(filename)
def initNumber(self, number):
if not self.getNumberDict(number):
self.db.insert({'number': number, 'accesses': [], 'info': '#yolo'})
def touchNumber(self, number):
self.initNumber(number)
#print(self.getNumberDict(number))
#accesses = self.getNumberDict(number)['accesses'].append(datetime.datetime.now())
#self.db.update({'accesses': accesses}, where('number') == number)
def getNumberDict(self, number):
return self.db.get(where('number') == number)
def getNumberList(self):
return (entry['number'] for entry in self.db.all())
def getAccesses(self, number):
# if not number in self.db['numbers']:
# return None
# if not 'info' in self.db['numbers'][number]:
# return None
#
# return self.db['numbers'][number]['info']
return []
def getInfo(self, number):
return self.getNumberDict(number)['info']
def setInfo(self, number, info):
self.initNumber(number)
self.db.update({'info': info}, where('number') == number)
print(self.db.all())
def deleteNumber(self, number):
self.db.remove(where('number') == number)
print(self.db.all())
def close(self):
self.db.close()
示例8: remove
# 需要导入模块: from tinydb import TinyDB [as 别名]
# 或者: from tinydb.TinyDB import remove [as 别名]
def remove(name: str) -> bool:
"""
Remove corpus
:param string name: corpus name
:return: True or False
"""
db = TinyDB(corpus_db_path())
temp = Query()
data = db.search(temp.name == name)
if len(data) > 0:
path = get_corpus_path(name)
os.remove(path)
db.remove(temp.name == name)
return True
return False
示例9: __init__
# 需要导入模块: from tinydb import TinyDB [as 别名]
# 或者: from tinydb.TinyDB import remove [as 别名]
class FolderManager:
def __init__(self, path):
self.db_file = os.path.join(path, CONF_DIR, FOLDER_DB_FN)
self._db = TinyDB(self.db_file)
def open_db(self):
self._db = TinyDB(self.db_file)
def close_db(self):
self._db.close()
def add_folder(self, file_name):
if not self.folder_exists(file_name):
entry = {'file_name': file_name}
self._db.insert(entry)
def get_all_entries(self):
return self._db.all()
def folder_exists(self, file_name):
""" checks if a folder has been added """
entries = self._db.search(where('file_name') == file_name)
if entries:
return True
else:
return False
def remove_element(self, file_name):
self._db.remove(where('file_name') == file_name)
def get_file_names(self):
""" returns all the file names of folders that the user has added """
file_names = []
for entry in self._db.all():
file_names.append(entry['file_name'])
return file_names
def get_folder_by_name(self, expected_name):
""" get documents by the specified property """
entry = self._db.get(where('file_name') == expected_name)
return entry
def clear_all(self):
self._db.purge()
示例10: __init__
# 需要导入模块: from tinydb import TinyDB [as 别名]
# 或者: from tinydb.TinyDB import remove [as 别名]
class BotHelper:
def __init__(self, bot):
self.db = TinyDB('db.json')
self.bot = bot
def executeAssignment(self, chat_id, assignment):
if assignment['command'] == 'add':
entries = Query()
if self.db.search(entries.trigger == assignment['trigger']):
self.bot.sendMessage(chat_id=chat_id, text='No duplicates allowed for now')
return False
else:
if assignment['response_type'] == 'image' or assignment['response_type'] == 'gif':
filename = assignment['response'].split('/')[-1]
extention = filename.split('.')[-1]
urllib.request.urlretrieve(assignment['response'], 'media/images/' + assignment['trigger'] + '.' + extention)
assignment['response'] = 'media/images/' + assignment['trigger'] + '.' + extention
self.db.insert({
'trigger': assignment['trigger'],
'response_type':assignment['response_type'],
'response': assignment['response'],
})
if assignment['command'] == 'del':
self.db.remove(where('trigger') == assignment['trigger'])
if assignment['command'] == 'list':
entries = self.db.all()
for entry in entries:
self.bot.sendMessage(chat_id=chat_id, text=entry)
def executeTrigger(self, chat_id, message):
words = message.split(' ')
entries = Query()
for word in words:
entry = self.db.search(entries.trigger == word)
if entry:
if entry[0]['response_type'] == 'text':
self.bot.sendMessage(chat_id=chat_id, text=entry[0]['response'])
if entry[0]['response_type'] == 'image':
img = open(entry[0]['response'], 'rb')
self.bot.sendPhoto(chat_id=chat_id, photo=img)
if entry[0]['response_type'] == 'gif':
img = open(entry[0]['response'], 'rb')
self.bot.sendDocument(chat_id=chat_id, document=img)
示例11: TinyDBConvertor
# 需要导入模块: from tinydb import TinyDB [as 别名]
# 或者: from tinydb.TinyDB import remove [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
示例12: write_to_cache_file
# 需要导入模块: from tinydb import TinyDB [as 别名]
# 或者: from tinydb.TinyDB import remove [as 别名]
def write_to_cache_file(
data,
cache_path,
type_id=0,
region_id=0,
logger=logging.getLogger(PROGNAME)
):
"""save data to tinyDB
Args:
data (:obj:`pandas.DataFrame`): data to write out
cache_path (str): path to cache file
type_id (int, optional): EVE Online type_id
region_id (int, optional): EVE Online region_id
logger (:obj:`logging.logger`): logging handle
Returns:
None
"""
## get DB ##
logger.info('Writing data to cache')
tdb = TinyDB(cache_path)
date_min = data['date'].min()
logger.debug(date_min)
## clean out existing entries ##
if (type_id and region_id):
logger.info('--Removing old cache entries')
tdb.remove(
(Query().region_id == region_id) &
(Query().type_id == type_id) &
(Query().date >= date_min)
)
caching_data_str = data.to_json(
date_format='iso',
orient='records'
)
cache_data = json.loads(caching_data_str)
logger.info('--Writing to cache file')
tdb.insert_multiple(cache_data)
示例13: DataStore
# 需要导入模块: from tinydb import TinyDB [as 别名]
# 或者: from tinydb.TinyDB import remove [as 别名]
class DataStore(object):
def __init__(self, store_path):
self.store_path = os.path.join(store_path,"META")
try:
os.makedirs(self.store_path)
except OSError as exc:
if exc.errno != errno.EEXIST:
raise
self.db = TinyDB(os.path.join(self.store_path,"__meta__.json"))
def add_file(self, file_path):
file_path = self._get_internal_path(file_path)
self._add_to_db(file_path)
def remove_file(self,file_path):
file_path = self._get_internal_path(file_path)
self._remove_from_db(file_path)
def list_all(self):
return self._list_all_db()
def _init_file_list(self):
with open(self.store_path,"r") as f:
for line in tqdm(f):
self.file_list.append(f)
def _init_db(self):
self.db = TinyDB(self.store_path)
def _add_to_db(self,file_path):
if not self.db.contains(where('file_path')== file_path):
self.db.insert({'file_path':file_path})
def _remove_from_db(self,file_path):
self.db.remove(where('file_path') == file_path)
def _list_all_db(self):
return [rec['file_path'] for rec in self.db.all()]
def _get_internal_path(self, path):
return get_internal_path(path)
示例14: Test_007_Delete_Not_existing_data_by_valid_query_Function
# 需要导入模块: from tinydb import TinyDB [as 别名]
# 或者: from tinydb.TinyDB import remove [as 别名]
class Test_007_Delete_Not_existing_data_by_valid_query_Function(unittest.TestCase):
def setUp(self):
self.db = TinyDB('db.json')
def tearDown(self):
self.db.purge()
self.db.all()
def test_simple_delete_not_exist(self):
print("case 7 Delete Non-existing data by valid query")
result=self.db.remove(where('Name') == 'Wendy')
self.assertEqual(result,None)
示例15: getDocByUrl
# 需要导入模块: from tinydb import TinyDB [as 别名]
# 或者: from tinydb.TinyDB import remove [as 别名]
def getDocByUrl(url):
cached = False
db = TinyDB('cache.json')
ago = int(((datetime.datetime.now() - datetime.timedelta(minutes=CACHE_MIN)) - datetime.datetime(1970,1,1)).total_seconds()) #.timestamp())
db.remove(where('date') < ago)
search = db.search((where('url') == url) & (where('date') > ago))
if len(search) > 0:
cached = True
print "URL: {0} was found in cache!\n".format(url)
if cached:
return base64.b64decode(search[0]['content'])
else:
req = makeUrlRequest(url)
if req != None:
content = req.read()
date = int((datetime.datetime.now() - datetime.datetime(1970,1,1)).total_seconds()) #.timestamp())
db.insert({'url':url,'date':date, 'content':base64.b64encode(content)})
return content
else:
print "ERROR: REQUEST COULD NOT BE MADE!\n"
return ""