mirror of
https://github.com/patrickbeane/quote-of-the-day.git
synced 2026-06-19 14:58:48 +00:00
fix(api): improve sqlite concurrency handling and return 503 when db is busy
This commit is contained in:
@@ -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():
|
||||||
quote = get_random_quote()
|
try:
|
||||||
|
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():
|
||||||
quote = get_random_quote()
|
try:
|
||||||
|
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)
|
||||||
|
|||||||
Reference in New Issue
Block a user