繁体   English   中英

python从json帖子打印列表中的项目

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM