Tinydb 简明教程
TinyDB - Middleware
TinyDB 中间件通过在现有存储周围进行封装来帮助我们自定义数据库存储行为。此中间件可提高数据库的性能。
TinyDB middleware helps us to customize database storage behavior by wrapping around the existing storage. This middleware improves the performance of the database.
Caching Middleware
顾名思义,此中间件通过减少磁盘 I/O 来提升数据库速度。CachingMiddleware 的工作原理如下:
This middleware, as its name implies, improves the speed of a database by reducing the disk I/O. The working of CachingMiddleware is as follows −
-
First, it catches all the read operations.
-
Then it writes the data to the disk after a configured number of write operations.
Syntax
使用 CachingMiddleware 的语法如下:
The syntax to use CachingMiddleware is as follows −
from tinydb.storages import JSONStorage
from tinydb.middlewares import CachingMiddleware
db = TinyDB('middleware.json', storage = CachingMiddleware(JSONStorage))
db.close()
Example
以下示例演示了如何在数据库中执行基本的中间件过程。
The following example shows how you can perform a basic middleware procedure in a database.
from tinydb import TinyDB
from tinydb.storages import JSONStorage
from tinydb.middlewares import CachingMiddleware
object = TinyDB('storage.json', storage=CachingMiddleware(JSONStorage))
object.all()
Output
它将生成如下输出:
It will produce the following output −
[
{
"roll_number":1,
"st_name":"elen",
"mark":250,
"subject":"TinyDB",
"address":"delhi"
},
{
"roll_number":2,
"st_name":"Ram",
"mark":[
250,
280
],
"subject":[
"TinyDB",
"MySQL"
],
"address":"delhi"
},
{
"roll_number":3,
"st_name":"kevin",
"mark":[
180,
200
],
"subject":[
"oracle",
"sql"
],
"address":"keral"
},
{
"roll_number":4,
"st_name":"lakan",
"mark":200,
"subject":"MySQL",
"address":"mumbai"
},
{
"roll_number":5,
"st_name":"karan",
"mark":275,
"subject":"oracle",
"address":"benglore"
}
]
关闭数据库以确保安全写入所有数据。
Close the database to make sure that all the data is safely written.
db.close()