作业12

作业:

今日作业:
'''
1、 编写日志装饰器,实现功能如:一旦函数f1执行,则将消息2017-07-21 11:12:11 f1 run写入到日志文件中,日志文件路径可以指定
注意:时间格式的获取
import time
time.strftime('%Y-%m-%d %X')
'''
import time


def log_write(func):
    def wrapper(*args, **kwargs):
        with open('access.log', mode='at', encoding='utf-8') as f:
            runtime = time.strftime('%Y-%m-%d %X')
            data = f'{runtime} {func.__name__} run\n'
            f.write(data)X
        res = func(*args, **kwargs)
        return res

    return wrapper


'''
2、基于迭代器的方式,用while循环迭代取值字符串、列表、元组、字典、集合、文件对象
'''
str1 = 'hello'
str1_iterator = str1.__iter__()
while True:
    try:
        res = str1_iterator.__next__()
        print(res)
    except StopIteration:
        break

l = ['h', 'e', 'l', 'l', 'o']
l_iterator = l.__iter__()
while True:
    try:
        res = l_iterator.__next__()
        print(res)
    except StopIteration:
        break

tup = ('h', 'e', 'l', 'l', 'o')
tup_iterator = tup.__iter__()
while True:
    try:
        res = tup_iterator.__next__()
        print(res)
    except StopIteration:
        break

dic = {'1': 'h', '2': 'e', '3': 'l', '4': 'l', '5': 'o'}
dic_iterator = dic.__iter__()
while True:
    try:
        res = dic_iterator.__next__()
        print(res)
    except StopIteration:
        break

set = {'h', 'e', 'l', 'o'}
set_iterator = set.__iter__()
while True:
    try:
        res = set_iterator.__next__()
        print(res)
    except StopIteration:
        break

'''
3、自定义迭代器实现range功能
'''

def my_range(start, stop, step=1):
    while start < stop:
        yield start
        start += step


====================  本周选做作业如下  ====================
编写小说阅读程序实现下属功能
# 一:程序运行开始时显示
    0 账号注册
    1 登录功能
    2 充值功能
    3 阅读小说


# 二:完成下述功能
2.1、账号注册
        -  针对文件db.txt,内容格式为:"用户名:密码:金额" 完成注册功能
2.2、充值功能

# 三:文件story_class.txt存放类别与小说文件路径,如下,读出来后可用eval反解出字典
{"0":{"0":["倚天屠狗记.txt",3],"1":["沙雕英雄转.txt",10]},"1":{"0":["令人羞耻的爱.txt",6],"1":["二狗的妻子与大草原的故事.txt",5]},}

3.1、用户登录成功后显示如下内容,根据用户选择,显示对应品类的小说编号、小说名字、以及小说的价格
"""
0 玄幻武侠
1 都市爱情
2 高效养猪36技
"""

3.2、用户输入具体的小说编号,提示是否付费,用户输入y确定后,扣费并显示小说内容,如果余额不足则提示余额不足

# 四:为功能2.2、3.1、3.2编写认证功能装饰器,要求必须登录后才能执行操作

# 五:为功能2.2、3.2编写记录日志的装饰器,日志格式为:"时间 用户名 操作(充值or消费) 金额"



# 附加:
# 可以拓展作者模块,作者可以上传自己的作品


# 导入模块
import os, sys, time

# 全局变量
login_user = {'name': None}
user_dict = {}
changed_money = None

# 装饰器:1.认证用户  2.日志装饰器
def auth(func):
    def wrapper(*args, **kwargs):
        if login_user.get('name'):
            res = func(*args, **kwargs)
            return res

        else:
            print('这里是没有登录用户')
            login()

    return wrapper


def log_it(func):
    def wrapper(*args, **kwargs):
        current_user = login_user['name']
        if func.__name__ == recharge.__name__:
            run_time = time.strftime('%Y-%m-%d %X')
            res = func(*args, **kwargs)
            data = f'{run_time} {current_user} 充值 {changed_money}元\n'
            with open('access.log',mode='at',encoding='utf-8') as f:
                f.write(data)
            return res
        elif func.__name__ == read_novel.__name__:
            run_time = time.strftime('%Y-%m-%d %X')
            res = func(*args, **kwargs)
            data = f'{run_time} {current_user} 充值 {changed_money}元\n'
            with open('access.log',mode='at',encoding='utf-8') as f:
                f.write(data)
            return res

    return wrapper


# 函数工具:1.打开db.txt,获得用户信息
def get_user_info():
    with open('db.txt', mode='rt', encoding='utf-8') as f:
        for line in f:
            line = line.strip('\n')
            db_name, db_pwd, db_balance = line.split(':')
            user_dict[db_name] = [db_pwd, int(db_balance)]


