Advertisement
gruntfutuk

employee_dict_eg

Oct 30th, 2022
883
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 4.82 KB | Source Code | 0 0
  1. import csv
  2. from pathlib import Path
  3. from password_func import hash_password, password_bad, generate_password, DEFAULT_PASSWORD
  4.  
  5.  
  6. def employee_create(
  7.         first: str,
  8.         last: str,
  9.         other: str,
  10.         grade: str,
  11.         salary: int,
  12.         position: str='',
  13.         password: str=DEFAULT_PASSWORD):
  14.     if not isinstance(salary, int):
  15.         try:
  16.             salary = int(salary)
  17.         except ValueError:
  18.             raise ValueError('Salary was not a number')
  19.     hashed_password = hash_password(password)
  20.     return {"first": first,
  21.         "last": last,
  22.         "other": other,
  23.         "grade": grade,
  24.         "salary": salary,
  25.         "position": position,
  26.         "password": hashed_password}
  27.  
  28. def report(employee: dict):  # for printing a record
  29.     bad_password = password_bad(employee['password'])
  30.     return (f'Employee: {employee["last"]}, {employee["first"]}.\n'
  31.             f'\tGrade: {employee["grade"]}, Position: {employee["position"]}\n'
  32.             f'\tSalary: £{employee["salary"]}\n'
  33.             f'\tDefault/empty/bad password: {bad_password}')
  34.  
  35. def line(employee: dict):  # for saving to csv format
  36.     return (f'{employee["first"]},{employee["last"]},{employee["other"]},'
  37.            f'{employee["grade"]},{employee["salary"]},{employee["position"]},{employee["password"]}')
  38.  
  39. def row(employee: dict):  # convert string of employee record to list for csv
  40.     return line(employee).split(',')
  41.  
  42. def key(employee: dict):
  43.     """create a unique key for each employee based on all name fields """
  44.     return f'{employee["last"]}_{employee["first"]}_{employee["other"]}'.casefold()
  45.  
  46.  
  47. def save_employees(filename: Path, employees: list):
  48.     """ save dictionary of Employee records to a CSV file """
  49.     if employees:  # check there's data to save, assume the data is valid
  50.         with filename.open('w') as file:  # open file (new or overwrite)
  51.             writer = csv.writer(file)  # writing in csv format
  52.             for employee in employees.values():  # retrieve each Employee record
  53.                 writer.writerow(row(employee))  # convert record to list of fields for CSV and write
  54.  
  55. def read_employees(filename: Path):
  56.     """ read Employee records from CSV into dictionary of Employee records"""
  57.     employees: dict = {}  # start with empty dictionary
  58.     if filename.is_file():  # make sure there is a file, lets assume we can read it
  59.         with filename.open() as file:
  60.             reader = csv.reader(file)
  61.             for idx, row in enumerate(reader):  # need a row number for error reporting
  62.                 try:  # attempt to convert row from csv data into an Employee record
  63.                     new_employee = employee_create(*row)
  64.                 except TypeError:  # probably too few/many fields on the row
  65.                     print(f'Bad Record - row {idx}: {row}')
  66.                 except ValueError as err:  # probably failed check there is a number for salary
  67.                     print(f'Bad Record - row {idx}: {row}')
  68.                     print(err)
  69.                 else:  # add new Employee record to dictionary if not duplicate name
  70.                     if not add_employee(new_employee, employees):
  71.                         print(f'Duplicate Name - row {idx}: {row}')
  72.  
  73.     return employees  # dictionary of Employee records
  74.  
  75. def add_employee(new_employee: dict, employees: list):
  76.     keyid = key(new_employee)  # generate unique key for potential new employee
  77.     if keyid in employees:  # check key is unique, if not retain False
  78.         return False
  79.     employees[keyid] = new_employee  # otherwise add employee to dictionary of Employee records
  80.     return True  # and return True to indicate new employee was added succesfully
  81.  
  82.  
  83. def report_all(employees: dict, report_header: str = "\n\nEmployees:\n", report_footer: str = ""):
  84.     """ print details of all Employee records in dictionary """
  85.     print(report_header)
  86.     for employee in employees.values():
  87.         print()
  88.         print(report(employee))
  89.     print(report_footer)
  90.  
  91.  
  92. filename = Path('employees.csv')
  93.  
  94. employees = read_employees(filename)  # see if we have employee data filed already
  95. if employees:
  96.     report_all(employees, "\nEmployee details read from file:\n")
  97.  
  98. # lets try to add some additional employees
  99. new_emps = (employee_create('Fred', "Bloggs", "William", "S5", 23_000, "Junior Chef"),
  100.             employee_create('Barry', "Smoth", "", "S6", 18_000, "Washer"),
  101.             employee_create('Alpha', "Beta", "Charlie", "S2", 43_000, "CFO", generate_password())
  102.             )
  103.  
  104. for employee in new_emps:
  105.     if add_employee(employee, employees):
  106.         print('\nAdded employee')
  107.     else:
  108.         print('\nEmployee already on file - details not updated')
  109.     print(report(employee))
  110.  
  111. save_employees(filename, employees)
  112. report_all(employees, '\n\nSaved to file Employee Details:\n')
  113.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement