KindAlien commited on
Commit
dc2f1a6
·
verified ·
1 Parent(s): 2ddbe8f

Update db.py

Browse files
Files changed (1) hide show
  1. db.py +24 -4
db.py CHANGED
@@ -1,6 +1,7 @@
1
  import pymysql
2
  import json
3
  import os
 
4
  from dotenv import load_dotenv
5
 
6
  load_dotenv(override=True)
@@ -85,18 +86,31 @@ def seed_credits_if_empty(hardcoded_map):
85
  except Exception as e:
86
  print(f"[DB ERROR] Failed to seed credits: {e}")
87
 
88
- def get_all_credits():
89
- """Retrieve all subject credits as a dictionary."""
 
 
 
 
 
 
 
 
 
 
90
  try:
91
  conn = get_db_connection()
92
  with conn.cursor() as cursor:
93
  cursor.execute("SELECT subject_code, credits FROM subject_credits")
94
  rows = cursor.fetchall()
95
  conn.close()
96
- return {row['subject_code']: row['credits'] for row in rows}
 
 
 
97
  except Exception as e:
98
  print(f"[DB ERROR] Failed to fetch credits: {e}")
99
- return {}
100
 
101
  def save_credit(subject_code, credits):
102
  """Save or update a subject credit."""
@@ -109,6 +123,12 @@ def save_credit(subject_code, credits):
109
  )
110
  conn.commit()
111
  conn.close()
 
 
 
 
 
 
112
  return True
113
  except Exception as e:
114
  print(f"[DB ERROR] Failed to save credit: {e}")
 
1
  import pymysql
2
  import json
3
  import os
4
+ import time
5
  from dotenv import load_dotenv
6
 
7
  load_dotenv(override=True)
 
86
  except Exception as e:
87
  print(f"[DB ERROR] Failed to seed credits: {e}")
88
 
89
+ _CREDITS_CACHE = {}
90
+ _CREDITS_LAST_FETCH = 0
91
+ _CACHE_TTL = 300 # 5 minutes cache to prevent Hostinger max_connections_per_hour (500) errors
92
+
93
+ def get_all_credits(force_refresh=False):
94
+ """Retrieve all subject credits as a dictionary with caching."""
95
+ global _CREDITS_CACHE, _CREDITS_LAST_FETCH
96
+
97
+ current_time = time.time()
98
+ if not force_refresh and _CREDITS_CACHE and (current_time - _CREDITS_LAST_FETCH < _CACHE_TTL):
99
+ return _CREDITS_CACHE
100
+
101
  try:
102
  conn = get_db_connection()
103
  with conn.cursor() as cursor:
104
  cursor.execute("SELECT subject_code, credits FROM subject_credits")
105
  rows = cursor.fetchall()
106
  conn.close()
107
+
108
+ _CREDITS_CACHE = {row['subject_code']: row['credits'] for row in rows}
109
+ _CREDITS_LAST_FETCH = current_time
110
+ return _CREDITS_CACHE
111
  except Exception as e:
112
  print(f"[DB ERROR] Failed to fetch credits: {e}")
113
+ return _CREDITS_CACHE if _CREDITS_CACHE else {}
114
 
115
  def save_credit(subject_code, credits):
116
  """Save or update a subject credit."""
 
123
  )
124
  conn.commit()
125
  conn.close()
126
+
127
+ # Instantly update cache
128
+ global _CREDITS_CACHE
129
+ if _CREDITS_CACHE is not None:
130
+ _CREDITS_CACHE[subject_code.upper()] = int(credits)
131
+
132
  return True
133
  except Exception as e:
134
  print(f"[DB ERROR] Failed to save credit: {e}")