import sqlite3 from datetime import datetime import inflection 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 = inflection.titleize(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]