Answered step by step
Verified Expert Solution
Link Copied!

Question

1 Approved Answer

Python Key Value Store Design Properly implement an application with a Key Value Database that incorporates the design principles of: Time to Live (TTL) keys

Python Key Value Store Design

Properly implement an application with a Key Value Database that incorporates the design principles of: Time to Live (TTL) keys

Directions:

Start from your main.py

main.py:

import pickledb from datetime import date import sqlite3 def DictName(Part1): #get current date today = date.today() # mm/dd/YY d1 = today.strftime("%mm%dd%Y") return str(Part1+'%%'+d1) def RemoveAll(): #remove all data from key value store db db.deldb() #load the student db db = pickledb.load('Student.db', False) def print_Menu(bHasStudentInfo): #print menu #Add/edit student if(bHasStudentInfo): print("A) Edit Student Info") else: print("A) Add Student Info") #display student info print("B) Display Student Info") #save student info to long term db print("C) Register Student") #display all reg students print("D) Display All Register Student") # Quit print("Q) Quit") def getMenuOption(): #get menu option option = str(input("Please enter in your option...")) #convert to upper case option = option.upper() #while menu option not valid choice while ((option < "A") and (option > "D") and (option != "Q") ): #display menu print_Menu() # get menu option option = str(input("Please enter in your option...")) # convert to upper case option = option.upper() return option def AddStudent(bStudentInfoExists,Name,Age,GPA,CellPh): if (bStudentInfoExists): #display current name print("Current Name:", Name) # prompt and get new name print("Name:") Name = GetValidString() if (not bStudentInfoExists): #create key value db if required db.dcreate(DictName('Student')) db.set(DictName('StudentExists'),1) # add name to dictionary in key value db db.dadd(DictName('Student'),('Name','test')) if (bStudentInfoExists): #display current Age print("Current Age:", Age) # prompt and get new Age Age = GetValidAge() # add age to dictionary in key value db db.dadd(DictName('Student'), ('Age',Age)) if (bStudentInfoExists): #display current GPA print("Current GPA:", GPA) # prompt and get new GPA GPA = GetValidGpa() # add gpa to dictionary in key value db db.dadd(DictName('Student'), ('GPA',GPA)) if (bStudentInfoExists): #display current Cell Phone Num print("Current Cell Phone Num:", CellPh) # prompt and get new Cell Phone Num print("Cell Phone Num:") CellPh = GetValidString() # add cellphone to dictionary in key value db db.dadd(DictName('Student'), ('CellPh',CellPh)) #set flag as now student info exists bStudentInfoExists = True return bStudentInfoExists,Name,Age,GPA,CellPh def GetValidString(): #prompt and read in string val = input("Enter in a value") #strip string of spaces val = val.strip() while (len(val)<=0): #while string empty # prompt and read in string val = input("Enter in a value") # strip string of spaces val = val.strip() #return valid string return val def GetValidAge(): #prompt and read in age val = int(input("Enter in an age")) while ((val<=0) or (val >120)): #while val is invalid age # prompt and read in age val = int(input("Enter in an age")) #return valid age return val def GetValidGpa(): #prompt and read in gpa val = float(input("Enter in a gpa")) while ((val<0) or (val >4.2)): #while val is invalid gpa # prompt and read in gpa val = float(input("Enter in a gpa")) #return valid gpa return val def DisplayStudent(Name,Age,GPA,CellPh): #display the student information print("**************") print("Name:",Name) print("Age:",Age) print("GPA:",GPA) print("Cell Phone Num:",CellPh) print("**************") def LoadStudent(): #load student from key value store Name=db.dget(DictName('Student'),'Name') Age=db.dget(DictName('Student'),'Age') GPA=db.dget(DictName('Student'),'GPA') CellPh=db.dget(DictName('Student'),'CellPh') #return student info return Name,Age,GPA,CellPh def RegStudent(Name,Age,GPA,CellPh): #connect to sqlite db conn = sqlite3.connect('RegData.db') #get cursor cur = conn.cursor() #insert new record sql_insert_query = """Insert Into Student ( 'StudentName','Age','GPA','CellPhone') Values (?, ?, ?, ?);""" cur.execute(sql_insert_query, (Name,Age,GPA,CellPh)) # commit and save changes to database conn.commit() # close database connection conn.close() #delete key store db RemoveAll() def DisplayAllRegStudents(): #connect to sqlite db conn = sqlite3.connect('RegData.db') #get cursor cur = conn.cursor() #get all record from Student table cur.execute('''Select * from Student;''') print(f"{'ID':8s}",f"{'Name':20s}",f"{'Age':5s}", f"{'GPA':7s}", f"{'Cell Phone':20s}") for r in cur.fetchall(): print(f"{str(r[0]):8s}",f"{r[1]:20s}",f"{str(r[2]):5s}", f"{str(r[3]):7s}", f"{r[4]:20s}") # close database connection conn.close() def mainApp(bStudentInfoExists): option ="" #init student attributes if (not bStudentInfoExists): #if student not in key value db #set to default values Name="" Age=0 GPA = 0.0 CellPh="" else: #if student is in key value db #set to saved values Name, Age, GPA, CellPh = LoadStudent() RemoveAll() #while user decides not to quit while (option != "Q"): #show menu print_Menu(bStudentInfoExists) #get option from user option = getMenuOption() if (option =="A"): #If option A chosen #add/edit student bStudentInfoExists, Name, Age, GPA, CellPh=AddStudent(bStudentInfoExists,Name,Age,GPA,CellPh) elif (option =="B"): #If option B chosen if (bStudentInfoExists == False): # If student does not exist #display err msg print("You must add a student first.") print("") else: #otherwise display student info DisplayStudent(Name,Age,GPA,CellPh) elif (option =="C"): #If option C chosen if (bStudentInfoExists == False): # If student does not exist #display err msg print("You must add a student first.") print("") else: #otherwise display student info RegStudent(Name,Age,GPA,CellPh) #reset flag bStudentInfoExists = False elif (option =="D"): DisplayAllRegStudents() return bStudentInfoExists # Press the green button in the gutter to run the script. if __name__ == '__main__': #check to see if there is student information #in the key value db if (db.get(DictName('StudentExists'))): if (db.dget(DictName('Student'),'Name')): bStudentInfoExists = True else: bStudentInfoExists = False else: bStudentInfoExists = False bStudentInfoExists = mainApp(bStudentInfoExists) #if student information was created #save the key value db if(bStudentInfoExists): db.dump()

