tinydb-serialization
provides serialization for objects that TinyDB
otherwise couldn't handle.
To use a serializer, create a SerializationMiddleware
instance with
the storage class you want to use and register the serializers you want
to use. Then you pass the middleware instance as the storage to TinyDB:
>>> from tinydb import TinyDB, Query
>>> from tinydb.storages import JSONStorage
>>> from tinydb_serialization import SerializationMiddleware
>>> from tinydb_serialization.serializers import DateTimeSerializer
>>>
>>> from datetime import datetime
>>>
>>> serialization = SerializationMiddleware(JSONStorage)
>>> serialization.register_serializer(DateTimeSerializer(), 'TinyDate')
>>>
>>> db = TinyDB('db.json', storage=serialization)
>>> db.insert({'date': datetime(2000, 1, 1, 12, 0, 0)})
>>> db.all()
[{'date': datetime.datetime(2000, 1, 1, 12, 0)}]
>>> query = Query()
>>> db.insert({'date': datetime(2010, 1, 1, 12, 0, 0)})
>>> db.search(query.date > datetime(2005, 1, 1))
[{'date': datetime.datetime(2010, 1, 1, 12, 0)}]
Important: A SerializationMiddleware
instance always wraps a database's storage.
This means that the SerializationMiddleware
instance cannot be shared
between multiple TinyDB
instances as they would use the same underlying storage
instance and thus share all data between both instances.
tinydb_serialization.serializers.DateTimeSerializer
: serializesdatetime
objects as ISO 8601 formatted stringstinydb_serialization.serializers.DateSerializer
: serializesdate
objects as ISO 8601 formatted strings
In this example we implement a serializer for datetime
objects (like the one provided
by this package):
from datetime import datetime
from tinydb_serialization import Serializer
class DateTimeSerializer(Serializer):
OBJ_CLASS = datetime # The class this serializer handles
def encode(self, obj):
return obj.isoformat()
def decode(self, s):
return datetime.fromisoformat(s)
- Include the
DateSerializer
in this package (see issue #16)
- Fix VSCode Pylance type error (see pull request #14)
- Add support for storages that encode as binary strings (see pull request #17)
- Drop Python 3.7 support
- Include the
DateTimeSerializer
in this package (see issue #10) - Drop Python 3.6 support (as 3.7 is needed for date parsing)
- Add TinyDB v4.0.0 support (see pull request #9)
- Don't modify the original element if it contains a list (see pull request #5)
- Handle nested data (nested dicts, lists) properly when serializing/deserializing (see pull request #3)
- Don't destroy original data when serializing (see pull request #2)
- Fix installation via pip (see issue #1)
- Initial release on PyPI