From b9540d4f975d834784d5a3ecfb8e21edb092c4da Mon Sep 17 00:00:00 2001 From: tomolopolis Date: Thu, 21 Dec 2023 17:57:19 +0000 Subject: [PATCH] 8693ca0ja: better error handling for missing cuis_file json files --- webapp/api/api/serializers.py | 11 ++++++++++- webapp/api/api/views.py | 9 +++++++-- 2 files changed, 17 insertions(+), 3 deletions(-) diff --git a/webapp/api/api/serializers.py b/webapp/api/api/serializers.py index 303a811f..6aa99515 100644 --- a/webapp/api/api/serializers.py +++ b/webapp/api/api/serializers.py @@ -1,4 +1,5 @@ import json +import logging from django.contrib.auth.models import User from rest_framework.fields import FileField @@ -8,6 +9,8 @@ from rest_framework import serializers +logger = logging.getLogger(__name__) + class UserSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = User @@ -69,7 +72,13 @@ class Meta: def to_representation(self, instance): data = super(ProjectAnnotateEntitiesSerializer, self).to_representation(instance) - cuis_from_file = json.load(open(instance.cuis_file.path)) if instance.cuis_file else [] + try: + cuis_from_file = json.load(open(instance.cuis_file.path)) if instance.cuis_file else [] + except FileNotFoundError: + logger.warning('cuis file %s cannot be found. Project: %s will fail to load. File ' + 'needs to be cleared and re-uploaded to load project', instance.cuis_file, + instance.name) + cuis_from_file = [] cui_list = [s.strip() for s in data['cuis'].split(',')] + cuis_from_file if len(data['cuis']) > 0 else cuis_from_file data['cuis'] = ','.join(cui_list) return data diff --git a/webapp/api/api/views.py b/webapp/api/api/views.py index ffb0ab11..bd08fee3 100644 --- a/webapp/api/api/views.py +++ b/webapp/api/api/views.py @@ -241,8 +241,13 @@ def prepare_documents(request): cuis = set([str(cui).strip() for cui in project.cuis.split(",")]) if project.cuis_file is not None and project.cuis_file: # Add cuis from json file if it exists - cuis.update(json.load(open(project.cuis_file.path))) - + try: + cuis.update(json.load(open(project.cuis_file.path))) + except FileNotFoundError: + return Response({'message': 'Missing CUI filter file', + 'description': 'Missing CUI filter file, %s, cannot be found on the filesystem, ' + 'but is still set on the project. To fix remove and reset the ' + 'cui filter file' % project.cuis_file}, status=500) try: for d_id in d_ids: document = Document.objects.get(id=d_id)