title: OOP Hacks description: OOP Hacks toc: true

comments: true

OOP Hacks

# 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$sCH..." dob: "1847-02-11"
name: "Nicholas Tesla", id: "nick", psw: "sha256$QtW..." dob: "1856-07-10"
* name: "Alexander Graham Bell", id: "lex", psw: "sha256$Tpa..." dob: "1847-03-03"
name: "Eli Whitney", id: "eli", psw: "sha256$ISs..." dob: "1765-12-08"
name: "Hedy Lemarr", id: "hedy", psw: "sha256$7bI..." dob: "1914-09-09"
Test 2, change user 3
name: "Thomas Edison", id: "toby", psw: "sha256$sCH..." dob: "1847-02-11"
name: "Nicholas Tesla", id: "nick", psw: "sha256$QtW..." dob: "1856-07-10"
* name: "John Mortensen", id: "jm1021", psw: "sha256$lXW..." dob: "1847-03-03"
name: "Eli Whitney", id: "eli", psw: "sha256$ISs..." dob: "1765-12-08"
name: "Hedy Lemarr", id: "hedy", psw: "sha256$7bI..." dob: "1914-09-09"
Test 3, make a dictionary
[{"_name": "Thomas Edison", "_uid": "toby", "_dob": "1847-02-11", "_password": "sha256$sCHIgT5BfMZLFsb4$017d2604e0600da1220a8b40241f6766e49be0129f8e3bbd86b11b62c4bf5e72", "_classOf": 1915}, {"_name": "Nicholas Tesla", "_uid": "nick", "_dob": "1856-07-10", "_password": "sha256$QtW2GkpuszbTm9MC$36bc84e832a67678780a7ac18f5d0bb33aef39b2f63dacbc6d6c566c70ab1630", "_classOf": 1873}, {"_name": "John Mortensen", "_uid": "jm1021", "_dob": "1847-03-03", "_password": "sha256$lXWFoRLOZdIVKMOm$a73387d576872cfe077250646564b9974d18b17055bd4ca77437b3733f926af9", "_classOf": 1870}, {"_name": "Eli Whitney", "_uid": "eli", "_dob": "1765-12-08", "_password": "sha256$ISsRmJoZfgO9Zg7H$a48c1e5f9692c1eb7f27753604c13e8b84e404e84faf9828cbfea06b461adb00", "_classOf": 1786}, {"_name": "Hedy Lemarr", "_uid": "hedy", "_dob": "1914-09-09", "_password": "sha256$7bI68J9yMyEOwKas$4d41a6603e479c86159798bd7b3c849cbb8da4dba32afaf198a289a0450e5589", "_classOf": 1936}]
Test 4, make a dictionary
[{"_name": "Thomas Edison", "_uid": "toby", "_dob": "1847-02-11", "_password": "sha256$sCHIgT5BfMZLFsb4$017d2604e0600da1220a8b40241f6766e49be0129f8e3bbd86b11b62c4bf5e72", "_classOf": 1915}, {"_name": "Nicholas Tesla", "_uid": "nick", "_dob": "1856-07-10", "_password": "sha256$QtW2GkpuszbTm9MC$36bc84e832a67678780a7ac18f5d0bb33aef39b2f63dacbc6d6c566c70ab1630", "_classOf": 1873}, {"_name": "John Mortensen", "_uid": "jm1021", "_dob": "1847-03-03", "_password": "sha256$lXWFoRLOZdIVKMOm$a73387d576872cfe077250646564b9974d18b17055bd4ca77437b3733f926af9", "_classOf": 1870}, {"_name": "Eli Whitney", "_uid": "eli", "_dob": "1765-12-08", "_password": "sha256$ISsRmJoZfgO9Zg7H$a48c1e5f9692c1eb7f27753604c13e8b84e404e84faf9828cbfea06b461adb00", "_classOf": 1786}, {"_name": "Hedy Lemarr", "_uid": "hedy", "_dob": "1914-09-09", "_password": "sha256$7bI68J9yMyEOwKas$4d41a6603e479c86159798bd7b3c849cbb8da4dba32afaf198a289a0450e5589", "_classOf": 1936}]
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)

