Archive

Archive for June 21, 2020

Python: Library Managment System -P4

June 21, 2020 1 comment


Learning : Python, DataBase, SQlite
Subject: Create Simple Library Managment System

In this Part we will work on Functions to Manage the Authors of the Books. We can enter the Authors in two ways, Even with Entering the book; such as when we are entering a New Book we can Select an Author from the list or (if the Author is not exist) we can select to Enter New Author. Or from the Author menu we can Enter New Author.

Here we are working on the Author Managment, and we will write the codes to:
Add New Authors.
Edit an Author.
Delete an Author.
Show Authors.

Here is the Author Menu with Functions Names..


We will start with Add New Author: In this Function we will ask the user to enter the Author Name then if the Author has Email or any Social Media Account, then the informations will be saved. Here is the code ..

# Authors Menu

def new_authors() :
    while True  :
        os.system('clear')
        print('\n   ====== Add New Authors ======') 
    
        author_name = input('\n   Enter the Author Name .. >  ').capitalize()
        author_email = input('   Enter the Author Email [Enter to be Empty].. >  ')

        c.execute ("select * from authors where a_name='{}'".format(author_name)) 
        result = c.fetchone()     
                 
        if (result != None) : 
             print('\n   We already have [{}] in the Auther Database. '.format(class_name)) 
        else:    
                c.execute ("INSERT INTO authors (a_name, a_email) VALUES(:a_name,:a_email)",{"a_name":author_name,"a_email":author_email})
                db_conn.commit() 
                print('\n      One Author Added ... ') 
                
                while True :
                    if input('\n   Do you want to Add any Social Media Account to this Author? [Y,N] .. >  ') in ['Y','y']: 
                        c.execute ("select max(a_id) from authors") 
                        auth_id = c.fetchone() 
                        sma_name = input('\n   Enter the Social Media Name.. > ').capitalize()
                        sma_link = input('   Enter the Social Media Link.. > ')
                        c.execute ("INSERT INTO sma (sma_name,sma_link,a_id) VALUES(:sma_name,:sma_link,:a_id)",{"sma_name":sma_name,"sma_link":sma_link,"a_id":auth_id[0]}) 
                        db_conn.commit() 
                    else:
                        break 

        if input('\n\n   Do you want to Add Another Author? [Y,N].. >  ') in ['N','n'] :
             input('\n   To Exit ... Press any key ..') 
             return


Now the Next function, Edit an Author information, here we will list down all the Authors Names and ID and the user will Enter the ID of the one to be Edited, then we will display each attribute and ask the user to Edited or just press Enter (leave it Empty) to keep the exist one. Also we will give the user the ability to Enter a new Social Media Account for the user if needed.

# Edit Author Function


def edit_authors() :
   
    os.system('clear')
    print('\n   ====== Edit Authors ======') 
    print('   The List of Authors We Have, Sorted in Alphbatic\n') 
    c.execute ("select * from authors where a_id > 0  order by a_name")     
    auth_list = c.fetchall() 
    
    # First we show all Authors so the user can select the One to be Edited.
    for auth in range (0,(len(auth_list)-1),4):
       try: 
           print('{:<3}{:<20}'.format(auth_list[auth][0],auth_list[auth][1]),end="")
           print('{:<3}{:<20}'.format(auth_list[auth+1][0],auth_list[auth+1][1]),end="")
           print('{:<3}{:<20}'.format(auth_list[auth+2][0],auth_list[auth+2][1]),end="")
           print('{:<3}{:<20}'.format(auth_list[auth+3][0],auth_list[auth+3][1]))
           
       except:
           pass # Just to avoid Index out of range.    


    edit_auth = input('\n\n   Enter the ID of the Author to Edit. [Q to Exit]  >  ')
    if edit_auth not in ['q','Q'] :
        try:
            c.execute ("select * from authors where a_id = {} ".format(int(edit_auth)))     
            auth_edi = c.fetchall()  
            # Get the Author Social Media Accounts SMA. 
            c.execute ("select * from sma where a_id = {}".format(int(edit_auth)))  
            sma_list = c.fetchall()
            print('         ID:',auth_edi[0][0])
            print('       Name:',auth_edi[0][1])
            print('      Email:',auth_edi[0][2])
            print('     Social Media:')
            for each in sma_list :  
                print('{:<11}{:  ').capitalize()
            a_email = input('   Enter the Author Email.  >  ') 
            if a_name > "" :
                c.execute("update authors set a_name = '{}' where a_id = {}".format(a_name,int(edit_auth))) 
                db_conn.commit() 
            if a_email > "" :      
                c.execute("update authors set a_email = '{}' where a_id = {}".format(a_email,int(edit_auth))) 
                db_conn.commit()      
            
            if (sma_list) != "" :
                for each in sma_list :  
                    sma_l = input('   Enter the {} Account. [D to Delete the Account]  >  '.format(each[2])) 
                    if sma_l > "" and (sma_l not in ['d','D'] ):
                        c.execute("update sma set sma_link = '{}' where a_id = {} and sma_name = '{}'".format(sma_l,int(edit_auth),each[2])) 
                        db_conn.commit() 
                    # If the user select D to Delete the SMA account. 
                    elif sma_l > "" and (sma_l in ['d','D']) :
                        c.execute ("delete from sma where sma_id = '{}' ".format(each[0]))
                        db_conn.commit()
                        print('   {} Account Deleted... '.format(each[2]))

            while True :
                    # If the user want to Add more SMA to the Author.
                    if input('\n   Do you want to Add any Social Media Account to this Author? [Y,N] .. >  ') in ['Y','y']: 
                        sma_name = input('\n   Enter the Social Media Name.. >  ').capitalize()
                        sma_link = input('   Enter the Social Media Link.. >  ')
                        c.execute ("INSERT INTO sma (sma_name,sma_link,a_id) VALUES(:sma_name,:sma_link,:a_id)",{"sma_name":sma_name,"sma_link":sma_link,"a_id":int(edit_auth)}) 
                        db_conn.commit() 
                    else:
                        break
                  
        except:
            
           print('\n   Not valid .. ')
    input('\n   To Exit ... Press any key ..')
    return



