本文整理汇总了Python中tinydb.TinyDB.tables方法的典型用法代码示例。如果您正苦于以下问题:Python TinyDB.tables方法的具体用法?Python TinyDB.tables怎么用?Python TinyDB.tables使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类tinydb.TinyDB
的用法示例。
在下文中一共展示了TinyDB.tables方法的9个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: test_non_default_table
# 需要导入模块: from tinydb import TinyDB [as 别名]
# 或者: from tinydb.TinyDB import tables [as 别名]
def test_non_default_table():
db = TinyDB(storage=MemoryStorage)
assert [TinyDB.DEFAULT_TABLE] == list(db.tables())
db = TinyDB(storage=MemoryStorage, default_table='non-default')
assert set(['non-default']) == db.tables()
db.purge_tables()
TinyDB.DEFAULT_TABLE = 'non-default'
db = TinyDB(storage=MemoryStorage)
assert set(['non-default']) == db.tables()
示例2: test_purge_table
# 需要导入模块: from tinydb import TinyDB [as 别名]
# 或者: from tinydb.TinyDB import tables [as 别名]
def test_purge_table():
db = TinyDB(storage=MemoryStorage)
assert [TinyDB.DEFAULT_TABLE] == list(db.tables())
db.purge_table(TinyDB.DEFAULT_TABLE)
assert [] == list(db.tables())
table_name = 'some-other-table'
db = TinyDB(storage=MemoryStorage)
db.table(table_name)
assert set([TinyDB.DEFAULT_TABLE, table_name]) == db.tables()
db.purge_table(table_name)
assert set([TinyDB.DEFAULT_TABLE]) == db.tables()
db.purge_table('non-existent-table-name')
assert set([TinyDB.DEFAULT_TABLE]) == db.tables()
示例3: TinydbStorage
# 需要导入模块: from tinydb import TinyDB [as 别名]
# 或者: from tinydb.TinyDB import tables [as 别名]
class TinydbStorage(interface.StorageInterface):
def __init__(self, db_path):
super(TinydbStorage, self).__init__()
self.db = TinyDB(db_path)
def create_table(self, table_name):
self._assert_no_table(table_name)
table = self.db.table(table_name)
table.insert({'table_exists': True})
def get_tables(self):
return self.db.tables()
def get(self, table_name, key):
self._assert_table(table_name)
table = self.db.table(table_name)
element = Query()
result = table.search(element.key == key)
if len(result) == 0:
raise interface.DataException("Key {} not found in table".format(key))
return result[0]['val']
def set(self, table_name, key, val):
self._assert_table(table_name)
table = self.db.table(table_name)
element = Query()
table.remove(element.key == key)
table.insert({'key': key, 'val': val})
def append(self, table_name, list_key, val):
self._assert_table(table_name)
table = self.db.table(table_name)
l = self.get(table_name, list_key)
#TODO: check if l is a list maybe
if val in l:
raise interface.DataException("Value: {0} already exists in list: {1}".format(val, list_key))
l.append(val)
element = Query()
table.update({'val': l}, element.key == list_key)
def remove(self, table_name, list_key, val):
#TODO: do
raise NotImplementedError("Storage module must implement this")
def _assert_no_table(self, table_name):
table = self.db.table(table_name)
if len(table) > 0:
raise interface.DataException("Table already exists: {}".format(table_name))
def _assert_table(self, table_name):
table = self.db.table(table_name)
if len(table) == 0:
raise interface.DataException("Table does not exist: {}".format(table_name))
示例4: _convert_to_sqlitedb
# 需要导入模块: from tinydb import TinyDB [as 别名]
# 或者: from tinydb.TinyDB import tables [as 别名]
def _convert_to_sqlitedb(self):
old_db = TinyDB(DATABASE_SETTINGS['database'])
self.mem_db = []
total = 0
for table in old_db.tables():
for item in old_db.table(table).all():
total += 1
print "MIGRATING DATABASE"
print "--OLD DATABASE: " + str(total)
i = 0
for table in old_db.tables():
for item in old_db.table(table).all():
if len(item['accn']) < 15:
if int(item['time']) > self.purge_date:
self.mem_db.append(item)
print " Converted: " + str(i) + " of " + str(total)
i += 1
self.dict_db[str(item['time'])] = item
else:
print "REMOVING OLD THING"
print "DATABASE MIGRATION COMPLETE"
print "COMMITING CHANGES"
self.get_last_filed()
示例5: TinyMongoDatabase
# 需要导入模块: from tinydb import TinyDB [as 别名]
# 或者: from tinydb.TinyDB import tables [as 别名]
class TinyMongoDatabase(object):
"""Representation of a Pymongo database"""
def __init__(self, database, foldername, storage):
"""Initialize a TinyDB file named as the db name in the given folder
"""
self._foldername = foldername
self.tinydb = TinyDB(
os.path.join(foldername, database + u".json"),
storage=storage
)
def __getattr__(self, name):
"""Gets a new or existing collection"""
return TinyMongoCollection(name, self)
def __getitem__(self, name):
"""Gets a new or existing collection"""
return TinyMongoCollection(name, self)
def collection_names(self):
"""Get a list of all the collection names in this database"""
return list(self.tinydb.tables())
示例6: DatabaseAccess
# 需要导入模块: from tinydb import TinyDB [as 别名]
# 或者: from tinydb.TinyDB import tables [as 别名]
class DatabaseAccess(object):
'''
Raw database access. This module might be unnecessary, it's just a simple
wrapper around TinyDB. It doesn't isolate the Query abstractions of TinyDB
so we don't get any portability or independence from TinyDB. But it is a
place to change storage, middleware, etc.
'''
def __init__(self, filename):
'''
Initialize a database with a file.
:param filename: database filename.
'''
self.filename = str(filename)
self.db = TinyDB(self.filename, storage=CachingMiddleware(JSONStorage))
def close(self):
'''Close the database file.'''
self.db.close()
def table(self, tableName):
return self.db.table(tableName)
# def insert(self, *args, **kwargs):
# '''Insert an object into the database.'''
# return self.db.insert(*args, **kwargs)
# def get(self, *args, **kwargs):
# '''Get an object from the database.'''
# return self.db.Get(*args, **kwargs)
# def contains(self, *args, **kwargs):
# '''Test an object from the database.'''
# return self.db.Get(*args, **kwargs)
# def search(self, *args, **kwargs):
# '''Query for objects.'''
# return self.db.search(*args, **kwargs)
# def remove(self, *args, **kwargs):
# '''Remove objects by query.'''
# return self.db.remove(*args, **kwargs)
def setSingleton(self, kind, model):
id = None
self.db.table(kind).purge()
id = self.db.table(kind).insert(model)
return id
def getSingleton(self, kind):
objs = self.db.table(kind).all()
if len(objs) == 0:
return None
return objs[0]
def getArgs(self):
return self.getSingleton('fashion.prime.args')
def isVerbose(self):
args = self.getArgs()
if args is None:
return False
return args["verbose"]
def isDebug(self):
args = self.getArgs()
if args is None:
return False
return args["debug"]
def kinds(self):
k = self.db.tables()
k.remove("_default")
return k
示例7: __init__
# 需要导入模块: from tinydb import TinyDB [as 别名]
# 或者: from tinydb.TinyDB import tables [as 别名]
class CanStorage:
__data_base = TinyDB
__current_sequence_table = TinyDB.table
__current_sequence = None
__max_sequence = None
__ready_to_store = False
def __init__(self, a_file_path):
"""
Opens (or creates) a data base file that that the instance of a
CanStorage interacts with.
:param a_file_path:
Path and file name. Note: path _has_ to exist, if not the program will
exit non-gracefully.
:return:
N/A
"""
self.__data_base = TinyDB(a_file_path)
# Check if we have a current sequence stored in the filemajigger
sequence_table = self.__data_base.table('sequence_counter')
sequence_check = sequence_table.search(where('sequence'))
# If a previous sequence exist we increment the max by one
if sequence_check:
self.__max_sequence = max(sequence_check)['sequence']
# If this is the first entry set current sequence to 0
else:
self.__max_sequence = 0
def print_debug_info(self):
"""
Provides debug information about contents of data base.
:return:
N/A
"""
print self.__data_base.all()
print self.__data_base.tables()
def __init_storage(self):
"""
Initialises a new storage table. Increments the sequence counter, stores
it for future use and creates a new named table for the new sequence of
data to be stored.
:return:
N/A
"""
self.__current_sequence = self.__max_sequence + 1
# Store the current sequence to db for next time the file is opened
sequence_table = self.__data_base.table('sequence_counter')
sequence_table.insert({'sequence': self.__current_sequence})
# Create new table entry for this sequence
sequence_name = 'sequence' + str(self.__current_sequence)
self.__current_sequence_table = self.__data_base.table(sequence_name)
self.__ready_to_store = True
def store(self, a_dict_or_list_entry):
"""
Stores a data entry in the currently opened data base table. If the
storage is not initialised it will call the initialising function to
create a new table for the current sequence of data to be stored.
:param a_dict_or_list_entry:
Either a list containing several dictionary entries or a single
dictionary entry containing a 'data_id' filed.
:return:
N/A
"""
if not self.__ready_to_store:
self.__init_storage()
# Check if we're storing a list or a dictionary
if type(a_dict_or_list_entry) == list:
# Cycle through all dictionaries stored in list
for list_entry in a_dict_or_list_entry:
# Get and remove the key from the dict
data_key = list_entry['data_id']
list_entry.pop('data_id', 0)
# Store the passed dictionary with its key being the data_id
# field
self.__current_sequence_table.insert({data_key: list_entry})
elif type(a_dict_or_list_entry) == dict:
# Get and remove the key from the dict
data_key = a_dict_or_list_entry['data_id']
a_dict_or_list_entry.pop('data_id', 0)
# Store the passed dictionary with its key being the data_id field
self.__current_sequence_table.insert({data_key:
a_dict_or_list_entry})
else:
exit('CanParser.store() expects list or dict entries!')
def load(self, a_sequence_number, a_key):
"""
Provides access to the data stored for the specified sequence number and
the specified key ('data_id').
:param a_sequence_number:
The sequence number of interest.
#.........这里部分代码省略.........
示例8: Flask
# 需要导入模块: from tinydb import TinyDB [as 别名]
# 或者: from tinydb.TinyDB import tables [as 别名]
from flask import Flask
from tinydb import TinyDB
from storage import YAMLStorage
app = Flask(__name__)
db = TinyDB('data.yaml', storage=YAMLStorage)
print(db.tables())
示例9: TinyRunDB
# 需要导入模块: from tinydb import TinyDB [as 别名]
# 或者: from tinydb.TinyDB import tables [as 别名]
#.........这里部分代码省略.........
res_idx = res_list[0][0]
resources = res_list[0][1]
if "resources" in value[0]:
de = defaultdict(list, resources["resources"])
for i, j in value[0]["resources"].items():
de[i].extend(j)
de = {"resources": de}
tx_rec[res_idx] = de
return t.update(tinySet(key, [de]), eids=[run_id])
return t.update(add(key, value), eids=[run_id])
@usedb
def get_tx_record(self, tx_id):
t = self.db.table(name='linchpin')
return t.get(eid=tx_id)
@usedb
def get_tx_records(self, tx_ids):
txs = {}
t = self.db.table(name='linchpin')
for tx_id in tx_ids:
txs[tx_id] = t.get(eid=tx_id)
return txs
@usedb
def get_record(self, table, action='up', run_id=None):
t = self.db.table(name=table)
if not run_id:
run_id = len(t.all())
if not run_id:
return (None, 0)
for rid in range(int(run_id), 0, -1):
record = t.get(eid=int(rid))
if record and record['action'] == action:
return (record, int(rid))
else:
record = t.get(eid=int(run_id))
if record:
return(record, int(run_id))
return (None, 0)
@usedb
def get_records(self, table, count=10):
records = {}
if table in self.db.tables():
t = self.db.table(name=table)
if len(t.all()):
start = len(t)
if count == 'all':
end = 0
else:
end = start - count
for i in xrange(start, end, -1):
records[i] = t.get(doc_id=i)
return records
@usedb
def get_tables(self):
tables = self.db.tables()
tables.remove(self.default_table)
return tables
def remove_record(self, table, key, value):
pass
def search(self, table, key=None):
t = self.db.table(name=table)
if key:
return t.search(key)
return t.all()
def query(self, table, query):
pass
def purge(self, table=None):
if table:
return self.db.purge_table(table)
return self.db.purge_tables()
def _closedb(self):
self.db.close()