TinyDB – Middleware


TinyDB – Middleware



”;


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

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

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()

Advertisements

”;

Leave a Reply

Your email address will not be published. Required fields are marked *