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
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:
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)
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)