home · contact · privacy
Add database connection, read and write Days through them.
authorChristian Heller <c.heller@plomlompom.de>
Sun, 17 Mar 2024 02:47:56 +0000 (03:47 +0100)
committerChristian Heller <c.heller@plomlompom.de>
Sun, 17 Mar 2024 02:47:56 +0000 (03:47 +0100)
plomtask/days.py
plomtask/db.py
plomtask/http.py
run.py

index 4e0c4747809bc1e352e492cf619fafb41f3f0bbb..02ad1a8f5223e1dbaee1ef445fd4e9b211ad4842 100644 (file)
@@ -1,6 +1,8 @@
 """Collecting Day and date-related items."""
 from datetime import datetime
+from sqlite3 import Row
 from plomtask.misc import HandledException
+from plomtask.db import DatabaseConnection
 
 DATE_FORMAT = '%Y-%m-%d'
 
@@ -23,6 +25,24 @@ class Day:
         if not self.datetime:
             raise HandledException(f'Given date of wrong format: {self.date}')
 
+    @classmethod
+    def add(cls, db_conn: DatabaseConnection, date: str):
+        """Add (or re-write) new Day(date) to database."""
+        db_conn.exec('REPLACE INTO days VALUES (?)', (date,))
+
+    @classmethod
+    def from_table_row(cls, row: Row):
+        """Make new Day from database row."""
+        return cls(row[0])
+
+    @classmethod
+    def all(cls, db_conn: DatabaseConnection):
+        """Return list of all Days in database."""
+        days = []
+        for row in db_conn.exec('SELECT * FROM days'):
+            days += [cls.from_table_row(row)]
+        return days
+
     @property
     def weekday(self):
         """Return what weekday matches self.date."""
index b7291dba4245852097f7dc3146e9b1d6d355bbcf..50eb737cbfa3924eb3f393dd5440ed08fce0b8d9 100644 (file)
@@ -40,3 +40,23 @@ class DatabaseFile:
                     diff_msg = Differ().compare(retrieved_schema.splitlines(),
                                                 stored_schema.splitlines())
                     raise HandledException(msg_err + '\n'.join(diff_msg))
+
+
+class DatabaseConnection:
+    """A single connection to the database."""
+
+    def __init__(self, db_file: DatabaseFile):
+        self.file = db_file
+        self.conn = sql_connect(self.file.path)
+
+    def commit(self):
+        """Commit SQL transaction."""
+        self.conn.commit()
+
+    def exec(self, code: str, inputs: tuple = ()):
+        """Add commands to SQL transaction."""
+        return self.conn.execute(code, inputs)
+
+    def close(self):
+        """Close DB connection."""
+        self.conn.close()
index baa730ed7a77272982cb03c8ec61ea76f22d0a12..2039cf91351db9c866fa75c3ec4c974d388490ce 100644 (file)
@@ -6,13 +6,15 @@ from os.path import split as path_split
 from jinja2 import Environment as JinjaEnv, FileSystemLoader as JinjaFSLoader
 from plomtask.days import Day
 from plomtask.misc import HandledException
+from plomtask.db import DatabaseConnection
 
 
 class TaskServer(HTTPServer):
     """Variant of HTTPServer that knows .jinja as Jinja Environment."""
 
-    def __init__(self, templates_dir, *args, **kwargs):
+    def __init__(self, templates_dir, db_file, *args, **kwargs):
         super().__init__(*args, **kwargs)
+        self.db = db_file
         self.jinja = JinjaEnv(loader=JinjaFSLoader(templates_dir))
 
 
@@ -46,7 +48,13 @@ class TaskHandler(BaseHTTPRequestHandler):
 
     def do_GET_calendar(self):
         """Show sorted Days."""
-        days = [Day('2024-01-03'), Day('2024-01-01'), Day('2024-01-02')]
+        conn = DatabaseConnection(self.server.db)
+        Day.add(conn, '2024-01-03')
+        Day.add(conn, '2024-01-01')
+        Day.add(conn, '2024-01-02')
+        days = Day.all(conn)
+        conn.commit()
+        conn.close()
         days.sort()
         return self.server.jinja.get_template('calendar.html').render(
                 days=days)
diff --git a/run.py b/run.py
index e0cdd8b8150dfbc0d8d54447a308ef79f6795037..ef6aeab6b7fd56a93ed3c9e76a7b5bbfe532b68c 100755 (executable)
--- a/run.py
+++ b/run.py
@@ -25,7 +25,7 @@ if __name__ == '__main__':
             else:
                 print('Not recognizing reply as "yes".')
                 raise HandledException('Cannot run without database.')
-        server = TaskServer(TEMPLATES_DIR,
+        server = TaskServer(TEMPLATES_DIR, db_file,
                             ('localhost', HTTP_PORT), TaskHandler)
         print(f'running at port {HTTP_PORT}')
         try: