From 0a5471217b9f562b92f32802de4260390f639880 Mon Sep 17 00:00:00 2001 From: "Juan J. Martinez" Date: Sat, 23 Mar 2024 19:01:29 +0000 Subject: Initial import --- model.py | 112 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 112 insertions(+) create mode 100644 model.py (limited to 'model.py') diff --git a/model.py b/model.py new file mode 100644 index 0000000..3f52115 --- /dev/null +++ b/model.py @@ -0,0 +1,112 @@ +import sqlite3 +from datetime import datetime +import re + +import markdown + + +def bootstrap_db(db): + with open("schema.sql", "rt") as fd: + schema = fd.read() + con = sqlite3.connect(db) + cur = con.cursor() + cur.executescript(schema) + con.commit() + cur.close() + con.close() + + +class Page(object): + def __init__( + self, + name="WikiHome", + version=None, + content="", + changelog=None, + updated_at=None, + history=False, + ): + now = datetime.utcnow() + if updated_at is None: + updated_at = now + + self.name = name + self.version = version + self.content = content + self.changelog = changelog + self.updated_at = updated_at + self.history = history + + def render(self): + return markdown.markdown(self.content) + + @property + def title(self): + pretty = " ".join(re.findall(r"[A-Z](?:[a-z]+|[A-Z]*(?=[A-Z]|$))", self.name)) + if self.history: + pretty = f"{pretty} (history)" + return pretty + + +class History(object): + def __init__(self, version, changelog, updated_at): + self.version = version + self.changelog = changelog + self.updated_at = updated_at + + +def get_page(db, name, version=None): + cur = db.cursor() + if version: + cur.execute( + "SELECT name, version, content, changelog, updated_at" + " FROM pages" + " WHERE name = :name AND version = :version", + dict(name=name, version=version), + ) + else: + cur.execute( + "SELECT name, version, content, changelog, updated_at" + " FROM pages" + " WHERE name = :name ORDER BY updated_at DESC LIMIT 1", + dict(name=name), + ) + row = cur.fetchone() + cur.close() + + if row: + return Page(*row, history=version is not None) + else: + return Page(name=name) + + +def save_page(db, page): + cur = db.cursor() + cur.execute( + "INSERT INTO pages" + " VALUES(:name, :version, :content, :changelog, :updated_at)", + dict( + name=page.name, + version=page.version, + content=page.content, + changelog=page.changelog, + updated_at=page.updated_at, + ), + ) + db.commit() + cur.close() + + +def get_page_history(db, name): + cur = db.cursor() + cur.execute( + "SELECT version, changelog, updated_at" + " FROM pages" + " WHERE name = :name ORDER BY updated_at DESC", + dict(name=name), + ) + rows = cur.fetchall() + cur.close() + + if rows: + return [History(*r) for r in rows] -- cgit v1.2.3