from werkzeug.security import generate_password_hash, check_password_hash
from datetime import date
import json

class User:    

    def __init__(self, name, uid, password, dob):
        self._name = name    # variables with self prefix become part of the object, 
        self._uid = uid
        self.set_password(password)
        self._dob = dob
    
    @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
        
    # check if uid parameter matches user id in object, return boolean
    def is_uid(self, uid):
        return self._uid == uid
    
    # dob property is returned as string, to avoid unfriendly outcomes
    @property
    def dob(self):
        dob_string = self._dob.strftime('%m-%d-%Y')
        return dob_string
    
    # dob should be have verification for type date
    @dob.setter
    def dob(self, dob):
        self._dob = dob
        
    # age is calculated and returned each time it is accessed
    @property
    def age(self):
        today = date.today()
        return today.year - self._dob.year - ((today.month, today.day) < (self._dob.month, self._dob.day))
    
    # dictionary is customized, removing password for security purposes
    @property
    def dictionary(self):
        dict = {
            "name" : self.name,
            "uid" : self.uid,
            "dob" : self.dob,
            "age" : self.age
        }
        return dict
    
    # 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 json dumps, this is ready for API response
    def __str__(self):
        return json.dumps(self.dictionary)
    
    # output command to recreate the object, uses attribute directly
    def __repr__(self):
        return f'User(name={self._name}, uid={self._uid}, password={self._password},dob={self._dob})'
    

if __name__ == "__main__":
    u1 = User(name='Thomas Edison', uid='toby', password='123toby', dob=date(1847, 2, 11))
    u2 = User(name='Taiyo Iwazak', uid='Tai', password='123Tai', dob=date(2006, 7, 13))
    u3 = User(name='Luna Iwazaki', uid='Lun', password='123Lun', dob=date(2005, 2, 11))
    u4 = User(name='Ethan tran', uid='Eth', password='123Tra', dob=date(2002, 9, 11))
    u5 = User(name='Nikhil C', uid='Nik', password='123Nik', dob=date(2006, 9, 10))
    users = [u1, u2, u3, u4, u5]
    for x in users:
        print(x.name.upper()+":")
        print("\t Name:", x.name)
        print("\t User ID:", x.uid)
        print("\t Date of Birth:", x.dob)
        print("\t Age:", x.age, "years old\n")
        
        print("JSON ready string:\n\t", x, "\n") 
        print("Raw Variables of object:\n\t", vars(x), "\n") 
        print("Raw Attributes and Methods of object:\n\t", dir(x), "\n")
        print("Representation to Re-Create the object:\n\t", repr(x), "\n") 
18
THOMAS EDISON:
	 Name: Thomas Edison
	 User ID: toby
	 Date of Birth: 02-11-1847
	 Age: 175 years old

JSON ready string:
	 {"name": "Thomas Edison", "uid": "toby", "dob": "02-11-1847", "age": 175} 

Raw Variables of object:
	 {'_name': 'Thomas Edison', '_uid': 'toby', '_password': 'sha256$2hRZk7HDSMWWfgDq$e28ef7e7dc622ea246bb450469fa87f674e2351f614e2c315421451c2e597944', '_dob': datetime.date(1847, 2, 11)} 

Raw Attributes and Methods of object:
	 ['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', '_dob', '_name', '_password', '_uid', 'age', 'dictionary', 'dob', 'is_password', 'is_uid', 'name', 'set_password', 'uid'] 

Representation to Re-Create the object:
	 User(name=Thomas Edison, uid=toby, password=sha256$2hRZk7HDSMWWfgDq$e28ef7e7dc622ea246bb450469fa87f674e2351f614e2c315421451c2e597944,dob=1847-02-11) 

TAIYO IWAZAK:
	 Name: Taiyo Iwazak
	 User ID: Tai
	 Date of Birth: 07-13-2006
	 Age: 16 years old

JSON ready string:
	 {"name": "Taiyo Iwazak", "uid": "Tai", "dob": "07-13-2006", "age": 16} 