# 函数工具:2.用户数据写入
def write_user_info():
    with open('db.txt', mode='wt', encoding='utf-8') as f:
        for key, value in user_dict.items():
            user_data_write = f'{key}:{value[0]}:{value[1]}\n'
            f.write(user_data_write)


# 功能函数
def login():
    print('登录功能——————')
    get_user_info()
    while True:
        if login_user.get('name'):
            current_user = login_user['name']
            print(f'当前用户:{current_user}已登录')
            break
        else:
            inp_name = input('请输入用户名>>>:').strip()
            if inp_name not in user_dict:
                print('用户名不存在')
                continue
            else:
                error_count = 0
                while True:
                    inp_pwd = input('请输入密码>>>:').strip()
                    if inp_pwd == user_dict[inp_name][0]:
                        login_user['name'] = inp_name
                        print('登录成功!')
                        # read_novel()
                        return
                    else:
                        print('密码错误,请重新输入!')
                        error_count += 1
                        if error_count == 3:
                            print('密码错误三次,请重新输入账户信息!')
                            break


def register():
    print('注册功能——————')
    get_user_info()
    while True:
        inp_name = input('请输入用户名>>>:').strip()
        if inp_name in user_dict:
            print('用户名已存在')
            continue
        else:
            inp_pwd = input('请输入密码>>>:').strip()
            user_dict[inp_name] = [inp_pwd, 0]
            write_user_info()
            print(f'用户:{inp_name} 注册成功!正在返回主界面...')
            break

@log_it
@auth
def recharge():
    global changed_money
    print('充值功能——————')
    get_user_info()
    current_user = login_user['name']
    while True:
        print(f'用户:{current_user},账户余额{user_dict[current_user][1]}元')
        recharge_nums = input('请输入充值金额>>>:').strip()
        if not recharge_nums.isdigit():
            print('请输入正确的数字!')
            continue
        recharge_nums = int(recharge_nums)
        user_dict[current_user][1] += recharge_nums
        changed_money = recharge_nums
        write_user_info()
        print(f'用户:{current_user},账户余额{user_dict[current_user][1]}元')
        return


@log_it
@auth
def read_novel():
    print('阅读功能——————')
    global changed_money
    current_user = login_user['name']
    novel_dict = {
        '0': '玄幻武侠',
        '1': '都市爱情',
        '2': '高效养猪36技'
    }
    while True:
        for k1, v1 in novel_dict.items():
            print(f'{k1}     {v1}')
        choice1 = input('请输入命令>>>:').strip()
        if choice1 in novel_dict:
            with open('story_class.txt', mode='rt', encoding='utf-8') as f:
                for line in f:
                    novel_list = eval(line)
            novel_info = novel_list[choice1]
            print(novel_info)
            for k2, v2 in novel_info.items():
                print(f'编号:{k2} 书名:{v2[0]} 价格:{v2[1]}元')
            tag = True
            while tag:
                cmd = input('请输入您想购买的小说编号>>>:').strip()
                print(novel_info[cmd][1], user_dict[current_user][1])
                if novel_info[cmd][1] < user_dict[current_user][1]:
                    print(f'选中{novel_info[cmd][0]},价格{novel_info[cmd][1]}')
                    while tag:
                        cmd2 = input('是否付费购买?输入Y/y确认,输入N/n取消>>>:').strip()
                        if cmd2 == 'Y' or cmd2 == 'y':
                            user_dict[current_user][1] -= int(novel_info[cmd][1])
                            changed_money = int(novel_info[cmd][1])
                            write_user_info()
                            print(
                                f'购买{novel_info[cmd][0]}成功,价格{novel_info[cmd][1]},用户{current_user},当前余额{user_dict[current_user][1]}')
                            with open(f'{novel_info[cmd][0]}', mode='rt', encoding='utf-8') as f:
                                data = f.read()
                                print(data)
                            return

                        elif cmd2 == 'N' or cmd2 == 'n':
                            print('返回小说主界面')
                            tag = False
                        else:
                            print('请输入正确的命令!')
                else:
                    print('用户余额不足')


        else:
            print('非法命令,请重新输入!')


# 主函数
main_func_dict = {
    "0": [register, '账号注册'],
    "1": [login, '登录功能'],
    "2": [recharge, '充值功能'],
    "3": [read_novel, '阅读小说'],
}

while True:
    print('=' * 50)
    for k, v in main_func_dict.items():
        print(f'{k}     {v[1]}')
    choice = input('请输入命令>>>:').strip()
    if choice in main_func_dict:
        main_func_dict[choice][0]()
    else:
        print('非法命令,请重新输入!')

你可能感兴趣的:(练习题,其他)