Model and Object-Oriented Programming
# 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)
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))
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
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])))