1. import os
  2. import time
  3. import requests
  4. import logging
  5. from threading import Thread
  6. class FileStreamer:
  7. def __init__(self, file_paths, api_endpoint, retry_interval=5, max_retries=3, log_file="file_streamer.log"):
  8. self.file_paths = file_paths
  9. self.api_endpoint = api_endpoint
  10. self.retry_interval = retry_interval
  11. self.max_retries = max_retries
  12. self.log_file = log_file
  13. self.logging.basicConfig(filename=self.log_file, level=logging.INFO,
  14. format='%(asctime)s - %(levelname)s - %(message)s')
  15. def stream_file(self, file_path):
  16. for attempt in range(self.max_retries):
  17. try:
  18. with open(file_path, 'rb') as f:
  19. files = {'file': (os.path.basename(file_path), f)}
  20. response = requests.post(self.api_endpoint, files=files)
  21. response.raise_for_status() # Raise HTTPError for bad responses (4xx or 5xx)
  22. self.logging.info(f"Successfully streamed {file_path} (attempt {attempt + 1})")
  23. return True # Indicate successful stream
  24. except requests.exceptions.RequestException as e:
  25. self.logging.error(f"Error streaming {file_path} (attempt {attempt + 1}): {e}")
  26. if attempt < self.max_retries - 1:
  27. self.logging.info(f"Retrying in {self.retry_interval} seconds...")
  28. time.sleep(self.retry_interval)
  29. else:
  30. self.logging.error(f"Failed to stream {file_path} after {self.max_retries} attempts.")
  31. return False # Indicate failed stream
  32. except Exception as e:
  33. self.logging.error(f"Unexpected error streaming {file_path} (attempt {attempt + 1}): {e}")
  34. return False # Indicate failed stream
  35. def process_files(self):
  36. threads = []
  37. for file_path in self.file_paths:
  38. thread = Thread(target=self.stream_file, args=(file_path,))
  39. threads.append(thread)
  40. thread.start()
  41. for thread in threads:
  42. thread.join()
  43. if __name__ == '__main__':
  44. # Example Usage
  45. file_paths = ['file1.txt', 'file2.txt', 'file3.txt'] # Replace with your file paths
  46. api_endpoint = 'http://your-api-endpoint.com/upload' # Replace with your API endpoint
  47. #Create dummy files if they don't exist
  48. for file_path in file_paths:
  49. if not os.path.exists(file_path):
  50. with open(file_path, "w") as f:
  51. f.write("This is a dummy file.")
  52. streamer = FileStreamer(file_paths, api_endpoint)
  53. streamer.process_files()
  54. print("File streaming complete.")

Add your comment