flag+文件操作
flag标志位,标识位,在其他语言中可能叫开关,个人觉得当作开关更容易理解。下面我们来利用这个开关来控制文件操作的流程,从而优雅的修改配置文件。
global log 127.0.0.1 local2 daemon maxconn 256 log 127.0.0.1 local2 info defaults log global mode http timeout connect 5000ms timeout client 50000ms timeout server 50000ms option dontlognull listen stats :8888 stats enable stats uri /admin stats auth admin:1234 frontend oldboy.org bind 0.0.0.0:80 option httplog option httpclose option forwardfor log global acl www hdr_reg(host) -i www.oldboy.org use_backend www.oldboy.org if www backend www.oldboy.org server 100.1.7.9 100.1.7.9 weight 20 maxconn 3000 原配置文件
我们的需求是:
1、实现fetch获取内容的功能
2、往配置文件中指定位置插入内容的功能
3、删除(或者修改)参数
1、查 输入:www.oldboy.org 获取当前backend下的所有记录 2、新建 输入: arg = { 'bakend': 'www.oldboy.org', 'record':{ 'server': '100.1.7.9', 'weight': 20, 'maxconn': 30 } } 3、删除 输入: arg = { 'bakend': 'www.oldboy.org', 'record':{ 'server': '100.1.7.9', 'weight': 20, 'maxconn': 30 } } 需求
思路梳理:
1)定义fetch()函数,函数内容为打开haproxy配置文件,找到backend开头的行,打开开关,找到第二backend开头的行,关闭开关,将开关开启状态下的行添加到我们定义的空列表中。
def fetch(a): result=[] flag = False with open('ha.conf','r')as f: for line in f: if line.strip()=='backend %s'%a: flag=True continue if flag==True: if line.strip().startswith('backend'): flag=False else: result.append(line.strip()) return result ret=fetch('www.oldboy.org') print(ret)
2)定义add()函数:
方法一:把内容添加进列表,然后把列表内容写入。
# a=input('请输入网址:') # a='www.oldboy.org' # b=input('请输入新纪录字典:') b='{"backend":"www.oldboy.org","record":{"server":"100.1.7.6","weight":20,"maxconn":30}}' b=json.loads(b) a=b["backend"] s=b["record"] s="server %s %s weight %s maxconn %s" % (s['server'],s['server'],s['weight'],s['maxconn']) title='backend %s' % a l1=chaxun(a) l1.append(s) print(l1) with open('mm') as read_obj, open('nn', 'w') as write_obj: flag = False #默认没有找到目标标题 has_write = False #默认列表内容还没有写 for line in read_obj: if line.strip() == title: write_obj.write(line) flag = True #找到标题 continue if flag and line.strip().startswith('backend'): flag = False #标题结束 if flag: #如果已经找到目标标题 if not has_write: #如果还没有写内容 for new_line in l1: temp = "%s %s \n" %(" "*8, new_line) write_obj.write(temp) has_write = True #列表内容书写完毕,即使flag=True,即使没遇到下一个backend,也不会书写内容 else: # 写入上下部分 write_obj.write(line)# a=input('请输入网址:') # a='www.oldboy.org' # b=input('请输入新纪录字典:') b='{"backend":"www.oldboy.org","record":{"server":"100.1.7.6","weight":20,"maxconn":30}}' b=json.loads(b) a=b["backend"] s=b["record"] s="server %s %s weight %s maxconn %s" % (s['server'],s['server'],s['weight'],s['maxconn']) title='backend %s' % a l1=chaxun(a) l1.append(s) print(l1) with open('mm') as read_obj, open('nn', 'w') as write_obj: flag = False #默认没有找到目标标题 has_write = False #默认列表内容还没有写 for line in read_obj: if line.strip() == title: write_obj.write(line) flag = True #找到标题 continue if flag and line.strip().startswith('backend'): flag = False #标题结束 if flag: #如果已经找到目标标题 if not has_write: #如果还没有写内容 for new_line in l1: temp = "%s %s \n" %(" "*8, new_line) write_obj.write(temp) has_write = True #列表内容书写完毕,即使flag=True,即使没遇到下一个backend,也不会书写内容 else: # 写入上下部分 write_obj.write(line)
方法二:读一行,写一行,直到写到第二个backend,再此之前插入内容即可。
# a=input('请输入网址:') # a='www.oldboy.org' # b=input('请输入新纪录字典:') b='{"backend":"www.oldboy.org","record":{"server":"100.1.7.6","weight":20,"maxconn":30}}' b=json.loads(b) a=b["backend"] s=b["record"] s="server %s %s weight %s maxconn %s" % (s['server'],s['server'],s['weight'],s['maxconn']) title='backend %s' % a l1=chaxun(a) l1.append(s) print(l1) with open('mm') as read_obj, open('nn', 'w') as write_obj: flag = False #默认没有找到目标标题 for line in read_obj: if line.strip() == title: write_obj.write(line) flag = True #找到标题 continue if flag and line.strip().startswith('backend'): write_obj.write("%s%s \n" %(" "*8, s)) write_obj.write(line) flag = False #标题结束 else: # 写入上下部分 write_obj.write(line)
整体实现功能,武sir的标准答案:
#!/usr/bin/env python # -*- coding:utf-8 -*- import json import os def fetch(backend): backend_title = 'backend %s' % backend record_list = [] with open('ha') as obj: flag = False for line in obj: line = line.strip() if line == backend_title: flag = True continue if flag and line.startswith('backend'): flag = False break if flag and line: record_list.append(line) return record_list def add(dict_info): backend = dict_info.get('backend') record_list = fetch(backend) backend_title = "backend %s" % backend current_record = "server %s %s weight %d maxconn %d" % (dict_info['record']['server'], dict_info['record']['server'], dict_info['record']['weight'], dict_info['record']['maxconn']) if not record_list: record_list.append(backend_title) record_list.append(current_record) with open('ha') as read_file, open('ha.new', 'w') as write_file: flag = False for line in read_file: write_file.write(line) for i in record_list: if i.startswith('backend'): write_file.write(i+'\n') else: write_file.write("%s%s\n" % (8*" ", i)) else: record_list.insert(0, backend_title) if current_record not in record_list: record_list.append(current_record) with open('ha') as read_file, open('ha.new', 'w') as write_file: flag = False has_write = False for line in read_file: line_strip = line.strip() if line_strip == backend_title: flag = True continue if flag and line_strip.startswith('backend'): flag = False if not flag: write_file.write(line) else: if not has_write: for i in record_list: if i.startswith('backend'): write_file.write(i+'\n') else: write_file.write("%s%s\n" % (8*" ", i)) has_write = True os.rename('ha','ha.bak') os.rename('ha.new','ha') def remove(dict_info): backend = dict_info.get('backend') record_list = fetch(backend) backend_title = "backend %s" % backend current_record = "server %s %s weight %d maxconn %d" % (dict_info['record']['server'], dict_info['record']['server'], dict_info['record']['weight'], dict_info['record']['maxconn']) if not record_list: return else: if current_record not in record_list: return else: del record_list[record_list.index(current_record)] if len(record_list) > 0: record_list.insert(0, backend_title) with open('ha') as read_file, open('ha.new', 'w') as write_file: flag = False has_write = False for line in read_file: line_strip = line.strip() if line_strip == backend_title: flag = True continue if flag and line_strip.startswith('backend'): flag = False if not flag: write_file.write(line) else: if not has_write: for i in record_list: if i.startswith('backend'): write_file.write(i+'\n') else: write_file.write("%s%s\n" % (8*" ", i)) has_write = True os.rename('ha','ha.bak') os.rename('ha.new','ha') if __name__ == '__main__': """ print '1、获取;2、添加;3、删除' num = raw_input('请输入序号:') data = raw_input('请输入内容:') if num == '1': fetch(data) else: dict_data = json.loads(data) if num == '2': add(dict_data) elif num == '3': remove(dict_data) else: pass """ #data = "www.oldboy.org" #fetch(data) #data = '{"backend": "tettst.oldboy.org","record":{"server": "100.1.7.90","weight": 20,"maxconn": 30}}' #dict_data = json.loads(data) #add(dict_data) #remove(dict_data) demo