update_task_images.py 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. """
  2. Update task images script.
  3. Updates all tasks to use a CORS-friendly image URL.
  4. """
  5. import sys
  6. import os
  7. import json
  8. # Add parent directory to path
  9. sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
  10. from database import get_db_connection
  11. # 新的图片 URL (支持 CORS)
  12. NEW_IMAGE_URL = "https://picsum.photos/id/40/800/600"
  13. # 旧的图片 URL
  14. OLD_IMAGE_URL = "https://bkimg.cdn.bcebos.com/pic/8cb1cb1349540923dd54185ba804c609b3de9c82e3d8"
  15. def update_task_images():
  16. """Update all tasks with the old image URL to use the new one."""
  17. with get_db_connection() as conn:
  18. cursor = conn.cursor()
  19. # Get all tasks
  20. cursor.execute("SELECT id, data FROM tasks")
  21. rows = cursor.fetchall()
  22. updated_count = 0
  23. for row in rows:
  24. task_id = row["id"]
  25. data_str = row["data"]
  26. try:
  27. data = json.loads(data_str) if isinstance(data_str, str) else data_str
  28. # Check if this task has the old image URL
  29. if data.get("image") == OLD_IMAGE_URL:
  30. data["image"] = NEW_IMAGE_URL
  31. cursor.execute(
  32. "UPDATE tasks SET data = %s WHERE id = %s",
  33. (json.dumps(data, ensure_ascii=False), task_id)
  34. )
  35. updated_count += 1
  36. print(f"✓ 更新任务: {task_id}")
  37. except Exception as e:
  38. print(f"✗ 跳过任务 {task_id}: {e}")
  39. print(f"\n共更新 {updated_count} 个任务")
  40. return updated_count
  41. if __name__ == "__main__":
  42. print("=" * 60)
  43. print("更新任务图片 URL 脚本")
  44. print("=" * 60)
  45. print(f"旧 URL: {OLD_IMAGE_URL}")
  46. print(f"新 URL: {NEW_IMAGE_URL}")
  47. print("-" * 60)
  48. try:
  49. count = update_task_images()
  50. print("\n" + "=" * 60)
  51. print("更新完成!")
  52. print("=" * 60)
  53. except Exception as e:
  54. print(f"\n错误: {e}")
  55. import traceback
  56. traceback.print_exc()
  57. sys.exit(1)