iis服务器助手广告广告
返回顶部
首页 > 资讯 > 后端开发 > Python >Python学习day3作业
  • 522
分享到

Python学习day3作业

作业Python 2023-01-31 07:01:33 522人浏览 安东尼

Python 官方文档:入门教程 => 点击学习

摘要

作业需求 HAproxy配置文件操作 根据用户输入,输出对应的backend下的server信息 可添加backend 和sever信息 可修改backend 和sever信息 可删除backend 和sever信息 操作配置文件前

作业需求
HAproxy配置文件操作

  1. 根据用户输入,输出对应的backend下的server信息
  2. 可添加backend 和sever信息
  3. 可修改backend 和sever信息
  4. 可删除backend 和sever信息
  5. 操作配置文件前进行备份
  6. 添加server信息时,如果ip已经存在则修改;如果backend不存在则创建;若信息与已有信息重复则不操作
  • 博客
  • 查询backend下的server信息
  • 添加backend和server信息
  • 修改backend 和sever信息
  • 删除backend和server信息

博客地址

ygqygq2的博客地址

基本流程图

基本流程图

程序代码

#!/usr/bin/env python
# _*_coding:utf-8_*_
'''
 * Created on 2016/11/7 21:24.
 * @author: Chinge_Yang.
'''

import shutil
import JSON


def list_function():
    print("Please choice the ID of a action.".center(50, "#"))
    print("【1】.Fetch haproxy.cfg backend infomation.")
    print("【2】.Add haproxy.cfg backend infomation.")
    print("【3】.Delete haproxy.cfg backend infomation.")
    print("End".center(50, "#"))


def fetch(backend):
    # 取出backend相关server信息
    result = []  # 定义结果列表
    with open("haproxy.cfg", "r", encoding="utf-8") as f:  # 循环读取文件
        flag = False  # 标记为假
        for line in f:
            # 以backend开头
            line = line.strip()
            if line.startswith("backend") and line == "backend " + backend:
                flag = True  # 读取到backend开头的信息,标记为真
                continue
            # 下一个backend开头
            if flag and line.strip().startswith("backend"):
                flag = False
                break
            # server信息添加到result列表
            if flag and line.strip():
                result.append(line.strip())
    return result


def writer(backend, record_list):
    with open("haproxy.cfg", "r") as old, open("new.cfg", "w") as new:
        flag = False
        for line in old:
            if line.strip().startswith('backend') and line.strip() == "backend " + backend:
                flag = True
                new.write(line)
                for new_line in record_list:
                    new.write(" " * 4 + new_line + "\n")
                continue  # 跳到下一次循环,避免下一个backend写二次

            if flag and line.strip().startswith("backend"):  # 下一个backend
                flag = False
                new.write(line)
                continue  # 退出此循环,避免server信息二次写入
            if line.strip() and not flag:
                new.write(line)


def add(backend, record):
    global change_flag
    record_list = fetch(backend)  # 查找是否存在记录
    if not record_list:  # backend不存在, record不存在
        with open('haproxy.cfg', 'r') as old, open('new.cfg', 'w') as new:
            for line in old:
                new.write(line)
            # 添加新记录
            new.write("\nbackend " + backend + "\n")
            new.write(" " * 4 + record + "\n")
        print("\033[32;1mAdd done\033[0m")
        change_flag = True
    else:  # backend存在,record存在
        if record in record_list:
            print("\033[31;1mRecord already in it,Nothing to do!\033[0m")
            change_flag = False
        else:  # backend存在,record不存在
            record_list.append(record)
            writer(backend, record_list)
            print("\033[32;1mAdd done\033[0m")
            change_flag = True


def delete(backend, record):
    global change_flag
    record_list = fetch(backend)  # 查找是否存在记录
    if not record_list:  # backend不存在, record不存在
        print("Not match the backend,no need delete!".center(50, "#"))
        change_flag = False
    else:  # backend存在,record存在
        if record in record_list:
            record_list.remove(record)  # 移除元素
            writer(backend, record_list)  # 写入
            print("\033[31;1mDelete done\033[0m")
            change_flag = True
        else:  # backend存在,record不存在
            print("Only match backend,no need delete!".center(50, "#"))
            change_flag = False
    return change_flag


