fix(api): improve sqlite concurrency handling and return 503 when db is busy

This commit is contained in:
2026-02-11 11:41:51 -05:00
parent ddf5e983e2
commit 588527e3b8
+17 -1
View File
@@ -14,13 +14,21 @@ random.seed()
DB_FILE = "quotes.db" DB_FILE = "quotes.db"
def get_db_connection():
"""Create a SQLite connection tuned for concurrent reads/writes"""
conn = sqlite3.connect(DB_FILE, timeout=5)
conn.execute("PRAGMA journal_mode = WAL")
conn.execute("PRAGMA busy_timeout = 5000")
return conn
def verify_db(): def verify_db():
"""Check to ensure the SQLite DB is available"""
if not os.path.exists(DB_FILE): if not os.path.exists(DB_FILE):
raise RuntimeError("quotes.db not found. Run add-quotes.py to initialize.") raise RuntimeError("quotes.db not found. Run add-quotes.py to initialize.")
def get_random_quote(): def get_random_quote():
"""Fetch a random quote from the database and increment delivered count""" """Fetch a random quote from the database and increment delivered count"""
conn = sqlite3.connect(DB_FILE) conn = get_db_connection()
c = conn.cursor() c = conn.cursor()
# Pick a random quote ID # Pick a random quote ID
@@ -46,7 +54,11 @@ def main():
@app.route("/quote") @app.route("/quote")
@limiter.limit("20/minute") @limiter.limit("20/minute")
def quote(): def quote():
try:
quote = get_random_quote() quote = get_random_quote()
except sqlite3.OperationalError:
return "Database is busy, please retry.", 503
if not quote: if not quote:
return "No quotes found in database!", 500 return "No quotes found in database!", 500
return f"{quote['quote']} - {quote['author']}" return f"{quote['quote']} - {quote['author']}"
@@ -54,7 +66,11 @@ def quote():
@app.route("/api/quote") @app.route("/api/quote")
@limiter.limit("50/minute") @limiter.limit("50/minute")
def quote_api(): def quote_api():
try:
quote = get_random_quote() quote = get_random_quote()
except sqlite3.OperationalError:
return jsonify({"error": "Database is busy, please retry"}), 503
if not quote: if not quote:
return jsonify({"error": "No quotes found"}), 500 return jsonify({"error": "No quotes found"}), 500
return jsonify(quote) return jsonify(quote)