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

View File

@@ -14,13 +14,21 @@ random.seed()
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():
"""Check to ensure the SQLite DB is available"""
if not os.path.exists(DB_FILE):
raise RuntimeError("quotes.db not found. Run add-quotes.py to initialize.")
def get_random_quote():
"""Fetch a random quote from the database and increment delivered count"""
conn = sqlite3.connect(DB_FILE)
conn = get_db_connection()
c = conn.cursor()
# Pick a random quote ID
@@ -46,7 +54,11 @@ def main():
@app.route("/quote")
@limiter.limit("20/minute")
def quote():
quote = get_random_quote()
try:
quote = get_random_quote()
except sqlite3.OperationalError:
return "Database is busy, please retry.", 503
if not quote:
return "No quotes found in database!", 500
return f"{quote['quote']} - {quote['author']}"
@@ -54,7 +66,11 @@ def quote():
@app.route("/api/quote")
@limiter.limit("50/minute")
def quote_api():
quote = get_random_quote()
try:
quote = get_random_quote()
except sqlite3.OperationalError:
return jsonify({"error": "Database is busy, please retry"}), 503
if not quote:
return jsonify({"error": "No quotes found"}), 500
return jsonify(quote)
@@ -62,4 +78,4 @@ def quote_api():
if __name__ == "__main__":
verify_db()
"""Running on Oracle's private network, in my instance - here it is 0.0.0.0 so only one node is needed"""
app.run(host="0.0.0.0", port=5051, debug=True)
app.run(host="0.0.0.0", port=5051, debug=True)