def output(servers):
    # 输出指定backend的server信息
    print("Match the server info:".center(50, "#"))
    for server in servers:
        print("\033[32;1m%s\033[0m" % server)
    print("#".center(50, "#"))


def input_json():
    # 判断输入,要求为json格式
    continue_flag = False
    while continue_flag is not True:
        backend_record = input("Input backend info(json):").strip()
        try:
            backend_record_dict = json.loads(backend_record)
        except Exception as e:
            print("\033[31;1mInput not a json data type!\033[0m")
            continue
        continue_flag = True
    return backend_record_dict


def operate(action):
    global change_flag
    if action == "fetch":
        backend_info = input("Input backend info:").strip()
        result = fetch(backend_info)  # 取出backend信息
        if result:
            output(result)  # 输出获取到的server信息
        else:
            print("\033[31;1mNot a match is found!\033[0m")
    elif action is None:
        print("\033[31;1mNothing to do!\033[0m")
    else:
        backend_record_dict = input_json()  # 要求输入json格式
        for key in backend_record_dict:
            backend = key
            record = backend_record_dict[key]
            if action == "add":
                add(backend, record)
            elif action == "delete":
                delete(backend, record)
        if change_flag is True:  # 文件有修改,才进行文件更新
            # 将操作结果生效
            shutil.copy("haproxy.cfg", "old.cfg")
            shutil.copy("new.cfg", "haproxy.cfg")
            result = fetch(backend)
            output(result)  # 输出获取到的server信息


def judge_input():
    # 判断输入功能编号,执行相应步骤
    input_info = input("Your input number:").strip()
    if input_info == "1":  # 查询指定backend记录
        action = "fetch"
    elif input_info == "2":  # 添加backend记录
        action = "add"
    elif input_info == "3":  # 删除backend记录
        action = "delete"
    elif input_info == "q" or input_info == "quit":
        exit("Bye,thanks!".center(50, "#"))
    else:
        print("\033[31;1mInput error!\033[0m")
        action = None
    return action


def main():
    exit_flag = False
    while exit_flag is not True:
        global change_flag
        change_flag = False
        list_function()
        action = judge_input()
        operate(action)


if __name__ == '__main__':
    main()

HAproxy配置文件操作

1.程序说明

实现功能如下

  • 查询backend下的server信息
  • 添加backend和server信息
  • 修改backend 和sever信息
  • 删除backend和server信息

2.程序测试配置文件

cat haproxy.cfg

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 51cto.com
    bind 0.0.0.0:80
    option httplog
    option httpclose
    option  forwardfor
    log global
    acl www hdr_reg(host) -i test01.example.com
    use_backend test01.example.com if www
backend test01.example.com
    server 100.1.7.10 100.1.7.10 weight 20 maxconn 3000
backend test.com
    server 100.1.7.90 100.1.7.90 weight 20 maxconn 3000
    server 100.1.7.66 100.1.7.66 weight 20 maxconn 3000
    server 100.1.7.27 100.1.7.27 weight 20 maxconn 3000
    server 100.1.7.13 100.1.7.13 weight 20 maxconn 3000

backend www.test.com
    server 100.1.7.13 100.1.7.13 weight 20 maxconn 3000

3.程序测试

Python config_haproxy.py
执行结果:

