- TinyDB Tutorial
- TinyDB - Home
- TinyDB - Introduction
- TinyDB - Environmental Setup
- TinyDB - Insert Data
- TinyDB - Retrieve Data
- TinyDB - Update Data
- TinyDB - Delete Data
- TinyDB - Querying
- TinyDB - Searching
- TinyDB - The where Clause
- TinyDB - The Exists() Query
- TinyDB - The Matches() Query
- TinyDB - The Test() Query
- TinyDB - The Any() Query
- TinyDB - The All() Query
- TinyDB - The one_of() Query
- TinyDB - Logical Negate
- TinyDB - Logical AND
- TinyDB - Logical OR
- TinyDB - Handling Data Query
- TinyDB - Modifying the Data
- TinyDB - Upserting Data
- TinyDB - Retrieving Data
- TinyDB - Document ID
- TinyDB - Tables
- TinyDB - Default Table
- TinyDB - Caching Query
- TinyDB - Storage Types
- TinyDB - Middleware
- TinyDB - Extend TinyDB
- TinyDB - Extensions
- TinyDB Useful Resources
- TinyDB - Quick Guide
- TinyDB - Useful Resources
- TinyDB - Discussion
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
To Continue Learning Please Login
Login with Google