From a105c642fcab2615b4b5728cc9908160dcaa98ca Mon Sep 17 00:00:00 2001 From: Kalibh Halford Date: Mon, 9 Oct 2023 11:24:45 +0100 Subject: [PATCH] Change return type hinting to support older Python syntax. Moved Netbox api logic from format_dict.py to netbox_data.py. --- Netbox_CSV_Read/Netbox_Api/netbox_data.py | 46 +++++++++++++++++++++++ 1 file changed, 46 insertions(+) create mode 100644 Netbox_CSV_Read/Netbox_Api/netbox_data.py diff --git a/Netbox_CSV_Read/Netbox_Api/netbox_data.py b/Netbox_CSV_Read/Netbox_Api/netbox_data.py new file mode 100644 index 00000000..579b9bba --- /dev/null +++ b/Netbox_CSV_Read/Netbox_Api/netbox_data.py @@ -0,0 +1,46 @@ +from Netbox_Api.netbox_connect import NetboxConnect +from Enums.dcim_device_id import DeviceInfoID +from Enums.dcim_device_no_id import DeviceInfoNoID +from operator import attrgetter +from typing import Optional + + +class NetboxGetID(NetboxConnect): + """ + This class retrieves field value ID's from Netbox. + """ + def __init__(self, url: str, token: str, api: Optional = None): + """ + This method initialises the class with the following parameters. + Also, it allows dependency injection testing. + :param url: Netbox website URL. + :param token: Netbox authentication token. + """ + if not api: + self.netbox = NetboxConnect(url, token).api_object() + else: + self.netbox = api + self.enums_id = DeviceInfoID + self.enums_no_id = DeviceInfoNoID + + def get_id(self, attr_string: str, netbox_value: str, site_value: str) -> int | str: + """ + This method uses the Pynetbox Api .get() method to retrieve the ID of a string value from Netbox. + :param attr_string: The attribute string to get. + :param netbox_value: The value to search for in Netbox. + :param site_value: The value of the site key in the dictionary + :return: Returns the value/ID + """ + attr_string = attr_string.upper() + attr_to_look_for = getattr(self.enums_id, attr_string).value # Gets Enums value + value = attrgetter(attr_to_look_for)(self.netbox) # Gets netbox attr + if attr_string == "DEVICE_TYPE": + value = value.get(slug=netbox_value).id + elif attr_string == "LOCATION": + if type(site_value) == int: + site_name = self.netbox.dcim.sites.get(site_value).name + site_slug = site_name.replace(" ", "-").lower() + value = value.get(name=netbox_value, site=site_slug) + else: + value = value.get(name=netbox_value).id + return value