########Please choice the ID of a action.#########
【1】.Fetch haproxy.cfg backend infomation.
【2】.Add haproxy.cfg backend infomation.
【3】.Delete haproxy.cfg backend infomation.
#######################End########################
Your input number:1
Input backend info:test.com
##############Match the server info:##############
server 100.1.7.90 100.1.7.90 weight 20 maxconn 3000
server 100.1.7.66 100.1.7.66 weight 20 maxconn 3000
server 100.1.7.27 100.1.7.27 weight 20 maxconn 3000
##################################################
########Please choice the ID of a action.#########
【1】.Fetch haproxy.cfg backend infomation.
【2】.Add haproxy.cfg backend infomation.
【3】.Delete haproxy.cfg backend infomation.
#######################End########################
Your input number:2
Input backend info(json):{"test.com":"testtest.com"}
Add done
##############Match the server info:##############
server 100.1.7.90 100.1.7.90 weight 20 maxconn 3000
server 100.1.7.66 100.1.7.66 weight 20 maxconn 3000
server 100.1.7.27 100.1.7.27 weight 20 maxconn 3000
testtest.com
##################################################
########Please choice the ID of a action.#########
【1】.Fetch haproxy.cfg backend infomation.
【2】.Add haproxy.cfg backend infomation.
【3】.Delete haproxy.cfg backend infomation.
#######################End########################
Your input number:1
Input backend info:test.com
##############Match the server info:##############
server 100.1.7.90 100.1.7.90 weight 20 maxconn 3000
server 100.1.7.66 100.1.7.66 weight 20 maxconn 3000
server 100.1.7.27 100.1.7.27 weight 20 maxconn 3000
testtest.com
##################################################
########Please choice the ID of a action.#########
【1】.Fetch haproxy.cfg backend infomation.
【2】.Add haproxy.cfg backend infomation.
【3】.Delete haproxy.cfg backend infomation.
#######################End########################
Your input number:3
Input backend info(json):{"test.com":"testtest.com"}
Delete done
##############Match the server info:##############
server 100.1.7.90 100.1.7.90 weight 20 maxconn 3000
server 100.1.7.66 100.1.7.66 weight 20 maxconn 3000
server 100.1.7.27 100.1.7.27 weight 20 maxconn 3000
##################################################
########Please choice the ID of a action.#########
【1】.Fetch haproxy.cfg backend infomation.
【2】.Add haproxy.cfg backend infomation.
【3】.Delete haproxy.cfg backend infomation.
#######################End########################
Your input number:4
Input error!
Nothing to do!
########Please choice the ID of a action.#########
【1】.Fetch haproxy.cfg backend infomation.
【2】.Add haproxy.cfg backend infomation.
【3】.Delete haproxy.cfg backend infomation.
#######################End########################
Your input number:3
Input backend info(json):d
Input not a json data type!
Input backend info(json):{"test01.example.com":"server 100.1.7.27 100.1.7.27 weight 20 maxconn 3000"}
########Only match backend,no need delete!########
########Please choice the ID of a action.#########
【1】.Fetch haproxy.cfg backend infomation.
【2】.Add haproxy.cfg backend infomation.
【3】.Delete haproxy.cfg backend infomation.
#######################End########################
Your input number:q
###################Bye,thanks!####################

Process finished with exit code 1

--结束END--

本文标题: Python学习day3作业

