import sys import requests from datetime import datetime import os from dotenv import load_dotenv import csv load_dotenv(override=True) host = os.getenv("HOST") login_user = os.getenv("USER") login_pass = os.getenv("PASS") src_file_subs = os.getenv("FILE_ROOT") + os.getenv("SUBSCRIPTION_FILE") def get_dynamic_path(): # Get today's date in the format YYYYMMDD today_date = datetime.now().strftime("%Y%m%d") # Construct the dynamic path path = os.path.join("C:\\Humbingo\\to_humbingo", today_date, "subscription.csv") return path print("Reading files: ", src_file_subs) def get_auth_token(): url = host + "/auth/token/" print("Using URL: ", url) payload = {"phone_no": login_user, "password": login_pass} try: response = requests.post(url, data=payload) response.raise_for_status() return response.json().get('access') except requests.exceptions.RequestException as e: print("Error obtaining auth token:", e) return None def send_data_to_api(csv_file_path, token, batch_size=1000): url = host + "/api/v1/migrateSubscriptions" print("Using URL: ", url) headers = {'Authorization': f'Bearer {token}'} for i in range(0, len(csv_file_path), batch_size): batch = csv_file_path[i:i + batch_size] try: # Send CSV file with data as multipart form-data files = {'file': open(csv_file_path, 'rb')} response = requests.post(url, files=files, headers=headers) # Check response status if response.status_code == 201: response_data = response.json() # Print the message print(f"Message from server: {response_data.get('message')}") print(f"Batch {i // batch_size + 1} sent successfully to the API") else: # Print the error message and response content print(f"Failed to send batch {i // batch_size + 1} to the API. Status code:", response.status_code) print("Response content:", response.content.decode('utf-8')) except Exception as e: # Print the general error message print("Error:", e) if __name__ == "__main__": # Get the file path from the command-line arguments or default path csv_file_path = get_dynamic_path() # Obtain the authentication token token = get_auth_token() if token: # Send the data to the API in batches with authentication send_data_to_api(csv_file_path, token) else: print("Failed to obtain auth token, cannot send data to API.")