Python Metamorphosis-2017-4-23

Posted by Warz on Sat, 06 Jul 2019 22:43:36 +0200

My first blog, this is a water test exercise. The dish served this time is Haporxy configuration file operation.

<1> Upper demand:

The specific configuration files are as follows:

 1 global
 2         log 127.0.0.1 local2
 3         daemon
 4         maxconn 256
 5         log 127.0.0.1 local2 info
 6 defaults
 7         log global
 8         mode http
 9         timeout connect 5000ms
10         timeout client 50000ms
11         timeout server 50000ms
12         option  dontlognull
13 
14 listen stats :8888
15         stats enable
16         stats uri       /admin
17         stats auth      admin:1234
18 
19 frontend oldboy.org
20         bind 0.0.0.0:80
21         option httplog
22         option httpclose
23         option  forwardfor
24         log global
25         acl www hdr_reg(host) -i www.oldboy.org
26         use_backend www.oldboy.org if www
27 
28 backend www.oldboy.org
29         server 100.1.7.9 weight 20 maxconn 3000

 

< 2 > Analytical needs:

1. Display the main information in the configuration file, which is the data after "backend".

2. The operation of adding, deleting and modifying data.

3. Make backup after each operation.

< 3 > Functional analysis:

1. Read configuration files and intercept useful data for printing.

2. It has the function of adding, deleting, modifying and checking, where there is user input, so it is necessary to make a judgment to prevent the program from crashing due to incorrect input.

3. Stitching the data after operation with the original irrelevant data and writing it into the configuration file

<4> Complete code:

  1 #--------------------------Haporxy Configuration file operation--------------------------------------
  2 #py3.4                            by:Yu Fan                                 2017-4-23
  3 #----------------------------------------------Read files to process data(Return to the dictionary Info{})-------
  4 def Deal_file():
  5     s = ""
  6     Info = {}
  7     with open("configuration file.txt","r") as f:
  8         for i in f:
  9             if i.startswith("backend"):
 10                 backend = i.strip().split(" ")[1]
 11                 Info[backend] = []
 12             elif i.strip().startswith("server"):
 13                 server = i.strip().split(" ")[1]
 14                 weight = i.strip().split(" ")[3]
 15                 maxconn = i.strip().split(" ")[5]
 16                 Server = {"server":server,"weight":weight,"maxconn":maxconn}
 17                 Info[backend].append(Server)
 18             else:
 19                 continue
 20     return Info
 21 #----------------------------------------------Information Preservation-----------------------------
 22 def Save_Info(Info):
 23     s = ""
 24     with open("configuration file.txt","r") as f:
 25         for i in f:
 26             if not i.startswith("backend"):
 27                 s = s + i
 28             else:
 29                 break
 30     s1 = ""
 31     for backend in Info:
 32         s2 = "backend " + backend
 33         s1 = s1 + s2 + "\n"
 34         for di in Info[backend]:
 35             server = di["server"]
 36             weight = di["weight"]
 37             maxconn = di["maxconn"]
 38             s3 = "      server {} weight {} maxconn {}".format(server,weight,maxconn)
 39             s1 = s1 + s3 + "\n"
 40     S = s + s1
 41     with open("configuration file.txt","w+") as F:
 42         F.write(S)
 43     return(S)
 44 #----------------------------------------------Display information, return instructions---------------------
 45 def Show(Info):
 46     show_list = []
 47     print("--------------------""\033[1;31;0m""HaProxy Configuration file management""\033[0m""-------------------------------")
 48     for i,n in enumerate(Info):
 49         show_list.append(n)
 50         print("\033[1;32;0m",i+1,n,"\033[0m")
 51     print("------------------------------------------------------------------------")
 52     order = input("Please enter instructions( A)New construction,.( D)Delete,( M)Amendment( C)Queries,( Q)Sign out:")
 53     while order not in ("A","D","M","C","Q"):
 54         order = input("\033[1;31;0m""Input error, please re-enter:""\033[0m")
 55     show_list = list(show_list)
 56     return order,show_list
 57 #----------------------------------------------Backend Number Input Judgment-------------------
 58 def Jude(choice,show_list):
 59     try:
 60         if eval(choice) not in range(len(show_list)+1):
 61             return True
 62         else:return False
 63     except:
 64         return True
 65 #----------------------------------------------Server Number Judgment-----------------------
 66 def JudeS(choiceS,a):
 67     try:
 68         if int(choiceS) in range(1,a+1) or int(choiceS) == 1:
 69             return False
 70         else:
 71             return True
 72     except:
 73         return True
 74 #----------------------------------------------Additional Information Judgment--------------------------
 75 def JudeA(backend,weight,maxconn):
 76     try:
 77         if backend.startswith("www") and int(weight) in range(50) and int(maxconn) in range(5000):
 78             return False
 79     except:
 80         return True
 81 #----------------------------------------------query---------------------------------
 82 def Check(show_list):
 83     choice = input("Please choose backend: ")
 84     while Jude(choice,show_list):
 85         choice = input("\033[1;31;0m""Input error, please re-enter:""\033[0m")
 86     choice = int(choice)
 87     print("------------------------------",show_list[choice-1],"------------------------------")
 88     for a,b in enumerate(Info[show_list[choice-1]]):
 89             print("{} server:{}     weight:{}   maxconn:{}".format(a+1,b["server"],b["weight"],b["maxconn"]))
 90     print("----------------------------------------------------------------------------")
 91     select = input("Please enter instructions( Q)Withdrawal,( B)Return:")
 92     while select not in ("Q","B"):
 93         select = input("\033[1;31;0m""Please enter the correct instruction:""\033[0m")
 94     if select == "Q":
 95         pass
 96     elif select == "B":
 97         main()
 98 #----------------------------------------------delete---------------------------------
 99 def Delete(show_list):
