Ptul2x5 commited on
Commit
0a463bb
·
verified ·
1 Parent(s): bb6ba93

Fix Database Restore

Browse files
Files changed (3) hide show
  1. app.py +15 -8
  2. database_manager.py +15 -8
  3. templates/base.html +3 -0
app.py CHANGED
@@ -22,12 +22,13 @@ app = Flask(__name__)
22
  app.config['SECRET_KEY'] = 'your-secret-key-change-this-in-production'
23
 
24
  # Database backup functions
25
- def backup_database():
26
  """Backup database to Hugging Face Hub"""
27
  try:
28
- db_manager.backup_database()
29
  except Exception as e:
30
  print(f"❌ Backup error: {e}")
 
31
 
32
  def restore_database():
33
  """Restore database from Hugging Face Hub"""
@@ -186,6 +187,10 @@ def health():
186
  @login_required
187
  def my_statistics():
188
  """Trang thống kê feedback cá nhân của user"""
 
 
 
 
189
  try:
190
  # Lấy thống kê feedback của user hiện tại
191
  user_feedbacks = Feedback.query.filter_by(user_id=current_user.id).all()
@@ -495,6 +500,11 @@ with app.app_context():
495
  total_users = User.query.count()
496
  print(f"📊 Total users in database: {total_users}")
497
 
 
 
 
 
 
498
  admin_user = User.query.filter_by(username='admin').first()
499
  if not admin_user:
500
  # Chỉ tạo admin nếu database hoàn toàn trống
@@ -519,13 +529,10 @@ with app.app_context():
519
 
520
  print("✅ Database đã sẵn sàng!")
521
 
522
- # Backup lại sau khi có thay đổi
523
  if total_users > 0:
524
- print("🔄 Backing up restored database...")
525
- if backup_database():
526
- print("✅ Restored database backed up successfully")
527
- else:
528
- print("⚠️ Failed to backup restored database")
529
 
530
  @app.route("/analyze-csv", methods=["POST"])
531
  @login_required
 
22
  app.config['SECRET_KEY'] = 'your-secret-key-change-this-in-production'
23
 
24
  # Database backup functions
25
+ def backup_database(force: bool = False):
26
  """Backup database to Hugging Face Hub"""
27
  try:
28
+ return db_manager.backup_database(force=force)
29
  except Exception as e:
30
  print(f"❌ Backup error: {e}")
31
+ return False
32
 
33
  def restore_database():
34
  """Restore database from Hugging Face Hub"""
 
187
  @login_required
188
  def my_statistics():
189
  """Trang thống kê feedback cá nhân của user"""
190
+ # Debug: Check user admin status
191
+ print(f"🔍 Debug - Current user: {current_user.username}")
192
+ print(f"🔍 Debug - Is admin: {current_user.is_admin}")
193
+
194
  try:
195
  # Lấy thống kê feedback của user hiện tại
196
  user_feedbacks = Feedback.query.filter_by(user_id=current_user.id).all()
 
500
  total_users = User.query.count()
501
  print(f"📊 Total users in database: {total_users}")
502
 
503
+ # Debug: List all users and their admin status
504
+ all_users = User.query.all()
505
+ for user in all_users:
506
+ print(f"👤 User: {user.username}, Admin: {user.is_admin}")
507
+
508
  admin_user = User.query.filter_by(username='admin').first()
509
  if not admin_user:
510
  # Chỉ tạo admin nếu database hoàn toàn trống
 
529
 
530
  print("✅ Database đã sẵn sàng!")
531
 
532
+ # Backup lại sau khi có thay đổi (chỉ khi cần thiết)
533
  if total_users > 0:
534
+ print("ℹ️ Database restored successfully with existing data")
535
+ print("💡 Backup will happen automatically when data changes")
 
 
 
536
 
537
  @app.route("/analyze-csv", methods=["POST"])
538
  @login_required
database_manager.py CHANGED
@@ -177,7 +177,7 @@ class DatabaseManager:
177
  except Exception as e:
178
  print(f"❌ Error converting JSON to SQLite: {e}")
179
 
180
- def backup_database(self) -> bool:
181
  """Backup database to Hugging Face Hub"""
182
  if not self.api:
183
  print("⚠️ Hugging Face API not available. Skipping backup.")
@@ -203,13 +203,20 @@ class DatabaseManager:
203
  json.dump(json_data, f, indent=2, ensure_ascii=False)
204
 
205
  # Upload to Hugging Face Hub
206
- self.api.upload_file(
207
- path_or_fileobj=temp_file,
208
- path_in_repo='feedback_backup.json',
209
- repo_id=self.repo_id,
210
- repo_type="dataset",
211
- commit_message=f"Backup database - {timestamp}"
212
- )
 
 
 
 
 
 
 
213
 
214
  # Clean up temporary file
215
  os.remove(temp_file)
 
177
  except Exception as e:
178
  print(f"❌ Error converting JSON to SQLite: {e}")
179
 
180
+ def backup_database(self, force: bool = False) -> bool:
181
  """Backup database to Hugging Face Hub"""
182
  if not self.api:
183
  print("⚠️ Hugging Face API not available. Skipping backup.")
 
203
  json.dump(json_data, f, indent=2, ensure_ascii=False)
204
 
205
  # Upload to Hugging Face Hub
206
+ try:
207
+ self.api.upload_file(
208
+ path_or_fileobj=temp_file,
209
+ path_in_repo='feedback_backup.json',
210
+ repo_id=self.repo_id,
211
+ repo_type="dataset",
212
+ commit_message=f"Backup database - {timestamp}"
213
+ )
214
+ except Exception as upload_error:
215
+ if "No files have been modified" in str(upload_error):
216
+ print("ℹ️ No changes to backup (same data as before)")
217
+ return True # This is actually success
218
+ else:
219
+ raise upload_error
220
 
221
  # Clean up temporary file
222
  os.remove(temp_file)
templates/base.html CHANGED
@@ -38,6 +38,9 @@
38
  </span>
39
 
40
  {% block navigation_buttons %}
 
 
 
41
  {% if current_user.is_admin %}
42
  <a href="{{ url_for('view_database') }}" class="btn-glass">
43
  <i class="fas fa-database"></i>
 
38
  </span>
39
 
40
  {% block navigation_buttons %}
41
+ <!-- Debug info (remove in production) -->
42
+ <small class="text-muted">User: {{ current_user.username }} | Admin: {{ current_user.is_admin }}</small>
43
+
44
  {% if current_user.is_admin %}
45
  <a href="{{ url_for('view_database') }}" class="btn-glass">
46
  <i class="fas fa-database"></i>