Raw Variables of object:
	 {'_name': 'Taiyo Iwazak', '_uid': 'Tai', '_password': 'sha256$vzRX5SqVju6GgT7q$65bb3bbe8907ea6bc8de2e03de45406ead8c3ae770628185f5c1f1e9a6e94e35', '_dob': datetime.date(2006, 7, 13)} 

Raw Attributes and Methods of object:
	 ['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', '_dob', '_name', '_password', '_uid', 'age', 'dictionary', 'dob', 'is_password', 'is_uid', 'name', 'set_password', 'uid'] 

Representation to Re-Create the object:
	 User(name=Taiyo Iwazak, uid=Tai, password=sha256$vzRX5SqVju6GgT7q$65bb3bbe8907ea6bc8de2e03de45406ead8c3ae770628185f5c1f1e9a6e94e35,dob=2006-07-13) 

LUNA IWAZAKI:
	 Name: Luna Iwazaki
	 User ID: Lun
	 Date of Birth: 02-11-2005
	 Age: 17 years old

JSON ready string:
	 {"name": "Luna Iwazaki", "uid": "Lun", "dob": "02-11-2005", "age": 17} 

Raw Variables of object:
	 {'_name': 'Luna Iwazaki', '_uid': 'Lun', '_password': 'sha256$PsMdzvbZCcgCGLCs$0180d68462671f852d61b67a96802703247a47f1a5f8eff66bbaa754d6137e81', '_dob': datetime.date(2005, 2, 11)} 

Raw Attributes and Methods of object:
	 ['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', '_dob', '_name', '_password', '_uid', 'age', 'dictionary', 'dob', 'is_password', 'is_uid', 'name', 'set_password', 'uid'] 

Representation to Re-Create the object:
	 User(name=Luna Iwazaki, uid=Lun, password=sha256$PsMdzvbZCcgCGLCs$0180d68462671f852d61b67a96802703247a47f1a5f8eff66bbaa754d6137e81,dob=2005-02-11) 

ETHAN TRAN:
	 Name: Ethan tran
	 User ID: Eth
	 Date of Birth: 09-11-2002
	 Age: 20 years old

JSON ready string:
	 {"name": "Ethan tran", "uid": "Eth", "dob": "09-11-2002", "age": 20} 

Raw Variables of object:
	 {'_name': 'Ethan tran', '_uid': 'Eth', '_password': 'sha256$bB5ZhS2oEf6nt3QI$2d064eb08acf7a2728615e8e22319114c67be935277bff4b452bad304f3673f2', '_dob': datetime.date(2002, 9, 11)} 

Raw Attributes and Methods of object:
	 ['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', '_dob', '_name', '_password', '_uid', 'age', 'dictionary', 'dob', 'is_password', 'is_uid', 'name', 'set_password', 'uid'] 

Representation to Re-Create the object:
	 User(name=Ethan tran, uid=Eth, password=sha256$bB5ZhS2oEf6nt3QI$2d064eb08acf7a2728615e8e22319114c67be935277bff4b452bad304f3673f2,dob=2002-09-11) 

NIKHIL C:
	 Name: Nikhil C
	 User ID: Nik
	 Date of Birth: 09-10-2006
	 Age: 16 years old

JSON ready string:
	 {"name": "Nikhil C", "uid": "Nik", "dob": "09-10-2006", "age": 16} 

Raw Variables of object:
	 {'_name': 'Nikhil C', '_uid': 'Nik', '_password': 'sha256$LQFJTQTmyK45Ingh$e5168359eef5de40d497c9bb9ca8a264ca3f2891af5a77045d1ff5e5227b32c2', '_dob': datetime.date(2006, 9, 10)} 

Raw Attributes and Methods of object:
	 ['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', '_dob', '_name', '_password', '_uid', 'age', 'dictionary', 'dob', 'is_password', 'is_uid', 'name', 'set_password', 'uid'] 

Representation to Re-Create the object:
	 User(name=Nikhil C, uid=Nik, password=sha256$LQFJTQTmyK45Ingh$e5168359eef5de40d497c9bb9ca8a264ca3f2891af5a77045d1ff5e5227b32c2,dob=2006-09-10)