Class and Object Code

# Werkzeug is a collection of libraries that can be used to create a WSGI (Web Server Gateway Interface)
# A gateway in necessary as a web server cannot communicate directly with Python.
# In this case, imports are focused on generating hash code to protect passwords.
from werkzeug.security import generate_password_hash, check_password_hash
import json
import datetime
from datetime import date

def calculate_age(born):
    today = date.today()
    return today.year - born.year - ((today.month, today.day) < (born.month, born.day))

# Define a User Class/Template
# -- A User represents the data we want to manage
class User:    
    # constructor of a User object, initializes the instance variables within object (self)
    def __init__(self, name, uid, dob, password, classOf):
        self._name = name    # variables with self prefix become part of the object, 
        self._uid = uid
        self._dob = dob
        self.set_password(password)
        self._classOf = classOf

    # a name getter method, extracts name from object
    @property
    def name(self):
        return self._name
    
    # a setter function, allows name to be updated after initial object creation
    @name.setter
    def name(self, name):
        self._name = name
    
    # a getter method, extracts email from object
    @property
    def uid(self):
        return self._uid
    
    # a setter function, allows name to be updated after initial object creation
    @uid.setter
    def uid(self, uid):
        self._uid = uid

    @property
    def dob(self):
        return self._dob
    
    @dob.setter
    def dob(self, dob):
        self._dob = dob

    @property
    def classOf(self):
        self._classOf = classOf
    
    @classOf.setter
    def classOf(self, dob):
        self._classOf = classOf
        
    # check if uid parameter matches user id in object, return boolean
    def is_uid(self, uid):
        return self._uid == uid
    
    @property
    def age(self):
        self._age = age 
    
    @property
    def password(self):
        return self._password[0:10] + "..." # because of security only show 1st characters

    # update password, this is conventional setter
    def set_password(self, password):
        """Create a hashed password."""
        self._password = generate_password_hash(password, method='sha256')

    # check password parameter versus stored/encrypted password
    def is_password(self, password):
        """Check against hashed password."""
        result = check_password_hash(self._password, password)
        return result
    
    # output content using str(object) in human readable form, uses getter
    def __str__(self):
        return f'name: "{self.name}", id: "{self.uid}", psw: "{self.password}" dob: "{self.dob}"'

    # output command to recreate the object, uses attribute directly
    def __repr__(self):
        return f'Person(name={self._name}, uid={self._uid}, password={self._password}, dob={self._dob})'
    def toJSON(self):
        excluded_fields = ["_password", "_dob"]
        return json.dumps(
            {
                k[1:]: v
                for k, v in self.__dict__.items()
                if k not in excluded_fields
            }
            | {"age": calculate_age(self._dob)},
            cls=DateTimeEncoder,
        )


# tester method to print users
def tester(users, uid, psw):
    result = None
    for user in users:
        # test for match in database
        if user.uid == uid and user.is_password(psw):  # check for match
            print("* ", end="")
            result = user
        # print using __str__ method
        print(str(user))
    return result

# place tester code inside of special if!  This allows include without tester running
if __name__ == "__main__":

    # define user objects
    u1 = User(name='Thomas Edison', uid='toby', dob = str(date(1847, 2, 11)), password='123toby', classOf=1915)
    u2 = User(name='Nicholas Tesla', uid='nick', dob = str(date(1856, 7, 10)), password='123nick', classOf = 1873)
    u3 = User(name='Alexander Graham Bell', uid='lex', dob = str(date(1847, 3, 3)), password='123lex', classOf = 1870)
    u4 = User(name='Eli Whitney', uid='eli', dob = str(date(1765, 12, 8)), password='123eli', classOf = 1786)
    u5 = User(name='Hedy Lemarr', uid='hedy', dob = str(date(1914, 9, 9)), password='123hedy', classOf = 1936)

    # put user objects in list for convenience
    users = [u1, u2, u3, u4, u5]

    # Find user
    print("Test 1, find user 3")
    u = tester(users, u3.uid, "123lex")


    # Change user
    print("Test 2, change user 3")
    u.name = "John Mortensen"
    u.uid = "jm1021"
    u.set_password("123qwerty")
    u = tester(users, u.uid, "123qwerty")


    # Make dictionary
    ''' 
    The __dict__ in Python represents a dictionary or any mapping object that is used to store the attributes of the object. 
    Every object in Python has an attribute that is denoted by __dict__. 
    Use the json.dumps() method to convert the list of Users to a JSON string.
    '''
    print("Test 3, make a dictionary")
    json_string = json.dumps([user.__dict__ for user in users]) 
    print(json_string)

    print("Test 4, make a dictionary")
    json_string = json.dumps([vars(user) for user in users]) 
    print(json_string)
