|
| 1 | +from cmd import Cmd |
| 2 | +import objectbox |
| 3 | +import datetime |
| 4 | +from example.model import * |
| 5 | + |
| 6 | + |
| 7 | +# objectbox expects date timestamp in milliseconds since UNIX epoch |
| 8 | +def now_ms() -> int: |
| 9 | + seconds: float = datetime.datetime.utcnow().timestamp() |
| 10 | + return round(seconds * 1000) |
| 11 | + |
| 12 | + |
| 13 | +def format_date(timestamp_ms: int) -> str: |
| 14 | + return "" if timestamp_ms == 0 else str(datetime.datetime.fromtimestamp(timestamp_ms / 1000)) |
| 15 | + |
| 16 | + |
| 17 | +class TasklistCmd(Cmd): |
| 18 | + prompt = "> " |
| 19 | + _ob = objectbox.Builder().model(get_objectbox_model()).directory("tasklist-db").build() |
| 20 | + _box = objectbox.Box(_ob, Task) |
| 21 | + |
| 22 | + def do_ls(self, _): |
| 23 | + """list tasks""" |
| 24 | + |
| 25 | + tasks = self._box.get_all() |
| 26 | + |
| 27 | + print("%3s %-29s %-29s %s" % ("ID", "Created", "Finished", "Text")) |
| 28 | + for task in tasks: |
| 29 | + print("%3d %-29s %-29s %s" % ( |
| 30 | + task.id, format_date(task.date_created), format_date(task.date_finished), task.text)) |
| 31 | + |
| 32 | + def do_new(self, text: str): |
| 33 | + """create a new task with the given text (all arguments concatenated)""" |
| 34 | + task = Task() |
| 35 | + task.text = text |
| 36 | + task.date_created = now_ms() |
| 37 | + self._box.put(task) |
| 38 | + |
| 39 | + def do_done(self, id: str): |
| 40 | + """mark task with the given ID as done""" |
| 41 | + task = self._box.get(int(id)) |
| 42 | + task.date_finished = now_ms() |
| 43 | + self._box.put(task) |
| 44 | + |
| 45 | + def do_exit(self, _): |
| 46 | + """close the program""" |
| 47 | + raise SystemExit() |
| 48 | + |
| 49 | + |
| 50 | +if __name__ == '__main__': |
| 51 | + app = TasklistCmd() |
| 52 | + app.cmdloop('Welcome to the ObjectBox tasks-list app example. Type help or ? for a list of commands.') |
0 commit comments