Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Standardise error messages #119

Open
wants to merge 8 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -193,28 +193,35 @@ def get_variant_type(self, id):
)
data = {}

list_of_comments = {}
for lgd_variant in queryset:
# Get the variant type term (ex:frameshift_variant)
accession = lgd_variant.variant_type_ot.accession

# Prepare the list of comments
list_of_comments = []
comments = lgd_variant.current_comments # Get the prefetched comments
for comment_obj in comments:
comment_text = comment_obj.comment
# Format date
date = None
if comment_obj.date is not None:
date = comment_obj.date.strftime("%Y-%m-%d")
list_of_comments.append(
{
"text": comment_obj.comment,
"date": date
}
)

accession = lgd_variant.variant_type_ot.accession
if accession not in list_of_comments:
list_of_comments[accession] = [{
"text": comment_text,
"date": date
}]
elif not any(comment['text'] == comment_text for comment in list_of_comments[accession]):
list_of_comments[accession].append({
"text": comment_text,
"date": date
})

if accession in data and lgd_variant.publication:
# Add pmid to list of publications
data[accession]["publications"].append(lgd_variant.publication.pmid)
data[accession]["comments"] = list_of_comments
data[accession]["comments"] = list_of_comments[accession]
# Check the variant inheritance - we group this data for each publication
if(lgd_variant.inherited is True):
data[accession]["inherited"] = lgd_variant.inherited
Expand All @@ -234,7 +241,7 @@ def get_variant_type(self, id):
"de_novo": lgd_variant.de_novo,
"unknown_inheritance": lgd_variant.unknown_inheritance,
"publications": publication_list,
"comments": list_of_comments
"comments": list_of_comments[accession]
}

return data.values()
Expand Down Expand Up @@ -1160,7 +1167,7 @@ def create(self, validated_data):
lgd_variant_type_obj.save()

