From c75757a70c4fbdeef9b8f7a08eb596c6622d7b51 Mon Sep 17 00:00:00 2001 From: Stephan Kerkman Date: Sat, 30 May 2026 21:01:47 +0200 Subject: [PATCH] fix: guard against malformed API response and empty matches list --- plants/services/plantnet.py | 25 ++++++++++++++----------- plants/views/identify.py | 2 ++ 2 files changed, 16 insertions(+), 11 deletions(-) diff --git a/plants/services/plantnet.py b/plants/services/plantnet.py index 507405d..945bb49 100644 --- a/plants/services/plantnet.py +++ b/plants/services/plantnet.py @@ -53,14 +53,17 @@ def identify(images): if not results: raise PlantNetError('No match found — try a different photo or organ.') - return [ - { - 'scientific_name': r['species']['scientificNameWithoutAuthor'], - 'common_names': r['species'].get('commonNames', []), - 'score': r['score'], - 'gbif_id': (r.get('gbif') or {}).get('id'), - 'family': r['species'].get('family', {}).get('scientificNameWithoutAuthor', ''), - 'genus': r['species'].get('genus', {}).get('scientificNameWithoutAuthor', ''), - } - for r in results[:5] - ] + try: + return [ + { + 'scientific_name': r['species']['scientificNameWithoutAuthor'], + 'common_names': r['species'].get('commonNames', []), + 'score': r['score'], + 'gbif_id': (r.get('gbif') or {}).get('id'), + 'family': r['species'].get('family', {}).get('scientificNameWithoutAuthor', ''), + 'genus': r['species'].get('genus', {}).get('scientificNameWithoutAuthor', ''), + } + for r in results[:5] + ] + except (KeyError, TypeError) as exc: + raise PlantNetError('Unexpected API response format.') from exc diff --git a/plants/views/identify.py b/plants/views/identify.py index 20425c6..55329da 100644 --- a/plants/views/identify.py +++ b/plants/views/identify.py @@ -63,6 +63,8 @@ def identify_confirm(request): return redirect('identify_upload') matches = request.session['identify_matches'] + if not matches: + return redirect('identify_upload') if request.method == 'POST': try: