---
type: "Source File"
title: "\"\"\""
description: "\"\"\" Lightweight /v/<slug> view tracking for copecheck.com. Writes to page_views.db (separate from copecheck.db). \"\"\" import sqlite3 import os from datetime import date DB_PATH = os.path.join(os.path.dirname(__file__)."
resource: "https://www.copecheck.com"
tags: ["copecheck", "main", "source-file", "py"]
timestamp: "2026-05-28T21:55:35Z"
site: "main"
source_path: "copecheck/page_views_tracker.py"
---

# """

Source path: `copecheck/page_views_tracker.py`  
Index snapshot generated: `2026-11-24T13:42:54Z`  
File modified: `2026-05-28T21:55:35Z`

```py
"""
Lightweight /v/<slug> view tracking for copecheck.com.
Writes to page_views.db (separate from copecheck.db).
"""
import sqlite3
import os
from datetime import date

DB_PATH = os.path.join(os.path.dirname(__file__), "page_views.db")

SCHEMA = """
CREATE TABLE IF NOT EXISTS page_views (
    slug       TEXT NOT NULL,
    title      TEXT NOT NULL DEFAULT '',
    url        TEXT NOT NULL DEFAULT '',
    view_date  DATE NOT NULL,
    view_count INTEGER NOT NULL DEFAULT 0,
    PRIMARY KEY (slug, view_date)
);
CREATE INDEX IF NOT EXISTS idx_pv_slug ON page_views(slug);
CREATE INDEX IF NOT EXISTS idx_pv_date ON page_views(view_date);
"""

def _get_conn():
    c = sqlite3.connect(DB_PATH, timeout=10)
    c.row_factory = sqlite3.Row
    c.execute("PRAGMA journal_mode=WAL")
    return c

def init_db():
    """Create tables if they don't exist. Safe to call multiple times."""
    c = _get_conn()
    try:
        c.executescript(SCHEMA)
        c.commit()
    finally:
        c.close()

def increment_view(slug: str, title: str, url: str) -> None:
    """
    Atomically increment today's view count for a /v/ slug.
    Updates title/url in case they've changed.
    Safe to call from a background thread.
    """
    today = date.today().isoformat()
    try:
        c = _get_conn()
        try:
            c.execute(
                """INSERT INTO page_views (slug, title, url, view_date, view_count)
                   VALUES (?, ?, ?, ?, 1)
                   ON CONFLICT(slug, view_date) DO UPDATE
                   SET view_count = view_count + 1,
                       title = excluded.title,
                       url   = excluded.url""",
                (slug, title, url, today),
            )
            c.commit()
        finally:
            c.close()
    except Exception:
        pass  # Never let view tracking break the app

def top_pages(days: int = 30, limit: int = 10, url_prefix: str = None) -> list:
    """Return top pages by rolling view total over the last N days.

    If url_prefix is given (e.g. "/figure/"), only rows whose url starts
    with that prefix are returned.
    """
    from datetime import timedelta
    cutoff = (date.today() - timedelta(days=days)).isoformat()
    c = _get_conn()
    try:
        if url_prefix:
            cur = c.execute(
                """SELECT slug, title, url,
                          SUM(view_count) AS total_views
                   FROM page_views
                   WHERE view_date >= ?
                     AND url LIKE ?
                   GROUP BY slug
                   ORDER BY total_views DESC
                   LIMIT ?""",
                (cutoff, url_prefix + "%", limit),
            )
        else:
            cur = c.execute(
                """SELECT slug, title, url,
                          SUM(view_count) AS total_views
                   FROM page_views
                   WHERE view_date >= ?
                   GROUP BY slug
                   ORDER BY total_views DESC
                   LIMIT ?""",
                (cutoff, limit),
            )
        return [dict(r) for r in cur.fetchall()]
    finally:
        c.close()

# Auto-init on import
init_db()
```
