Model and Object-Oriented Programming Hacks

Object Oriented Programming is a part of learning Python. The objective of this blog is to introduce OOP with the intention of PBL task to create a database. The foundations for a database is defining a Class and understanding instance data and methods. A database is often a focus of backend coding as it will store persistent data, that can be recalled after the immediate session is closed.

from datetime import date
import json
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)
# 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
from datetime import date
import json

class User:    

    def __init__(self, name, uid, password, dob, classOf):
        self._name = name    # variables with self prefix become part of the object, 
        self._uid = uid
        self.set_password(password)
        self._dob = dob
        self._classOf = classOf
    
    @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

    @property
    def classOf(self):
        return self._classOf
    
    # gradDate should be have verification for type date
    @classOf.setter
    def classOf(self, classOf):
        self._classOf = classOf
        
    # 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,
            "classOf" : self.classOf
        }
        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}, classOf={self._classOf})'
    
# define tester
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

# add users
if __name__ == "__main__":
    u1 = User(name='Lydia Cho', uid='lyds', password='123lyds', dob=date(2006, 4, 12), classOf='2024')
    u2 = User(name='Alexa Carlson', uid='lex', password='lex321', dob=date(2006, 5, 16), classOf='2024')
    u3 = User(name='Ava Carlson', uid='aves', password='aves543', dob=date(2006, 5, 16), classOf='2024')
    u4 = User(name='Sri Kotturi', uid='sri', password='sri333', dob=date(2005, 12, 13), classOf='2024')

# def variable for users    
users = [u1, u2, u3, u4]

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


    # Change user
print("Test 2, change user 3")
u.name = "Bubba (Lillia) C"
u.uid = "bubbs"
u.set_password("bubba4life")
u = tester(users, u.uid, "bubba4life")
    
    
print("JSON ready string:\n", u1, "\n") 
print("Raw Variables of object:\n", vars(u1), "\n") 
print("Raw Attributes and Methods of object:\n", dir(u1), "\n")
print("Representation to Re-Create the object:\n", repr(u1), "\n") 
Test 1, find user 3
{"name": "Lydia Cho", "uid": "lyds", "dob": "04-12-2006", "age": 16, "classOf": "2024"}
{"name": "Alexa Carlson", "uid": "lex", "dob": "05-16-2006", "age": 16, "classOf": "2024"}
* {"name": "Ava Carlson", "uid": "aves", "dob": "05-16-2006", "age": 16, "classOf": "2024"}
{"name": "Sri Kotturi", "uid": "sri", "dob": "12-13-2005", "age": 17, "classOf": "2024"}
Test 2, change user 3
{"name": "Lydia Cho", "uid": "lyds", "dob": "04-12-2006", "age": 16, "classOf": "2024"}
{"name": "Alexa Carlson", "uid": "lex", "dob": "05-16-2006", "age": 16, "classOf": "2024"}
* {"name": "Bubba (Lillia) C", "uid": "bubbs", "dob": "05-16-2006", "age": 16, "classOf": "2024"}
{"name": "Sri Kotturi", "uid": "sri", "dob": "12-13-2005", "age": 17, "classOf": "2024"}
JSON ready string:
 {"name": "Lydia Cho", "uid": "lyds", "dob": "04-12-2006", "age": 16, "classOf": "2024"} 

Raw Variables of object:
 {'_name': 'Lydia Cho', '_uid': 'lyds', '_password': 'sha256$uNkMIwzoeNgUvFpE$06cb74281cd4a029c3cf2879d2325542872c25e51a8877cf8bbc0b1559341cce', '_dob': datetime.date(2006, 4, 12), '_classOf': '2024'} 

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__', '_classOf', '_dob', '_name', '_password', '_uid', 'age', 'classOf', 'dictionary', 'dob', 'is_password', 'is_uid', 'name', 'set_password', 'uid'] 

Representation to Re-Create the object:
 User(name=Lydia Cho, uid=lyds, password=sha256$uNkMIwzoeNgUvFpE$06cb74281cd4a029c3cf2879d2325542872c25e51a8877cf8bbc0b1559341cce,dob=2006-04-12, classOf=2024)