100     choice = input("delete Backend(B) or  Server(S)?: ")
101     while(choice not in ("B","S")):
102         choice = input("\033[1;31;0m""Please enter the correct instruction:""\033[0m")
103     selection = input("Please choose Backend No.")
104     while Jude(selection,show_list):
105         selection = input("\033[1;31;0m""Please enter the correct number:""\033[0m")
106     selection = int(selection)
107     if choice =="B":
108         del Info[show_list[selection-1]]
109         Save_Info(Info)
110         print("\033[1;31;0m""Delete successfully!""\033[0m")
111         main()
112     elif choice == "S":
113         print("------------------------------",show_list[selection-1],"------------------------------")
114         for a,b in enumerate(Info[show_list[selection-1]]):
115             print("{} server:{}     weight:{}   maxconn:{}".format(a+1,b["server"],b["weight"],b["maxconn"]))
116         print("----------------------------------------------------------------------------")
117         choiceS = input("Select what to delete Server:")
118         while JudeS(choiceS,a):
119             choiceS = input("\033[1;31;0m""Please enter the correct number:""\033[0m")
120         choiceS = int(choiceS)
121         Info[show_list[selection-1]].pop(choiceS-1)
122         Save_Info(Info)
123         print("\033[1;31;0m""Delete successfully!""\033[0m")
124         main()
125 #----------------------------------------------increase---------------------------------
126 def Add():
127     print("-->Please enter details.<--")
128     backend = input("Backend Name:")
129     server = input("Server Name:")
130     weight = input("weight(weight): ")
131     maxconn = input("Maximum number of links(maxconn):")
132     while JudeA(backend,weight,maxconn):
133         print("\033[1;31;0m""Input information error, please re-enter!!!""\033[0m")
134         Add()
135     if backend not in Info:
136         Info[backend] = [{"server":server,"weight":weight,"maxconn":maxconn}]
137         print(">>>>>Successful new construction")
138     else:
139         flag = 1
140         for ser in Info[backend]:
141             if server == ser["server"]:
142                 flag = 0
143                 ser["weight"] = weight
144                 ser["maxconn"] = maxconn
145                 print(">>>>>backend and server Information already exists.""\033[1;31;0m""server Information has been modified""\033[0m")
146         if flag:
147             Info[backend].append({"server":server,"weight":weight,"maxconn":maxconn})
148             print(">>>>>backend It already exists.""\033[1;31;0m""server Added Successfully""\033[0m")
149     Save_Info(Info)
150     main()
151 #----------------------------------------------modify---------------------------------
152 def Modify(show_list):
153     selection = input("modify backend(B)  or  server(S)?>")
154     while (selection not in ("B","S")):
155         selection = input("\033[1;31;0m""Please enter the correct answer.:""\033[0m")
156     choice = input("Please enter what you want to modify. backend number:")
157     while Jude(choice,show_list):
158         choice = input("\033[1;31;0m""Please enter the correct number.:""\033[0m")
159     choice = int(choice)
160     if selection == "B":
161         backend = input("modify backend The name is:")
162         while not backend.startswith("www"):
163             backend = input("\033[1;31;0m""Please enter legitimate backend Name:""\033[0m")
164         temp = Info[show_list[choice-1]]
165         del Info[show_list[choice-1]]
166         Info[backend] = temp
167         Save_Info(Info)
168         print("\033[1;31;0m""modify backend Success""\033[0m")
169         main()
170     else:
171         print("------------------------------",show_list[choice-1],"------------------------------")
172         for a,b in enumerate(Info[show_list[choice-1]]):
173             print("{} server:{}     weight:{}   maxconn:{}".format(a+1,b["server"],b["weight"],b["maxconn"]))
174         print("----------------------------------------------------------------------------")
175         selection = input("Which to modify? server?>")
176         while JudeS(selection,a):
177             selection = input("\033[1;31;0m""Please enter the correct one. server number:""\033[0m")
178         selection = int(selection)
179         sername = input("modify server For:")
180         Info[show_list[choice-1]][a-1]["server"] = sername
181         Save_Info(Info)
182         print("\033[1;31;0m""modify server Success""\033[0m")
183         main()
184 #----------------------------------------------Instruction Processing------------------------------
185 def Deal_order(order,show_list):
186     if order =="Q":          #Sign out
187         pass
188     elif order =="A"  :      #Newly build
189         Add()
190     elif order == "D":       #delete
191         Delete(show_list)
192     elif order == "M":       #modify
193         Modify(show_list)
194     elif order == "C":
195         Check(show_list)
196     else:
197         order = input("\033[1;31;0m""Input error, please re-enter:""\033[0m")
198         Deal_order(order,show_list)
199 #----------------------------------------------Principal function--------------------------------
200 def main():
201     order,show_list = Show(Info)
202     Deal_order(order,show_list)
203 if __name__=="__main__":
204     Info = Deal_file()
205     main()