本文链接: http://www.lsjlt.com/news/192179.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
  • Python学习day3作业
    作业需求 HAproxy配置文件操作 根据用户输入,输出对应的backend下的server信息 可添加backend 和sever信息 可修改backend 和sever信息 可删除backend 和sever信息 操作配置文件前...
    99+
    2023-01-31
    作业 Python
  • python 学习day3
    set(无序不重复的序列)创建两种方式 例一:s1 = {1,2,3} 例二:s2 = set() ,s3 = set([1,2,3,4,5])功能 s2.add(123) #添加s2集合中123元素 s2.clear() #清除内容 s2...
    99+
    2023-01-31
    python
  • python学习(day3)
    1、集合的使用:#1、集合的操作: list_1 = [1,4,5,7,3,6,7,9] list_1 = set(list_1)#创建集合 list_2 = set([2,6,0,22,66,8,4]) print(list_1,typ...
    99+
    2023-01-31
    python
  • Python-day3作业-haprox
    #!/usr/bin/env pythonimport os,sys,time,re,prettytable,jsonfrom collections import defaultdict,OrderedDictconf='haproxy....
    99+
    2023-01-31
    作业 Python haprox
  • day3 python 学习随笔
    三目运算(三元运算)例:result = 1 if 2 == 2 else 32. set是一个无序且不重复的元素集合3.生成器range不是生成器 和 xrange 是生成器readlines不是生成器 和 xreadlines 是生成器...
    99+
    2023-01-31
    随笔 python
  • Python学习记录day3
    Python学习记录 day3今天是银角大王武sir讲课。先回顾了上节课所学,然后讲到了面向对象思想。setset是一个无序且不重复,可嵌套的元素集合class set(object):     """     set() -> ne...
    99+
    2023-01-31
    Python
  • Python学习day1作业总结
    为了以后更好更快速的复习,此博客记录我对作业的总结。对于基础作业,我认为最重要的是过程,至于实现是不是完美,代码是不是完美,虽然重要,但是作业过程中,用到的知识点是值得总结和整理的。1. 用户输入帐号密码进行登陆  2. 用户信息保存在文件...
    99+
    2023-01-31
    作业 Python
  • Python练习题(day3)
    一、函数练习题: 1、写函数,用户传入修改的文件名,与要修改的内容,执行函数,完成批了修改操作 2、写函数,计算传入字符串中【数字】、【字母】、【空格] 以及 【其他】的个数 3、写函数,判断用户传入的对象(字符串、列表、元组)长度是否大于...
    99+
    2023-01-31
    练习题 Python
  • Python学习之day3数据结构之列表
                                                          数据结构之列表一、列表定义      列表是处理一组有序项目的数据结构,即你可以在一个列表中存储一个序列的项目。列表中的项目应包括在...
    99+
    2023-01-31
    数据结构 列表 Python
  • python学习心得-第一天-作业
    python学习第一天作业作业1用户输入帐号密码进行登陆用户信息保存在文件内用户密码输入错误三次后锁定用户代码:#__author__ = 'leslie' #-*-coding:utf-8-*- # #1. 用户输入帐号密码进行登陆 #2...
    99+
    2023-01-31
    作业 学习心得 python
  • 从零开始学Python-day3
    Python--Day3学习要有定位,明确目标地去学习。---leavespython02---list知识一 list的概念    列表的概念:列表可以完成大多数集合类的数据结构实现。它支持字符,数字,字符串甚至可以包含列表(所谓嵌套)。...
    99+
    2023-01-31
    从零开始 Python
  • Python第一次作业练习
    题目分析:"""参考学校的相关规定。对于四分制,百分制中的90分及以上可视为绩点中的4分,80 分及以上为3分,70 分以上为2分,60 分以上为1分;五分制中的5分为四分制中的4分,4分为3分,3分为2分,2分为1分。要求: ...
    99+
    2023-09-21
    python 开发语言
  • Python学习 :文件操作
      文件基本操作流程: 一、 创建文件对象  二、 调用文件方法进行操作 三、 关闭文件(注意:只有在关闭文件后,才会写入数据)   fh = open('李白诗句','w',encoding='utf-8') fh.write('''...
    99+
    2023-01-30
    操作 文件 Python
  • Python学习—文件操作
    1.文件基础知识 1.文件是存储在外部介质上的数据的集合,文件的基本单位是字节,文件所含的字节数就是文件的长度。每个字节都有一个默认的位置,位置从0开始,文件头的位置就是0,文件尾的位置是文件内容结束后的后一个位置,该位置上没有文件内容,为...
    99+
    2023-01-31
    操作 文件 Python
  • Python学习:作用域(namespa
    Python作用域基础Python有四个作用域:L(Local)本地也称作局部作用域;E(Enclosing)闭包函数外的函数中;G(global)全局作用域;B(Built-in)内建作用域;变量可以在三个不同的地方分配:如果一个变量在d...
    99+
    2023-01-31
    作用 Python namespa
  • Python学习路线:Python就业指导建议
    最近有很多伙伴希望我能给一些关于python的就业指导;之前出过很多关于Python学习路线的就业指导方面文章,但是并不是很完善,所以希望这期关于python的就业指导能够很全面很详细的聊聊就业的那些事,以下都是个人经验和建议,如有偏差还望...
    99+
    2023-06-02
  • Python 学习笔记 - 操作MySQ
    Python里面操作MySQL可以通过两个方式:pymysql模块ORM框架的SQLAchemey本节先学习第一种方式。学习Python模块之前,首先看看MySQL的基本安装和使用,具体语法可以参考豆子之前的博客http://beanxyz...
    99+
    2023-01-31
    学习笔记 操作 Python
  • Python学习之文件操作
    #/usr/bin/python content='''\                      #这里使用''' This is a test file for python ''' f=file('content.txt','w'...
    99+
    2023-01-31
    操作 文件 Python
  • python之day3(文件操作、字符转
    文件操作 f=open(“yesterday”,”r”,encoding=”utf-8”)  #以只读模式打开文件data=f.read()                             #读取所有内容data2=f.read()...
    99+
    2023-01-31
    字符 操作 文件
  • python学习-使用MySQLdb操作
    操作环境为python2.7 centos7一、MySQLdb的安装与配置MySQLdb是用于Python连接mysql数据库的接口,它实现了Python数据库api规范2.0。按照以下方式安装yum install epel-releas...
    99+
    2023-01-31
    操作 python MySQLdb
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作