时序和随机,函数解耦,模块化和函数模块保护

1.函数解耦:

fetch()和change()函数中均用到文件处理的操作,所以定义file_handler()做统一处理,防止fetch和change中都夹杂文件处理的内容,增强代码的可读性和维护性

#!user/bin/env python
# -*- coding:utf-8 -*-
import os
def file_handler(backend_data,res=None,type='fetch'):  #位置参数在左,默认参数在右
    # print(backend_data)
    if type == 'fetch':
        with open('haproxy.conf','r') as read_f:
            li = []
            tag = False
            for read_line in read_f:
                # print(read_line)
                if read_line.strip() == backend_data:
                    tag = True
                    continue
                if tag and read_line.startswith('backend'): #找到backend 并且 下一行以backend开头(加上tag防止在目标行之前先找到backend)
                    break
                if tag:
                    print('33[1;45m%s33[0m' %read_line,end='')
                    li.append(read_line)
        return li
    elif type == 'change':
        with open('haproxy.conf', 'r') as 
                read_f, open('haproxy_new.conf', 'w') as write_f:
            tag = False
            has_writen_tag = False
            for read_line in read_f:
                if read_line.strip() == backend_data:
                    tag = True
                    # write_f.write(read_line)
                    continue
                if tag and read_line.startswith('backend'):
                    tag = False
                if not tag:
                    write_f.write(read_line)
                else:
                    if not has_writen_tag:
                        for record in res:
                            write_f.write(record)
                        has_writen_tag = True
        os.rename('haproxy.conf', 'haproxy.conf.bak')  # 对haproxy.conf文件重新命名为haproxy.conf.bak
        os.rename('haproxy_new.conf', 'haproxy.conf')  # 对haproxy_new.conf重新命名为haproxy.conf
        os.remove('haproxy.conf.bak')  # 移除.bak文件
def fetch(data):
    # print('33[1;43m这是查询功能33[0m')
    # print('33[1;43m用户数据是33[0m',data)
    backend_data = 'backend %s' %data
    return file_handler(backend_data)
def add():
    pass
def change(data):
    # print('这是修改功能')
    print('用户输入的数据是',data)
    backend = data[0]['backend'] #文件中的一条记录 查找1 www.oldboy1.org
    backend_data = 'backend %s'%backend #backend www.oldboy1.org
    #        server 2.2.2.4 2.2.2.4 weight 20 maxconn 3000
    #        server 2.2.2.5 2.2.2.5 weight 30 maxconn 4000
    # [{'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}}]
    old_server_record = '%sserver %s %s weight %s maxconn %s
'%(' '*8,data[0]['record']['server'],
                                                                data[0]['record']['server'],
                                                                data[0]['record']['weight'],
                                                                data[0]['record']['maxconn'])
    new_server_record = '%sserver %s %s weight %s maxconn %s
'%(' '*8,data[1]['record']['server'],
                                                                data[1]['record']['server'],
                                                                data[1]['record']['weight'],
                                                                data[1]['record']['maxconn'])
    print('用户想要修改的记录是',old_server_record)   #查找2{'server':'2.2.2.4','weight':20,'maxconn':3000}
    res = fetch(backend) #fetch('www.oldboy1.org')
    # print('来自查找函数',res)
    print('来自修改函数--->',res)
    if not res or old_server_record not in res:
        print('修改记录不存在')
    else:
        index = res.index(old_server_record)
        res[index] = new_server_record
    res.insert(0,'%s
' %backend_data)
    file_handler(backend_data,res=res,type='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
    }
    bool = True
    while bool:
        print(msg)
        choice = input('please input your item:')
        if not choice:continue
        if choice == '5':break
        data = input('请输入你的数据:')
        if data == '':
            continue
        if choice != '1':
            data = eval(data)
        res = msg_dic[choice](data)
        print(res)

 2.py文件相互调用和‘__name__’用法

module:
import功能:
1.
执行py2文件中的所有内容,并把py1中调用到的在py1中执行
2.
引入变量名
__name__功能:
1.
在当前py文件中执行,输出__main__,用于不让他人调用本机主程序,如启动文件是bin.py
if __main__ == '__name__':
    main.run()
所以当他人调用bin.py时,__main__ = 当前路径名,!='__name__', 那么代码将不会被调用

2.
在调用py文件中执行,输出当前文件路径, 用于控制不执行代码功能,如
if __name__ == '__main__':
    print('......')
    print('.......)

3.time三个内置表达式:

a时间戳;b结构化时间;c结构化时间转化为字符串时间

4.随机random()模块用法

5.生成验证码的两种方法

import sys
import time
print(sys.path)
print(time.time())

# import time
#time三个内置表达式
#1时间戳 功能:计算+显示 如1552394377.8605232
print(time.time())
#2结构化时间 如time.struct_time(tm_year=2019, tm_mon=3, tm_mday=12, tm_hour=20, tm_min=39, tm_sec=37, tm_wday=1, tm_yday=71, tm_isdst=0)
t = time.localtime(time.time())
print(t)
print(time.localtime()) #当地时间 结构化时间
print(t.tm_year) #t为对象 可调用属性
print(t.tm_wday)
print(time.gmtime()) #世界标准时间
#3结构化时间转化为时间戳
print(time.mktime(time.localtime()))

#将结构化时间转化为字符串时间
print(time.strftime('%Y-%m-%d %X',time.localtime()))
#将字符时间转化为结构化时间,
print(time.strptime('2016:12:24:20:47:17','%Y:%m:%d:%X'))
print(time.asctime()) #结构化时间-->国定格式的字符串时间 形式为结构化参数(对比结构化时间)
print(time.ctime()) #时间戳-->固定格式的字符串时间

# import datetime
print(datetime.datetime.now()) #当前时间,时间排布更合理

#创建模块,不要和py内置模块重名
import re
print(re.findall(r'123','1223312333443'))

#随机random()模块
import random
ret = random.random()
ret = random.randint(1,3) #从1-3中随机抽数,3可以取到
ret = random.randrange(1,3) #从1-3中水机抽数,3不可以取到
ret = random.choice([11,22,33,44,55]) #冲列表中随机选取一个数
ret = random.sample([11,22,33,44,55],2) #从列表中随机选取两个数
ret = [1,2,3,4,5]
random.shuffle(ret)
print(ret)

#随机验证码解法1
import random
def verify_code():
    ret = []
    j = 0
    while j < 5:
        for i in range(1,5):
                num = str(random.randint(0,9))
                letter = chr(random.randint(65, 90))
                letter1 = chr(random.randint(97,122))
                letter2 = str(random.choice([letter,letter1]))
                value = str(random.choice([num,letter2]))
                ret.append(value)
        print(''.join(ret))
        ret = []
        j +=1
if __name__ == '__main__':
    verify_code()

#随机验证码解法2
import random
def verify_code():
    ret = ''
    for i in range(4):
        num = random.randint(0,9)
        ltr1 = chr(random.randint(65,90))
        ltr2 = chr(random.randint(97,122))
        ltr = random.choice([ltr1,ltr2])
        s = str(random.choice([num,ltr]))
        ret +=s
    return ret
if __name__ == '__main__':
    res = verify_code()
    print(res)

dic = {}
for i in range(60,125):
    if chr(i).isalpha():
        dic[i] = chr(i)
dic = dict(zip(dic.values(),dic.keys()))
print(dic['A'],dic['Z'],dic['a'],dic['z'])
原文地址:https://www.cnblogs.com/yuyukun/p/10507968.html