<5> Processing flow:

 

The main functions of <6> are introduced.

Deal_file(): Read the configuration file, intercept the operation data, find the interception position through String.startswith() to get the data, and return to the dictionary form.

 1 def Deal_file():
 2     s = ""
 3     Info = {}
 4     with open("configuration file.txt","r") as f:
 5         for i in f:
 6             if i.startswith("backend"):
 7                 backend = i.strip().split(" ")[1]
 8                 Info[backend] = []
 9             elif i.strip().startswith("server"):
10                 server = i.strip().split(" ")[1]
11                 weight = i.strip().split(" ")[3]
12                 maxconn = i.strip().split(" ")[5]
13                 Server = {"server":server,"weight":weight,"maxconn":maxconn}
14                 Info[backend].append(Server)
15             else:
16                 continue
17     return Info

2.Save_Info(): Save the data after operation and the original irrelevant data, and receive the dictionary as a parameter.

 1 def Save_Info(Info):
 2     s = ""
 3     with open("configuration file.txt","r") as f:
 4         for i in f:
 5             if not i.startswith("backend"):
 6                 s = s + i
 7             else:
 8                 break
 9     s1 = ""
10     for backend in Info:
11         s2 = "backend " + backend
12         s1 = s1 + s2 + "\n"
13         for di in Info[backend]:
14             server = di["server"]
15             weight = di["weight"]
16             maxconn = di["maxconn"]
17             s3 = "      server {} weight {} maxconn {}".format(server,weight,maxconn)
18             s1 = s1 + s3 + "\n"
19     S = s + s1
20     with open("configuration file.txt","w+") as F:
21         F.write(S)
22     return(S)

