Inventree Python API HTTPError'ları nasıl yakalanır ve analiz edilir

Bu örnek, inventree Part.create() için Part with this Part Number already exists hatası ile diğer hatalar arasında nasıl ayrım yapılacağını gösterir. Diğer tüm hatalar basitçe yeniden fırlatılır. Bkz. Inventree Python API: Yeni bir parça nasıl oluşturulur

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
    # NOT: errmsg aşağıdaki anahtarlara sahip bir sözlüktür
    # 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", [])
    # Bir non_field_error varsa ve "Part with this ... already exists" içeriyorsa
    if len(non_field_errors) > 0 and re.match(r"Part with this .* already exists", non_field_errors[0]):
        print("Bu parça zaten mevcut")
    else:
        raise ex

Check out similar posts by category: InvenTree Python