Tinydb 简明教程
TinyDB - Extend TinyDB
可以扩展 TinyDB 并修改其行为。有四种方法可以做到:
It is possible to extend TinyDB and modify its behaviour. There are four ways to do so −
-
Custom middleware
-
Custom storages
-
Hooks and overrides
-
Subclassing TinyDB and table
在本章中,我们将详细了解每种方法。
In this chapter, let’s understand each of these methods in detail.
Custom Middleware
有时用户不想编写新的存储模块。在这种情况下,用户可以修改现有存储模块的行为。让我们来看一个示例,其中我们将构建一个用于过滤空项的自定义中间件:
Sometimes the user does not want to write a new storage module. In such cases, the user can modify the behaviour of an existing storage module. Let’s see an example in which we will build a custom middleware filtering out the empty items −
首先,让我们查看将通过自定义中间件的数据:
First, let’s see the data that will go through the custom middleware −
{
'_default': {
1: {'key1': 'value1'},
2: {'key2': 'value2'},
……………,
N: {'keyN': 'valueN'}
},
现在,让我们看看如何实现自定义中间件:
Now, let’s see how we can implement the custom middleware −
class RemoveEmptyItemsMiddleware(Middleware):
def __init__(self, storage_cls):
super(self).__init__(storage_cls)
def read(self):
data = self.storage.read()
for _default in data:
st_name = data
for doc_id in table:
item = st_name
if item == {}:
del st_name
return data
def close(self):
self.storage.close()
Custom Storage
如前所述,TinyDB 随附两种类型的存储:内存中存储和 JSON 文件存储。除此之外,TinyDB 还提供了一个选项以添加我们自己的自定义存储。在以下示例中,让我们看看如何使用 PyYAML 添加 YAML 存储:
As discussed earlier, TinyDB comes with two types of storages: in-memory and JSON file storage. Along with that, TinyDB also provides an option to add our own custom storage. In the following example, let’s see how we can add a YAML storage using PyYAML −
import yaml
class YAMLStorage(Storage):
def __init__(self, db.json):
self. db.json = db.json
To read the file −
To read the file −
def read(self):
with open(self.db.json) as handle:
try:
info = yaml.safe_load(handle.read())
return info
except yaml.YAMLError:
return None
To write the file −
To write the file −
def write(self, info):
with open(self.db.json, 'w+') as handle:
yaml.dump(info, handle)
To close the file −
To close the file −
def close(self):
pass
Hooks and Overrides
有时,自定义存储和自定义中间件都无法按照您想要的方式工作。在这样的情况下,用户可以使用预定义的挂钩和覆盖来修改 TinyDB 的行为。作为一个示例,我们将配置默认表的名称如下:
Sometimes, both custom storage and custom middleware cannot work in the way you want. In such cases, user can use predefined hooks and overrides to modify the behaviour of TinyDB. As an example, we will be configuring the name of the default table as follows −
TinyDB.default_table_name = 'student_detail'
我们还可以分配缓存容量,如下所示:
We can also assign cache capacity as follows −
TinyDB.table_class.default_query_cache_capacity = 50
Subclassing TinyDB and Table
这是我们可以用来修改 TinyDB 行为的最后一种方法。作为一个示例,我们将创建一个子类,该子类可以与钩子和覆盖一起使用来覆盖默认类。
This is the last way we can use to modify the behaviour of TinyDB. As an example, we will be creating a subclass that can be used with hooks and overrides to override the default classes.
Class ExtendTable(Table):
TinyDB.table_class = student_detail