主要的目的
1、函数
2、文件处理
3、tag的用法
4、程序的解耦
实现代码
#!/usr/bin/python3
import os
def file_handler(backend_data, res = None,type = 'fetch'):
if type == 'fetch':
with open('haproxy.conf', 'r') as f:
tag = False
ret = []
for line in f:
if line.strip() == backend_data:
tag = True
continue
if line.startswith('backend'): break
if tag:
print('\033[1;45m%s\n\033[0m' % line.strip(), end='')
ret.append(line)
return ret
elif type == 'change':
with open('haproxy.conf', 'r') as read_f, \
open('haproxy.conf_new', 'w') as write_f:
tag = False
has_write = False
for read_line in read_f: # server
if read_line.startswith('backend'):
tag = False
if read_line.strip() == backend_data:
tag = True
continue
if not tag:
write_f.write(read_line)
else:
if not has_write:
for record in res:
write_f.write(record)
has_write = True
os.rename('haproxy.conf', 'haproxy.conf.bak')
os.rename('haproxy.conf_new', 'haproxy.conf')
os.remove('haproxy.conf.bak')
def fetch(data):
print('查询功能')
print('\033[1;43m用户数据是\033[0m',data)
backend_data = 'backend %s'%(data)
return file_handler(backend_data)
def add():
pass
# [{'backend':'www.oldboy1.org','record':{'server':'2.2.2.4','weight':20,'maxconn':3000}},{'backend':'www.oldboy1.org','record':{'server':'2.2.2.5','weight':30,'maxconn':4000}}]
def change(data):
print('这是修改功能')
backend = data[0]['backend'] #文件中的一条记录 www.oldboy1.org
backend_data = 'backend %s'%backend #backend www.oldboy1.org
# 原数据格式 server 101.1000.7.9 101.1000.7.9 weight 20 maxconn 30
old_server_record = '%s server %s %s weight %s maxconn %s\n'%(' '* 7,data[0]['record']['server'],
data[0]['record']['server'],
data[0]['record']['weight'],
data[0]['record']['maxconn'])
new_server_record = '%s server %s %s weight %s maxconn %s\n' % (' ' * 7, data[1]['record']['server'],
data[1]['record']['server'],
data[1]['record']['weight'],
data[1]['record']['maxconn'])
res = fetch(backend) #查询文件中的一条记录
res.insert(0,'%s\n'%backend_data)
print('来自change函数-----> ',res)
if not res or old_server_record not in res:
return '你要修改的记录不存在'
else:
index = res.index(old_server_record)
res[index] = new_server_record
file_handler(backend_data, res = res, type = 'change')
def delete():
pass
#[{'backend':'www.oldboy1.org','record':{'server':'2.2.2.5','weight':30,'maxconn':4000}},{'backend':'www.oldboy1.org','record':{'server':'2.2.2.4','weight':20,'maxconn':3000}}]
#执行的功能,测试代码在这下面下
if __name__ == '__main__':
msg = """
1:查询
2:添加
3:修改
4:删除
5:退出
"""
msg_dict = {'1':fetch,
'2':add,
'3':change,
'4':delete
}
while True:
print(msg)
choice = input('请输入功能:').strip()
if not choice :continue
if choice == '5':break
data =input('请输入你的数据').strip()
#除了查询其他功能都要加一个字符串转对应的数据结构的类型,因为通过input输入的内容是字符串类型的
if choice != '1':
data = eval(data)
res = msg_dict[choice](data)
print(res)
注意:
修改文件名
#首先先添加模块
import os
#将 haproxy.conf 修改为 haproxy.conf.bak,就是修改个文件名
os.rename('haproxy.conf','haproxy.conf.bak') os.rename('haproxy.conf_new','haproxy.conf') os.remove('haproxy.conf.bak')