P_chandra_migrator/m_group.py

58 lines
2.0 KiB
Python
Raw Normal View History

2024-10-03 12:17:31 +00:00
import sys
import requests
from dbfread import DBF
from datetime import date
import csv
import datetime
import os
from dotenv import load_dotenv
load_dotenv(override=True)
host=os.getenv("HOST")
login_user = os.getenv("USER")
login_pass = os.getenv("PASS")
src_file_grp = os.getenv("FILE_ROOT")+os.getenv("GROUP_FILE")
src_file_pa = os.getenv("FILE_ROOT")+os.getenv("PEN_FILE")
def get_dynamic_path():
# Get today's date in the format YYYYMMDD
today_date = datetime.datetime.now().strftime("%Y%m%d")
# Construct the dynamic path
path = os.path.join("C:\\Humbingo\\to_humbingo", today_date, "groups.csv")
return path
print("Reading files: ", src_file_grp, src_file_pa)
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):
try:
url = host+"/api/v1/migrateGroups"
print("Using URL: "+url)
files = {'file': open(csv_file_path, 'rb')}
headers = {'Authorization': f'Bearer {token}'}
response = requests.post(url, files=files, headers=headers)
if response.status_code == 200:
response_data = response.json()
print(f"Message from server: {response_data.get('message')}")
print("CSV file sent successfully to the API")
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)
if __name__ == "__main__":
token = get_auth_token()
if token:
send_data_to_api(get_dynamic_path(), token)
else:
print("Failed to obtain auth token, cannot send data to API.")