P_chandra_migrator/m_transactions.py

66 lines
2.2 KiB
Python

import os
import requests
import datetime
from dotenv import load_dotenv
load_dotenv(override=True)
# Environment variables
host = os.getenv("HOST")
login_user = os.getenv("USER")
login_pass = os.getenv("PASS")
# Construct dynamic CSV file path
def get_dynamic_path():
today_date = datetime.datetime.now().strftime("%Y%m%d")
path = os.path.join("C:\\Humbingo\\to_humbingo", today_date, "trxn.csv")
return path
# Authenticate and get token
def get_auth_token():
url = host + "/auth/token/"
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
# Send CSV data to the API
def send_data_to_api(csv_file_path, token):
url = host + "/api/v1/migrateTransactions"
headers = {'Authorization': f'Bearer {token}'}
try:
with open(csv_file_path, 'rb') as csvfile:
files = {'file': csvfile}
response = requests.post(url, files=files, headers=headers)
if response.status_code == 201:
print(f"Message from server: {response.json().get('message')}")
elif response.status_code == 401:
print("Token expired. Re-authenticating...")
new_token = get_auth_token()
if new_token:
send_data_to_api(csv_file_path, new_token)
else:
print("Failed to re-authenticate.")
else:
print("Failed to send CSV file to the API. Status code:", response.status_code)
print("Response content:", response.content.decode('utf-8'))
except Exception as e:
print("Error:", e)
# Main execution
if __name__ == '__main__':
token = get_auth_token()
if not token:
print("Failed to obtain auth token, cannot send data to API.")
exit()
csv_file_path = get_dynamic_path()
if os.path.exists(csv_file_path):
send_data_to_api(csv_file_path, token)
else:
print(f"CSV file {csv_file_path} not found.")