Python蜕变-2017-4-23
我的第一篇博客,这是试水练习。这次上的菜是Haporxy配置文件操作。
<1> 上需求:
具体配置文件如下:
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
View Code
<2>分析需求:
1.将配置文件中的主要信息也就是“backend”后的数据展示出来。
2.能够对数据进行增删改查的操作。
3.每次操作后进行备份。
<3>功能分析:
1.读取配置文件并截取有用数据打印。
2.具备增删改查功能,在此有用户输入,所以有必要进行判断,防止错误输入导致程序崩溃。
3.将操作后的数据与原始的无关数据进行拼接写入配置文件
<4>完整代码:
1 #--------------------------Haporxy配置文件操作-------------------------------------- 2 #py3.4 by:羽凡 2017-4-23 3 #----------------------------------------------读取文件处理数据(返回字典Info{})------- 4 def Deal_file(): 5 s = "" 6 Info = {} 7 with open("配置文件.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 #----------------------------------------------信息保存----------------------------- 22 def Save_Info(Info): 23 s = "" 24 with open("配置文件.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("配置文件.txt","w+") as F: 42 F.write(S) 43 return(S) 44 #----------------------------------------------展示信息,返回指令--------------------- 45 def Show(Info): 46 show_list = [] 47 print("--------------------""\033[1;31;0m""HaProxy配置文件管理""\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("请输入指令(A)新建、(D)删除、(M)修改、(C)查询、(Q)退出:") 53 while order not in ("A","D","M","C","Q"): 54 order = input("\033[1;31;0m""输入错误,请重新输入:""\033[0m") 55 show_list = list(show_list) 56 return order,show_list 57 #----------------------------------------------Backend编号输入判断------------------- 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编号判断----------------------- 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 #----------------------------------------------新增信息判断-------------------------- 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 #----------------------------------------------查询--------------------------------- 82 def Check(show_list): 83 choice = input("请选择backend:") 84 while Jude(choice,show_list): 85 choice = input("\033[1;31;0m""输入错误,请重新输入:""\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("请输入指令(Q)退出、(B)返回:") 92 while select not in ("Q","B"): 93 select = input("\033[1;31;0m""请输入正确指令:""\033[0m") 94 if select == "Q": 95 pass 96 elif select == "B": 97 main() 98 #----------------------------------------------删除--------------------------------- 99 def Delete(show_list): 100 choice = input("删除Backend(B) or Server(S)?:") 101 while(choice not in ("B","S")): 102 choice = input("\033[1;31;0m""请输入正确的指令:""\033[0m") 103 selection = input("请选择Backend编号:") 104 while Jude(selection,show_list): 105 selection = input("\033[1;31;0m""请输入正确的编号:""\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""删除成功!""\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("选择要删除的Server:") 118 while JudeS(choiceS,a): 119 choiceS = input("\033[1;31;0m""请输入正确的编号:""\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""删除成功!""\033[0m") 124 main() 125 #----------------------------------------------增加--------------------------------- 126 def Add(): 127 print("————>请输入详细信息<————") 128 backend = input("Backend名称:") 129 server = input("Server名称:") 130 weight = input("权重(weight):") 131 maxconn = input("最大链接数(maxconn):") 132 while JudeA(backend,weight,maxconn): 133 print("\033[1;31;0m""输入信息错误,请重新输入!!!""\033[0m") 134 Add() 135 if backend not in Info: 136 Info[backend] = [{"server":server,"weight":weight,"maxconn":maxconn}] 137 print(">>>>>新建成功") 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及server信息已存在,""\033[1;31;0m""server信息已修改""\033[0m") 146 if flag: 147 Info[backend].append({"server":server,"weight":weight,"maxconn":maxconn}) 148 print(">>>>>backend已存在,""\033[1;31;0m""server添加成功""\033[0m") 149 Save_Info(Info) 150 main() 151 #----------------------------------------------修改--------------------------------- 152 def Modify(show_list): 153 selection = input("修改backend(B) or server(S)?>") 154 while (selection not in ("B","S")): 155 selection = input("\033[1;31;0m""请输入正确回答:""\033[0m") 156 choice = input("请输入要修改的backend编号:") 157 while Jude(choice,show_list): 158 choice = input("\033[1;31;0m""请输入正确编号:""\033[0m") 159 choice = int(choice) 160 if selection == "B": 161 backend = input("修改backend名称为:") 162 while not backend.startswith("www"): 163 backend = input("\033[1;31;0m""请输入合法的backend名称:""\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""修改backend成功""\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("修改哪个server?>") 176 while JudeS(selection,a): 177 selection = input("\033[1;31;0m""请输入正确的server编号:""\033[0m") 178 selection = int(selection) 179 sername = input("修改server为:") 180 Info[show_list[choice-1]][a-1]["server"] = sername 181 Save_Info(Info) 182 print("\033[1;31;0m""修改server成功""\033[0m") 183 main() 184 #----------------------------------------------指令处理------------------------------ 185 def Deal_order(order,show_list): 186 if order =="Q": #退出 187 pass 188 elif order =="A" : #新建 189 Add() 190 elif order == "D": #删除 191 Delete(show_list) 192 elif order == "M": #修改 193 Modify(show_list) 194 elif order == "C": 195 Check(show_list) 196 else: 197 order = input("\033[1;31;0m""输入错误,请重新输入:""\033[0m") 198 Deal_order(order,show_list) 199 #----------------------------------------------主函数-------------------------------- 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()
View Code
<5>处理流程:
<6>主要函数功能介绍:
1.Deal_file():读取配置文件,并截取操作数据,通过String.startswith()找到截取位置获取数据,返回字典形式。
1 def Deal_file(): 2 s = "" 3 Info = {} 4 with open("配置文件.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
View Code
2.Save_Info():将操作后的数据与原始无关数据拼接保存,接收字典作为参数。
1 def Save_Info(Info): 2 s = "" 3 with open("配置文件.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("配置文件.txt","w+") as F: 21 F.write(S) 22 return(S)
View Code
3.Show():将要操作的数据打印出来提示输入操作指令,白名单判断输入指令,进行判断,返回输入指令和打印列表。
效果:
1 def Show(Info): 2 show_list = [] 3 print("--------------------""\033[1;31;0m""HaProxy配置文件管理""\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("请输入指令(A)新建、(D)删除、(M)修改、(C)查询、(Q)退出:") 9 while order not in ("A","D","M","C","Q"): 10 order = input("\033[1;31;0m""输入错误,请重新输入:""\033[0m") 11 show_list = list(show_list) 12 return order,show_list
View Code
4.Jude()、JudeA()、JudeS()分别对输入的backend编号、server编号和新建的数据信息进行简单判断。
1 #----------------------------------------------Backend编号输入判断------------------- 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编号判断----------------------- 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 #----------------------------------------------新增信息判断-------------------------- 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
View Code
5.Deal_order():接受来自Show()的返回值,对输入的指令进行分流给不同的函数处理。
1 def Deal_order(order,show_list): 2 if order =="Q": #退出 3 pass 4 elif order =="A" : #新建 5 Add() 6 elif order == "D": #删除 7 Delete(show_list) 8 elif order == "M": #修改 9 Modify(show_list) 10 elif order == "C": 11 Check(show_list) 12 else: 13 order = input("\033[1;31;0m""输入错误,请重新输入:""\033[0m") 14 Deal_order(order,show_list)
View Code
6.Check():查询,主要查看backend下的server信息。
效果:
1 #----------------------------------------------查询--------------------------------- 2 def Check(show_list): 3 choice = input("请选择backend:") 4 while Jude(choice,show_list): 5 choice = input("\033[1;31;0m""输入错误,请重新输入:""\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("请输入指令(Q)退出、(B)返回:") 12 while select not in ("Q","B"): 13 select = input("\033[1;31;0m""请输入正确指令:""\033[0m") 14 if select == "Q": 15 pass 16 elif select == "B": 17 main()
View Code
7.Add():新建,可以新建backend若已存在则在backend下新建server信息,若两种都存在则修改server信息。
1 #----------------------------------------------增加--------------------------------- 2 def Add(): 3 print("————>请输入详细信息<————") 4 backend = input("Backend名称:") 5 server = input("Server名称:") 6 weight = input("权重(weight):") 7 maxconn = input("最大链接数(maxconn):") 8 while JudeA(backend,weight,maxconn): 9 print("\033[1;31;0m""输入信息错误,请重新输入!!!""\033[0m") 10 Add() 11 if backend not in Info: 12 Info[backend] = [{"server":server,"weight":weight,"maxconn":maxconn}] 13 print(">>>>>新建成功") 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及server信息已存在,""\033[1;31;0m""server信息已修改""\033[0m") 22 if flag: 23 Info[backend].append({"server":server,"weight":weight,"maxconn":maxconn}) 24 print(">>>>>backend已存在,""\033[1;31;0m""server添加成功""\033[0m") 25 Save_Info(Info) 26 main()
View Code
8.Delete():删除,可以删除backend或Server信息。
效果:
1 #----------------------------------------------删除--------------------------------- 2 def Delete(show_list): 3 choice = input("删除Backend(B) or Server(S)?:") 4 while(choice not in ("B","S")): 5 choice = input("\033[1;31;0m""请输入正确的指令:""\033[0m") 6 selection = input("请选择Backend编号:") 7 while Jude(selection,show_list): 8 selection = input("\033[1;31;0m""请输入正确的编号:""\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""删除成功!""\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("选择要删除的Server:") 21 while JudeS(choiceS,a): 22 choiceS = input("\033[1;31;0m""请输入正确的编号:""\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""删除成功!""\033[0m") 27 main()
View Code
9.Modify():修改,修改backend或是Server信息。
效果:
1 def Modify(show_list): 2 selection = input("修改backend(B) or server(S)?>") 3 while (selection not in ("B","S")): 4 selection = input("\033[1;31;0m""请输入正确回答:""\033[0m") 5 choice = input("请输入要修改的backend编号:") 6 while Jude(choice,show_list): 7 choice = input("\033[1;31;0m""请输入正确编号:""\033[0m") 8 choice = int(choice) 9 if selection == "B": 10 backend = input("修改backend名称为:") 11 while not backend.startswith("www"): 12 backend = input("\033[1;31;0m""请输入合法的backend名称:""\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""修改backend成功""\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("修改哪个server?>") 25 while JudeS(selection,a): 26 selection = input("\033[1;31;0m""请输入正确的server编号:""\033[0m") 27 selection = int(selection) 28 sername = input("修改server为:") 29 Info[show_list[choice-1]][a-1]["server"] = sername 30 Save_Info(Info) 31 print("\033[1;31;0m""修改server成功""\033[0m") 32 main()
View Code
转载于:https://www.cnblogs.com/AngelYuFan/p/6752460.html
Python蜕变-2017-4-23相关推荐
- 微课|中学生可以这样学Python(例8.23):快速排序算法
适用教材: 董付国,应根球.<中学生可以这样学Python>.清华大学出版社,2017. 第8章 常用算法的Python实现 例8.23 快速排序算法 京东购买链接:https://i ...
- MxCAD5.2 2017.2.23更新
MxCAD5.2 2017.2.23更新 [2017-03-07 22:24:55] 下载地址: MxCAD软件安装包(64位): http://www.mxcad.net/MxCADx64Setup ...
- 成都市等市、州2009年《工程量清单计价定额》人工费调整批复〔2017〕23
四川省建设工程造价管理总站 川建价发[2017]23号 四川省建设工程造价管理总站 关于对成都市等12个市.州 2009年<四川省建设工程工程量清单计价定额> 人工费调整的批复 各有关市. ...
- 2017第23届河北(石家庄)国际医疗器械展览会会刊(参展商名录)
2017第23届河北(石家庄)国际医疗器械展览会会刊(参展商名录) 展会名称: 2017第23届河北(石家庄)国际医疗器械展览会 所属展馆: 石家庄国际博览中心 开展时间: 2017-03-02 至 ...
- 2017 05 23 Python求1000内的完全数
趁build项目的时间写了昨晚的第一个小作业,可见android build一次项目的时间-_-` #!/usr/bin/env python # coding:utf-8 import sysrel ...
- 面试遇到的 python 问题 -- 2017年 手写代码
1.二维数组中的查找 在一个二维数组中,每一行都按照从左到右递增的顺序排序,每一列都按照从上到下递增的顺序排序.请完成一个函数,输入这样的一个二维数组和一个整数,判断数组中是否含有该整数. # -*- ...
- python转cython_Cython 0.23 发布 Python 的 C 语言扩展
Cython 0.23 发布,此版本相比第二个测试版本改进很小,还有一些 bug 修复. 此版本是个重要的特性版本,值得关注的改进如下: * PEP 492 (async/await) 和 PEP 4 ...
- [2017.3.23]Miller-Rabin
水了一下Miller-Rabin 代码巨水无比--虽然有一定概率出错,但小于0.01(测5组) logn测试素数,很优秀 codevs素数判定2 http://codevs.cn/problem/17 ...
- python split函数 空格_Python随笔29:Python基础编程练习题23~24
注:本文所有代码均经过Python 3.7实际运行检验,保证其严谨性. Python编程 Python基础练习题23:求三角形斜边上的高 输入直角三角形两直角边a.b的值,输出斜边上的高,最后结果使用 ...
- Python 开发者 2017 应该关注的 7 个类库
六月 北京 | 高性能计算之GPU CUDA培训 6月22-24日三天密集式学习 快速带你入门阅读全文> 正文共2613个字,1图,预计阅读时间6分钟. Django 依然是 Python 开 ...
最新文章
- linux shell只读变量、删除变量
- 网站设计大访问量应用的解决方案
- c语言编译 64位,cmake – 编译32位和64位
- 永磁直驱风力发电机结构图_国内首台10MW海上永磁直驱风力发电机研制成功
- ReentrantLock 中的 4 个坑!
- ubuntu mysql lessons
- 小小知识点(三十六)EXCEL闪退解决办法
- IDEA 强大文件对比功能
- 如何将APP安装包发布到360手机助手上
- 2022.10.25 固体物理
- 041-推箱子游戏1
- 使用Wamp在win7上搭WEB服务器
- 安利截图神器:Snipaste
- MYSQL压力测试工具
- 0xfffffff1 lr_CortexM处理器的一些特性记录
- 怎么用python编写记事本_利用Python开发实现简单的记事本
- CodeForces961F- k-substrings(哈希)
- 【读书】你有认真看见过这个世界吗?
- 带保护装置的水塔自动进水装置
- adroid 中公里除时间_广东首条中低速磁浮专线清远旅游专线首期将在9月开始铺轨...
热门文章
- 烧写文件系统——韦东山嵌入式Linux学习笔记11
- C语言再学习 -- 创建excel文件
- UNIX再学习 -- 标准I/O
- C语言再学习 -- 结构和其他数据形式
- 用python内置函数算复杂度吗_番外篇: Python 面试感受
- vscode最好看的主题推荐_新学期,幼儿园环创主题墙及楼道,这样布置最好看!...
- 【译】Persistent reverse (NAT bypassing) SSH tunnel access with autossh
- 卷积神经网络中不同类型的卷积方式介绍
- Android应用安全之Content Provider安全
- 高性能负载均衡设计入门篇