import os
import time
import requests
import logging
from threading import Thread
class FileStreamer:
def __init__(self, file_paths, api_endpoint, retry_interval=5, max_retries=3, log_file="file_streamer.log"):
self.file_paths = file_paths
self.api_endpoint = api_endpoint
self.retry_interval = retry_interval
self.max_retries = max_retries
self.log_file = log_file
self.logging.basicConfig(filename=self.log_file, level=logging.INFO,
format='%(asctime)s - %(levelname)s - %(message)s')
def stream_file(self, file_path):
for attempt in range(self.max_retries):
try:
with open(file_path, 'rb') as f:
files = {'file': (os.path.basename(file_path), f)}
response = requests.post(self.api_endpoint, files=files)
response.raise_for_status() # Raise HTTPError for bad responses (4xx or 5xx)
self.logging.info(f"Successfully streamed {file_path} (attempt {attempt + 1})")
return True # Indicate successful stream
except requests.exceptions.RequestException as e:
self.logging.error(f"Error streaming {file_path} (attempt {attempt + 1}): {e}")
if attempt < self.max_retries - 1:
self.logging.info(f"Retrying in {self.retry_interval} seconds...")
time.sleep(self.retry_interval)
else:
self.logging.error(f"Failed to stream {file_path} after {self.max_retries} attempts.")
return False # Indicate failed stream
except Exception as e:
self.logging.error(f"Unexpected error streaming {file_path} (attempt {attempt + 1}): {e}")
return False # Indicate failed stream
def process_files(self):
threads = []
for file_path in self.file_paths:
thread = Thread(target=self.stream_file, args=(file_path,))
threads.append(thread)
thread.start()
for thread in threads:
thread.join()
if __name__ == '__main__':
# Example Usage
file_paths = ['file1.txt', 'file2.txt', 'file3.txt'] # Replace with your file paths
api_endpoint = 'http://your-api-endpoint.com/upload' # Replace with your API endpoint
#Create dummy files if they don't exist
for file_path in file_paths:
if not os.path.exists(file_path):
with open(file_path, "w") as f:
f.write("This is a dummy file.")
streamer = FileStreamer(file_paths, api_endpoint)
streamer.process_files()
print("File streaming complete.")
Add your comment