44 lines
1.1 KiB
Python
44 lines
1.1 KiB
Python
"""Flask-bound extensions: per-request DB connections and teardown.
|
|
|
|
These helpers depend on Flask's `g` and must only be used inside an
|
|
application/request context. Pure (Flask-free) helpers live in
|
|
services/ and repositories/.
|
|
"""
|
|
|
|
import logging
|
|
import sqlite3
|
|
|
|
from flask import g
|
|
|
|
import config
|
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
|
|
def get_db():
|
|
"""Return a per-request SQLite connection (row access by name)."""
|
|
if "db" not in g:
|
|
conn = sqlite3.connect(config.DB_PATH)
|
|
conn.row_factory = sqlite3.Row
|
|
g.db = conn
|
|
return g.db
|
|
|
|
|
|
def get_watchdog_db():
|
|
"""Return a per-request SQLite connection to the watchdog db (read-only)."""
|
|
if "watchdog_db" not in g:
|
|
conn = sqlite3.connect(f"file:{config.WATCHDOG_DB}?mode=ro", uri=True)
|
|
conn.row_factory = sqlite3.Row
|
|
g.watchdog_db = conn
|
|
return g.watchdog_db
|
|
|
|
|
|
def close_db(exception=None):
|
|
"""Teardown handler registered via app.teardown_appcontext."""
|
|
conn = g.pop("db", None)
|
|
if conn is not None:
|
|
conn.close()
|
|
wconn = g.pop("watchdog_db", None)
|
|
if wconn is not None:
|
|
wconn.close()
|