Tinydb 简明教程

TinyDB - Middleware

TinyDB 中间件通过在现有存储周围进行封装来帮助我们自定义数据库存储行为。此中间件可提高数据库的性能。

Caching Middleware

顾名思义,此中间件通过减少磁盘 I/O 来提升数据库速度。CachingMiddleware 的工作原理如下:

  1. 首先,它会捕获所有读取操作。

  2. 然后,它会在配置的写入操作次数后将数据写入磁盘。

Syntax

使用 CachingMiddleware 的语法如下:

from tinydb.storages import JSONStorage
from tinydb.middlewares import CachingMiddleware
db = TinyDB('middleware.json', storage = CachingMiddleware(JSONStorage))
db.close()

Example

以下示例演示了如何在数据库中执行基本的中间件过程。

from tinydb import TinyDB
from tinydb.storages import JSONStorage
from tinydb.middlewares import CachingMiddleware
object = TinyDB('storage.json', storage=CachingMiddleware(JSONStorage))
object.all()

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"
   }
]

关闭数据库以确保安全写入所有数据。

db.close()