You must add

1) Time to Live (TTL) keys (15 points)

You must add functionality so that it deletes keys that are more than 3 days old.

TTL:

import pickledb from datetime import date,timedelta db = pickledb.load('test.db', False) def genKey(stdNum): #get current date today = date.today() # mm/dd/YY d1 = today.strftime("%mm%dd%Y") return str('Student'+':'+d1+':'+stdNum) #student 1 stdNum = input("Enter in student number") db.dcreate(genKey(stdNum)) name = input("Enter in your name") age = int(input("Enter in your age")) gpa = float(input("Enter in your gpa")) db.dadd(genKey(stdNum),('stu-name',name)) db.dadd(genKey(stdNum),('stu-age',age)) db.dadd(genKey(stdNum),('stu-gpa',gpa)) #student 2 stdNum = input("Enter in student number") db.dcreate(genKey(stdNum)) name = input("Enter in your name") age = int(input("Enter in your age")) gpa = float(input("Enter in your gpa")) db.dadd(genKey(stdNum),('stu-name',name)) db.dadd(genKey(stdNum),('stu-age',age)) db.dadd(genKey(stdNum),('stu-gpa',gpa)) #show all print(db.getall()) #find a student stdNum = input("Enter in student number") if (db.exists(genKey(stdNum))): print(db.dgetall(genKey(stdNum))) #Delete students past time #get date 5 days ago day = date.today() + timedelta(days=-5) print(day) #Locate all key value dict stores with this # date and remove them using drem command db.dump() 

I have already provided the code, I just need to know how to implement TTL in the main.py and not have it as a separate python file.

Step by Step Solution

There are 3 Steps involved in it

Step: 1

blur-text-image

Get Instant Access to Expert-Tailored Solutions

See step-by-step solutions with expert insights and AI powered tools for academic success

Step: 2

blur-text-image

Step: 3

blur-text-image

Ace Your Homework with AI

Get the answers you need in no time with our AI-driven, step-by-step assistance

Get Started

Recommended Textbook for

Database Design Application Development And Administration

Authors: Michael V. Mannino

3rd Edition

0071107010, 978-0071107013

More Books

Students also viewed these Databases questions

Question

2. What are your challenges in the creative process?

Answered: 1 week ago