When running the code, we need to go back and forth to Show_Author function to see the effect of the Adding, Editing or Deleting functions that we are working one. Now, we will write the Delete_author Function, and as the Edit one first we will list all the Authors on the screen with there ID’s and ask the user to Enter the ID for the one to be Deleted. .. Here is the code.

# Delete an Author


def delete_authors():
    os.system('clear')
    print('\n   ====== Delete Authors ======') 
    print('   The List of Authors We Have, Sorted in Alphbatic\n') 
    c.execute ("select * from authors where a_id > 0  order by a_name")     
    auth_list = c.fetchall() 
    
    # First we show all Authors so the user can select the One to be Deleted.
    for auth in range (0,(len(auth_list)-1),4):
       try: 
           print('{:<3}{:<20}'.format(auth_list[auth][0],auth_list[auth][1]),end="")
           print('{:<3}{:<20}'.format(auth_list[auth+1][0],auth_list[auth+1][1]),end="")
           print('{:<3}{:<20}'.format(auth_list[auth+2][0],auth_list[auth+2][1]),end="")
           print('{:<3}{:  '))
    if del_auth not in ['q','Q'] :
        try:
            c.execute ("select * from authors where a_id = {} ".format(int(del_auth)))     
            auth_det = c.fetchall() 

            print('         ID:',auth_det[0][0])
            print('       Name:',auth_det[0][1])
            print('      Email:',auth_det[0][2])

            if input('\n     Are you Sure you want to Delete this Author? [Y,N].  >   ') in ['Y','y'] :
        
                c.execute ("delete from authors where a_id = '{}' ".format(int(del_auth)))
                db_conn.commit()  
                # To delete any SMA linked to this Author.
                c.execute ("delete from sma where a_id = '{}' ".format(int(del_auth)))
                db_conn.commit()
                input('\n   One Author has been Deleted... Press any Key > ')    
             
            else:
                print('\n   You Select NOT To Delete Author "{}" . '.format(auth_det[0][1]))
                input('\n   To Exit ... Press any key ..') 
        except:
            input('\n   Not valid .. ')
    return



Last Function in this part is Show Authors information, this is easy and short code, we will list down on the screen all the Authors Name, Email, SMA sorted by the Authors Name. Here is the code..

# Function to Show All Authors

def show_authors() :
    os.system('clear')
    print('\n   ====== Show Authors ======')
    print('   The List of Authors We Have, Sorted in Alphbatic\n') 
    c.execute ("select * from authors where a_id > 0  order by a_name")     
    auth_list = c.fetchall()           
    for auth in range (0,(len(auth_list))):
       try: 
           # For each Author we fetch the Social Media Accounts. 
           c.execute ("select * from sma where a_id = {}".format(auth_list[auth][0]))  
           sma_list = c.fetchall()
           print('\n     ID: {}'.format(auth_list[auth][0])) 
           print('   Name: {}'.format(auth_list[auth][1]))
           print('  Email: {}'.format(auth_list[auth][2]))
           print('  Social Media:')
           # Here we print-out the SMA for the Author.
           for each in sma_list :  
              print('{:<11}{:<13} [ {} ]'.format('',each[2],each[3]))
           print('-'*50)           
       except:
           pass     
    
    input('\n\n         ... Press any Key ..')           



Next We will work on Book Managment Menu to Add, Edit, Delete and Show Books in our Library.

[ NOTE ]
1. I am using Galaxy Tab and QPython3 App.
2. All the above codes are available in the Download Section/Page under the project name.
3. The application codes, Functions, Menus and other parts of the Application are subject of changes. In case of changes I will mention that.


:: Library Managment System ::

Part 1 Part 2 Part 3 Part 4

To Download my Python code (.py) files Click-Here




Follow me on Twitter..




By: Ali Radwani