Day15作业

# 今日作业:
# 1、 编写日志装饰器,实现功能如:一旦函数f1执行,则将消息2017-07-21 11:12:11 f1 run写入到日志文件中,日志文件路径可以指定
# 注意:时间格式的获取
# import time
# time.strftime('%Y-%m-%d %X')
# import time
# time.strftime('%Y-%m-%d %X')
# import time
#
# def outter(func):
# def wrapper(*args, **kwargs):
# res = func(*args, **kwargs)
# file = input('请输入日志路径:')
# with open(file, 'at', encoding='utf-8') as f:
# t = time.strftime('%Y-%m-%d %H:%M:%S')
# n =f'{t} f1 run\n'
# f.write(n)
# return res
# return wrapper
#
# @outter
# def index(x, y):
# time.sleep(1)
# print('index==>',x,y)
#
# index(1, 2)
# 2、基于迭代器的方式,用while循环迭代取值字符串、列表、元组、字典、集合、文件对象
# # names = 'asdfasfasfd'
# # names = [1, 2, 3, 4]
# # names = (1, 2, 3, 4)
# # names=['lqz_sb','yj_sb','jason_sb','egon']
# # names = {1, 2, 3, 4}
# # name = iter(names)
# # while True:
# # try:
# # print(next(name))
# # except:
# # StopIteration
# # break
# with open('access.log', 'r', encoding='utf-8') as names:
# name = iter(names)
# while True:
# try:
# print(next(name))
# except:
# StopIteration
# break
# 3、自定义迭代器实现range功能
# def my_range(start, stop, step = 1):
# while start < stop:
# yield start
# start += step
#
# g = my_range(1,5)
# for i in g:
# print(i)
#
#
# ==================== 本周选做作业如下 ====================
# 编写小说阅读程序实现下属功能
# # 一:程序运行开始时显示
# 0 账号注册
# 1 登录功能
# 2 充值功能
# 3 阅读小说
# 2.1、账号注册
# - 针对文件db.txt,内容格式为:"用户名:密码:金额" 完成注册功能
# # 五:为功能2.2、3.2编写记录日志的装饰器,日志格式为:"时间 用户名 操作(充值or消费) 金额"
#
# # 三:文件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编写认证功能装饰器,要求必须登录后才能执行操作
import time
import os


def deco1(ac):
def outter(func):
def wrapper(*args, **kwargs):
with open('login.txt', 'r', encoding='utf-8') as f:
login_status = eval(f.readline())
name = login_status['name']
with open('db.txt', 'r', encoding='utf-8') as rf:
for line in rf:
name, pwd, money = line.strip('\n').split(':')
a = int(money)
res = func(*args, **kwargs)
with open('db.txt', 'r', encoding='utf-8') as rf:
for line in rf:
name, pwd, money = line.strip('\n').split(':')
b = int(money)
c = abs(b - a)
with open('log.txt', 'at', encoding='utf-8') as f:
t = time.strftime('%Y-%m-%d %H:%M:%S')
n = f'{t} {name} {ac} {c}\n'
f.write(n)

return res

return wrapper

return outter


def deco(func):
def wrapper(*args, **kwargs):
with open('login.txt', 'r', encoding='utf-8') as f:
login_status = eval(f.readline())
if login_status['name'] is None:
print('请先登录!')
return run()
res = func(*args, **kwargs)
return res

return wrapper


# 2.1、账号注册
# - 针对文件db.txt,内容格式为:"用户名:密码:金额" 完成注册功能
def register():
user_name = input('please your name:').strip()
user_pwd = input('please your pwd:').strip()
with open('db.txt', 'a', encoding='utf-8') as f:
res = f'{user_name}:{user_pwd}:0\n'
f.write(res)
print('注册成功!')


def login():
with open('login.txt', 'r', encoding='utf-8') as f:
login_status = eval(f.readline())
if login_status['name'] is None:
inp_name = input('your name:').strip()
inp_pwd = input('your password:').strip()
with open('db.txt', 'r', encoding='utf-8') as rf:
for line in rf:
name, pwd, money = line.strip('\n').split(':')
if inp_name == name and inp_pwd == pwd:
print('login successful')
with open('login.txt', 'w', encoding='utf-8') as wf:
res = "{'name':'%s','password':'%s'}\n" % (name, pwd)
wf.write(res)
break
else:
print('name or pwd error')
return
else:
print('用户已登录!')


# 2.2、充值功能

@deco
@deco1('充值')
def recharge():
inp_money = int(input('请输入充值金额:').strip())
with open('db.txt', 'r', encoding='utf-8') as f1, \
open('db.txt.swp', 'w', encoding='utf-8') as f2:
for line in f1:
with open('login.txt', 'r', encoding='utf-8') as f:
login_status = eval(f.readline())
if login_status['name'] in line:
name, password, money = line.strip("\n").split(':')
money = int(money)
new_money = inp_money + money
f2.write(line.replace(str(money), str(new_money)))
os.remove('db.txt')
os.rename('db.txt.swp', 'db.txt')


