1
これは、APIを扱うための私のライブラリから抜粋したものです。私はfilter_entries関数を書くための代替(潜在的にクリーナー)、またはもっとpythonicな方法について興味があります。ディクショナリのリストをフィルタリングするためのきれいな方法
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
助けてください。
私は大丈夫です。私はすべてのifステートメントを個別に整形して、すべてを整列させて読みやすく(例: '='、 '' if''' in)します。それ以外は、私はあなたを本当に助けることができません。 – ChickenFeet