Python中的图书馆系统

时间:2019-06-14 20:07:22

标签: python python-3.x oop

我正在尝试修复一些方法,例如在我的公共图书馆系统中“还原备份”。但是我已经坚持了好几个星期。下面的代码,但很多。我希望阅读起来不那么复杂。

主要思想和目的是将代码保存和存储在JSON文件中。指令编写如下,一次运行一种方法。因此,我尝试制作一本新书,例如将其存储在JSON文件中。代码已编写,但我似乎无法使备份+恢复功能正常工作。

我尝试基本上为它编写新方法

"""TODO:
Done - filling the system with books from a file of books in JSON format (file with books).  You may add a fake ISBN number to book items and generate the number of book items per book.
Done - filling the system with customers from a file of people ( file).
Done - adding a book item.
Done - adding a customer.
Done - searching a book.
Done - making a book loan.
Done - making a backup of the system in JSON format.
Not Done - restoring the system from a backup.
 """


import json
import csv

"""
    Created class 'Book' for adding a new book,
    Returning the new dict() back to the class 'bookItems'
    where it will be added to the bookcollection
"""

class Book:
    @staticmethod
    def createBook(FileBookcollection):
        #parameters is for the inputUser. So it shows the right text for the user
        parameters = ["author","country","imageLink","language","link","pages","title","year"]
        newBook = dict()
        for item in parameters:
            inputUser = input("Fill in the " + item + " of the book: ")
            if inputUser == "":
                newBook[item] = None
            else:
                #adding the parameters as key and inputUser as value to the dict newBook
                newBook[item] = inputUser
        #Adding ISBN to the Dict with a counter that counts the Len(Dict) + 1
        newBook["ISBN"] = str(len(FileBookcollection) + 1)
        return newBook


class bookItems:
    def __init__(this,JSONFileBookCollection):
        this.JSONFileBookCollection = JSONFileBookCollection
        #Adding ISBN to the Dict with a counter that counts the Len(Dict) + 1
        #every row has a unique ISBN in total list
        numberCounter = 0
        for book in JSONFileBookCollection:
            numberCounter += 1
            book["ISBN"] = str(numberCounter)

    def createBook(this):
        newBook = Book.createBook(this.JSONFileBookCollection)
        this.JSONFileBookCollection.append(newBook)

    """Method that will be called from the class 'Catalog' to show all the books"""
    def getAllBooks(this):
        return this.JSONFileBookCollection
"""
    def restoreBooksBackup(this):
        with open(r".\bookCollectionBackup.json") as jsonFile:
            bookList = json.load(jsonFile)
            this.JSONFileBookCollection = bookList
"""


class Catalog:
    def __init__(this, dumbJSON):
        this.dumbJSON = dumbJSON

    def getAllBooks(this):
        return this.dumbJSON.getAllBooks()

    def showAllBooks(this):
        for book in this.dumbJSON.getAllBooks():
            for itemsBooks in book:
                print(itemsBooks," : ", book[itemsBooks])
            print("\n--------------------------------------------------------------\n")

    def getBookByLang(this):
        booksByLang = []
        userInput = input("What language is the book in?" )
        for book in this.dumbJSON.getAllBooks():
            if book["language"] == userInput:
                booksByLang.append(book)

        for results in booksByLang:
            print(results)

    def getBooksByAuthor(this):
        booksByAuthor = []
        userInput = input("What author is the book from?")
        for book in this.dumbJSON.getAllBooks():
            if book["author"] == userInput:
                booksByAuthor.append(book)

        for results in booksByAuthor:
            print(results)

    def getBooksByTitle(this):
        booksByTitle = []
        userInput = input("What's the title from the book?")
        for book in this.dumbJSON.getAllBooks():
            if book["title"] == userInput:
                booksByTitle.append(book)

        for results in booksByTitle:
            print(results)

    def getBooksByISBN(this):
        booksByISBN = []
        userInput = input("What's the ISBN number?")
        for book in this.dumbJSON.getAllBooks():
            if book["ISBN"] == userInput:
                booksByISBN.append(book)

        for results in booksByISBN:
            print(results)

    def restoreBooksBackup(this):
        this.dumbJSON.restoreBooksBackup()
"""
"""
class Person:
    def __init__(this, personsList):
        this.personsList = personsList

    def addPerson(this):
        parameters = ["Number", "Gender", "NameSet", "GivenName", "Surname", "StreetAddress", "ZipCode", "City", "EmailAddress", "Username", "TelephoneNumber"]
        newPerson = list()
        newCustomer = dict()
        for item in parameters:
            inputUser = input("Fill in the " + item + " of the customer: ")
            if inputUser == "":
                newPerson.append(None)
            else:
                newPerson.append(inputUser)
        this.personsList.append(newPerson)

    def getAllPersons(this):
        return this.personsList

    def restorePersonsListBackup(this):
        with open(r".\backupFakeNames.csv","r") as output:
            new_csv = csv.reader(output)
            totalPersonListBackup = []
            for line in new_csv:
                totalPersonListBackup.append(line)
        this.personsList = totalPersonListBackup