@deco
@deco1('消费')
def read():
while True:
with open('story_class.txt', 'r', encoding='utf-8') as f:
res = eval(f.read())
for k in read_dic:
print('%s %s' % (k, read_dic[k]))
choice = input('请输入您的指令编号:').strip()
if choice == '0':
while True:
print('q 返回上一级')
dict1 = {}
for i in res[choice]:
dict1[i] = res[choice][i]
for k1 in dict1:
print('%s %s 售价:%s' % (k1, dict1[k1][0], dict1[k1][1]))
choice1 = input('请输入您想要阅读的书籍编号:').strip()
if choice1 == 'q':
break
elif choice1 in dict1:
print('是否付费阅读 y/n')
d = input('>>:').strip()
if d == 'y' or d == 'Y':
with open('db.txt', 'r', encoding='utf-8') as f1, \
open('db.txt.swp', 'w', encoding='utf-8') as f2:
for line in f1:
with open('login.txt', 'r', encoding='utf-8') as f:
login_status = eval(f.readline())
if login_status['name'] in line:
name, password, money = line.strip("\n").split(':')
money = int(money)
m = int(dict1[choice1][1])
if money > m:
new_money = money - m
f2.write(line.replace(str(money), str(new_money)))
with open(f'{dict1[k1][0]}', 'r', encoding='utf-8') as f:
print(f.read())
else:
print("账户余额不足")
os.remove('db.txt')
os.rename('db.txt.swp', 'db.txt')
else:
print('本书籍不存在')
if choice == '1':
while True:
print('q 返回上一级')
dict2 = {}
for i in res[choice]:
dict2[i] = res[choice][i]
for k2 in dict2:
print('%s %s 售价:%s' % (k2, dict2[k2][0], dict2[k2][1]))
choice2 = input('请输入您想要阅读的书籍编号:').strip()
if choice2 == 'q':
break
elif choice2 in dict2:
print('是否付费阅读 y/n')
d = input('>>:').strip()
if d == 'y' or d == 'Y':
with open('db.txt', 'r', encoding='utf-8') as f1, \
open('db.txt.swp', 'w', encoding='utf-8') as f2:
for line in f1:
with open('login.txt', 'r', encoding='utf-8') as f:
login_status = eval(f.readline())
if login_status['name'] in line:
name, password, money = line.strip("\n").split(':')
money = int(money)
m = int(dict2[choice2][1])
if money > m:
new_money = money - m
f2.write(line.replace(str(money), str(new_money)))
with open(f'{dict2[k1][0]}', 'r', encoding='utf-8') as f:
print(f.read())
else:
print("账户余额不足")
os.remove('db.txt')
os.rename('db.txt.swp', 'db.txt')
else:
print('本书籍不存在')
if choice == '2':
print('暂无该分区')
if choice == '3':
break


# # 附加:
# # 可以拓展作者模块,作者可以上传自己的作品
@deco
@deco1('上传小说')
def author():
# 0 玄幻武侠
# 1 都市爱情
# 2 高效养猪36技
while True:
for k in read_dic:
print('%s %s' % (k, read_dic[k]))
c = input('请输入书籍类型:').strip()
a_num = input('请输入书籍编号').strip()
a_name = input('请输入书籍名称:').strip()
a_price = input('请输入书籍价格:').strip()
a_flie = input('书籍内容:')
# {"0":{"0":["倚天屠狗记.txt",3],"1":["沙雕英雄转.txt",10]},"1":{"0":["令人羞耻的爱.txt",6],"1":["二狗的妻子与大草原的故事.txt",5]},}
with open('story_class.txt', 'r', encoding='utf-8') as f:
res = eval(f.read())
if c == '0':
res['0'][a_num] = [a_name, a_price]
with open(a_name, 'w', encoding='utf-8') as f1, \
open('story_class.txt', 'w', encoding='utf-8') as f2:
f1.write(a_flie)
f2.write(res)
print('上传成功')
break
elif c == '1':
res['1'][a_num] = [a_name, a_price]
with open(a_name, 'w', encoding='utf-8') as f1, \
open('story_class.txt', 'w', encoding='utf-8') as f2:
f1.write(a_flie)
f2.write(res)
print('上传成功')
break
elif c == '2':
res['2'][a_num] = [a_name, a_price]
with open(a_name, 'w', encoding='utf-8') as f1, \
open('story_class.txt', 'w', encoding='utf-8') as f2:
f1.write(a_flie)
f2.write(res)
print('上传成功')
break
else:
print('请选择正确分区')
break


@deco
def log_out():
with open('login.txt', 'w', encoding='utf-8') as wf:
res = "{'name':%s,'password':%s}\n" % (None, None)
wf.write(res)
print('已退出当前用户!')


func_dic = {
'0': [register, '注册功能'],
'1': [login, '登录功能'],
'2': [recharge, '充值功能'],
'3': [read, '阅读功能'],
'4': [author, '上传书籍'],
'5': [log_out, '退出登录']
}
read_dic = {
'0': '玄幻武侠',
'1': '都市爱情',
'2': '高效养猪36技',
'3': '退出阅读'
}


def run():
while True:
for k in func_dic:
print('%s %s' % (k, func_dic[k][1]))
choice = input('请输入您的指令编号:').strip()
if choice in func_dic:
func_dic[choice][0]()
else:
print('未识别的指令')


run()

# # 二:完成下述功能


#

#
#
#
posted @ 2020-07-22 20:55  画堂晨起  阅读(114)  评论(0编辑  收藏  举报