这是一次结合前几次小练习的综合性作业,也算是对前面学习内容小结吧
1、该系统有三个用户”alex”, “pizza”, “john”
2、这三个用户对应的角色和密码分别是:”管理员”, “教师”, “学生”, “alex123”, “pizza123”, “john123”
3、每个用户只有3次登录机会,失败三次锁定该用户,程序终止
4、每个用户登录之后,根据其对应的角色,显示欢迎信息
1、该图书馆中有书籍:《Python基础编程》,《Python进阶编程》,《Python高级编程》,《Django入门指南》
2、上述管理系统中的教师和学生两个角色可以借书,每次借书后该用户的薪资减少100元(第一次借书时充值)
3、借书之后,图书馆中收藏的该书籍数量减少
4、借书过程中会展示当前借阅书籍和余额信息,借书完毕后打印本次所借所有书籍和余额。
5、只有学生和老师可以借书,管理员不行
6、借书过程持续进行,按q退出
1、教师和学生两个角色可以还书,每次还书后该用户的薪资增加100元
2、还书过程中会展示当前所还书籍和余额信息,还书完毕后打印本次所还书籍和余额。
3、还书之后,图书馆中收藏的该书籍数量增加
4、只有学生和老师可以还书,管理员没借书,理应不能还书
5、还书过程持续进行,按q退出
1、管理员可以增加用户(账号,密码,身份)、删除用户、增加书籍(更改旧书数量,添加新书)、删除书籍
2、每个角色在程序重启并登录之后,当前状态与上一次退出时的状态保持一致
3、每个角色在程序重启并登录之后,当前状态与上一次退出时的状态保持一致
1、学生和教师可以查询借书和还书的全部历史信息,包括时间。
完整代码如下,后附下载链接:
# encoding='UTF-8'
import json
import os
import time
import functools
func_dict={}
def mask(option):
def outter(func):
func_dict[option] = func
@functools.wraps(func)
def inner(*args, **kwargs):
return func(*args, **kwargs)
return inner
return outter
def login():
if os.path.exists("user_info.txt"):
with open("user_info.txt", mode="r", encoding="utf-8") as file:
user_info = json.load(file)
else:
user_info = \
{
'alex': {'pwd': 'alex123', 'role': 'admin', 'state': True},
'pizza': {'pwd': 'pizza123', 'role': 'teacher', 'state': True, 'balance': -1, 'book_shelf': [],
'history': {}},
'john': {'pwd': 'john123', 'role': 'student', 'state': True, 'balance': -1, 'book_shelf': [],
'history': {}}
}
with open("user_info.txt", mode="w", encoding="utf-8") as file:
json.dump(user_info, file)
count = 0
while count < 3:
user_name = input("Please input username:")
password = input("Please input password:")
if user_name in user_info:
if user_info[user_name]['state']:
if password == user_info[user_name]['pwd']:
print("Welcome back " + user_name + "!")
return user_name
else:
print("The name or password may be incorrect!")
else:
print("The account has been locked!")
else:
print("User does not exist")
count += 1
if count == 3:
user_info[user_name]['stat'] = False
with open("user_info.txt", mode='w', encoding="utf-8")as file:
json.dump(user_info, file)
exit("You have tried too many times and the account has been locked!")
@mask("Borrow books")
def borrow_book(user_name):
if os.path.exists("book_info.txt"):
book_info = []
with open("book_info.txt", mode="r", encoding="utf-8")as file:
for line in file.readlines():
line = line.strip()
line = line.split()
book_info.append(line)
# print(int(book_info[0][1]))
else:
book_info = \
[
['《Python基础编程》', 10],
['《Python进阶编程》', 10],
['《Python高级编程》', 10],
['《Django入门指南》', 10]
]
with open("book_info.txt", mode="w", encoding="utf-8") as file:
for i in range(len(book_info)):
s = str(book_info[i]).replace('[', '').replace(']', '')
s = s.replace("'", '').replace(',', '') + '\n'
file.write(s)
current_borrow = []
with open("user_info.txt", mode="r", encoding="utf-8") as file:
user_info = json.load(file)
if user_info[user_name]['role'] != 'admin':
if user_info[user_name]['balance'] != -1:
balance = user_info[user_name]['balance']
else:
balance = input("Please recharge:")
flag = 1
while flag:
if balance.isdigit():
balance = int(balance)
flag = 0
else:
print("balance must be numeric:")
balance = input("Please recharge:")
while True:
for index, book in enumerate(book_info):
print(index, book[0], book[1])
choice = input("Please choose the book you want to borrow:")
if choice.isdigit():
choice = int(choice)
if choice < len(book_info) and choice > -1:
book_info[choice][1] = int(book_info[choice][1])
if book_info[choice][1] > 0:
if balance > 99:
current_borrow.append(book_info[choice][0])
user_info[user_name]['book_shelf'].append(book_info[choice][0])
balance -= 100
book_info[choice][1] -= 1
now = time.strftime("%Y-%m-%d-%H_%M_%S", time.localtime(time.time()))
# write borrow_history
user_info[user_name]['history'][now] = book_info[choice][0] + " borrow"
with open("user_info.txt", mode="w", encoding="utf-8")as file:
json.dump(user_info, file)
print("\033[1;34;40m%s\033[0m" % str(book_info[choice][0]) + " has already added in current-borrow!\
And your balance is: " + "\033[1;31;40m%s\033[0m" % balance)
else:
print("You don't have enough balance:" + "\033[1;31;40m%s\033[0m" % balance)
continue
else:
print("The book you borrowed is insufficient")
else:
print("choice can only in 0-", len(book_info) - 1)
elif choice == 'q':
if len(current_borrow) != 0:
print("Thank you sir and what you have borrowed are:\n")
for index, book in enumerate(current_borrow):
print(index + 1, book)
print("Your balance is:" + "\033[1;31;40m%s\033[0m" % balance)
# write balance and book_info
user_info[user_name]['balance'] = balance
with open("user_info.txt", mode='w', encoding="utf-8")as file:
json.dump(user_info, file)
with open("book_info.txt", mode="w", encoding="utf-8") as file:
for i in range(len(book_info)):
s = str(book_info[i]).replace('[', '').replace(']', '')
s = s.replace("'", '').replace(',', '') + '\n'
file.write(s)
exit()
else:
print("cannot identify non-numeric except q")
else:
print("No permission to borrow books")
@mask("Return books")
def return_book(user_name):
if os.path.exists("book_info.txt"):
book_info = []
with open("book_info.txt", mode="r", encoding="utf-8")as file:
for line in file.readlines():
line = line.strip()
line = line.split()
book_info.append(line)
with open("user_info.txt", mode="r", encoding="utf-8")as file:
user_info = json.load(file)
if user_info[user_name]['role'] != 'admin':
current_return = []
balance = user_info[user_name]['balance']
if user_info[user_name]['book_shelf']:
while True:
if user_info[user_name]['book_shelf']:
for index, book in enumerate(user_info[user_name]['book_shelf']):
print(index, book)
choice = input("Please select the book to return:")
if choice.isdigit():
choice = int(choice)
if choice < len(user_info[user_name]['book_shelf']) and choice > -1:
for i in range(len(book_info)):
if book_info[i][0] == user_info[user_name]['book_shelf'][choice]:
book_info[i][1] = int(book_info[i][1])
book_info[i][1] += 1
balance += 100
current_return.append(user_info[user_name]['book_shelf'][choice])
now = time.strftime("%Y-%m-%d-%H_%M_%S", time.localtime(time.time()))
# write return_history
user_info[user_name]['history'][now] = book_info[choice][0] + " return"
tmp = user_info[user_name]['book_shelf'].pop(choice)
with open("user_info.txt", mode="w", encoding="utf-8")as file:
json.dump(user_info, file)
print("\033[1;34;40m%s\033[0m" % tmp + " has already returned!\
And your balance is: " + "\033[1;31;40m%s\033[0m" % balance)
else:
print("choice can only in 0-", len(user_info[user_name]['book_shelf']))
elif choice == 'q':
if current_return != 0:
print("Thank you sir and what you have returned are:\n")
for index, book in enumerate(current_return):
print(index + 1, book)
print("Your balance is:" + "\033[1;31;40m%s\033[0m" % balance)
# write balance and book_info
user_info[user_name]['balance'] = balance
with open("user_info.txt", mode='w', encoding="utf-8")as file:
json.dump(user_info, file)
with open("book_info.txt", mode="w", encoding="utf-8") as file:
for i in range(len(book_info)):
s = str(book_info[i]).replace('[', '').replace(']', '')
s = s.replace("'", '').replace(',', '') + '\n'
file.write(s)
exit()
else:
print("Your balance is:" + "\033[1;31;40m%s\033[0m" % balance)
# write balance and book_info
user_info[user_name]['balance'] = balance
with open("user_info.txt", mode='w', encoding="utf-8")as file:
json.dump(user_info, file)
with open("book_info.txt", mode="w", encoding="utf-8") as file:
for i in range(len(book_info)):
s = str(book_info[i]).replace('[', '').replace(']', '')
s = s.replace("'", '').replace(',', '') + '\n'
file.write(s)
exit("Your books are all returned!")
else:
exit("You haven't borrowed any books yet!")
else:
exit("No permission to return books")
@mask("Search history")
def search_history(user_name):
if os.path.exists("user_info.txt"):
with open("user_info.txt", mode="r", encoding="utf-8") as file:
user_info = json.load(file)
if user_info[user_name]['role'] != 'admin':
for history in user_info[user_name]['history'].items():
print(history)
else:
exit("No permission to search history!")
else:
print("There is no history for seeking")
@mask("Manage library")
def manage_library(user_name):
with open("user_info.txt", mode="r", encoding="utf-8") as file:
user_info = json.load(file)
if user_info[user_name]['role'] != 'admin':
exit("Permission denied!")
else:
if os.path.exists("book_info.txt"):
book_info = []
with open("book_info.txt", mode="r", encoding="utf-8")as file:
for line in file.readlines():
line = line.strip()
line = line.split()
book_info.append(line)
else:
book_info = \
[
['《Python基础编程》', 10],
['《Python进阶编程》', 10],
['《Python高级编程》', 10],
['《Django入门指南》', 10]
]
with open("book_info.txt", mode="w", encoding="utf-8") as file:
for i in range(len(book_info)):
s = str(book_info[i]).replace('[', '').replace(']', '')
s = s.replace("'", '').replace(',', '') + '\n'
file.write(s)
if os.path.exists("user_info.txt"):
with open("user_info.txt", mode="r", encoding="utf-8") as file:
user_info = json.load(file)
else:
user_info = \
{
'alex': {'pwd': 'alex123', 'role': 'admin', 'state': True},
'pizza': {'pwd': 'pizza123', 'role': 'teacher', 'state': True, 'balance': -1, 'book_shelf': [],
'history': {}},
'john': {'pwd': 'john123', 'role': 'student', 'state': True, 'balance': -1, 'book_shelf': [],
'history': {}}
}
with open("user_info.txt", mode="w", encoding="utf-8") as file:
json.dump(user_info, file)
while True:
choose = input \
("""
1.change the number of book
2.add new book
3.add new account
4.delete account
5.quiet
""")
if choose == '1':
for index, book in enumerate(book_info):
print(index, book)
selection = input("select the book you want to change:")
if selection.isdigit():
selection = int(selection)
num = input("inpuy the number you want wo change:")
if num.isdigit():
num = int(num)
if num > 0:
book_info[selection][1] = int(book_info[selection][1])
book_info[selection][1] = num
elif num == 0:
book_info.pop(selection)
else:
print("you can only input Positive number")
else:
print("you can only input number!")
else:
print("you can only input number!")
continue
elif choose == '2':
name = input("input the book's name:")
number = input("input the book's number:")
tmp = [name, number]
book_info.append(tmp)
continue
elif choose == '3':
new_name = input("Please input the username:")
new_pwd = input("Please input the password:")
new_role = input("Please input student or teacher:")
user_info[new_name]={'pwd': new_pwd, 'role': new_role, 'state': True, 'balance': -1, 'book_shelf': [],
'history': {}}
elif choose == '4':
for i in user_info:
print(i)
del_user = input("Please input the user you want to delete")
if del_user in user_info:
del user_info[del_user]
else:
print("There is no such account!")
elif choose == '5':
with open("book_info.txt", mode="w", encoding="utf-8") as file:
for i in range(len(book_info)):
s = str(book_info[i]).replace('[', '').replace(']', '')
s = s.replace("'", '').replace(',', '') + '\n'
file.write(s)
with open("user_info.txt", mode='w', encoding="utf-8")as file:
json.dump(user_info, file)
exit()
else:
print("Sorry, you can only type 1~5")
continue
username = login()
for index, item in enumerate(list(func_dict), start=1):
print(index, item)
c = int(input(">>>"))
v = func_dict[list(func_dict)[c - 1]]
v(username)
代码链接提取码:lsxm