1 """Web server stuff."""
2 from __future__ import annotations
3 from dataclasses import dataclass
4 from typing import Any, Callable
5 from base64 import b64encode, b64decode
6 from http.server import BaseHTTPRequestHandler
7 from http.server import HTTPServer
8 from urllib.parse import urlparse, parse_qs
9 from os.path import split as path_split
10 from jinja2 import Environment as JinjaEnv, FileSystemLoader as JinjaFSLoader
11 from plomtask.dating import date_in_n_days
12 from plomtask.days import Day
13 from plomtask.exceptions import HandledException, BadFormatException, \
15 from plomtask.db import DatabaseConnection, DatabaseFile
16 from plomtask.processes import Process, ProcessStep, ProcessStepsNode
17 from plomtask.conditions import Condition
18 from plomtask.todos import Todo
20 TEMPLATES_DIR = 'templates'
23 class TaskServer(HTTPServer):
24 """Variant of HTTPServer that knows .jinja as Jinja Environment."""
26 def __init__(self, db_file: DatabaseFile,
27 *args: Any, **kwargs: Any) -> None:
28 super().__init__(*args, **kwargs)
30 self.jinja = JinjaEnv(loader=JinjaFSLoader(TEMPLATES_DIR))
34 """Wrapper for validating and retrieving dict-like HTTP inputs."""
36 def __init__(self, dict_: dict[str, list[str]],
37 strictness: bool = True) -> None:
39 self.strict = strictness
41 def get_str(self, key: str, default: str = '',
42 ignore_strict: bool = False) -> str:
43 """Retrieve single/first string value of key, or default."""
44 if key not in self.inputs.keys() or 0 == len(self.inputs[key]):
45 if self.strict and not ignore_strict:
46 raise BadFormatException(f'no value found for key {key}')
48 return self.inputs[key][0]
50 def get_first_strings_starting(self, prefix: str) -> dict[str, str]:
51 """Retrieve dict of (first) strings at key starting with prefix."""
53 for key in [k for k in self.inputs.keys() if k.startswith(prefix)]:
54 ret[key] = self.inputs[key][0]
57 def get_int(self, key: str) -> int:
58 """Retrieve single/first value of key as int, error if empty."""
59 val = self.get_int_or_none(key)
61 raise BadFormatException(f'unexpected empty value for: {key}')
64 def get_int_or_none(self, key: str) -> int | None:
65 """Retrieve single/first value of key as int, return None if empty."""
66 val = self.get_str(key, ignore_strict=True)
71 except ValueError as e:
72 msg = f'cannot int form field value for key {key}: {val}'
73 raise BadFormatException(msg) from e
75 def get_float(self, key: str) -> float:
76 """Retrieve float value of key from self.postvars."""
77 val = self.get_str(key)
80 except ValueError as e:
81 msg = f'cannot float form field value for key {key}: {val}'
82 raise BadFormatException(msg) from e
84 def get_all_str(self, key: str) -> list[str]:
85 """Retrieve list of string values at key."""
86 if key not in self.inputs.keys():
88 return self.inputs[key]
90 def get_all_int(self, key: str) -> list[int]:
91 """Retrieve list of int values at key."""
92 all_str = self.get_all_str(key)
94 return [int(s) for s in all_str if len(s) > 0]
95 except ValueError as e:
96 msg = f'cannot int a form field value for key {key} in: {all_str}'
97 raise BadFormatException(msg) from e
100 class TaskHandler(BaseHTTPRequestHandler):
101 """Handles single HTTP request."""
102 # pylint: disable=too-many-public-methods
104 conn: DatabaseConnection
106 form_data: InputsParser
109 def send_html(self, html: str, code: int = 200) -> None:
110 """Send HTML as proper HTTP response."""
111 self.send_response(code)
113 self.wfile.write(bytes(html, 'utf-8'))
116 def _request_wrapper(http_method: str, not_found_msg: str
117 ) -> Callable[..., Callable[[TaskHandler], None]]:
118 def decorator(f: Callable[..., str | None]
119 ) -> Callable[[TaskHandler], None]:
120 def wrapper(self: TaskHandler) -> None:
122 self.conn = DatabaseConnection(self.server.db)
123 parsed_url = urlparse(self.path)
124 self.site = path_split(parsed_url.path)[1]
125 params = parse_qs(parsed_url.query, strict_parsing=True)
126 self.params = InputsParser(params, False)
127 handler_name = f'do_{http_method}_{self.site}'
128 if hasattr(self, handler_name):
129 handler = getattr(self, handler_name)
130 redir_target = f(self, handler)
132 self.send_response(302)
133 self.send_header('Location', redir_target)
136 msg = f'{not_found_msg}: {self.site}'
137 raise NotFoundException(msg)
138 except HandledException as error:
139 html = self.server.jinja.\
140 get_template('msg.html').render(msg=error)
141 self.send_html(html, error.http_code)
147 @_request_wrapper('GET', 'Unknown page')
148 def do_GET(self, handler: Callable[[], str | dict[str, object]]
150 """Render page with result of handler, or redirect if result is str."""
151 template = f'{self.site}.html'
152 ctx_or_redir = handler()
153 if str == type(ctx_or_redir):
155 assert isinstance(ctx_or_redir, dict)
156 html = self.server.jinja.get_template(template).render(**ctx_or_redir)
160 @_request_wrapper('POST', 'Unknown POST target')
161 def do_POST(self, handler: Callable[[], str]) -> str:
162 """Handle POST with handler, prepare redirection to result."""
163 length = int(self.headers['content-length'])
164 postvars = parse_qs(self.rfile.read(length).decode(),
165 keep_blank_values=True, strict_parsing=True)
166 self.form_data = InputsParser(postvars)
167 redir_target = handler()
173 def do_GET_(self) -> str:
174 """Return redirect target on GET /."""
177 def _do_GET_calendar(self) -> dict[str, object]:
178 """Show Days from ?start= to ?end=.
180 Both .do_GET_calendar and .do_GET_calendar_txt refer to this to do the
181 same, the only difference being the HTML template they are rendered to,
182 which .do_GET selects from their method name.
184 start = self.params.get_str('start')
185 end = self.params.get_str('end')
187 end = date_in_n_days(366)
188 ret = Day.by_date_range_with_limits(self.conn, (start, end), 'id')
189 days, start, end = ret
190 days = Day.with_filled_gaps(days, start, end)
192 day.collect_calendarized_todos(self.conn)
193 today = date_in_n_days(0)
194 return {'start': start, 'end': end, 'days': days, 'today': today}
196 def do_GET_calendar(self) -> dict[str, object]:
197 """Show Days from ?start= to ?end= – normal view."""
198 return self._do_GET_calendar()
200 def do_GET_calendar_txt(self) -> dict[str, object]:
201 """Show Days from ?start= to ?end= – minimalist view."""
202 return self._do_GET_calendar()
204 def do_GET_day(self) -> dict[str, object]:
205 """Show single Day of ?date=."""
206 date = self.params.get_str('date', date_in_n_days(0))
207 make_type = self.params.get_str('make_type')
208 todays_todos = Todo.by_date(self.conn, date)
210 for todo in todays_todos:
211 total_effort += todo.performed_effort
212 conditions_present = []
215 for todo in todays_todos:
216 for condition in todo.conditions + todo.blockers:
217 if condition not in conditions_present:
218 conditions_present += [condition]
219 enablers_for[condition.id_] = [p for p in
220 Process.all(self.conn)
221 if condition in p.enables]
222 disablers_for[condition.id_] = [p for p in
223 Process.all(self.conn)
224 if condition in p.disables]
225 seen_todos: set[int] = set()
226 top_nodes = [t.get_step_tree(seen_todos)
227 for t in todays_todos if not t.parents]
228 return {'day': Day.by_id(self.conn, date, create=True),
229 'total_effort': total_effort,
230 'top_nodes': top_nodes,
231 'make_type': make_type,
232 'enablers_for': enablers_for,
233 'disablers_for': disablers_for,
234 'conditions_present': conditions_present,
235 'processes': Process.all(self.conn)}
237 def do_GET_todo(self) -> dict[str, object]:
238 """Show single Todo of ?id=."""
242 """Collect what's useful for Todo steps tree display."""
245 process: Process | None
246 children: list[TodoStepsNode] # pylint: disable=undefined-variable
247 fillable: bool = False
249 def walk_process_steps(id_: int,
250 process_step_nodes: list[ProcessStepsNode],
251 steps_nodes: list[TodoStepsNode]) -> None:
252 for process_step_node in process_step_nodes:
254 node = TodoStepsNode(id_, None, process_step_node.process, [])
255 steps_nodes += [node]
256 walk_process_steps(id_, list(process_step_node.steps.values()),
259 def walk_todo_steps(id_: int, todos: list[Todo],
260 steps_nodes: list[TodoStepsNode]) -> None:
263 for match in [item for item in steps_nodes
265 and item.process == todo.process]:
268 for child in match.children:
269 child.fillable = True
270 walk_todo_steps(id_, todo.children, match.children)
273 node = TodoStepsNode(id_, todo, None, [])
274 steps_nodes += [node]
275 walk_todo_steps(id_, todo.children, node.children)
277 def collect_adoptables_keys(steps_nodes: list[TodoStepsNode]
280 for node in steps_nodes:
282 assert isinstance(node.process, Process)
283 assert isinstance(node.process.id_, int)
284 ids.add(node.process.id_)
285 ids = ids | collect_adoptables_keys(node.children)
288 id_ = self.params.get_int('id')
289 todo = Todo.by_id(self.conn, id_)
290 todo_steps = [step.todo for step in todo.get_step_tree(set()).children]
291 process_tree = todo.process.get_steps(self.conn, None)
292 steps_todo_to_process: list[TodoStepsNode] = []
293 walk_process_steps(0, list(process_tree.values()),
294 steps_todo_to_process)
295 for steps_node in steps_todo_to_process:
296 steps_node.fillable = True
297 walk_todo_steps(len(steps_todo_to_process), todo_steps,
298 steps_todo_to_process)
299 adoptables: dict[int, list[Todo]] = {}
300 any_adoptables = [Todo.by_id(self.conn, t.id_)
301 for t in Todo.by_date(self.conn, todo.date)
303 for id_ in collect_adoptables_keys(steps_todo_to_process):
304 adoptables[id_] = [t for t in any_adoptables
305 if t.process.id_ == id_]
306 return {'todo': todo, 'steps_todo_to_process': steps_todo_to_process,
307 'adoption_candidates_for': adoptables,
308 'process_candidates': Process.all(self.conn),
309 'todo_candidates': any_adoptables,
310 'condition_candidates': Condition.all(self.conn)}
312 def do_GET_todos(self) -> dict[str, object]:
313 """Show Todos from ?start= to ?end=, of ?process=, ?comment= pattern"""
314 sort_by = self.params.get_str('sort_by')
315 start = self.params.get_str('start')
316 end = self.params.get_str('end')
317 process_id = self.params.get_int_or_none('process_id')
318 comment_pattern = self.params.get_str('comment_pattern')
320 ret = Todo.by_date_range_with_limits(self.conn, (start, end))
321 todos_by_date_range, start, end = ret
322 todos = [t for t in todos_by_date_range
323 if comment_pattern in t.comment
324 and ((not process_id) or t.process.id_ == process_id)]
325 if sort_by == 'doneness':
326 todos.sort(key=lambda t: t.is_done)
327 elif sort_by == '-doneness':
328 todos.sort(key=lambda t: t.is_done, reverse=True)
329 elif sort_by == 'title':
330 todos.sort(key=lambda t: t.title_then)
331 elif sort_by == '-title':
332 todos.sort(key=lambda t: t.title_then, reverse=True)
333 elif sort_by == 'comment':
334 todos.sort(key=lambda t: t.comment)
335 elif sort_by == '-comment':
336 todos.sort(key=lambda t: t.comment, reverse=True)
337 elif sort_by == '-date':
338 todos.sort(key=lambda t: t.date, reverse=True)
340 todos.sort(key=lambda t: t.date)
341 return {'start': start, 'end': end, 'process_id': process_id,
342 'comment_pattern': comment_pattern, 'todos': todos,
343 'all_processes': Process.all(self.conn), 'sort_by': sort_by}
345 def do_GET_conditions(self) -> dict[str, object]:
346 """Show all Conditions."""
347 pattern = self.params.get_str('pattern')
348 conditions = Condition.matching(self.conn, pattern)
349 sort_by = self.params.get_str('sort_by')
350 if sort_by == 'is_active':
351 conditions.sort(key=lambda c: c.is_active)
352 elif sort_by == '-is_active':
353 conditions.sort(key=lambda c: c.is_active, reverse=True)
354 elif sort_by == '-title':
355 conditions.sort(key=lambda c: c.title.newest, reverse=True)
357 conditions.sort(key=lambda c: c.title.newest)
358 return {'conditions': conditions,
362 def do_GET_condition(self) -> dict[str, object]:
363 """Show Condition of ?id=."""
364 id_ = self.params.get_int_or_none('id')
365 c = Condition.by_id(self.conn, id_, create=True)
366 ps = Process.all(self.conn)
367 return {'condition': c, 'is_new': c.id_ is None,
368 'enabled_processes': [p for p in ps if c in p.conditions],
369 'disabled_processes': [p for p in ps if c in p.blockers],
370 'enabling_processes': [p for p in ps if c in p.enables],
371 'disabling_processes': [p for p in ps if c in p.disables]}
373 def do_GET_condition_titles(self) -> dict[str, object]:
374 """Show title history of Condition of ?id=."""
375 id_ = self.params.get_int_or_none('id')
376 condition = Condition.by_id(self.conn, id_)
377 return {'condition': condition}
379 def do_GET_condition_descriptions(self) -> dict[str, object]:
380 """Show description historys of Condition of ?id=."""
381 id_ = self.params.get_int_or_none('id')
382 condition = Condition.by_id(self.conn, id_)
383 return {'condition': condition}
385 def do_GET_process(self) -> dict[str, object]:
386 """Show Process of ?id=."""
387 id_ = self.params.get_int_or_none('id')
388 process = Process.by_id(self.conn, id_, create=True)
389 title_64 = self.params.get_str('title_b64')
391 title = b64decode(title_64.encode()).decode()
392 process.title.set(title)
393 owners = process.used_as_step_by(self.conn)
394 for step_id in self.params.get_all_int('step_to'):
395 owners += [Process.by_id(self.conn, step_id)]
396 preset_top_step = None
397 for process_id in self.params.get_all_int('has_step'):
398 preset_top_step = process_id
399 return {'process': process, 'is_new': process.id_ is None,
400 'preset_top_step': preset_top_step,
401 'steps': process.get_steps(self.conn), 'owners': owners,
402 'n_todos': len(Todo.by_process_id(self.conn, process.id_)),
403 'process_candidates': Process.all(self.conn),
404 'condition_candidates': Condition.all(self.conn)}
406 def do_GET_process_titles(self) -> dict[str, object]:
407 """Show title history of Process of ?id=."""
408 id_ = self.params.get_int_or_none('id')
409 process = Process.by_id(self.conn, id_)
410 return {'process': process}
412 def do_GET_process_descriptions(self) -> dict[str, object]:
413 """Show description historys of Process of ?id=."""
414 id_ = self.params.get_int_or_none('id')
415 process = Process.by_id(self.conn, id_)
416 return {'process': process}
418 def do_GET_process_efforts(self) -> dict[str, object]:
419 """Show default effort history of Process of ?id=."""
420 id_ = self.params.get_int_or_none('id')
421 process = Process.by_id(self.conn, id_)
422 return {'process': process}
424 def do_GET_processes(self) -> dict[str, object]:
425 """Show all Processes."""
426 pattern = self.params.get_str('pattern')
427 processes = Process.matching(self.conn, pattern)
428 sort_by = self.params.get_str('sort_by')
429 if sort_by == 'steps':
430 processes.sort(key=lambda p: len(p.explicit_steps))
431 elif sort_by == '-steps':
432 processes.sort(key=lambda p: len(p.explicit_steps), reverse=True)
433 elif sort_by == 'owners':
434 processes.sort(key=lambda p: p.n_owners or 0)
435 elif sort_by == '-owners':
436 processes.sort(key=lambda p: p.n_owners or 0, reverse=True)
437 elif sort_by == 'effort':
438 processes.sort(key=lambda p: p.effort.newest)
439 elif sort_by == '-effort':
440 processes.sort(key=lambda p: p.effort.newest, reverse=True)
441 elif sort_by == '-title':
442 processes.sort(key=lambda p: p.title.newest, reverse=True)
444 processes.sort(key=lambda p: p.title.newest)
445 return {'processes': processes, 'sort_by': sort_by, 'pattern': pattern}
449 def _change_versioned_timestamps(self, cls: Any, attr_name: str) -> str:
450 """Update history timestamps for VersionedAttribute."""
451 id_ = self.params.get_int_or_none('id')
452 item = cls.by_id(self.conn, id_)
453 attr = getattr(item, attr_name)
454 for k, v in self.form_data.get_first_strings_starting('at:').items():
457 attr.reset_timestamp(old, f'{v}.0')
459 cls_name = cls.__name__.lower()
460 return f'/{cls_name}_{attr_name}s?id={item.id_}'
462 def do_POST_day(self) -> str:
463 """Update or insert Day of date and Todos mapped to it."""
464 date = self.params.get_str('date')
465 day = Day.by_id(self.conn, date, create=True)
466 day.comment = self.form_data.get_str('day_comment')
468 make_type = self.form_data.get_str('make_type')
469 for process_id in sorted(self.form_data.get_all_int('new_todo')):
470 if 'empty' == make_type:
471 process = Process.by_id(self.conn, process_id)
472 todo = Todo(None, process, False, date)
475 Todo.create_with_children(self.conn, process_id, date)
476 done_ids = self.form_data.get_all_int('done')
477 comments = self.form_data.get_all_str('comment')
478 efforts = self.form_data.get_all_str('effort')
479 for i, todo_id in enumerate(self.form_data.get_all_int('todo_id')):
480 todo = Todo.by_id(self.conn, todo_id)
481 todo.is_done = todo_id in done_ids
482 if len(comments) > 0:
483 todo.comment = comments[i]
485 todo.effort = float(efforts[i]) if efforts[i] else None
487 for condition in todo.enables:
488 condition.save(self.conn)
489 for condition in todo.disables:
490 condition.save(self.conn)
491 return f'/day?date={date}&make_type={make_type}'
493 def do_POST_todo(self) -> str:
494 """Update Todo and its children."""
495 # pylint: disable=too-many-locals
496 # pylint: disable=too-many-branches
497 id_ = self.params.get_int('id')
498 for _ in self.form_data.get_all_str('delete'):
499 todo = Todo .by_id(self.conn, id_)
500 todo.remove(self.conn)
502 todo = Todo.by_id(self.conn, id_)
503 adopted_child_ids = self.form_data.get_all_int('adopt')
504 processes_to_make_full = self.form_data.get_all_int('make_full')
505 processes_to_make_empty = self.form_data.get_all_int('make_empty')
506 fill_fors = self.form_data.get_first_strings_starting('fill_for_')
507 for v in fill_fors.values():
508 if v.startswith('make_empty_'):
509 processes_to_make_empty += [int(v[11:])]
510 elif v.startswith('make_full_'):
511 processes_to_make_full += [int(v[10:])]
513 adopted_child_ids += [int(v)]
515 for child in todo.children:
516 assert isinstance(child.id_, int)
517 if child.id_ not in adopted_child_ids:
518 to_remove += [child.id_]
519 for id_ in to_remove:
520 child = Todo.by_id(self.conn, id_)
521 todo.remove_child(child)
522 for child_id in adopted_child_ids:
523 if child_id in [c.id_ for c in todo.children]:
525 child = Todo.by_id(self.conn, child_id)
526 todo.add_child(child)
527 for process_id in processes_to_make_empty:
528 process = Process.by_id(self.conn, process_id)
529 made = Todo(None, process, False, todo.date)
532 for process_id in processes_to_make_full:
533 made = Todo.create_with_children(self.conn, process_id, todo.date)
535 effort = self.form_data.get_str('effort', ignore_strict=True)
536 todo.effort = float(effort) if effort else None
537 todo.set_conditions(self.conn,
538 self.form_data.get_all_int('condition'))
539 todo.set_blockers(self.conn, self.form_data.get_all_int('blocker'))
540 todo.set_enables(self.conn, self.form_data.get_all_int('enables'))
541 todo.set_disables(self.conn, self.form_data.get_all_int('disables'))
542 todo.is_done = len(self.form_data.get_all_str('done')) > 0
543 todo.calendarize = len(self.form_data.get_all_str('calendarize')) > 0
544 todo.comment = self.form_data.get_str('comment', ignore_strict=True)
546 for condition in todo.enables:
547 condition.save(self.conn)
548 for condition in todo.disables:
549 condition.save(self.conn)
550 return f'/todo?id={todo.id_}'
552 def do_POST_process_descriptions(self) -> str:
553 """Update history timestamps for Process.description."""
554 return self._change_versioned_timestamps(Process, 'description')
556 def do_POST_process_efforts(self) -> str:
557 """Update history timestamps for Process.effort."""
558 return self._change_versioned_timestamps(Process, 'effort')
560 def do_POST_process_titles(self) -> str:
561 """Update history timestamps for Process.title."""
562 return self._change_versioned_timestamps(Process, 'title')
564 def do_POST_process(self) -> str:
565 """Update or insert Process of ?id= and fields defined in postvars."""
566 # pylint: disable=too-many-branches
567 id_ = self.params.get_int_or_none('id')
568 for _ in self.form_data.get_all_str('delete'):
569 process = Process.by_id(self.conn, id_)
570 process.remove(self.conn)
572 process = Process.by_id(self.conn, id_, create=True)
573 process.title.set(self.form_data.get_str('title'))
574 process.description.set(self.form_data.get_str('description'))
575 process.effort.set(self.form_data.get_float('effort'))
576 process.set_conditions(self.conn,
577 self.form_data.get_all_int('condition'))
578 process.set_blockers(self.conn, self.form_data.get_all_int('blocker'))
579 process.set_enables(self.conn, self.form_data.get_all_int('enables'))
580 process.set_disables(self.conn,
581 self.form_data.get_all_int('disables'))
582 process.calendarize = self.form_data.get_all_str('calendarize') != []
583 process.save(self.conn)
584 assert isinstance(process.id_, int)
585 steps: list[ProcessStep] = []
586 for step_id in self.form_data.get_all_int('keep_step'):
587 if step_id not in self.form_data.get_all_int('steps'):
588 raise BadFormatException('trying to keep unknown step')
589 for step_id in self.form_data.get_all_int('steps'):
590 if step_id not in self.form_data.get_all_int('keep_step'):
592 step_process_id = self.form_data.get_int(
593 f'step_{step_id}_process_id')
594 parent_id = self.form_data.get_int_or_none(
595 f'step_{step_id}_parent_id')
596 steps += [ProcessStep(step_id, process.id_, step_process_id,
598 for step_id in self.form_data.get_all_int('steps'):
599 for step_process_id in self.form_data.get_all_int(
600 f'new_step_to_{step_id}'):
601 steps += [ProcessStep(None, process.id_, step_process_id,
603 new_step_title = None
604 for step_identifier in self.form_data.get_all_str('new_top_step'):
606 step_process_id = int(step_identifier)
607 steps += [ProcessStep(None, process.id_, step_process_id,
610 new_step_title = step_identifier
612 process.set_steps(self.conn, steps)
613 process.set_step_suppressions(self.conn,
615 get_all_int('suppresses'))
616 process.save(self.conn)
618 new_owner_title = None
619 for owner_identifier in self.form_data.get_all_str('step_of'):
621 owners_to_set += [int(owner_identifier)]
623 new_owner_title = owner_identifier
624 process.set_owners(self.conn, owners_to_set)
625 params = f'id={process.id_}'
627 title_b64_encoded = b64encode(new_step_title.encode()).decode()
628 params = f'step_to={process.id_}&title_b64={title_b64_encoded}'
629 elif new_owner_title:
630 title_b64_encoded = b64encode(new_owner_title.encode()).decode()
631 params = f'has_step={process.id_}&title_b64={title_b64_encoded}'
632 return f'/process?{params}'
634 def do_POST_condition_descriptions(self) -> str:
635 """Update history timestamps for Condition.description."""
636 return self._change_versioned_timestamps(Condition, 'description')
638 def do_POST_condition_titles(self) -> str:
639 """Update history timestamps for Condition.title."""
640 return self._change_versioned_timestamps(Condition, 'title')
642 def do_POST_condition(self) -> str:
643 """Update/insert Condition of ?id= and fields defined in postvars."""
644 id_ = self.params.get_int_or_none('id')
645 for _ in self.form_data.get_all_str('delete'):
646 condition = Condition.by_id(self.conn, id_)
647 condition.remove(self.conn)
649 condition = Condition.by_id(self.conn, id_, create=True)
650 condition.is_active = self.form_data.get_all_str('is_active') != []
651 condition.title.set(self.form_data.get_str('title'))
652 condition.description.set(self.form_data.get_str('description'))
653 condition.save(self.conn)
654 return f'/condition?id={condition.id_}'