3.Show (): The data to be operated is printed out to prompt the input operation instructions, the white list judges the input instructions, makes the judgement, and returns the input instructions and the print list.

Effect:

 1 def Show(Info):
 2     show_list = []
 3     print("--------------------""\033[1;31;0m""HaProxy Configuration file management""\033[0m""-------------------------------")
 4     for i,n in enumerate(Info):
 5         show_list.append(n)
 6         print("\033[1;32;0m",i+1,n,"\033[0m")
 7     print("------------------------------------------------------------------------")
 8     order = input("Please enter instructions( A)New construction,.( D)Delete,( M)Amendment( C)Queries,( Q)Sign out:")
 9     while order not in ("A","D","M","C","Q"):
10         order = input("\033[1;31;0m""Input error, please re-enter:""\033[0m")
11     show_list = list(show_list)
12     return order,show_list

4.Jude (), JudeA () and JudeS () respectively make simple judgments on the input backend number, server number and new data information.

 1 #----------------------------------------------Backend Number Input Judgment-------------------
 2 def Jude(choice,show_list):
 3     try:
 4         if eval(choice) not in range(len(show_list)+1):
 5             return True
 6         else:return False
 7     except:
 8         return True
 9 #----------------------------------------------Server Number Judgment-----------------------
10 def JudeS(choiceS,a):
11     try:
12         if int(choiceS) in range(1,a+1) or int(choiceS) == 1:
13             return False
14         else:
15             return True
16     except:
17         return True
18 #----------------------------------------------Additional Information Judgment--------------------------
19 def JudeA(backend,weight,maxconn):
20     try:
21         if backend.startswith("www") and int(weight) in range(50) and int(maxconn) in range(5000):
22             return False
23     except:
24         return True

5.Deal_order (): Accepts the return value from Show (), and shunts the input instructions to different functions.

 1 def Deal_order(order,show_list):
 2     if order =="Q":          #Sign out
 3         pass
 4     elif order =="A"  :      #Newly build
 5         Add()
 6     elif order == "D":       #delete
 7         Delete(show_list)
 8     elif order == "M":       #modify
 9         Modify(show_list)
10     elif order == "C":
11         Check(show_list)
12     else:
13         order = input("\033[1;31;0m""Input error, please re-enter:""\033[0m")
14         Deal_order(order,show_list)

6.Check (): Query, mainly look at the server information under backend.

Effect:

 1 #----------------------------------------------query---------------------------------
 2 def Check(show_list):
 3     choice = input("Please choose backend: ")
 4     while Jude(choice,show_list):
 5         choice = input("\033[1;31;0m""Input error, please re-enter:""\033[0m")
 6     choice = int(choice)
 7     print("------------------------------",show_list[choice-1],"------------------------------")
 8     for a,b in enumerate(Info[show_list[choice-1]]):
 9             print("{} server:{}     weight:{}   maxconn:{}".format(a+1,b["server"],b["weight"],b["maxconn"]))
10     print("----------------------------------------------------------------------------")
11     select = input("Please enter instructions( Q)Withdrawal,( B)Return:")
12     while select not in ("Q","B"):
13         select = input("\033[1;31;0m""Please enter the correct instruction:""\033[0m")
14     if select == "Q":
15         pass
16     elif select == "B":
17         main()

7.Add (): New, you can create a new backend, if it already exists, you can create a new server information under the backend, and if both exist, you can modify the server information.

 1 #----------------------------------------------increase---------------------------------
 2 def Add():
 3     print("-->Please enter details.<--")
 4     backend = input("Backend Name:")
 5     server = input("Server Name:")
 6     weight = input("weight(weight): ")
 7     maxconn = input("Maximum number of links(maxconn):")
 8     while JudeA(backend,weight,maxconn):
 9         print("\033[1;31;0m""Input information error, please re-enter!!!""\033[0m")
