stop flask duplicating a loaded variable

后端 未结 2 1210
陌清茗
陌清茗 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: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.

提交回复
热议问题