Test 1, find user 3
name: "Thomas Edison", id: "toby", psw: "sha256$rle..." dob: "1847-02-11"
name: "Nicholas Tesla", id: "nick", psw: "sha256$B26..." dob: "1856-07-10"
* name: "Alexander Graham Bell", id: "lex", psw: "sha256$yip..." dob: "1847-03-03"
name: "Eli Whitney", id: "eli", psw: "sha256$2Zp..." dob: "1765-12-08"
name: "Hedy Lemarr", id: "hedy", psw: "sha256$NG7..." dob: "1914-09-09"
Test 2, change user 3
name: "Thomas Edison", id: "toby", psw: "sha256$rle..." dob: "1847-02-11"
name: "Nicholas Tesla", id: "nick", psw: "sha256$B26..." dob: "1856-07-10"
* name: "John Mortensen", id: "jm1021", psw: "sha256$y2N..." dob: "1847-03-03"
name: "Eli Whitney", id: "eli", psw: "sha256$2Zp..." dob: "1765-12-08"
name: "Hedy Lemarr", id: "hedy", psw: "sha256$NG7..." dob: "1914-09-09"
Test 3, make a dictionary
[{"_name": "Thomas Edison", "_uid": "toby", "_dob": "1847-02-11", "_password": "sha256$rleKIoZEGyXN225F$f32449046b27eedb115fdc806740113d9dcfa90f25a5033696ce6349f23503bf", "_classOf": 1915}, {"_name": "Nicholas Tesla", "_uid": "nick", "_dob": "1856-07-10", "_password": "sha256$B26oJTlDyZXmf6RM$86405e3dce9d031f0fb86783bf5f71c89cafc9d0118aa9dd2298ade4ba4993f8", "_classOf": 1873}, {"_name": "John Mortensen", "_uid": "jm1021", "_dob": "1847-03-03", "_password": "sha256$y2Nj93qM2WNtyIBI$3a24083fb2be1be114fa5134990d43c209358c99b84de13422241d419c4b9e6d", "_classOf": 1870}, {"_name": "Eli Whitney", "_uid": "eli", "_dob": "1765-12-08", "_password": "sha256$2Zp7OiFHyklIvs2y$9c64af41d095b480eb20e6b83b221987ac8349d983b9844017d684a2709ddb79", "_classOf": 1786}, {"_name": "Hedy Lemarr", "_uid": "hedy", "_dob": "1914-09-09", "_password": "sha256$NG7WN824QVnw70oz$08c14a52764e2b776676c15558b019104c1e92bd2744d1d4b3ec6a4792a680d9", "_classOf": 1936}]
Test 4, make a dictionary
[{"_name": "Thomas Edison", "_uid": "toby", "_dob": "1847-02-11", "_password": "sha256$rleKIoZEGyXN225F$f32449046b27eedb115fdc806740113d9dcfa90f25a5033696ce6349f23503bf", "_classOf": 1915}, {"_name": "Nicholas Tesla", "_uid": "nick", "_dob": "1856-07-10", "_password": "sha256$B26oJTlDyZXmf6RM$86405e3dce9d031f0fb86783bf5f71c89cafc9d0118aa9dd2298ade4ba4993f8", "_classOf": 1873}, {"_name": "John Mortensen", "_uid": "jm1021", "_dob": "1847-03-03", "_password": "sha256$y2Nj93qM2WNtyIBI$3a24083fb2be1be114fa5134990d43c209358c99b84de13422241d419c4b9e6d", "_classOf": 1870}, {"_name": "Eli Whitney", "_uid": "eli", "_dob": "1765-12-08", "_password": "sha256$2Zp7OiFHyklIvs2y$9c64af41d095b480eb20e6b83b221987ac8349d983b9844017d684a2709ddb79", "_classOf": 1786}, {"_name": "Hedy Lemarr", "_uid": "hedy", "_dob": "1914-09-09", "_password": "sha256$NG7WN824QVnw70oz$08c14a52764e2b776676c15558b019104c1e92bd2744d1d4b3ec6a4792a680d9", "_classOf": 1936}]
from werkzeug.security import generate_password_hash, check_password_hash
import json
from datetime import date


