Could you please check my code below. There is no error but as I checked on the kobo media files there is no uploaded csv files on the kobo form medial files.
import os
import requests
import json
KC_URL = ‘KoBoCAT REST API’
KF_URL = ‘https://kf.kobotoolbox.org/api/v2/assets/aSXwstUL******************/submissions/’
TOKEN = ‘5b359613c8f***************************’ # Replace with your KoBoToolbox API token
XFORM = ‘aSXwstUL2U3W**********’ # Replace with the relevant KoBoToolbox form ID
FILE_FOLDER = ‘/Users/andisulasikin/PycharmProjects/pythonProject/uploadtokobo’ # Replace with the local folder path where your CSV files are stored
MIME = ‘text/csv’
headers = {‘Authorization’: f’Token {TOKEN}'}
#Get a list of all files in the folder
file_list = [f for f in os.listdir(FILE_FOLDER) if os.path.isfile(os.path.join(FILE_FOLDER, f))]
for filename in file_list:
files = {‘data_file’: (filename, open(os.path.join(FILE_FOLDER, filename), ‘rb’).read(), MIME)}
data = {
‘data_value’: filename,
‘xform’: XFORM,
‘data_type’: ‘media’,
‘data_file_type’: MIME,
}
# Download metadata.json
response = requests.get(fr"{KC_URL}/metadata.json", headers=headers)
try:
dict_response = json.loads(response.text)
except json.JSONDecodeError:
dict_response = []
# Delete appropriate entry in the metadata.json (delete old file)
found = False
for each in dict_response:
if isinstance(each, dict) and each.get('xform') == XFORM and each.get('data_value') == filename:
found = True
del_id = each['id']
response = requests.delete(fr"{KC_URL}/metadata/{del_id}", headers=headers)
break
if not found:
print(f"File {filename} not found in metadata. Proceeding with initial upload.")
# Upload the changed file
response = requests.post(fr"{KC_URL}/metadata.json", data=data, files=files, headers=headers) print("All files uploaded successfully.")