Skip to content

Commit 235bf7a

Browse files
committed
kobo attachments error handling
1 parent 0185669 commit 235bf7a

File tree

2 files changed

+56
-26
lines changed

2 files changed

+56
-26
lines changed

routes/routes121.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -520,7 +520,7 @@ async def create_121_program_from_kobo(
520520
)
521521

522522
if len(MISSINGFIELDS) != 0:
523-
print("Missing hidden fields in the template: ", MISSINGFIELDS)
523+
logger.error(f"Missing required keys in kobo form: {MISSINGFIELDS}")
524524
raise HTTPException(
525525
status_code=400,
526526
detail=f"Missing required keys in kobo form: {MISSINGFIELDS}",

utils/utilsKobo.py

Lines changed: 55 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22
import time
33
from fastapi import Header
44
import sys
5+
from utils.logger import logger
56

67

78
def required_headers_kobo(kobotoken: str = Header(), koboasset: str = Header()):
@@ -34,31 +35,60 @@ def get_kobo_attachment(URL, kobo_token):
3435
def get_attachment_dict(kobo_data, kobotoken=None, koboasset=None):
3536
"""Create a dictionary that maps the attachment filenames to their URL."""
3637
attachments, attachments_list = {}, []
37-
if kobotoken and koboasset and "_id" in kobo_data.keys():
38-
time.sleep(30)
39-
headers = {"Authorization": f"Token {kobotoken}"}
40-
URL = f"https://kobo.ifrc.org/api/v2/assets/{koboasset}/data/{kobo_data['_id']}/?format=json"
41-
data_request = requests.get(URL, headers=headers)
42-
data = data_request.json()
43-
if "_attachments" in data.keys():
44-
attachments_list = data["_attachments"]
45-
if len(attachments_list) == 0:
46-
if "_attachments" in kobo_data.keys():
47-
attachments_list = kobo_data["_attachments"]
48-
for attachment in attachments_list:
49-
filename = attachment["filename"].split("/")[-1]
50-
downloadurl = attachment["download_large_url"]
51-
mimetype = attachment["mimetype"]
52-
attachments[filename] = {"url": downloadurl, "mimetype": mimetype}
53-
else:
54-
for attachment in attachments_list:
55-
filename = attachment["filename"].split("/")[-1]
56-
downloadurl = (
57-
"https://kc.ifrc.org/media/original?media_file="
58-
+ attachment["filename"]
59-
)
60-
mimetype = attachment["mimetype"]
61-
attachments[filename] = {"url": downloadurl, "mimetype": mimetype}
38+
39+
try:
40+
if kobotoken and koboasset and "_id" in kobo_data.keys():
41+
time.sleep(30)
42+
headers = {"Authorization": f"Token {kobotoken}"}
43+
URL = f"https://kobo.ifrc.org/api/v2/assets/{koboasset}/data/{kobo_data['_id']}/?format=json"
44+
45+
try:
46+
data_request = requests.get(URL, headers=headers, timeout=30)
47+
data_request.raise_for_status()
48+
data = data_request.json()
49+
50+
if "_attachments" in data.keys():
51+
attachments_list = data["_attachments"]
52+
logger.info(f"Retrieved {len(attachments_list)} attachments from API for submission {kobo_data['_id']}")
53+
except requests.exceptions.RequestException as e:
54+
logger.error(f"Failed to fetch attachment data from Kobo API for submission {kobo_data['_id']}: {e}")
55+
# Fall back to using attachments from kobo_data if available
56+
except ValueError as e:
57+
logger.error(f"Failed to parse JSON response from Kobo API: {e}")
58+
59+
if len(attachments_list) == 0:
60+
if "_attachments" in kobo_data.keys():
61+
attachments_list = kobo_data["_attachments"]
62+
logger.info(f"Using {len(attachments_list)} attachments from kobo_data")
63+
for attachment in attachments_list:
64+
try:
65+
filename = attachment["filename"].split("/")[-1]
66+
downloadurl = attachment["download_url"]
67+
mimetype = attachment["mimetype"]
68+
attachments[filename] = {"url": downloadurl, "mimetype": mimetype}
69+
except KeyError as e:
70+
logger.warning(f"Missing expected key in attachment: {e}. Skipping attachment.")
71+
continue
72+
else:
73+
for attachment in attachments_list:
74+
try:
75+
filename = attachment["filename"].split("/")[-1]
76+
downloadurl = (
77+
"https://kc.ifrc.org/media/original?media_file="
78+
+ attachment["filename"]
79+
)
80+
mimetype = attachment["mimetype"]
81+
attachments[filename] = {"url": downloadurl, "mimetype": mimetype}
82+
except KeyError as e:
83+
logger.warning(f"Missing expected key in attachment: {e}. Skipping attachment.")
84+
continue
85+
86+
logger.info(f"Successfully processed {len(attachments)} attachments")
87+
88+
except Exception as e:
89+
logger.error(f"Unexpected error in get_attachment_dict: {e}")
90+
return {}
91+
6292
return attachments
6393

6494

0 commit comments

Comments
 (0)