def calculate_age(born):
    today = date.today()
    return today.year - born.year - ((today.month, today.day) < (born.month, born.day))


class User:
    def __init__(self, name, classOf, dob, uid, password):
        self._name = name
        self._uid = uid
        self._dob = dob
        self._classOf = classOf
        self.set_password(password)

    @property
    def name(self):
        return self._name

    @name.setter
    def name(self, name):
        self._name = name

    @property
    def uid(self):
        return self._uid

    @uid.setter
    def uid(self, uid):
        self._uid = uid

    @property
    def dob(self):
        return self._dob

    @dob.setter
    def dob(self, dob):
        self._dob = dob

    @property
    def classOf(self):
        return self._classOf

    @classOf.setter
    def classOf(self, classOf):
        self._classOf = classOf

    def is_uid(self, uid):
        return self._uid == uid

    @property
    def password(self):
        return self._password[0:8] + "..."

    def set_password(self, password):
        self._password = generate_password_hash(password, method="sha256")

    def is_password(self, password):
        result = check_password_hash(self._password, password)
        return result

    def toJSON(self):
        excluded_fields = ["_password", "_dob"]
        return json.dumps(
            {
                k[1:]: v
                for k, v in self.__dict__.items()
                if k not in excluded_fields
            }
            | {"age": calculate_age(self._dob)},
            cls=DateTimeEncoder,
        )

    def __str__(self):
        return f'name: "{self.name}", class of: {self.classOf}, id: "{self.uid}", psw: "{self.password}"'

    def __repr__(self):
        return f"Person(name={self._name}, classOf={self._classOf}, uid={self._uid}, password={self._password})"


def tester(users, uid, psw):
    result = None
    for user in users:
        if user.is_uid(uid) and user.is_password(psw):
            print("* ", end="")
            result = user
        print(str(user))
    return result


class DateTimeEncoder(json.JSONEncoder):
    def default(self, obj):
        if isinstance(obj, date):
            return obj.isoformat()


if __name__ == "__main__":
    u1 = User(
        name="Thomas Edison",
        classOf=2024,
        dob=date(2022, 12, 25),
        uid="toby",
        password="123toby",
    )
    u2 = User(
        name="Nicholas Tesla",
        classOf=2025,
        dob=date(2021, 1, 7),
        uid="nick",
        password="123nick",
    )
    u3 = User(
        name="Alexander Graham Bell",
        classOf=2024,
        dob=date(2020, 10, 18),
        uid="lex",
        password="123lex",
    )
    u4 = User(
        name="Eli Whitney",
        classOf=2026,
        dob=date(2019, 9, 16),
        uid="eli",
        password="123eli",
    )
    u5 = User(
        name="Hedy Lemarr",
        classOf=2027,
        dob=date(2018, 3, 12),
        uid="hedy",
        password="123hedy",
    )

    users = [u1, u2, u3, u4, u5]

    print("Test 1: find user 3")
    u = tester(users, u3.uid, "123lex")

    print("\nTest 2: change user 3")
    u.name = "John Mortensen"
    u.uid = "jm1021"
    u.set_password("123qwerty")
    u = tester(users, u.uid, "123qwerty")

    print("\nTest 3: generate JSON")
    json_strings = [u.toJSON() for u in users]
    print("\n".join(json_strings))
