How to Extend TinyDB

Storages

To write a custom storage, subclass Storage:

class tinydb.storages.Storage

The abstract base class for all Storages.

A Storage (de)serializes the current state of the database and stores it in some place (memory, file on disk, ...).

read()

Read the last stored state.

Any kind of deserialization should go here.

Return type:dict
write(data)

Write the current state of the database to the storage.

Any kind of serialization should go here.

Parameters:data (dict) – The current state of the database.

To use your custom storage, use:

db = TinyDB(storage=YourStorageClass)

Hint

TinyDB will pass all arguments and keyword arguments (except for storage) to your storage’s __init__.

For example implementations, check out the source of JSONStorage or MemoryStorage.

Middlewares

To write a custom storage, subclass Middleware:

class tinydb.middlewares.Middleware

The base class for all Middlewares.

Middlewares hook into the read/write process of TinyDB allowing you to extend the behaviour by adding caching, logging, ...

Your middleware’s __init__ method has to accept exactly one argument which is the class of the “real” storage. It has to be stored as _storage_cls (see CachingMiddleware for an example).

storage

This will contain the underlying Storage

read(self)

Modify the way TinyDB reads data.

To access the underlying storage’s read method, use self.storage.read.

write(self, data)

Modify the way TinyDB writes data.

To access the underlying storage’s read method, use self.storage.read.

To use your middleware, use:

db = TinyDB(storage=YourMiddleware(SomeStorageClass))

For example implementations, check out the source of CachingMiddleware or ConcurrencyMiddleware.

About TinyDB

TinyDB is a tiny, document oriented database optimized for your happiness :)

Useful Links

Table Of Contents

Navigation