解耦

import os
def file_handle(file_name, backend_data, res = None, type = 'fetch'):
    backend_data = 'backend ' + backend_data + '\n' # 读取的文本有换行符,需要做下拼接
    if (type == 'fetch'):
        with open(file_name, 'r', encoding='utf-8') as read_file: # 使用with打开文件不用手动关闭
            tag = False # 是否匹配到用户查询内容,作为开始存储和结束标志
            ret = [] # 用于存储查询成功读取的内容
            for v in read_file: # 一行一行遍历文件内容
                if v == backend_data: # 匹配到用户查询内容行
                    tag = True # 设置开始存储标志True
                    continue # 不打印,本次循环结束,继续执行下次循环
                if tag and  v.startswith('backend'): # 是否读取结束
                    break # 循环结束
                if tag:
                    ret.append(v) # 存储内容
        return ret
    elif type == 'change':
        with open(file_name, 'r', encoding='utf-8') as read_f, open('haproxy_new.conf', 'w',
                                                                         encoding='utf-8') as write_f:
            tag = False
            for line in read_f:
                if tag and line.startswith('backend'):
                    tag = False  # 如果是改写内容,并且到了改写内容结束位置
                if tag:
                    continue  # 如果是改写内容,跳过不执行,继续下一次循环
                if line == backend_data:
                    tag = True
                write_f.write(line)
                if tag:
                    write_f.writelines(res)
            # os.rename('haproxy.conf', 'haproxy.conf.bak')
        os.remove('haproxy.conf')
        os.rename('haproxy_new.conf', 'haproxy.conf')
def fetch(data):
    # print('用户查询数据: %s' % data)
    return file_handle('haproxy.conf', data)
def add():
    pass

def change(data):
    # print('这是修改功能:')
    # print('用户输入的数据是 %s' % data)
    backend = data[0]['backend']
    record = data[0]['record']
    old_server_record = '%sserver %s weight %s maxconn %s\n' % (' '*8, record['server'], record['weight'], record['maxconn'])
    res = fetch(backend)
    if not res or old_server_record not in res:
        return '修改的记录不存在!'
    else:
        index = res.index(old_server_record)
        record_1 = data[1]['record']
        res[index] = '%sserver %s weight %s maxconn %s\n' % (' ' * 8, record_1['server'], record_1['weight'], record_1['maxconn'])

        file_handle('haproxy.conf', backend, res, 'change')
def delete():
    pass
if __name__ == '__main__': # 只有在一个文件单独执行时会运行,防止引用时运行
    msg='''
        1:查询
        2:添加
        3:修改
        4:删除
        5:退出
    '''
    msg_dic = {
        '1': fetch,
        '2': add,
        '3': change,
        '4': delete,
        '5': exit
    }
    while 1:
        print(msg)
        choice = input('请输入你的选项').strip() # 去除两边空格和换行符
        if not choice:
            continue
        if choice == '5': # 用户选择退出,执行推出操作
            exit()
        data = input('请输入查询内容').strip()
        if choice != '1':
            data = eval(data) # 除了查询之外的操作,都对输入的字符串进行转换提取数据结构
        res = msg_dic[choice](data) # 执行msg_dic对应的函数
        print(res) # 打印执行函数的返回值
# [{'backend': 'www.oldboy1.org', 'record': {'server': '101.1000.7.9 101.1000.7.9', 'weight':  '500', 'maxconn': '502'}}, {'backend': 'www.oldboy1.test', 'record': {'server': '101.1000.7.9 101.1000.7.9', 'weight': '509', 'maxconn': '02'}}]
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值