TinyDB - Extend 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

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 −

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 −

def write(self, info):
   with open(self.db.json, 'w+') as handle:
      yaml.dump(info, handle)

To close the file −

def close(self):
   pass

Hooks and Overrides

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

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
Advertisements