我正在嘗試創建可以從 API 庫中提取資訊的函式,但我很難弄清楚如何將變數選擇傳遞給函式而不被讀取為值。
代碼示例:
def get_list(api, val = None):
response =[]
list = api
for i in list:
response.append(f'i.{val}')
return (response)
devices = get_list(api.devices.all(), 'name')
print(devices )
給我一長串“i.name”
我需要將i.name決議為變數選擇而不是實際值
我累了:
response.append(vars()[f'i.{val}']) # locals(), globals()
但我得到錯誤:“KeyError:'i.name'”
我認為問題在于“i.name”并沒有真正作為函式中的變數存在。
uj5u.com熱心網友回復:
當您使用設備呼叫此函式時,您將引數“名稱”作為“val”傳遞,然后您將其回圈并附加到結果中。
如果您還可以在此處包含您想要的結果,那將很有幫助,因為目前尚不清楚。
uj5u.com熱心網友回復:
我正在使用 LibremsAPI 庫從 LibreNMS 讀取資料
常規 GET 請求如下所示:
ip_list []
for device in lnms.devices.all():
ip_list.append(device.ip)
name_list []
for device in lnms.devices.all():
ip_list.append(device.sysName)
因此,為了不必對我需要的 api 請求進行每一個變體,我們的想法是有一個“串列”函式。
uj5u.com熱心網友回復:
我是 Python 的新手,從上面的文字中可以看出我沒有很好地解釋自己,所以這是我試圖讓事情更清楚的嘗試。
命令“lnms_device_names = get_data(lnms.devices.all(), 'sysName')”
原始嘗試:
def get_data(devices, key):
response = []
for device in devices:
response.append(device.key)
return response
# => Endpoint devices/29/key does not exists
def get_data(devices, key):
response = []
for device in devices:
response.append(f'device.{key}')
return response
# => ['device.sysName', 'device.sysName', 'device.sysName', 'device.sysName']
在此執行緒中使用建議失敗的嘗試:
def get_data(devices, key):
return [device[key] for device in devices]
# => TypeError: 'LibreNMSEndpoint' object is not subscriptable
def get_data(devices, key):
response = []
for device in devices:
response.append(device[key])
return response
# => TypeError: 'LibreNMSEndpoint' object is not subscriptable
def get_data(devices, key):
response = []
for device in devices:
response.append(f'{device}.{key}') # same result with f'{str(device)}.{key}'
return response
# => full data dump no filtering by key
不使用任何功能時的外觀
#WORKS:
lnms_device_names = []
for device in lnms.devices.all():
lnms_device_names.append(device.sysName)
# => ['dc2-h1-ipn03', 'dc2-h1-spine1', 'dc2-h1-spine2', 'dc2-h1-leaf1']
資料結構:
{
"device_id": 1,
"inserted": "2022-08-15 15:50:33",
"hostname": "172.21.142.10",
"sysName": "dc2-h1-ipn03",
"display": null,
"ip": "",
"overwrite_ip": null,
"community": "xxxxxxx",
"authlevel": null,
"authname": null,
"authpass": null,
"authalgo": null,
"cryptopass": null,
"cryptoalgo": null,
"snmpver": "v2c",
"port": 161,
"transport": "udp",
"timeout": null,
"retries": null,
"snmp_disable": 0,
"bgpLocalAs": 1,
"sysObjectID": ".1.3.6.1.4.1.9.12.3.1.3.1812",
"sysDescr": "Cisco NX-OS(tm) nxos.7.0.3.I7.9.bin, Software (nxos), Version 7.0(3)I7(9), RELEASE SOFTWARE Copyright (c) 2002-2020 by Cisco Systems, Inc. Compiled 8/27/2020 4:00:00",
"sysContact": null,
"version": "7.0(3)I7(9)",
"hardware": "N9K-C93180YC-EX",
"features": null,
"location_id": 1,
"os": "nxos",
"status": 1,
"status_reason": "",
"ignore": 0,
"disabled": 0,
"uptime": 47671869,
"agent_uptime": 0,
"last_polled": "2022-11-02 15:28:35",
"last_poll_attempted": null,
"last_polled_timetaken": 8.46,
"last_discovered_timetaken": 293.18,
"last_discovered": "2022-11-02 12:05:18",
"last_ping": "2022-11-02 15:31:02",
"last_ping_timetaken": 1.83,
"purpose": null,
"type": "network",
"serial": "xxxxxx",
"icon": "cisco.svg",
"poller_group": 0,
"override_sysLocation": 0,
"notes": null,
"port_association_mode": 1,
"max_depth": 0,
"disable_notify": 0,
"dependency_parent_id": null,
"dependency_parent_hostname": null,
"location": "xxxxx",
"lat": 64.132453,
"lng": -21.877419
},
{
"device_id": 2,
....
....
uj5u.com熱心網友回復:
據我了解,您想撰寫一個函式,這樣您就不必重復for
ip_list = []
for device in lnms.devices.all():
ip_list.append(device.ip)
name_list = []
for device in lnms.devices.all():
ip_list.append(device.sysName)
首先,在您的代碼中,您將list其用作不應該導致list內置關鍵字的變數。
此評論解釋了為什么您的代碼不起作用
這就是它的作業方式
def get_data(devices, attr):
response = []
for device in devices:
response.append(getattr(device, attr))
return response
甚至更短的使用串列理解
def get_data(devices, attr):
return [getattr(device, attr) for device in devices]
然后你可以做
ip_list = []
ip_list = get_data(lnms.devices.all(), 'ip')
name_list = []
name_list = get_data(lnms.devices.all(), 'sysName')
如果你不想重復lnms.devices.all()
你可以撰寫如下函式
def get_data_from_devices(attr):
response = []
for device in lnms.devices.all():
response.append(getattr(device, attr))
return response
或者使用串列理解
def get_data_from_devices(attr):
return [getattr(device, attr) for device in lnms.devices.all()]
然后你會稱它們為
ip_list = []
ip_list = get_data_from_devices('ip')
name_list = []
name_list = get_data_from_devices('sysName')
PS:需要更好的函式名稱
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/526588.html
標籤:Pythonapi
上一篇:呼叫電報api洗掉換行符