class Customer:
    def __init__(this, allPersonsInfo,userNames, CustomerList):
        this.CustomerList = CustomerList
        this.allPersonsInfo = allPersonsInfo
        this.userNames = userNames


        counter = 0
        #Repeat itself 20 times but not sure how to debug that. It works for now but could be fixed later
        for person in this.allPersonsInfo.getAllPersons():
            this.CustomerList[userNames[counter]] = person
            counter +=1

    def getAllCustomers(this):
        return this.CustomerList

    def showAllPersonsInfo(this):
        for username in this.userNames:
            print(this.CustomerList[username])
            print("\n")

    def getAllPersonsInfo(this):
        return this.allPersonsInfo.getAllPersons()

    def getAllUserNames(this):
        return this.userNames

    def restorePersonsListBackup(this):
        this.allPersonsInfo.restorePersonsListBackup()

class administration:
    def __init__(this, bookCollection, AllCustomers, loanBookList):
        this.AllCustomers = AllCustomers
        this.bookCollection = bookCollection
        this.loanBookList = loanBookList
        this.allPersonsInfo = AllCustomers.getAllPersonsInfo()

        for book in this.bookCollection.getAllBooks():
            this.loanBookList[book["ISBN"]] = None

    def setLoanBookPerson(this, isbnCode, customerUsername):
        if customerUsername in this.AllCustomers.getAllUserNames():
            if isbnCode in this.loanBookList.keys():
                if this.loanBookList[isbnCode] != None:
                    print("This book is already used:")
                else:
                    this.loanBookList[isbnCode] = customerUsername
                    for book in this.bookCollection.getAllBooks():
                        if book["ISBN"] == isbnCode:
                            print(customerUsername,"loan book by title:",book["title"])
            else:
                print("isbn code does not exist!")
        else:
            print("Username does not exist!")

    def setLoanBookNobody(this, isbnCode):
        if int(isbnCode) > len(this.loanBookList):
            print("Wrong isbn code, type BookLoanedToPerson.showAllIsbnCodes() to check all the isbn codes ")
        else:
            this.loanBookList[isbnCode] = None

    def showAllAvailableBooks(this):
        for book in this.loanBookList:
            if this.loanBookList[book] == None:
                print("\nThis book is available for loan: ", book)

    def showAllIsbnCodes(this):
        for code in this.loanBookList.keys():
            print("isbn code: " + code)
    def makeBackup(this):
        with open(r".\backupFakeNames.csv","w",newline="") as output:
            new_csv = csv.writer(output)
            new_csv.writerows(this.allPersonsInfo)

        with open(r".\bookCollectionBackup.json","w") as jsonFile:
            json.dump(this.bookCollection.getAllBooks(),jsonFile)

        with open(r".\loanbookListBackup.json","w") as jsonFile:
            json.dump(this.loanBookList,jsonFile)

    def restoreBackUp(this):
        pass
"""
        with open(r".\bookCollectionBackup.json") as jsonFile:
            bookList = json.load(jsonFile)
            this.bookCollection.dumbJSON.JSONFileBookCollection = bookList
        with open(r".\backupFakeNames.csv","r") as output:
            new_csv = csv.reader(output)
            totalPersonListBackup = []
            for line in new_csv:
                totalPersonListBackup.append(line)
        this.AllCustomers.allPersonsInfo.personsList = totalPersonListBackup
        #this.bookCollection.restoreBooksBackup()
        with open(r".\loanbookListBackup.json") as jsonFile:
            fileLoanBookBackup = json.load(jsonFile)
        this.loanBookList = fileLoanBookBackup
"""

if __name__=="__main__":

    reader = csv.reader(open('FakeNameSet20.csv', 'r'))
    totalPersonList = []
    userNameList = []
    PreMadeCustomerDict = dict()

    for line in reader:
        userNameList.append(line[9])
        totalPersonList.append(line)

    """PersonalInfoAllpeople exist of list with list of all info over books """
    PersonalInfoAllpeople = Person(totalPersonList)
    CustomerList = Customer(PersonalInfoAllpeople, userNameList,PreMadeCustomerDict)

    with open('booksset1.json') as jsonFile:
        bookList = json.load(jsonFile)

    bookCollection = bookItems(bookList)
    booksCatalog = Catalog(bookCollection)

    emptyDict = dict()
    BookLoanedToPerson = administration(booksCatalog,CustomerList,emptyDict)

    """-----------------------------------------------------------------------------------"""

    #Examples of wrong input:
    BookLoanedToPerson.setLoanBookPerson("200","kaas")
    BookLoanedToPerson.setLoanBookPerson("200","Reech1950")
    #Example of putting a ISBN code & username so that person will loan that book
    BookLoanedToPerson.setLoanBookPerson("2","Reech1950")
    #Example of person delivering book back. Where only the isbn code needs to be given
    BookLoanedToPerson.setLoanBookNobody(2)
    #Example of searching for a ISBN code. It will give a input where you need to fillin a correct isbn code
    booksCatalog.getBooksByISBN()


"""
How to add a new book to library:
bookCollection.createBook()
How to show all the books that is in posession of the library:
booksCatalog.showAllBooks()
How to show all Persons:
CustomerList.showAllPersonsInfo()
How to add a new customer:
PersonalInfoAllpeople.addPerson()
How to search for available books in the library:
BookLoanedToPerson.showAllAvailableBooks()
How to set certain book on loan:
BookLoanedToPerson.setLoanBookPerson(isbn-code,Username)
BookLoanedToPerson.setLoanBookPerson("1","Ancion")
How to set a backup from all the data
BookLoanedToPerson.makeBackup()
How to show all the books that's by Language.
booksCatalog.getBookByLang()
How to show all the isbn codes:
BookLoanedToPerson.showAllIsbnCodes()
""" 

没有显示错误消息

0 个答案:

没有答案