from dataclasses import asdict, dataclass import tinydb import tinyrecord import flask app = flask.Flask(__name__) db = tinydb.TinyDB('notes.json').table('notes') @dataclass class Note: id: int text: str x: float = 100.0 y: float = 100.0 width: float = 220.0 height: float = 220.0 deleted: bool = False @staticmethod def fresh_id() -> int: return len(db.all()) def save(self): note = tinydb.Query() if len(db.search(note.id == self.id)): with tinyrecord.transaction(db) as tr: tr.update(asdict(self), note.id == self.id) else: with tinyrecord.transaction(db) as tr: tr.insert(asdict(self)) @app.route('/') def index(): return flask.send_from_directory('static', 'index.html') @app.route('/note', methods=['GET']) def notes(): return flask.jsonify(db.all()) @app.route('/note', methods=['POST']) def post_note(): params = flask.request.json if 'id' not in params: params['id'] = Note.fresh_id() note = Note(**flask.request.json) print(note) note.save() return "OK"