def __init__(self, name='db.json', purge=False): # test initial number of tables serialization = SerializationMiddleware() serialization.register_serializer(DateTimeSerializer(), 'TinyDate') self.db = tinydb.TinyDB('Data/' + name, storage=serialization) if purge: self.db.purge_tables() self._init_db()
def test_serializer(tmpdir): path = str(tmpdir.join('db.json')) serializer = SerializationMiddleware(JSONStorage) serializer.register_serializer(DateTimeSerializer(), 'TinyDate') db = TinyDB(path, storage=serializer) date = datetime(2000, 1, 1, 12, 0, 0) db.insert({'date': date}) db.insert({'int': 2}) assert db.count(where('date') == date) == 1 assert db.count(where('int') == 2) == 1
import os import settings from flask import Flask from tinydb import TinyDB from tinydb.storages import JSONStorage from tinydb.middlewares import SerializationMiddleware import models.device app = Flask(__name__) serialization = SerializationMiddleware() serialization.register_serializer(models.device.DeviceSerializer, 'TinyDevice') db = TinyDB(settings.TINYDB_PATH, storage=serialization) import controllers.routes app.debug = True if __name__ == '__main__': app.run(debug=True)
def prepare_db(name: str) -> TinyDB: """Creates new database with registered datetime serializer""" serialization = SerializationMiddleware() serialization.register_serializer(DateTimeSerializer(), 'TinyDate') db = TinyDB(name, storage=serialization) return db
import datetime from tinydb.storages import JSONStorage from tinydb.serialize import Serializer from tinydb.middlewares import SerializationMiddleware class DateTimeSerializer(Serializer): OBJ_CLASS = datetime.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') serialization = SerializationMiddleware() serialization.register_serializer(DateTimeSerializer(), 'TinyDate')