Advertisement
Guest User

Untitled

a guest
Jun 19th, 2019
88
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 12.13 KB | None | 0 0
  1. import json
  2. from abc import ABC, abstractmethod
  3. import csv
  4. import pprint
  5.  
  6. class Handler:
  7. def __init__(self):
  8. self.content = None
  9. @abstractmethod
  10. def read(self):
  11. pass
  12. @abstractmethod
  13. def store(self,es,fname,path):
  14. pass
  15. def getContent(self): # Check: why this is not abstract?
  16. return self.content
  17.  
  18.  
  19. class JSONHandler(Handler):
  20. def __init__(self, filename, path=''):
  21. super().__init__() # Check: why do we call parent's initializer?
  22. self.jsonFile = path+filename # Check: specialization - behaviour/property that the child adds to the parent
  23.  
  24. def read(self): # Check: why do1 we provide implementation here?
  25. fo = open(self.jsonFile,'r')
  26. c = fo.read()
  27. self.content = json.loads(c) # Check: deserialize json content
  28. fo.close()
  29.  
  30. def store(self, es, fname, path):
  31. #this method to store given list of elements as es in a json file
  32. # and serialize es and save it in the file
  33. savepath = path + "/"+fname
  34.  
  35. with open(savepath, 'w+') as outfile:
  36. data = []
  37. for elements in es:
  38. #json.dump(ele.__dict__, outfile)
  39. #data.append(elements.__dict__)
  40. data.append(elements.__dict__)
  41. json.dump(data, outfile, indent=2, sort_keys=False )
  42.  
  43. class CSVHandler(Handler):
  44. def __init__(self, filename, path=''): # Check: looks very similar to the init of JSONHandler. Any suggestion?
  45. super().__init__()
  46. self.csvFile = path+filename
  47.  
  48. def read(self):
  49. # fo = open(self.csvFile, 'r')
  50. # c = fo.read()
  51. # self.content = csv.DictReader(c) # Check: deserialize json content
  52.  
  53. with open(self.csvFile) as file:
  54. csv_reader = csv.reader(file, delimiter='\t')
  55. dict_list=[]
  56. for row in csv_reader:
  57. dict_list.append(row)
  58. self.content = dict_list
  59.  
  60. # fo.close()
  61. # with open(self.csvFile, 'r') as csv_file:
  62. # csv_reader = csv.DictReader(csv_file, delimiter=',')
  63. # dict_list=[]
  64. # for row in csv_reader:
  65. # dict_list.append(row)
  66. # self.content = dict_list
  67. ##pprint.pprint(self.content)
  68.  
  69. print('csv file content is being read here ...')
  70.  
  71. def store(self,es,fname,path):
  72. # this method to store given list of elements as es in a json file
  73. # and serialize es and save it in the file
  74. savepath = path + "/" + fname
  75.  
  76. with open(savepath, 'w+') as outfile:
  77. data = []
  78. for elements in es:
  79. # json.dump(ele.__dict__, outfile)
  80. # data.append(elements.__dict__)
  81. data.append(elements.__dict__)
  82. json.dump(data, outfile, indent=2, sort_keys=False)
  83.  
  84.  
  85. # print('csv file content is being written here ...')
  86.  
  87. #parentclass
  88. class ToString:
  89. @abstractmethod
  90. def __str__(self):
  91. pass
  92.  
  93. #child class
  94. class Book(ToString):
  95. lastId = 0 # Check: why do we need this static member?
  96. status = ""
  97.  
  98. @staticmethod # Check: why static method?
  99. def __nextId():
  100. Book.lastId = Book.lastId + 1
  101. return Book.lastId
  102.  
  103. def __init__(self,author='',country='',imageLink='',language = '',link='',pages='',title='' , year='', status=''):
  104. self.author = author
  105. self.country = country
  106. self.imageLink = imageLink
  107. self.language = language
  108. self.link = link
  109. self.pages = pages
  110. self.title = title
  111. self.year = year
  112. self.status = status
  113. self.BookID = Book.__nextId()
  114.  
  115. def lend(self):
  116. self.status = "lend"
  117.  
  118. def not_lend(self):
  119. self.status = "not lend"
  120.  
  121. def __str__(self):
  122. return "ID: "+str(self.BookID)+"\nAuthor: "+self.author +". "+"\nCountry:"+self.country+". "+ "\nImageLink: "+self.imageLink+"\nLanguage:"+self.language+". "+"\nLink:"+self.link+ "\nPages:"+str(self.pages)+". "+"\nTitle:"+self.title+". "+"Year:"+str(self.year)+". " +"\nStatus:"+self.status+". "
  123.  
  124. class BookManager:
  125.  
  126. def __init__(self, handler):
  127. self.handler = handler
  128. self.books = []
  129.  
  130. def loadBooks(self):
  131. self.handler.read()
  132. booksList = self.handler.getContent()
  133. for u in booksList:
  134. auth = u['author']
  135. country = u['country']
  136. imageLink = u['imageLink']
  137. language = u['language']
  138. link = u['link']
  139. pages = u['pages']
  140. title = u['title']
  141. year = u['year']
  142. status = u['status']
  143. self.books.append(Book(auth,country,imageLink,language,link,pages,title,year,status))
  144.  
  145. def storeBooks(self,fn,path):
  146. self.handler.store(self.books,fn,path)
  147.  
  148. def getBooks(self):
  149. return self.books
  150.  
  151.  
  152.  
  153.  
  154. class Person(ToString):
  155. firstName = ""
  156. surName = ""
  157. gender = ""
  158. emailAddress = ""
  159. userName = ""
  160. personType = ""
  161. idRegNum = 0
  162.  
  163. @staticmethod # Check: why static method?
  164. def __nextId():
  165. Person.idRegNum = Person.idRegNum + 1
  166. return Person.idRegNum
  167.  
  168. def __init__(self,fn,ln,gender,emailAddress,userName,personType):
  169. self.firstName= fn
  170. self.surName= ln
  171. self.gender= gender
  172. self.emailAddress = emailAddress
  173. self.userName = userName
  174. self.personType = personType
  175. self.PersonId = Person.__nextId()
  176.  
  177.  
  178. def __str__(self):
  179. return "RegId"+str(self.PersonId)+"Firstname" + self.firstName + "Surname" + self.surName +"gender"+self.gender+"email adress"+self.emailAddress+"Username"+self.userName
  180.  
  181. class Customer(Person):
  182. nameSet = ""
  183. streetAddress = ""
  184. zipCode = ""
  185. city = ""
  186. telephoneNumber = ""
  187.  
  188. def __init__(self,fn,ln,gender,emailAddress,nameSet,streetAddress,zipCode,city,userName,telephoneNumber,personType):
  189. super().__init__(fn,ln,gender,emailAddress,userName,personType)
  190. self.nameSet = nameSet
  191. self.streetAddress = streetAddress
  192. self.zipCode = zipCode
  193. self.city = city
  194. self.telephoneNumber = telephoneNumber
  195.  
  196. def __str__(self):
  197. super().__str__()
  198. return "\nNameset"+self.nameSet+"Street Address"+self.streetAddress+"Zipcode"+self.zipCode+"City"+self.city+"Telephone Number"+self.telephoneNumber
  199.  
  200.  
  201. class Student(Customer):
  202. rollNumber=0
  203. department=""
  204. semester=""
  205. batch=""
  206.  
  207.  
  208. @staticmethod # Check: why static method?
  209. def __nextId():
  210. Student.rollNumber = Student.rollNumber + 1
  211. return Student.rollNumber
  212.  
  213.  
  214. def __init__(self,fn,ln,gender,emailAddress,nameSet,streetAddress,zipCode,city,userName,telephoneNumber,personType, rollNumber, department, semester, batch):
  215. super().__init__(fn,ln,gender,emailAddress,nameSet,streetAddress,zipCode,city,userName,telephoneNumber,personType)
  216. self.rollNumber= rollNumber
  217. self.department= department
  218. self.semester= semester
  219. self.batch = batch
  220.  
  221. def __str__(self):
  222. super().__str__()
  223. return "\nRollnumber"+self.rollNumber+"department"+self.department+"semester"+self.semester+"batch"+self.batch
  224.  
  225.  
  226.  
  227. class PersonManager:
  228.  
  229. def __init__(self, handler):
  230. self.handler = handler
  231. self.persons = []
  232.  
  233. def loadStudents(self):
  234. self.handler.read()
  235. personsList = self.handler.getContent()
  236. for u in personsList:
  237. print(u[0])
  238. #print(u[1])
  239.  
  240. #number = u[0]
  241. # gender = u[1]
  242. # nameSet = u[2]
  243. # fn = u[3]
  244. # ln = u[4]
  245. # streetAddress = u[5]
  246. # zipCode = u[6]
  247. # city = u[7]
  248. # emailAddress = u[8]
  249. # userName = u[9]
  250. # telephoneNumber = u[10]
  251. # #personType = u[11]
  252. # rollNumber = u[11]
  253. # department = u[12]
  254. # semester = u[13]
  255. # batch = u[14]
  256.  
  257. # self.persons.append(Student(number,gender,nameSet,fn,ln,streetAddress,zipCode,city,emailAddress,userName,telephoneNumber,rollNumber,department,semester,batch))
  258.  
  259.  
  260. def storePersons(self,fn,path):
  261. self.handler.store(self.persons,fn,path)
  262.  
  263. def getPersons(self):
  264. return self.persons
  265.  
  266.  
  267.  
  268. if __name__ == '__main__':
  269. #this is where the json file is imported
  270. h = JSONHandler('booksset1.json')
  271. # h = CSVHandler('booksset1.csv')
  272. bookManager = BookManager(h)
  273. bookManager.loadBooks()
  274. booksInfo = bookManager.getBooks()
  275.  
  276. # c = CSVHandler('FakeNameSet20.csv')
  277. # personManager = PersonManager(c)
  278. # personManager.loadStudents()
  279. # personsInfo = personManager.getPersons()
  280. # print(personsInfo)
  281.  
  282. # 1. Login as customer
  283. ##1. View All Books
  284. ##2. Choose Books by Number to lend
  285. ##3. Choose Books by Number to give back
  286.  
  287. # 2. Login as Administrator
  288. ##1. Add Book
  289. ##2. Remove Book
  290. ##3. Make a JSON BACKUP for Books
  291. ##4. Make a CSV BACKUP for Customers & Administrators
  292.  
  293. #Menu
  294. while True:
  295. print("""\n MENU
  296. 1. View All Books
  297. 2. Choose Books by Number to lend
  298. 3. Choose Books by Number to give back
  299. 4. Add Book
  300. 5. Remove Book
  301. 6. Make a JSON BACKUP
  302. 7.
  303. 8.
  304. 9.
  305. 10. Exit
  306. """)
  307. chosenMenu=int(input("Make a choice of menu\n"))
  308. if chosenMenu==1:
  309.  
  310.  
  311. for u in booksInfo:
  312. print("------****-----\n")
  313. print(u)
  314. print("------****-----\n")
  315.  
  316. elif chosenMenu==2:
  317.  
  318.  
  319.  
  320. n=int(input("Enter id. of book you want to lend:"))
  321.  
  322. print(booksInfo[n-1])
  323.  
  324. booksInfo[n - 1].lend()
  325.  
  326. print(booksInfo[n - 1])
  327.  
  328.  
  329.  
  330.  
  331. elif chosenMenu==3:
  332.  
  333. n = int(input("Enter id. of book you want to give back:"))
  334.  
  335. print(booksInfo[n - 1])
  336.  
  337. booksInfo[n - 1].not_lend()
  338.  
  339. print(booksInfo[n - 1])
  340.  
  341.  
  342. elif chosenMenu==4:
  343. print("Welcome you want to add a book Go ahead!\n")
  344. authorfield = input("Enter the author name:")
  345. countryfield = input("Enter the country:")
  346. imageLink = input("Enter the Imagelink:")
  347. language = input("Enter the language:")
  348. link = input("Enter the link:")
  349. while True:
  350. try:
  351. pages = int(input("Enter the pages - number:"))
  352. break
  353. except:
  354. print("Enter a valid number only...!")
  355. continue
  356.  
  357. title = input("Enter the title:")
  358.  
  359. while True:
  360. try:
  361. year = int(input("Enter year - number:"))
  362. break
  363. except:
  364. print("Enter a valid number only...!")
  365. continue
  366.  
  367. status = "not lend"
  368.  
  369. booksInfo.append(Book(authorfield,countryfield,imageLink,language,link,pages,title,year,status))
  370.  
  371.  
  372. elif chosenMenu==5:
  373. isremoved = False
  374. givenId = int(input("Enter id. of book you want to remove:"))
  375. indexToBeDeleted = 0
  376. for e in booksInfo:
  377. if(e.BookID == givenId):
  378. isremoved = True
  379. booksInfo.pop(indexToBeDeleted)
  380. break
  381. indexToBeDeleted = indexToBeDeleted + 1
  382. if(isremoved == False):
  383. print("Given ID doesn't exist")
  384. else:
  385. print("ID "+str(givenId)+" is successfully removed from the libary")
  386. elif chosenMenu==6:
  387. #bookManager.storeBooks("backup1.json","C:/Users/rahul/Documents/School/Analyse/analyses 3/assignment3/PLS3")
  388. bookManager.storeBooks("backup1.json","../../PLS3/")
  389. print("File is backed up at PLS3 folder\n")
  390.  
  391. elif chosenMenu==7:
  392.  
  393. print("\nTill Next Time!")
  394. sys.exit()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement