Python入門練習題(4)-圖書管理系統

這是一次結合前幾次小練習的綜合性作業,也算是對前面學習內容小結吧

實現功能:

一、登陸模塊:

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

2018.8.6

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章