Test 1: find user 3
name: "Thomas Edison", class of: 2024, id: "toby", psw: "sha256$R..."
name: "Nicholas Tesla", class of: 2025, id: "nick", psw: "sha256$e..."
* name: "Alexander Graham Bell", class of: 2024, id: "lex", psw: "sha256$8..."
name: "Eli Whitney", class of: 2026, id: "eli", psw: "sha256$N..."
name: "Hedy Lemarr", class of: 2027, id: "hedy", psw: "sha256$T..."

Test 2: change user 3
name: "Thomas Edison", class of: 2024, id: "toby", psw: "sha256$R..."
name: "Nicholas Tesla", class of: 2025, id: "nick", psw: "sha256$e..."
* name: "John Mortensen", class of: 2024, id: "jm1021", psw: "sha256$b..."
name: "Eli Whitney", class of: 2026, id: "eli", psw: "sha256$N..."
name: "Hedy Lemarr", class of: 2027, id: "hedy", psw: "sha256$T..."

Test 3: generate JSON
{"name": "Thomas Edison", "uid": "toby", "classOf": 2024, "age": 0}
{"name": "Nicholas Tesla", "uid": "nick", "classOf": 2025, "age": 2}
{"name": "John Mortensen", "uid": "jm1021", "classOf": 2024, "age": 2}
{"name": "Eli Whitney", "uid": "eli", "classOf": 2026, "age": 3}
{"name": "Hedy Lemarr", "uid": "hedy", "classOf": 2027, "age": 4}

Hacks

Add new attributes/variables to the Class. Make class specific to your CPT work.

  • Add classOf attribute to define year of graduation
    • Add setter and getter for classOf
  • Add dob attribute to define date of birth
    • This will require investigation into Python datetime objects as shown in example code below
    • Add setter and getter for dob
  • Add instance variable for age, make sure if dob changes age changes
    • Add getter for age, but don't add/allow setter for age
  • Update and format tester function to work with changes

Start a class design for each of your own Full Stack CPT sections of your project

  • Use new code cell in this notebook
  • Define init and self attributes
  • Define setters and getters
  • Make a tester

Start Code for Hacks

from datetime import date

def calculate_age(born):
    today = date.today()
    return today.year - born.year - ((today.month, today.day) < (born.month, born.day))

dob = date(2004, 12, 31)
age = calculate_age(dob)
print(age)
import json

class Notebook:
   def __init__(self, calc, bio, poe, csp, ush):
      self._calc = calc
      self._bio = bio
      self._poe = poe
      self._csp = csp
      self._ush = ush

   @property 
   def calc(self):
      return self._calc

   @property 
   def bio(self):
      return self._bio

   @property 
   def poe(self):
      return self._poe
   
   @property 
   def csp(self):
      return self._csp

   @property 
   def ush(self):
      return self._ush

   @calc.setter
   def calc(self, calc):
      self._calc = calc

   @bio.setter
   def calc(self, bio):
      self._bio = bio

   @poe.setter
   def calc(self, poe):
      self._poe = poe

   @csp.setter
   def csp(self, csp):
      self._csp = csp

   @ush.setter
   def ush(self, ush):
      self._ush = ush

   @property
   def dictionary(self):
      dic = {
         "calc": self.calc,
         "bio": self.bio,
         "poe": self.poe,
         "csp": self.csp,
         "ush": self.ush,
      }
      return dic

   def __str__(self):
      return json.dumps(self.dictionary)

   def __repr__(self):
      return 'Notebook(calc={self._calc}, bio={self._bio}, poe={self._poe}, csp={self._csp}, ush={self._ush})'

Notebook1 = Notebook(1,2,3,4,5)
Notebook2 = Notebook(6,7,8,9,10)
print(Notebook1)
print(Notebook2)

notebooks = [Notebook1, Notebook2]

print(json.dumps(str([notebook for notebook in notebooks])))
{"calc": 3, "bio": 2, "poe": 3, "csp": 4, "ush": 5}
{"calc": 8, "bio": 7, "poe": 8, "csp": 9, "ush": 10}
"[Notebook(calc={self._calc}, bio={self._bio}, poe={self._poe}, csp={self._csp}, ush={self._ush}), Notebook(calc={self._calc}, bio={self._bio}, poe={self._poe}, csp={self._csp}, ush={self._ush})]"