aboutsummaryrefslogtreecommitdiff
path: root/model.py
diff options
context:
space:
mode:
authorJuan J. Martinez <jjm@usebox.net>2024-03-23 19:01:29 +0000
committerJuan J. Martinez <jjm@usebox.net>2024-03-23 19:10:43 +0000
commit0a5471217b9f562b92f32802de4260390f639880 (patch)
treedaf0655fe2753351d7fac9010e3b50c499194bb2 /model.py
downloadpersonal-wiki-pybottle-0a5471217b9f562b92f32802de4260390f639880.tar.gz
personal-wiki-pybottle-0a5471217b9f562b92f32802de4260390f639880.zip
Initial import
Diffstat (limited to 'model.py')
-rw-r--r--model.py112
1 files changed, 112 insertions, 0 deletions
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]