tinydb-serialization
provides serialization for objects that TinyDB
otherwise couldn't handle.
In this example we implement a serializer for datetime
objects:
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.strftime('%Y-%m-%dT%H:%M:%S')
def decode(self, s):
return datetime.strptime(s, '%Y-%m-%dT%H:%M:%S')
You can use your serializer like this:
>>> from tinydb import TinyDB
>>> from tinydb.storages import JSONStorage
>>> from tinydb_serialization import SerializationMiddleware
>>> from tinydb import Query
>>>
>>> from datetime import datetime
>>>
>>>
>>> serialization = SerializationMiddleware()
>>> 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)}]
- 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