stop flask duplicating a loaded variable

后端 未结 2 1211
陌清茗
陌清茗 2021-01-07 10:34

I\'m building a basic cloud infrastructure management site and have a problem with the page that lists virtual machines.

The flask app pulls a list that is generate

相关标签:
2条回答
  • 2021-01-07 10:39

    You need to initialise vm_list with an empty dict. And if a key exists, then append to its list, else set the dict[key] with an empty list. This is done by setdefault.

    Try this:

    def zip_list():
        ...
        vm_list = {}
        for node in driver.list_nodes():
            vm_list.setdefault('vmid', []).append(node.uuid)
            vm_list.setdefault('name', []).append(node.name)
            vm_list.setdefault('state', []).append(node.state)
            vm_list.setdefault('platform', []).append(node.platform)
        ...
            myVms = zip(vm_list['name'], vm_list['vmid'], vm_list['platform'], vm_list['state'])
            return myVms
    
    0 讨论(0)
  • 2021-01-07 10:41

    You are close - the variable you actually need to reset each time is not myVms but vm_list, as follows:

    class Node:
        counter = 0
    
        def __init__(self):
            c_str = str(Node.counter)
            self.uuid = "asdf" + c_str
            self.name = "test " + c_str
            self.state = "wow " + c_str + " such state"
            Node.counter += 1
    
    
    class Driver:
        def __init__(self, number_of_nodes):
            self.nodes = []
            for x in range(number_of_nodes):
                self.nodes.append(Node())
            self.name = "the greatest driver"
    
        def list_nodes(self) -> list:
            return self.nodes
    
    
    driver = Driver(10)
    
    
    def zip_list():
        vm_list = {'vmid': [], 'name': [], 'state': [], 'platform': []}
        for node in driver.list_nodes():
            vm_list["vmid"].append(node.uuid)
            vm_list["name"].append(node.name)
            vm_list["state"].append(node.state)
            vm_list["platform"].append(driver.name)
    
        myVms = zip(vm_list['name'], vm_list['vmid'], vm_list['platform'], vm_list['state'])
        return myVms
    
    
    print("First time:")
    
    my_list = zip_list()
    for i in my_list:
        print(i)
    
    print("Second time:")
    
    my_list = zip_list()
    for i in my_list:
        print(i)
    

    If you initialise vm_list outside of the zip_list() function instead, you will see the doubling up that you are experiencing.

    0 讨论(0)
提交回复
热议问题