Jak zachytit a analyzovat Inventree Python API HTTPErrors

Tento příklad ukazuje, jak rozlišit mezi Part with this Part Number already exists errorem a ostatními errory pro inventree Part.create(). Jakýkoliv jiný error je jednoduše re-raised. Viz Inventree Python API: Jak vytvořit nový part

inventree_error_handling.py
try:
    part = Part.create(api, {
        'name': product.mpn,
        'description': product.description,
        'category': get_part_category_by_pathstring(api, "Elektronik-Komponenten").pk,
    })
except requests.exceptions.HTTPError as ex:
    errmsg, = ex.args
    # NOTE: errmsg is a dictionary with the following keys
    # errmsg["detail"] == "Error occurred during API request"
    # errmsg["data"] == {'name': 'VHR-4N-BK', 'description': '...', ...}
    # errmsg["params"] == {'format': 'json'}
    # errmsg["body"] == "{'non_field_erro   rs': ['Part with this Part Number already exists.']}""

    body = json.loads(errmsg.get("body", []))
    non_field_errors = body.get("non_field_errors", [])
    # If there is a non field error and it contains "Part with this ... already exists",
    if len(non_field_errors) > 0 and re.match(r"Part with this .* already exists", non_field_errors[0]):
        print("This part already exists")
    else:
        raise ex

Podívejte se na podobné články podle kategorie: InvenTree Python