app.py 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. from flask import Flask, send_file, jsonify, request
  2. import zipfile
  3. import os
  4. import tempfile
  5. import threading
  6. from datetime import datetime
  7. app = Flask(__name__)
  8. class ZipCreator:
  9. def __init__(self, source_path, temp_dir):
  10. self.source_path = f"/var/www/{source_path}"
  11. self.temp_dir = temp_dir
  12. #self.zip_file_path = os.path.join(temp_dir, 'files.zip')
  13. self.zip_file_name = os.path.basename(source_path) + '.zip'
  14. self.zip_file_path = os.path.join(temp_dir, self.zip_file_name)
  15. self.status = "pending"
  16. self.error = None
  17. def create_zip(self):
  18. try:
  19. with zipfile.ZipFile(self.zip_file_path, 'w') as zip_file:
  20. for root, dirs, files in os.walk(self.source_path):
  21. # Clear the dirs list to prevent descending into subdirectories
  22. dirs.clear()
  23. for file in files:
  24. if file.lower().endswith(('.jpg', '.jpeg')): # Filter only JPEG files
  25. file_path = os.path.join(root, file)
  26. zip_file.write(file_path, os.path.relpath(file_path, self.source_path))
  27. self.status = "completed"
  28. except Exception as e:
  29. self.status = "failed"
  30. self.error = str(e)
  31. finally:
  32. # Ensure the temp directory is cleaned up after download
  33. def cleanup_temp_dir():
  34. import time
  35. time.sleep(30) # Wait 30 seconds to ensure download is complete
  36. try:
  37. os.remove(self.zip_file_path)
  38. os.rmdir(self.temp_dir)
  39. except Exception as e:
  40. print(f"Error cleaning up temp directory: {e}")
  41. threading.Thread(target=cleanup_temp_dir).start()
  42. # Global variable to hold the current zip creation task
  43. current_task = None
  44. @app.route("/start_zip", methods=["POST"])
  45. def start_zip():
  46. global current_task
  47. source_path = request.json['source_path']
  48. temp_dir = tempfile.mkdtemp()
  49. current_task = ZipCreator(source_path, temp_dir)
  50. threading.Thread(target=current_task.create_zip).start()
  51. return jsonify({"message": "Zip creation started"})
  52. @app.route("/status", methods=["GET"])
  53. def status():
  54. global current_task
  55. if current_task:
  56. return jsonify({"status": current_task.status, "error": current_task.error})
  57. else:
  58. return jsonify({"status": "no_task"})
  59. @app.route("/download", methods=["GET"])
  60. def download():
  61. global current_task
  62. if current_task and current_task.status == "completed":
  63. return send_file(current_task.zip_file_path, as_attachment=True)
  64. elif current_task and current_task.status == "failed":
  65. return jsonify({"error": current_task.error}), 500
  66. else:
  67. return jsonify({"error": "Zip not ready"}), 400
  68. if __name__ == "__main__":
  69. app.run(host='0.0.0.0', port=5000)