From: Christian Heller Date: Wed, 20 Mar 2024 00:29:58 +0000 (+0100) Subject: Minor refactorings. X-Git-Url: https://plomlompom.com/repos/%7B%7B%20web_path%20%7D%7D/decks/%7B%7Bprefix%7D%7D/todo?a=commitdiff_plain;h=ab5a23f86261ef74b00fd77ff198275bac6b82fd;p=plomtask Minor refactorings. --- diff --git a/plomtask/days.py b/plomtask/days.py index ba466b5..89c957e 100644 --- a/plomtask/days.py +++ b/plomtask/days.py @@ -51,10 +51,13 @@ class Day: return days @classmethod - def by_date(cls, db_conn: DatabaseConnection, date: str): + def by_date(cls, db_conn: DatabaseConnection, + date: str, create: bool = False): """Retrieve Day by date if in DB, else return None.""" for row in db_conn.exec('SELECT * FROM days WHERE date = ?', (date,)): return cls.from_table_row(row) + if create: + return cls(date) return None @property diff --git a/plomtask/http.py b/plomtask/http.py index d9fa6a0..8106d13 100644 --- a/plomtask/http.py +++ b/plomtask/http.py @@ -25,10 +25,7 @@ class TaskHandler(BaseHTTPRequestHandler): def do_GET(self): """Handle any GET request.""" try: - conn = DatabaseConnection(self.server.db) - parsed_url = urlparse(self.path) - site = path_split(parsed_url.path)[1] - params = parse_qs(parsed_url.query) + conn, site, params = self._init_handling() if 'calendar' == site: html = self.do_GET_calendar(conn) elif 'day' == site: @@ -55,10 +52,7 @@ class TaskHandler(BaseHTTPRequestHandler): def do_POST(self): """Handle any POST request.""" try: - conn = DatabaseConnection(self.server.db) - parsed_url = urlparse(self.path) - site = path_split(parsed_url.path)[1] - params = parse_qs(parsed_url.query) + conn, site, params = self._init_handling() length = int(self.headers['content-length']) postvars = parse_qs(self.rfile.read(length).decode(), keep_blank_values=1) @@ -74,13 +68,17 @@ class TaskHandler(BaseHTTPRequestHandler): def do_POST_day(self, conn: DatabaseConnection, date: str, postvars: dict): """Update or insert Day of date and fields defined in postvars.""" comment = postvars['comment'][0] - day = Day.by_date(conn, date) - if day: - day.comment = comment - else: - day = Day(date, comment) + day = Day.by_date(conn, date, create=True) + day.comment = comment day.save(conn) + def _init_handling(self): + conn = DatabaseConnection(self.server.db) + parsed_url = urlparse(self.path) + site = path_split(parsed_url.path)[1] + params = parse_qs(parsed_url.query) + return conn, site, params + def _redirect(self, target: str): self.send_response(302) self.send_header('Location', target)