本文整理汇总了Python中tinydb.storages.JSONStorage方法的典型用法代码示例。如果您正苦于以下问题:Python storages.JSONStorage方法的具体用法?Python storages.JSONStorage怎么用?Python storages.JSONStorage使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类tinydb.storages
的用法示例。
在下文中一共展示了storages.JSONStorage方法的9个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: create_ports
# 需要导入模块: from tinydb import storages [as 别名]
# 或者: from tinydb.storages import JSONStorage [as 别名]
def create_ports(tmpdir, monkeypatch):
def _create_ports(ports):
def get_db():
tmp_db = tmpdir.join("db.json")
db = TinyDB(
str(tmp_db),
storage=CachingMiddleware(JSONStorage)
)
for port in ports:
db.insert({
'name': port[0],
'port': port[1],
"description": port[2],
"protocol": port[3]
})
return db
return monkeypatch.setattr(whatportis.db, "get_database", get_db)
return _create_ports
示例2: __init__
# 需要导入模块: from tinydb import storages [as 别名]
# 或者: from tinydb.storages import JSONStorage [as 别名]
def __init__(self, name=None, data_dir=None, **kwargs):
"""Create a period with a TinyDB database backend, identified by 'name'.
If 'data_dir' is given, the database storage type is JSON (the storage
filepath is derived from the Period's name). Otherwise the data is
stored in memory.
Keyword args are passed to the TinyDB constructor. See the respective
docs for detailed information.
"""
super().__init__(name=name)
# evaluate args/kwargs for TinyDB constructor. This overwrites the
# 'storage' kwarg if explicitly passed
if data_dir is None:
args = []
kwargs["storage"] = storages.MemoryStorage
else:
args = [os.path.join(data_dir, "{}.json".format(self.name))]
kwargs["storage"] = storages.JSONStorage
self._db = TinyDB(*args, **kwargs)
self._create_category_cache()
示例3: test_serializer
# 需要导入模块: from tinydb import storages [as 别名]
# 或者: from tinydb.storages import JSONStorage [as 别名]
def test_serializer(tmpdir):
path = str(tmpdir.join('db.json'))
serializer = SerializationMiddleware(JSONStorage)
serializer.register_serializer(DateTimeSerializer(), 'TinyDate')
db = TinyDB(path, storage=serializer)
date = datetime(2000, 1, 1, 12, 0, 0)
db.insert({'date': date})
db.insert({'int': 2})
assert db.count(where('date') == date) == 1
assert db.count(where('int') == 2) == 1
示例4: test_serializer_nondestructive
# 需要导入模块: from tinydb import storages [as 别名]
# 或者: from tinydb.storages import JSONStorage [as 别名]
def test_serializer_nondestructive(tmpdir):
path = str(tmpdir.join('db.json'))
serializer = SerializationMiddleware(JSONStorage)
serializer.register_serializer(DateTimeSerializer(), 'TinyDate')
db = TinyDB(path, storage=serializer)
data = {'date': datetime.utcnow(), 'int': 3, 'list': []}
data_before = dict(data) # implicitly copy
db.insert(data)
assert data == data_before
示例5: test_serializer_recursive
# 需要导入模块: from tinydb import storages [as 别名]
# 或者: from tinydb.storages import JSONStorage [as 别名]
def test_serializer_recursive(tmpdir):
path = str(tmpdir.join('db.json'))
serializer = SerializationMiddleware(JSONStorage)
serializer.register_serializer(DateTimeSerializer(), 'TinyDate')
db = TinyDB(path, storage=serializer)
date = datetime(2000, 1, 1, 12, 0, 0)
datenow = datetime.utcnow()
dates = [{'date': date, 'hp': 100}, {'date': datenow, 'hp': 1}]
data = {'dates': dates, 'int': 10}
db.insert(data)
db.insert({'int': 2})
assert db.count(where('dates').any(where('date') == date)) == 1
assert db.count(where('int') == 2) == 1
示例6: __init__
# 需要导入模块: from tinydb import storages [as 别名]
# 或者: from tinydb.storages import JSONStorage [as 别名]
def __init__(self):
"""Adds self to messages and event's `data` field.
Through this instance you can access TinyDB instance (data["tinydbproxy"].tinydb).
This plugin should be included first!
"""
super().__init__()
self.order = (-95, 95)
self.tinydb = TinyDB(path=self.get_path("tinydb_database.json"), storage=CachingMiddleware(JSONStorage))
示例7: get_database
# 需要导入模块: from tinydb import storages [as 别名]
# 或者: from tinydb.storages import JSONStorage [as 别名]
def get_database():
return TinyDB(path, storage=CachingMiddleware(JSONStorage))
示例8: new
# 需要导入模块: from tinydb import storages [as 别名]
# 或者: from tinydb.storages import JSONStorage [as 别名]
def new(cls, script, commit, params, campaign_dir, overwrite=False):
"""
Initialize a new class instance with a set configuration and filename.
The created database has the same name of the campaign directory.
Args:
script (str): the ns-3 name of the script that will be used in this
campaign;
commit (str): the commit of the ns-3 installation that is used to
run the simulations.
params (list): a list of the parameters that can be used on the
script.
campaign_dir (str): The path of the file where to save the DB.
overwrite (bool): Whether or not existing directories should be
overwritten.
"""
# We only accept absolute paths
if not Path(campaign_dir).is_absolute():
raise ValueError("Path is not absolute")
# Make sure the directory does not exist already
if Path(campaign_dir).exists() and not overwrite:
raise FileExistsError("The specified directory already exists")
elif Path(campaign_dir).exists() and overwrite:
# Verify we are not deleting files belonging to the user
campaign_dir_name = os.path.basename(campaign_dir)
folder_contents = set(os.listdir(campaign_dir))
allowed_files = set(
['data', '%s.json' % campaign_dir_name] +
# Allow hidden files (like .DS_STORE in macos)
[os.path.basename(os.path.normpath(f)) for f in
glob.glob(os.path.join(campaign_dir, ".*"))])
if(not folder_contents.issubset(allowed_files)):
raise ValueError("The specified directory cannot be overwritten"
" because it contains user files.")
# This operation destroys data.
shutil.rmtree(campaign_dir)
# Create the directory and database file in it
# The indent and separators ensure the database is human readable.
os.makedirs(campaign_dir)
tinydb = TinyDB(os.path.join(campaign_dir, "%s.json" %
os.path.basename(campaign_dir)),
storage=CachingMiddleware(JSONStorage))
# Save the configuration in the database
config = {
'script': script,
'commit': commit,
'params': sorted(params)
}
tinydb.table('config').insert(config)
tinydb.storage.flush()
return cls(tinydb, campaign_dir)
示例9: load
# 需要导入模块: from tinydb import storages [as 别名]
# 或者: from tinydb.storages import JSONStorage [as 别名]
def load(cls, campaign_dir):
"""
Initialize from an existing database.
It is assumed that the database json file has the same name as its
containing folder.
Args:
campaign_dir (str): The path to the campaign directory.
"""
# We only accept absolute paths
if not Path(campaign_dir).is_absolute():
raise ValueError("Path is not absolute")
# Verify file exists
if not Path(campaign_dir).exists():
raise ValueError("Directory does not exist")
# Extract filename from campaign dir
filename = "%s.json" % os.path.split(campaign_dir)[1]
filepath = os.path.join(campaign_dir, filename)
try:
# Read TinyDB instance from file
tinydb = TinyDB(filepath,
storage=CachingMiddleware(JSONStorage))
# Make sure the configuration is a valid dictionary
assert set(
tinydb.table('config').all()[0].keys()) == set(['script',
'params',
'commit'])
except:
# Remove the database instance created by tinydb
os.remove(filepath)
raise ValueError("Specified campaign directory seems corrupt")
return cls(tinydb, campaign_dir)
###################
# Database access #
###################