以下是我的库中用于处理API的片段。我很好奇一种替代(可能更干净)或更pythonic的方式来编写我的filter_entries函数。
def json_from_url(url):
from urllib2 import urlopen
import json
response = urlopen(url)
data = response.read().decode("utf-8")
return json.loads(data)
class netdb:
""" Class construct for portal"""
def __init__(self, url):
self.json = json_from_url(url)
def filter_entries(self, names=[], sites=[], regions=[], vendors=[], models=[], live=True, output='json'):
""" Function to pull devices down from portalAPI based off filters """
netdbDevices = dict(self.json)
if names: netdbDevices['objects'] = [device for device in netdbDevices['objects'] if device['name'] in names]
if sites: netdbDevices['objects'] = [device for device in netdbDevices['objects'] if device['site']['dns_prefix'] in sites]
if models: netdbDevices['objects'] = [device for device in netdbDevices['objects'] if device['name'].split("-")[0] in models]
if vendors: netdbDevices['objects'] = [device for device in netdbDevices['objects'] if device['vendor']['name'] in vendors]
if regions: netdbDevices['objects'] = [device for device in netdbDevices['objects'] if get_region_name(device['site']['dns_prefix']) in regions]
if live == True: netdbDevices['objects'] = [device for device in netdbDevices['objects'] if device['status'] == 1]
if output == 'json':
return netdbDevices
if output == 'hostname':
hostnames = []
for each in netdbDevices['objects']:
hostnames.append( '%s.%s' % (each['name'], each['site']['dns_prefix']) )
return hostnames
任何帮助都将不胜感激。
答案 0 :(得分:0)
代码看起来很好(除了最后3行需要缩进)并且因为你说它有效,所以这是codereview堆栈的问题。我可以考虑改变它的唯一方法是在列表推导中干掉极少量的重复逻辑,但实际上这是一个品味问题。由于我的个人品味适用于功能,我可能会写:
def FilterDevices(netdbDevices, values, getter):
if values:
netdbDevices['objects'] = [device for device in netdbDevices['objects'] if getter(device) in values]
FilterDevices(netdbDevices, names, lambda device: device['name'])
FilterDevices(netdbDevices, sites, lambda device: device['site']['dns_prefix'])
FilterDevices(netdbDevices, models, lambda device: device['name'].split("-")[0])
FilterDevices(netdbDevices, vendors, lambda device: device['vendor']['name'])
FilterDevices(netdbDevices, regions, lambda device: get_region_name(device['site']['dns_prefix']))
FilterDevices(netdbDevices, [1] if live else [], lambda device: device['status'])