Unit 2.4 Hacks
Hacks for 2.4a and 2.4b
Procedural abstraction?
- There is lots of procedural abstraction in both 2.4a and 2.4b
- Everywhere where a procedure is named is an example of procedural abstraction. Naming helps keep things clean and easy and can be re-used later
- The same procedure being used or called more than once is also an example of procedural abstraction and this happens multiple times.
Debugging Examples
"""
These imports define the key objects
"""
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
"""
These object and definitions are used throughout the Jupyter Notebook.
"""
# Setup of key Flask object (app)
app = Flask(__name__)
# Setup SQLAlchemy object and properties for the database (db)
database = 'sqlite:///customer.db' # path and filename of database
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
app.config['SQLALCHEMY_DATABASE_URI'] = database
app.config['SECRET_KEY'] = 'SECRET_KEY'
db = SQLAlchemy()
# This belongs in place where it runs once per project
db.init_app(app)
# --------------------------------------------------------------------------------------------------------------------------------------------
""" database dependencies to support sqlite examples """
import datetime
from datetime import datetime
import json
from sqlalchemy.exc import IntegrityError
from werkzeug.security import generate_password_hash, check_password_hash
''' Tutorial: https://www.sqlalchemy.org/library.html#tutorials, try to get into a Python shell and follow along '''
# Define the User class to manage actions in the 'users' table
# -- Object Relational Mapping (ORM) is the key concept of SQLAlchemy
# -- a.) db.Model is like an inner layer of the onion in ORM
# -- b.) User represents data we want to store, something that is built on db.Model
# -- c.) SQLAlchemy ORM is layer on top of SQLAlchemy Core, then SQLAlchemy engine, SQL
class customer(db.Model):
__tablename__ = 'customers' # table name is plural, class name is singular
# Define the User schema with "vars" from object
customerid = db.Column(db.Integer, primary_key=True)
_customername = db.Column(db.String(255), unique=False, nullable=False)
_customeruid = db.Column(db.String(255), unique=True, nullable=False)
_customerpassword = db.Column(db.String(255), unique=False, nullable=False)
_state = db.Column(db.Date)
# constructor of a User object, initializes the instance variables within object (self)
def __init__(self, customername, customeruid, customerpassword="123qwerty", state=datetime.today()):
self._customername = customername # variables with self prefix become part of the object,
self._customeruid = customeruid
self.set_password(customerpassword)
if isinstance(state, str): # not a date type
state = state=datetime.today()
self._state = state
# a name getter method, extracts name from object
@property
def customername(self):
return self._customername
# a setter function, allows name to be updated after initial object creation
@customername.setter
def customername(self, customername):
self._customername = customername
# a getter method, extracts uid from object
@property
def customeruid(self):
return self._customeruid
# a setter function, allows uid to be updated after initial object creation
@customeruid.setter
def uid(self, customeruid):
self._customeruid = customeruid
# check if uid parameter matches user id in object, return boolean
def is_uid(self, customeruid):
return self._customeruid == customeruid
@property
def customerpassword(self):
return self._customerpassword[0:10] + "..." # because of security only show 1st characters
# update password, this is conventional method used for setter
def set_customerpassword(self, customerpassword):
"""Create a hashed password."""
self._customerpassword = generate_password_hash(customerpassword, method='sha256')
# check password parameter against stored/encrypted password
def is_customerpassword(self, customerpassword):
"""Check against hashed password."""
result = check_password_hash(self._customerpassword, customerpassword)
return result
# dob property is returned as string, a string represents date outside object
@property
def state(self):
state_string = self._state.strftime('%m-%d-%Y')
return state_string
# dob setter, verifies date type before it is set or default to today
@state.setter
def state(self, state):
if isinstance(state, str): # not a date type
state = state=datetime.today()
self.state = state
# age is calculated field, age is returned according to date of birth
@property
def age(self):
today = datetime.today()
return today.year - self.state.year - ((today.month, today.day) < (self.state.month, self.state.day))
# output content using str(object) is in human readable form
# output content using json dumps, this is ready for API response
def __str__(self):
return json.dumps(self.read())
# CRUD create/add a new record to the table
# returns self or None on error
def create(self):
try:
# creates a person object from User(db.Model) class, passes initializers
db.session.add(self) # add prepares to persist person object to Users table
db.session.commit() # SqlAlchemy "unit of work pattern" requires a manual commit
return self
except IntegrityError:
db.session.remove()
return None
# CRUD read converts self to dictionary
# returns dictionary
def read(self):
return {
"customerid": self.id,
"customername": self.name,
"customeruid": self.uid,
"state": self.state,
"age": self.age,
}
# CRUD update: updates user name, password, phone
# returns self
def update(self, customername="", customeruid="", customerpassword=""):
"""only updates values with length"""
if len(customername) > 0:
self.customername = customername
if len(customeruid) > 0:
self.customeruid = customeruid
if len(customerpassword) > 0:
self.set_customerpassword(customerpassword)
db.session.add(self) # performs update when id exists
db.session.commit()
return self
# CRUD delete: remove self
# None
def delete(self):
db.session.delete(self)
db.session.commit()
return None