10         Add()
11     if backend not in Info:
12         Info[backend] = [{"server":server,"weight":weight,"maxconn":maxconn}]
13         print(">>>>>Successful new construction")
14     else:
15         flag = 1
16         for ser in Info[backend]:
17             if server == ser["server"]:
18                 flag = 0
19                 ser["weight"] = weight
20                 ser["maxconn"] = maxconn
21                 print(">>>>>backend and server Information already exists.""\033[1;31;0m""server Information has been modified""\033[0m")
22         if flag:
23             Info[backend].append({"server":server,"weight":weight,"maxconn":maxconn})
24             print(">>>>>backend It already exists.""\033[1;31;0m""server Added Successfully""\033[0m")
25     Save_Info(Info)
26     main()

8.Delete (): Delete, you can delete backend or Server information.

Effect:

 

 1 #----------------------------------------------delete---------------------------------
 2 def Delete(show_list):
 3     choice = input("delete Backend(B) or  Server(S)?: ")
 4     while(choice not in ("B","S")):
 5         choice = input("\033[1;31;0m""Please enter the correct instruction:""\033[0m")
 6     selection = input("Please choose Backend No.")
 7     while Jude(selection,show_list):
 8         selection = input("\033[1;31;0m""Please enter the correct number:""\033[0m")
 9     selection = int(selection)
10     if choice =="B":
11         del Info[show_list[selection-1]]
12         Save_Info(Info)
13         print("\033[1;31;0m""Delete successfully!""\033[0m")
14         main()
15     elif choice == "S":
16         print("------------------------------",show_list[selection-1],"------------------------------")
17         for a,b in enumerate(Info[show_list[selection-1]]):
18             print("{} server:{}     weight:{}   maxconn:{}".format(a+1,b["server"],b["weight"],b["maxconn"]))
19         print("----------------------------------------------------------------------------")
20         choiceS = input("Select what to delete Server:")
21         while JudeS(choiceS,a):
22             choiceS = input("\033[1;31;0m""Please enter the correct number:""\033[0m")
23         choiceS = int(choiceS)
24         Info[show_list[selection-1]].pop(choiceS-1)
25         Save_Info(Info)
26         print("\033[1;31;0m""Delete successfully!""\033[0m")
27         main()

9.Modify (): Modify, modify backend or Server information.

Effect:

 

 1 def Modify(show_list):
 2     selection = input("modify backend(B)  or  server(S)?>")
 3     while (selection not in ("B","S")):
 4         selection = input("\033[1;31;0m""Please enter the correct answer.:""\033[0m")
 5     choice = input("Please enter what you want to modify. backend number:")
 6     while Jude(choice,show_list):
 7         choice = input("\033[1;31;0m""Please enter the correct number.:""\033[0m")
 8     choice = int(choice)
 9     if selection == "B":
10         backend = input("modify backend The name is:")
11         while not backend.startswith("www"):
12             backend = input("\033[1;31;0m""Please enter legitimate backend Name:""\033[0m")
13         temp = Info[show_list[choice-1]]
14         del Info[show_list[choice-1]]
15         Info[backend] = temp
16         Save_Info(Info)
17         print("\033[1;31;0m""modify backend Success""\033[0m")
18         main()
19     else:
20         print("------------------------------",show_list[choice-1],"------------------------------")
21         for a,b in enumerate(Info[show_list[choice-1]]):
22             print("{} server:{}     weight:{}   maxconn:{}".format(a+1,b["server"],b["weight"],b["maxconn"]))
23         print("----------------------------------------------------------------------------")
24         selection = input("Which to modify? server?>")
25         while JudeS(selection,a):
26             selection = input("\033[1;31;0m""Please enter the correct one. server number:""\033[0m")
27         selection = int(selection)
28         sername = input("modify server For:")
29         Info[show_list[choice-1]][a-1]["server"] = sername
30         Save_Info(Info)
31         print("\033[1;31;0m""modify server Success""\033[0m")
32         main()

Topics: Python