# The LGDPhenotypeSummary is created - next step is to create the LGDVariantTypeComment
if(comment != ""):
if comment != "":
try:
lgd_comment_obj = LGDVariantTypeComment.objects.get(
comment = comment,
Expand Down Expand Up @@ -1251,7 +1258,7 @@ def create(self, validated_data):
lgd_variant_type_obj.save()

# The LGDPhenotypeSummary is created - next step is to create the LGDVariantTypeComment
if(comment != ""):
if comment != "":
try:
lgd_comment_obj = LGDVariantTypeComment.objects.get(
comment = comment,
Expand Down Expand Up @@ -1283,7 +1290,7 @@ class Meta:
class LGDVariantTypeListSerializer(serializers.Serializer):
"""
Serializer to accept a list of variant types.
Called by: LGDAddVariantTypes()
Called by: LGDEditVariantTypes()
"""
variant_types = LGDVariantTypeSerializer(many=True)

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ def test_not_found(self):
response = self.client.get(self.url_disease)

self.assertEqual(response.status_code, 404)
self.assertEqual(response.data["message"], "No matching Disease found for: CACNA1F-related Aland Island")
self.assertEqual(response.data["error"], "No matching Disease found for: CACNA1F-related Aland Island")

class DiseaseSummaryTests(TestCase):
"""
Expand Down Expand Up @@ -98,4 +98,4 @@ def test_not_found(self):
response = self.client.get(self.url_disease)

self.assertEqual(response.status_code, 404)
self.assertEqual(response.data["message"], "No matching Disease found for: CACNA1F-related Aland Island")
self.assertEqual(response.data["error"], "No matching Disease found for: CACNA1F-related Aland Island")
Original file line number Diff line number Diff line change
Expand Up @@ -48,4 +48,4 @@ def test_invalid(self):
response = self.client.get(self.url_publication)

self.assertEqual(response.status_code, 404)
self.assertEqual(response.data["detail"], "Invalid PMID(s): 0")
self.assertEqual(response.data["error"], "Invalid PMID(s): 0")
Original file line number Diff line number Diff line change
Expand Up @@ -134,4 +134,4 @@ def test_search_not_found(self):
response = self.client.get(url_search_gene)

self.assertEqual(response.status_code, 404)
self.assertEqual(response.data["message"], "No matching Gene found for: TUBB4A")
self.assertEqual(response.data["error"], "No matching Gene found for: TUBB4A")
2 changes: 1 addition & 1 deletion gene2phenotype_project/gene2phenotype_app/views/attrib.py
Original file line number Diff line number Diff line change
Expand Up @@ -111,7 +111,7 @@ def get_queryset(self):
attrib_type_obj = AttribType.objects.get(code=code)
except AttribType.DoesNotExist:
return Response(
{"message": f"Attrib type {code} not found"},
{"error": f"Attrib type {code} not found"},
status=status.HTTP_404_NOT_FOUND
)

Expand Down
2 changes: 1 addition & 1 deletion gene2phenotype_project/gene2phenotype_app/views/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ def handle_no_permission(self, name_type, name):

def handle_exception(self, exc):
if isinstance(exc, Http404):
return Response({"message": str(exc)}, status=status.HTTP_404_NOT_FOUND)
return Response({"error": str(exc)}, status=status.HTTP_404_NOT_FOUND)

return super().handle_exception(exc)

Expand Down
82 changes: 60 additions & 22 deletions gene2phenotype_project/gene2phenotype_app/views/curation.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,29 +40,43 @@ def post(self, request):
with open(json_file_path, 'r') as file:
schema = json.load(file)
except FileNotFoundError:
return Response({"message": "Schema file not found"}, status=status.HTTP_404_NOT_FOUND)
return Response(
{"error": "Schema file not found"}, status=status.HTTP_404_NOT_FOUND
)

# json format accepts null values but in python these values are represented as 'None'
# dumps() converts 'None' to 'null' before json validation
input_data = json.dumps(request.data)
input_json_data = json.loads(input_data)

if "json_data" not in input_json_data:
return Response({"message": "Invalid data format: 'json_data' is missing"}, status=status.HTTP_400_BAD_REQUEST)
return Response(
{"error": "Invalid data format: 'json_data' is missing"},
status=status.HTTP_400_BAD_REQUEST
)

# Validate the JSON data against the schema
try:
validate(instance=input_json_data["json_data"], schema=schema)
except jsonschema.exceptions.ValidationError as e:
return Response({"message": "JSON data does not follow the required format. Required format is" + str(e)}, status=status.HTTP_400_BAD_REQUEST)
return Response(
{"error": "JSON data does not follow the required format. Required format is" + str(e)},
status=status.HTTP_400_BAD_REQUEST
)

serializer = self.serializer_class(data=request.data, context={'user': user})

if serializer.is_valid():
instance = serializer.save()
return Response({"message": f"Data saved successfully for session name '{instance.session_name}'", "result": f"{instance.stable_id.stable_id}"}, status=status.HTTP_200_OK)
return Response(
{
"message": f"Data saved successfully for session name '{instance.session_name}'",
"result": f"{instance.stable_id.stable_id}"
},
status=status.HTTP_200_OK
)
else:
return Response({"errors": serializer.errors}, status=status.HTTP_400_BAD_REQUEST)
return Response({"error": serializer.errors}, status=status.HTTP_400_BAD_REQUEST)

class ListCurationEntries(BaseView):
"""
Expand Down Expand Up @@ -203,7 +217,10 @@ def update(self, request, *args, **kwargs):
with open(json_file_path, 'r') as file:
schema = json.load(file)
except FileNotFoundError:
return Response({"message": "Schema file not found"}, status=status.HTTP_404_NOT_FOUND)
return Response(
{"error": "Schema file not found"},
status=status.HTTP_404_NOT_FOUND
)

# json format accepts null values but in python these values are represented as 'None'
# dumps() converts 'None' to 'null' before json validation
Expand All @@ -214,7 +231,10 @@ def update(self, request, *args, **kwargs):
try:
validate(instance=input_json_data["json_data"], schema=schema)
except jsonschema.exceptions.ValidationError as e:
return Response({"message": "JSON data does not follow the required format. Required format is" + str(e)}, status=status.HTTP_400_BAD_REQUEST)
return Response(
{"error": "JSON data does not follow the required format. Required format is" + str(e)},
status=status.HTTP_400_BAD_REQUEST
)

# Update data - it replaces the data
serializer = CurationDataSerializer(
Expand All @@ -225,10 +245,16 @@ def update(self, request, *args, **kwargs):

if serializer.is_valid():
instance = serializer.save()
return Response({"message": f"Data updated successfully for session name '{instance.session_name}'"}, status=status.HTTP_200_OK)
return Response(
{"message": f"Data updated successfully for session name '{instance.session_name}'"},
status=status.HTTP_200_OK
)

else:
return Response({"errors": serializer.errors}, status=status.HTTP_400_BAD_REQUEST)
return Response(
{"error": serializer.errors},
status=status.HTTP_400_BAD_REQUEST
)

class PublishRecord(APIView):
"""
Expand Down Expand Up @@ -264,19 +290,22 @@ def post(self, request, stable_id):
# Delete entry from 'curation_data'
curation_obj.delete()

return Response({
"message": f"Record '{lgd_obj.stable_id.stable_id}' published successfully"
}, status=status.HTTP_201_CREATED)
return Response(
{"message": f"Record '{lgd_obj.stable_id.stable_id}' published successfully"},
status=status.HTTP_201_CREATED
)

except LocusGenotypeDisease.DoesNotExist:
Response({
"message": f"Failed to publish record ID '{stable_id}'"
}, status=status.HTTP_400_BAD_REQUEST)
Response(
{"error": f"Failed to publish record ID '{stable_id}'"},
status=status.HTTP_400_BAD_REQUEST
)

except CurationData.DoesNotExist:
return Response({
"message": f"Curation data not found for ID '{stable_id}'"
}, status=status.HTTP_404_NOT_FOUND)
return Response(
{"error": f"Curation data not found for ID '{stable_id}'"},
status=status.HTTP_404_NOT_FOUND
)

class DeleteCurationData(generics.DestroyAPIView):
"""
Expand Down Expand Up @@ -331,12 +360,21 @@ def destroy(self, request, *args, **kwargs):
stable_id = self.kwargs['stable_id']

if not curation_obj or len(curation_obj) == 0:
return Response({"error": f"Cannot find ID {stable_id}"}, status=status.HTTP_404_NOT_FOUND)
return Response(
{"error": f"Cannot find ID {stable_id}"},
status=status.HTTP_404_NOT_FOUND
)

try:
# delete record + G2P ID
self.perform_destroy(curation_obj, stable_id)
except:
return Response({"message": f"Cannot delete data for ID {stable_id}"}, status=status.HTTP_404_NOT_FOUND)

return Response({"message": f"Data deleted successfully for ID {stable_id}"}, status=status.HTTP_204_NO_CONTENT)
return Response(
{"error": f"Cannot delete data for ID {stable_id}"},
status=status.HTTP_404_NOT_FOUND
)

return Response(
{"message": f"Data deleted successfully for ID {stable_id}"},
status=status.HTTP_204_NO_CONTENT
)
14 changes: 10 additions & 4 deletions gene2phenotype_project/gene2phenotype_app/views/disease.py
Original file line number Diff line number Diff line change
Expand Up @@ -193,7 +193,10 @@ def post(self, request):
diseases = request.data # list of diseases {'id': ..., 'name': ...}

if not isinstance(diseases, list):
return Response({"error": "Request should be a list"}, status=status.HTTP_400_BAD_REQUEST)
return Response(
{"error": "Request should be a list"},
status=status.HTTP_400_BAD_REQUEST
)

updated_diseases = []
errors = []
Expand Down Expand Up @@ -230,7 +233,7 @@ def post(self, request):
response_data["updated"] = updated_diseases

if errors:
response_data["errors"] = errors
response_data["error"] = errors

return Response(response_data, status=status.HTTP_200_OK if updated_diseases else status.HTTP_400_BAD_REQUEST)

Expand All @@ -242,7 +245,10 @@ def post(self, request):
data_to_update = request.data

if not isinstance(data_to_update, list):
return Response({"error": "Request should be a list"}, status=status.HTTP_400_BAD_REQUEST)
return Response(
{"error": "Request should be a list"},
status=status.HTTP_400_BAD_REQUEST
)

updated_records = []
errors = []
Expand Down Expand Up @@ -279,6 +285,6 @@ def post(self, request):
response_data["Updated records"] = updated_records

if errors:
response_data["Errors"] = errors
response_data["error"] = errors

return Response(response_data, status=status.HTTP_200_OK if updated_records else status.HTTP_400_BAD_REQUEST)
Loading