Event Hooks give you more flexibility than middleware.
For example, you can achieve compress/decompress data without creating a new Storage class.
It is the low-level API for Modifier and Index
Called before json dumping
ChainType:ActionCentipedeActionType:async
str(event name)Storage(storage)dict(data)
Noneordict(data)
Return any non-None value will overwrite data to be saved.
Called after json dumping
ChainType:ActionCentipedeActionType:async
str(event name)Storage(storage)str|bytes(json str or bytes)
Noneorstr|bytes(json str or bytes)
Return any non-None value will overwrite data to be saved.
Called before json loading Executed in reversed order
ChainType:ActionCentipedeActionType:async
str(event name)Storage(storage)str|bytes(json str or bytes)
Noneorstr|bytes(json str or bytes)
Return any non-None value will overwrite data to be read.
Called after json loading Executed in reversed order
ChainType:ActionCentipedeActionType:async
str(event name)Storage(storage)dict(data)
Noneordict(data)
Called when storage is closed
ChainType:ActionChainActionType:async
str(event name)Storage(storage)
None
Return any non-None value will overwrite data to be read.
Called when a document is created
ChainType:ActionChainActionType:sync
str(event name)Table(table)BaseDocument(document)
None
Called when a document is read
ChainType:ActionChainActionType:sync
str(event name)Table(table)BaseDocument(document)
None
Called when a document is updated
ChainType:ActionChainActionType:sync
str(event name)Table(table)BaseDocument(document)
None
Called when a document is deleted
ChainType:ActionChainActionType:sync
str(event name)Table(table)BaseDocument(document)
None
Called when a table is truncated
ChainType:ActionChainActionType:sync
str(event name)Table(table)
None
s = Storage()
# By accessing the attribute `on`, you can register a new func to the event
@s.on.write.pre
async def f(ev, s, data): # Will be executed on event `write.pre`
...async def main():
db = TinyDB('test.json')
@db.storage.on.write.pre
async def mul(ev: str, s: Storage, data: dict):
data["_default"]["1"]['answer'] *= 2 # Manipulate data, not a good idea, just for demonstration
@db.storage.on.write.post
async def _print(ev, s, anystr):
print(anystr) # print json dumped string
# No return value or return None will not affect tdata
await db.insert({"answer": 21}) # insert() will trigger both write events
await db.close()
# Reload
db = TinyDB('test.json')
print(await db.search(Query().answer == 42)) # >>> [{'answer': 42}]