[英]python to print item in list from a json post
我正在運行 Python 3.7 Flask RestFul 我有數據以 json 格式發布到我的 api Flask 應用程序。 我收到的數據如下所示:
{'username': 'admin', 'password': 'mypassword', 'host': [{'address': '192.168.2.5', 'config': 'set system host-name device01', 'address': '192.168.2.2', 'config': 'set system host-name device02'}]}
List 'host':最多可以有幾百個設備/ip地址
我需要通過列表解析並僅打印出 IP 地址和配置,因此我需要將其設置為:
192.168.2.5
192.168.2.2
等等......所以我可以通過IP地址列表循環並連接到設備並應用每個設備不同的配置。
我需要的結構作為回報,以便我可以循環並連接到設備 IP 地址,然后應用配置將是...
192.168.2.5
set system host-name device01
192.168.2.2
set system host-name device02
是 IP 地址 = ips 並且配置 = config
我的python代碼在下面...
app = Flask(__name__)
api = Api(app)
class build(Resource):
def post(self):
data = request.get_json(force=True)
print(data)
jobname = data['jobname']
username = data['username']
password = data['password']
configs = []
ips = []
for x in data['host']:
if 'address' in x:
ips.append(x['address'])
elif 'config' in x:
configs.append(x['config'])
commands = zip(ips, configs)
for command in commands:
iplist = '{}'.format(command[0])
print(iplist)
conf = '{}'.format(command[1])
print(conf)
# Connect to Device and load config
dev = Device(host=iplist, user=username, passwd=password)
dev.open()
print("connect to %s " % iplist)
dev.timeout = 600
#print(dev.cli("show version"))
dev.bind(cfg=Config)
dev.cfg.load(conf, format='set', merge=True)
dev.cfg.commit()
dev.close()
api.add_resource(build, '/build')
if __name__ == '__main__':
app.debug = True
app.run(host='0.0.0.0', port=5000)
這假設地址和配置是有序的。 無論是誰給你數據或輸出數據都可以合並地址和配置字典,使這更安全、更簡單。
import gevent
data = request.get_json(force=True)
def execute(username, password, command):
command = command[0]
dev = Device(host=command, user=username, passwd=password)
dev.open()
print("connect to %s " % command)
dev.timeout = 600
print(dev.cli("show version"))
dev.bind(cfg=Config)
dev.cfg.load(command, format='set', merge=True)
dev.cfg.commit()
dev.close()
commands = []
data = {'username': 'admin', 'password': 'mypassword', 'host': [{'address': '192.168.2.5','config': 'set system host-name device01'}, {'address': '192.168.2.2','config': 'set system host-name device02'}]}
username = data['username']
password = data['password']
for x in data['host']:
if 'address' in x:
commands.append((x['address'],x['config']))
threads = [gevent.spawn(execute, username, password, command) for command in commands]
gevent.joinall(threads)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.