Home > other >  How do I skip a script in Python depending on the value returned from a request?
How do I skip a script in Python depending on the value returned from a request?

Time:10-10

I am writing a script in Python that uses requests to get uid fields from an api. The uid retrieved is to be used as part of a second url where another request is to be made. When the uid is inserted into the second url, a list is supposed to be returned which I then iterate over and extract some data. The only problem is that some requests to the new url return an empty list which then throws an error when I try to iterate over. Here is the code:

taxon_url = f"https://records-ws.nbnatlas.org/occurrences/search?q=data_resource_uid:{uid}&fq=taxon_concept_lsid:*&facets=taxon_concept_lsid&pageSize=0&flimit=-1"
taxon_response = requests.get(taxon_url)
json_response = taxon_response.json()

jsonpath_expr = parse('$..facetResults[*].fieldResult[*]')
resources = [ match.value for match in jsonpath_expr.find(json_response) ]

for label in resources:
    taxon_id = label['label']
    print(taxon_id)

So, as I mentioned, the resources returned should be a list which in some cases in an empty list and this throws the local variable referenced before assignment even though it is explicitly assigned error for taxon_id for the next part of the script:

class_url = f"https://species-ws.nbnatlas.org/species/{taxon_id}"
class_response = requests.get(class_url)
class_json = class_response.json()

Your assistance is highly appreciated

CodePudding user response:

You can check if the length of the resources list is grater than 0 like:

taxon_url = f"https://records-ws.nbnatlas.org/occurrences/search?q=data_resource_uid:{uid}&fq=taxon_concept_lsid:*&facets=taxon_concept_lsid&pageSize=0&flimit=-1"
taxon_response = requests.get(taxon_url)
json_response = taxon_response.json()

jsonpath_expr = parse('$..facetResults[*].fieldResult[*]')
resources = [ match.value for match in jsonpath_expr.find(json_response) ]
if len(resources) > 0:
  for label in resources:
     taxon_id = label['label']
     print(taxon_id)

Or you can also use a try-except.

CodePudding user response:

if your resources list is empty, the code block under the for loop won't assign taxon_id. So you should define a default value for taxon_id variable for printing/using it without errors. Or you can always check if the list is empty or use try/except.

  • Related