corkboard.py 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. from dataclasses import asdict, dataclass
  2. import tinydb
  3. import tinyrecord
  4. import flask
  5. app = flask.Flask(__name__)
  6. db = tinydb.TinyDB('notes.json').table('notes')
  7. @dataclass
  8. class Note:
  9. id: int
  10. text: str
  11. x: float = 100.0
  12. y: float = 100.0
  13. width: float = 220.0
  14. height: float = 220.0
  15. deleted: bool = False
  16. @staticmethod
  17. def fresh_id() -> int:
  18. return len(db.all())
  19. def save(self):
  20. note = tinydb.Query()
  21. if len(db.search(note.id == self.id)):
  22. with tinyrecord.transaction(db) as tr:
  23. tr.update(asdict(self), note.id == self.id)
  24. else:
  25. with tinyrecord.transaction(db) as tr:
  26. tr.insert(asdict(self))
  27. @app.route('/')
  28. def index():
  29. return flask.send_from_directory('static', 'index.html')
  30. @app.route('/note', methods=['GET'])
  31. def notes():
  32. return flask.jsonify(db.all())
  33. @app.route('/note', methods=['POST'])
  34. def post_note():
  35. params = flask.request.json
  36. if 'id' not in params:
  37. params['id'] = Note.fresh_id()
  38. note = Note(**flask.request.json)
  39. print(note)
  40. note.save()
  41. return "OK"