From 588527e3b82b4decdc324c4ed0cf520f874ffdbd Mon Sep 17 00:00:00 2001 From: patrickbeane Date: Wed, 11 Feb 2026 11:41:51 -0500 Subject: [PATCH] fix(api): improve sqlite concurrency handling and return 503 when db is busy --- quotes.py | 24 ++++++++++++++++++++---- 1 file changed, 20 insertions(+), 4 deletions(-) diff --git a/quotes.py b/quotes.py index 7a68e9f..1a3ae7b 100644 --- a/quotes.py +++ b/quotes.py @@ -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) \ No newline at end of file + app.run(host="0.0.0.0", port=5051, debug=True)