Zheng Qu commited on
Commit
12fd00c
β€’
1 Parent(s): e2f2b83

temporarily add, will change code to have better error handling

Browse files
Files changed (1) hide show
  1. app_utils.py +39 -11
app_utils.py CHANGED
@@ -4,20 +4,31 @@ import datetime
4
  from pathlib import Path
5
  from dotenv import load_dotenv
6
  from tinydb import TinyDB, Query
7
- from tinydb.storages import JSONStorage
8
- from tinydb.middlewares import CachingMiddleware
9
  import tempfile
10
 
11
  load_dotenv()
12
- SESSION_ID = os.getenv('SESSION_ID')
13
  print(f"Session ID: {SESSION_ID}")
14
- DB_PATH = 'submissions.json'
15
  ADMIN_PASSWD = os.getenv('ADMIN_PASSWD', 'default_password')
16
  SUBMISSIONS_DIR = 'submissions'
17
 
18
- # TinyDB connection setup
19
- db = TinyDB(DB_PATH, storage=CachingMiddleware(JSONStorage))
20
- submissions_table = db.table('submissions')
 
 
 
 
 
 
 
 
 
 
 
 
21
  print("Using TinyDB for data storage")
22
 
23
  def load_problems():
@@ -31,7 +42,9 @@ def load_problems():
31
  print(f"Loaded problem: {json_file.stem}")
32
  return problems
33
 
 
34
  def save_submission(session, name, email, problem_id, code, hint_requested):
 
35
  timestamp = datetime.datetime.now().isoformat()
36
  submission = {
37
  'session': session,
@@ -44,29 +57,40 @@ def save_submission(session, name, email, problem_id, code, hint_requested):
44
  }
45
  query = Query()
46
  submissions_table.upsert(submission, (query.session == session) & (query.name == name) & (query.email == email) & (query.problem_id == problem_id))
 
 
47
 
48
  def save_all_submissions(name, email, codes_dict, hints_dict):
 
49
  try:
50
  for problem_id, code in codes_dict.items():
51
  hint_requested = hints_dict.get(problem_id, False)
52
  save_submission(SESSION_ID, name, email, problem_id, code, hint_requested)
 
53
  return "βœ… All submissions saved successfully!"
54
  except Exception as e:
 
55
  return f"❌ Error saving submissions: {str(e)}"
56
 
57
  def check_password(password):
58
  return password == ADMIN_PASSWD
59
 
60
  def get_all_students():
61
- return list(set([submission['name'] for submission in submissions_table.all()]))
 
 
 
62
 
63
  def get_student_submissions(name):
 
64
  query = Query()
65
  submissions = submissions_table.search(query.name == name)
66
  submissions.sort(key=lambda x: datetime.datetime.fromisoformat(x['timestamp']), reverse=True)
 
67
  return submissions
68
 
69
  def export_submissions():
 
70
  try:
71
  submissions = submissions_table.all()
72
  submissions.sort(key=lambda x: datetime.datetime.fromisoformat(x['timestamp']), reverse=True)
@@ -76,12 +100,16 @@ def export_submissions():
76
  temp_file = tempfile.NamedTemporaryFile(delete=False, mode='w', suffix='.json')
77
  temp_file.write(data)
78
  temp_file.close()
 
79
  return temp_file.name
80
  except Exception as e:
81
  print(f"Error in export_submissions: {str(e)}")
 
82
  return None
83
 
84
  def refresh_submissions():
85
- submissions = submissions_table.all()
86
- submissions.sort(key=lambda x: datetime.datetime.fromisoformat(x['timestamp']), reverse=True)
87
- return submissions
 
 
 
4
  from pathlib import Path
5
  from dotenv import load_dotenv
6
  from tinydb import TinyDB, Query
7
+ from tinydb_serialization import SerializationMiddleware
8
+ from tinydb_sqlite import SQLiteStorage
9
  import tempfile
10
 
11
  load_dotenv()
12
+ SESSION_ID = os.getenv('SESSION_ID', 'default_session')
13
  print(f"Session ID: {SESSION_ID}")
 
14
  ADMIN_PASSWD = os.getenv('ADMIN_PASSWD', 'default_password')
15
  SUBMISSIONS_DIR = 'submissions'
16
 
17
+ print("Using TinyDB with SQLiteStorage for data storage")
18
+
19
+ def get_db():
20
+ """Initialize and return a TinyDB instance with SQLiteStorage."""
21
+ serialization = SerializationMiddleware()
22
+ storage = SQLiteStorage(
23
+ 'submissions.db',
24
+ serialization=serialization,
25
+ connection_kwargs={'check_same_thread': False}
26
+ )
27
+ db = TinyDB(storage=storage)
28
+ submissions_table = db.table('submissions')
29
+ return db, submissions_table
30
+
31
+
32
  print("Using TinyDB for data storage")
33
 
34
  def load_problems():
 
42
  print(f"Loaded problem: {json_file.stem}")
43
  return problems
44
 
45
+
46
  def save_submission(session, name, email, problem_id, code, hint_requested):
47
+ db, submissions_table = get_db()
48
  timestamp = datetime.datetime.now().isoformat()
49
  submission = {
50
  'session': session,
 
57
  }
58
  query = Query()
59
  submissions_table.upsert(submission, (query.session == session) & (query.name == name) & (query.email == email) & (query.problem_id == problem_id))
60
+ db.close()
61
+
62
 
63
  def save_all_submissions(name, email, codes_dict, hints_dict):
64
+ db, submissions_table = get_db()
65
  try:
66
  for problem_id, code in codes_dict.items():
67
  hint_requested = hints_dict.get(problem_id, False)
68
  save_submission(SESSION_ID, name, email, problem_id, code, hint_requested)
69
+ db.close()
70
  return "βœ… All submissions saved successfully!"
71
  except Exception as e:
72
+ db.close()
73
  return f"❌ Error saving submissions: {str(e)}"
74
 
75
  def check_password(password):
76
  return password == ADMIN_PASSWD
77
 
78
  def get_all_students():
79
+ db, submissions_table = get_db()
80
+ result = list(set([submission['name'] for submission in submissions_table.all()]))
81
+ db.close()
82
+ return result
83
 
84
  def get_student_submissions(name):
85
+ db, submissions_table = get_db()
86
  query = Query()
87
  submissions = submissions_table.search(query.name == name)
88
  submissions.sort(key=lambda x: datetime.datetime.fromisoformat(x['timestamp']), reverse=True)
89
+ db.close()
90
  return submissions
91
 
92
  def export_submissions():
93
+ db, submissions_table = get_db()
94
  try:
95
  submissions = submissions_table.all()
96
  submissions.sort(key=lambda x: datetime.datetime.fromisoformat(x['timestamp']), reverse=True)
 
100
  temp_file = tempfile.NamedTemporaryFile(delete=False, mode='w', suffix='.json')
101
  temp_file.write(data)
102
  temp_file.close()
103
+ db.close()
104
  return temp_file.name
105
  except Exception as e:
106
  print(f"Error in export_submissions: {str(e)}")
107
+ db.close()
108
  return None
109
 
110
  def refresh_submissions():
111
+ db, submissions_table = get_db()
112
+ all_submissions = submissions_table.all()
113
+ all_submissions.sort(key=lambda x: datetime.datetime.fromisoformat(x['timestamp']), reverse=True)
114
+ db.close()
115
+ return all_submissions